From 4cfb78756c4db62e81a55a1174329bfa788f7e1b Mon Sep 17 00:00:00 2001 From: Martijn Govers Date: Fri, 13 Nov 2026 13:00:47 +0100 Subject: [PATCH 1/6] use more finegrained top-level error codes Signed-off-by: Martijn Govers --- .../include/power_grid_model_c/basics.h | 9 ++ .../power_grid_model_c/src/handle.hpp | 7 +- .../src/input_sanitization.hpp | 34 ++++---- .../power_grid_model_c/src/model.cpp | 4 + .../include/power_grid_model_cpp/handle.hpp | 83 +++++++++++++++++-- src/power_grid_model/_core/error_handling.py | 24 +++++- tests/native_api_tests/test_api_dataset.cpp | 10 +-- tests/native_api_tests/test_api_logger.cpp | 6 +- tests/native_api_tests/test_api_meta_data.cpp | 2 +- tests/native_api_tests/test_api_model.cpp | 32 +++---- .../test_api_model_multi_dimension.cpp | 4 +- .../test_api_model_update.cpp | 8 +- .../native_api_tests/test_api_validation.cpp | 2 +- 13 files changed, 165 insertions(+), 60 deletions(-) diff --git a/power_grid_model_c/power_grid_model_c/include/power_grid_model_c/basics.h b/power_grid_model_c/power_grid_model_c/include/power_grid_model_c/basics.h index 34a08d424f..929d056afd 100644 --- a/power_grid_model_c/power_grid_model_c/include/power_grid_model_c/basics.h +++ b/power_grid_model_c/power_grid_model_c/include/power_grid_model_c/basics.h @@ -204,6 +204,15 @@ enum PGM_ErrorCode { PGM_regular_error = 1, /**< some error occurred which is not in the batch calculation */ PGM_batch_error = 2, /**< some error occurred which is in the batch calculation */ PGM_serialization_error = 3, /**< some error occurred which is in the (de)serialization process */ + PGM_dataset_error = 4, /**< Error occurs during dataset handling. */ + PGM_data_error = 5, /**< There was a problem with the contents of the provided data. */ + PGM_calculation_error = 6, /**< Error occurs during the actual calculation. */ + PGM_illegal_operation = + 7, /**< An illegal operation was attempted to the C API, such as accessing a null pointer. */ + PGM_bad_request = 8, /**< A bad request was attempted to the C API, such as providing the wrong dataset type. */ + PGM_not_implemented = 9, /**< The functionality is either not supported or not yet implemented. */ + PGM_internal_error = 10, /**< There was an internal error. */ + PGM_unknown_error = 255, /**< An unknown error occurred. */ }; /** diff --git a/power_grid_model_c/power_grid_model_c/src/handle.hpp b/power_grid_model_c/power_grid_model_c/src/handle.hpp index 323056bf3e..80a61f991a 100644 --- a/power_grid_model_c/power_grid_model_c/src/handle.hpp +++ b/power_grid_model_c/power_grid_model_c/src/handle.hpp @@ -15,6 +15,7 @@ #include #include +#include #include #include @@ -65,6 +66,10 @@ struct DefaultExceptionHandler { std::exception_ptr const ex_ptr = std::current_exception(); try { std::rethrow_exception(ex_ptr); + } catch (power_grid_model::PowerGridError const& ex) { + // TODO(mgovers): temporary hack to expose base code in prep of #1635 + auto const base_error_code = std::to_underlying(ex.error_code()) % 256; + handle_regular_error(handle, ex, static_cast(base_error_code), extra_message); } catch (std::exception const& ex) { // NOSONAR(S1181) handle_regular_error(handle, ex, error_code, extra_message); } catch (...) { // NOSONAR(S2738) @@ -82,7 +87,7 @@ struct DefaultExceptionHandler { } static void handle_unkown_error(PGM_Handle& handle) noexcept { - handle.err_code = PGM_regular_error; + handle.err_code = PGM_unknown_error; handle.err_msg = "Unknown error!\n"; } }; diff --git a/power_grid_model_c/power_grid_model_c/src/input_sanitization.hpp b/power_grid_model_c/power_grid_model_c/src/input_sanitization.hpp index 51734dcd66..036f6957e7 100644 --- a/power_grid_model_c/power_grid_model_c/src/input_sanitization.hpp +++ b/power_grid_model_c/power_grid_model_c/src/input_sanitization.hpp @@ -6,22 +6,17 @@ #include "power_grid_model_c/basics.h" -#include -#include -#include +#include + +#include +#include +#include #include +#include #include namespace power_grid_model_c { -class IllegalOperationError : public std::exception { - public: - explicit IllegalOperationError(std::string_view message) : msg_{std::format("Illegal operation: {}\n", message)} {} - - char const* what() const noexcept final { return msg_.c_str(); } - - private: - std::string msg_; -}; +using power_grid_model::IllegalOperationError; template constexpr T compile_time_safe_cast(U const& value) noexcept { static_assert(std::convertible_to, @@ -36,14 +31,23 @@ template constexpr T compile_time_safe_cast(U const& va } } +template + requires std::convertible_to +constexpr std::optional optional_safe_cast(U value) noexcept { + if (std::in_range(value)) { + return std::optional{std::in_place, static_cast(value)}; + } + return std::nullopt; +} + template requires std::convertible_to constexpr auto safe_cast(U value) { if constexpr (std::same_as) { return value; } else { - if (std::in_range(value)) { - return static_cast(value); + if (auto const result = optional_safe_cast(value)) { + return *result; } throw IllegalOperationError{"Value out of range for target type"}; } @@ -62,7 +66,7 @@ template constexpr PGM_Idx to_c_size(T value) { } template constexpr bool safe_bool(T value) { return value != T{0}; } -template constexpr T to_c_bool(bool value) { return value ? T{1} : T{0}; } +template constexpr T to_c_bool(bool value) noexcept { return value ? T{1} : T{0}; } // safe enum conversion from C integer type to C++ enum type. // diff --git a/power_grid_model_c/power_grid_model_c/src/model.cpp b/power_grid_model_c/power_grid_model_c/src/model.cpp index ddab6ba22b..0c68cb65c1 100644 --- a/power_grid_model_c/power_grid_model_c/src/model.cpp +++ b/power_grid_model_c/power_grid_model_c/src/model.cpp @@ -182,6 +182,10 @@ struct BatchExceptionHandler : public power_grid_model_c::DefaultExceptionHandle handle_regular_error(handle, ex, PGM_batch_error); handle.failed_scenarios = ex.failed_scenarios(); handle.batch_errs = ex.err_msgs(); + } catch (PowerGridError const& ex) { + // TODO(mgovers): temporary hack to expose base code in prep of #1635 + auto const base_error_code = std::to_underlying(ex.error_code()) % 256; + handle_regular_error(handle, ex, static_cast(base_error_code)); } catch (std::exception& ex) { // NOSONAR(S1181) handle_regular_error(handle, ex, PGM_regular_error); } catch (...) { // NOSONAR(S2738) diff --git a/power_grid_model_c/power_grid_model_cpp/include/power_grid_model_cpp/handle.hpp b/power_grid_model_c/power_grid_model_cpp/include/power_grid_model_cpp/handle.hpp index e7ba5c883c..4e1024ef5d 100644 --- a/power_grid_model_c/power_grid_model_cpp/include/power_grid_model_cpp/handle.hpp +++ b/power_grid_model_c/power_grid_model_cpp/include/power_grid_model_cpp/handle.hpp @@ -8,6 +8,7 @@ #include "basics.hpp" +#include "power_grid_model_c/basics.h" #include "power_grid_model_c/handle.h" #include "power_grid_model_c/logger.h" @@ -29,12 +30,6 @@ class PowerGridError : public std::exception { std::string message_; }; -class PowerGridRegularError : public PowerGridError { - public: - using PowerGridError::PowerGridError; - Idx error_code() const noexcept override { return PGM_regular_error; } -}; - class PowerGridSerializationError : public PowerGridError { public: using PowerGridError::PowerGridError; @@ -57,11 +52,59 @@ class PowerGridBatchError : public PowerGridError { std::vector failed_scenarios_; }; +class PowerGridDatasetError : public PowerGridError { + public: + using PowerGridError::PowerGridError; + Idx error_code() const noexcept override { return PGM_dataset_error; } +}; + +class PowerGridDataError : public PowerGridError { + public: + using PowerGridError::PowerGridError; + Idx error_code() const noexcept override { return PGM_data_error; } +}; + +class PowerGridCalculationError : public PowerGridError { + public: + using PowerGridError::PowerGridError; + Idx error_code() const noexcept override { return PGM_calculation_error; } +}; + +class PowerGridIllegalOperationError : public PowerGridError { + public: + using PowerGridError::PowerGridError; + Idx error_code() const noexcept override { return PGM_illegal_operation; } +}; + +class PowerGridBadRequest : public PowerGridError { + public: + using PowerGridError::PowerGridError; + Idx error_code() const noexcept override { return PGM_bad_request; } +}; + +class PowerGridNotImplementedError : public PowerGridError { + public: + using PowerGridError::PowerGridError; + Idx error_code() const noexcept override { return PGM_not_implemented; } +}; + +class PowerGridInternalError : public PowerGridError { + public: + using PowerGridError::PowerGridError; + Idx error_code() const noexcept override { return PGM_internal_error; } +}; + +class PowerGridUnknownError : public PowerGridError { + public: + using PowerGridError::PowerGridError; + Idx error_code() const noexcept override { return PGM_unknown_error; } +}; + class Handle { public: Handle() { if (get() == nullptr) { - throw PowerGridRegularError{"Failed to create handle. This usually points to a severe system issue, such " + throw PowerGridError{"Failed to create handle. This usually points to a severe system issue, such " "as insufficient or corrupted memory."}; } } @@ -79,7 +122,7 @@ class Handle { return; case PGM_regular_error: clear_error(); - throw PowerGridRegularError{error_message}; + throw PowerGridError{error_message}; case PGM_batch_error: { Idx const n_failed_scenarios = PGM_n_failed_scenarios(handle_ptr); std::vector failed_scenarios(n_failed_scenarios); @@ -96,6 +139,30 @@ class Handle { case PGM_serialization_error: clear_error(); throw PowerGridSerializationError{error_message}; + case PGM_dataset_error: + clear_error(); + throw PowerGridDatasetError{error_message}; + case PGM_data_error: + clear_error(); + throw PowerGridDataError{error_message}; + case PGM_calculation_error: + clear_error(); + throw PowerGridCalculationError{error_message}; + case PGM_illegal_operation: + clear_error(); + throw PowerGridIllegalOperationError{error_message}; + case PGM_bad_request: + clear_error(); + throw PowerGridBadRequest{error_message}; + case PGM_not_implemented: + clear_error(); + throw PowerGridNotImplementedError{error_message}; + case PGM_internal_error: + clear_error(); + throw PowerGridInternalError{error_message}; + case PGM_unknown_error: + clear_error(); + throw PowerGridUnknownError{error_message}; default: clear_error(); throw PowerGridError{error_message}; diff --git a/src/power_grid_model/_core/error_handling.py b/src/power_grid_model/_core/error_handling.py index f298c964e7..aa0b8933bb 100644 --- a/src/power_grid_model/_core/error_handling.py +++ b/src/power_grid_model/_core/error_handling.py @@ -54,6 +54,14 @@ class _PgmCErrorCode(IntEnum): REGULAR_ERROR = 1 BATCH_ERROR = 2 SERIALIZATION_ERROR = 3 + DATASET_ERROR = 4 + DATA_ERROR = 5 + CALCULATION_ERROR = 6 + ILLEGAL_OPERATION = 7 + BAD_REQUEST = 8 + NOT_IMPLEMENTED = 9 + INTERNAL_ERROR = 10 + UNKNOWN_ERROR = 255 _MISSING_CASE_FOR_ENUM_RE = re.compile(r" is not implemented for (.+) #(-?\d+)!\n") @@ -155,10 +163,6 @@ def find_error(batch_size: int = 1, decode_error: bool = True) -> RuntimeError | match error_code: case _PgmCErrorCode.NO_ERROR: return None - case _PgmCErrorCode.REGULAR_ERROR: - error_message = get_pgc().error_message() - error_message += VALIDATOR_MSG - return _interpret_error(error_message, decode_error=decode_error) case _PgmCErrorCode.BATCH_ERROR: error_message = "There are errors in the batch calculation." + VALIDATOR_MSG error = PowerGridBatchError(error_message) @@ -173,6 +177,18 @@ def find_error(batch_size: int = 1, decode_error: bool = True) -> RuntimeError | mask[error.failed_scenarios] = False error.succeeded_scenarios = all_scenarios[mask] return error + case _ if error_code in ( + _PgmCErrorCode.REGULAR_ERROR, + _PgmCErrorCode.DATASET_ERROR, + _PgmCErrorCode.DATA_ERROR, + _PgmCErrorCode.CALCULATION_ERROR, + _PgmCErrorCode.ILLEGAL_OPERATION, + _PgmCErrorCode.BAD_REQUEST, + _PgmCErrorCode.NOT_IMPLEMENTED, + _PgmCErrorCode.INTERNAL_ERROR, + ): + error_message = get_pgc().error_message() + VALIDATOR_MSG + return _interpret_error(error_message, decode_error=decode_error) case _PgmCErrorCode.SERIALIZATION_ERROR: return PowerGridSerializationError(get_pgc().error_message()) case _: diff --git a/tests/native_api_tests/test_api_dataset.cpp b/tests/native_api_tests/test_api_dataset.cpp index 2633d94c52..a804b1dfe7 100644 --- a/tests/native_api_tests/test_api_dataset.cpp +++ b/tests/native_api_tests/test_api_dataset.cpp @@ -177,27 +177,27 @@ TEST_CASE_TEMPLATE("Native readable dataset - indptr sanitization", DatasetType, SUBCASE("add_buffer with too low starting point indptr") { std::vector const indptr{-1, 1, 1, 3}; CHECK_THROWS_AS_MESSAGE(dataset.add_buffer("node", -1, indptr.back(), indptr.data(), nullptr), - PowerGridRegularError, doctest::Contains(indptr_bounds_error_message)); + PowerGridDatasetError, doctest::Contains(indptr_bounds_error_message)); } SUBCASE("add_buffer with too high starting point indptr") { std::vector const indptr{1, 1, 1, 3}; CHECK_THROWS_AS_MESSAGE(dataset.add_buffer("node", -1, indptr.back(), indptr.data(), nullptr), - PowerGridRegularError, doctest::Contains(indptr_bounds_error_message)); + PowerGridDatasetError, doctest::Contains(indptr_bounds_error_message)); } SUBCASE("add_buffer with too few elements") { std::vector const indptr{0, 1, 1, 3}; CHECK_THROWS_AS_MESSAGE(dataset.add_buffer("node", -1, indptr.back() + 1, indptr.data(), nullptr), - PowerGridRegularError, doctest::Contains(indptr_bounds_error_message)); + PowerGridDatasetError, doctest::Contains(indptr_bounds_error_message)); } SUBCASE("add_buffer with too many elements") { std::vector const indptr{0, 1, 1, 3}; CHECK_THROWS_AS_MESSAGE(dataset.add_buffer("node", -1, indptr.back() - 1, indptr.data(), nullptr), - PowerGridRegularError, doctest::Contains(indptr_bounds_error_message)); + PowerGridDatasetError, doctest::Contains(indptr_bounds_error_message)); } SUBCASE("add_buffer with non-monotonic indptr") { std::vector const indptr{0, 2, 1, 3}; CHECK_THROWS_AS_MESSAGE(dataset.add_buffer("node", -1, indptr.back(), indptr.data(), nullptr), - PowerGridRegularError, doctest::Contains(indptr_monotonic_error_message)); + PowerGridDatasetError, doctest::Contains(indptr_monotonic_error_message)); } } diff --git a/tests/native_api_tests/test_api_logger.cpp b/tests/native_api_tests/test_api_logger.cpp index 34e73ea584..6639e4d7fc 100644 --- a/tests/native_api_tests/test_api_logger.cpp +++ b/tests/native_api_tests/test_api_logger.cpp @@ -193,15 +193,15 @@ TEST_CASE("Logger - invalid type returns error") { HandleGuard const g; PGM_Logger const* bad = PGM_create_logger(g.get(), 999); CHECK(bad == nullptr); - CHECK(PGM_error_code(g.get()) == PGM_regular_error); + CHECK(PGM_error_code(g.get()) == PGM_bad_request); } -TEST_CASE("Logger - get_output with null callback returns a regular error") { +TEST_CASE("Logger - get_output with null callback is an illegal operation") { HandleGuard const g; LoggerGuard const lg{g.get(), PGM_logger_type_info}; PGM_logger_get_output(g.get(), lg.get(), nullptr, nullptr); - CHECK(PGM_error_code(g.get()) == PGM_regular_error); + CHECK(PGM_error_code(g.get()) == PGM_illegal_operation); } TEST_CASE("Logger - unregister stops subsequent output") { diff --git a/tests/native_api_tests/test_api_meta_data.cpp b/tests/native_api_tests/test_api_meta_data.cpp index d75ec57ec1..163d90b49c 100644 --- a/tests/native_api_tests/test_api_meta_data.cpp +++ b/tests/native_api_tests/test_api_meta_data.cpp @@ -68,7 +68,7 @@ TEST_CASE("API Meta Data") { using namespace std::string_literals; CHECK_THROWS_WITH_AS(MetaData::get_attribute_by_name("No_dataset", "no_name", "no attribute"), - doctest::Contains("You supplied wrong name and/or index!"), PowerGridRegularError); + doctest::Contains("You supplied wrong name and/or index!"), PowerGridError); } } } diff --git a/tests/native_api_tests/test_api_model.cpp b/tests/native_api_tests/test_api_model.cpp index 14d503a3e2..3e6e63c96a 100644 --- a/tests/native_api_tests/test_api_model.cpp +++ b/tests/native_api_tests/test_api_model.cpp @@ -303,14 +303,14 @@ TEST_CASE("API Model") { std::vector indexer(ids_to_index.size()); CHECK_THROWS_WITH_AS( model_2.get_indexer("node", std::ssize(ids_to_index), ids_to_index.data(), indexer.data()), - doctest::Contains("The id cannot be found: 4"), PowerGridRegularError); + doctest::Contains("The id cannot be found: 4"), PowerGridDataError); } SUBCASE("Bad weather: wrong type") { std::vector const ids_to_index{2, 1, 3, 2}; std::vector indexer(ids_to_index.size()); CHECK_THROWS_WITH_AS( model_2.get_indexer("sym_load", std::ssize(ids_to_index), ids_to_index.data(), indexer.data()), - doctest::Contains("Wrong type for object with id 2"), PowerGridRegularError); + doctest::Contains("Wrong type for object with id 2"), PowerGridDataError); } } @@ -373,7 +373,7 @@ TEST_CASE("API Model") { auto const bad_model_lambda = [&bad_input_dataset]() { Model const wrong_model{50.0, bad_input_dataset}; }; - check_throws_with(bad_model_lambda, PGM_regular_error, "Conflicting id detected:"s); + check_throws_with(bad_model_lambda, PGM_data_error, "Conflicting id detected:"s); } SUBCASE("Update error") { @@ -401,7 +401,7 @@ TEST_CASE("API Model") { model.update(bad_single_owning_update_dataset.dataset); }; - check_throws_with(bad_update_lambda, PGM_regular_error, "The id cannot be found:"s); + check_throws_with(bad_update_lambda, PGM_data_error, "The id cannot be found:"s); } SUBCASE("Update error in calculation") { @@ -448,7 +448,7 @@ TEST_CASE("API Model") { options.set_calculation_type(-128); model.calculate(options, single_output_dataset); }; - check_throws_with(bad_calc_type_lambda, PGM_regular_error, "CalculationType is not implemented for"s); + check_throws_with(bad_calc_type_lambda, PGM_bad_request, "CalculationType is not implemented for"s); } SUBCASE("Invalid tap changing strategy error") { @@ -456,7 +456,7 @@ TEST_CASE("API Model") { options.set_tap_changing_strategy(-128); model.calculate(options, single_output_dataset); }; - check_throws_with(bad_tap_strat_lambda, PGM_regular_error, "get_optimizer_type is not implemented for"s); + check_throws_with(bad_tap_strat_lambda, PGM_bad_request, "get_optimizer_type is not implemented for"s); } SUBCASE("Tap changing strategy") { @@ -475,12 +475,12 @@ TEST_CASE("API Model") { auto const calc_error_lambda = [&model, &single_output_dataset](auto const& opt) { model.calculate(opt, single_output_dataset); }; - check_throws_with(calc_error_lambda, PGM_regular_error, "Iteration failed to converge after"s, options); + check_throws_with(calc_error_lambda, PGM_calculation_error, "Iteration failed to converge after"s, options); // wrong method options.set_calculation_type(PGM_state_estimation); options.set_calculation_method(PGM_iterative_current); - check_throws_with(calc_error_lambda, PGM_regular_error, + check_throws_with(calc_error_lambda, PGM_bad_request, "The calculation method is invalid for this calculation!"s, options); } @@ -890,7 +890,7 @@ TEST_CASE("API Model") { if (std::ranges::find(supported_type_methods, calculation_method) == std::end(supported_type_methods)) { CHECK_THROWS_WITH_AS(model.calculate(options, output_dataset), invalid_calculation_method_pattern, - PowerGridRegularError); + PowerGridBadRequest); } else { try { model.calculate(options, output_dataset); @@ -929,7 +929,7 @@ TEST_CASE("API Model") { auto const construct_model = [&input_dataset_se] { return Model{50.0, input_dataset_se}; }; CHECK_THROWS_WITH_AS(construct_model(), "PowerSensor measurement is not supported for object of type Link", - PowerGridRegularError); + PowerGridDataError); } SUBCASE("AsymPowerSensor") { @@ -958,7 +958,7 @@ TEST_CASE("API Model") { auto const construct_model = [&input_dataset_se] { return Model{50.0, input_dataset_se}; }; CHECK_THROWS_WITH_AS(construct_model(), "PowerSensor measurement is not supported for object of type Link", - PowerGridRegularError); + PowerGridDataError); } } @@ -981,7 +981,7 @@ TEST_CASE("API Model") { auto const& input_dataset_2 = owning_input_dataset_2.dataset; auto construct_model = [&] { Model{50.0, input_dataset_2}; }; - CHECK_THROWS_WITH_AS(construct_model(), "Conflicting id detected: 1\n", PowerGridRegularError); + CHECK_THROWS_WITH_AS(construct_model(), "Conflicting id detected: 1\n", PowerGridDataError); } SUBCASE("Test non-existing id") { @@ -1004,7 +1004,7 @@ TEST_CASE("API Model") { auto const& input_dataset_2 = owning_input_dataset_2.dataset; auto construct_model = [&] { Model{50.0, input_dataset_2}; }; - CHECK_THROWS_WITH_AS(construct_model(), "The id cannot be found: 99\n", PowerGridRegularError); + CHECK_THROWS_WITH_AS(construct_model(), "The id cannot be found: 99\n", PowerGridDataError); } SUBCASE("Test id for wrong type") { @@ -1061,11 +1061,11 @@ TEST_CASE("API Model") { SUBCASE("Correct type") { CHECK_NOTHROW(construct_model()); } SUBCASE("Wrong branch terminal node") { link_from_node[0] = 9; - CHECK_THROWS_WITH_AS(construct_model(), "Wrong type for object with id 9\n", PowerGridRegularError); + CHECK_THROWS_WITH_AS(construct_model(), "Wrong type for object with id 9\n", PowerGridDataError); } SUBCASE("Wrong voltage sensor measured object") { sym_voltage_sensor_measured_object[0] = 5; - CHECK_THROWS_WITH_AS(construct_model(), "Wrong type for object with id 5\n", PowerGridRegularError); + CHECK_THROWS_WITH_AS(construct_model(), "Wrong type for object with id 5\n", PowerGridDataError); } SUBCASE("Wrong power sensor measured object type") { using enum MeasuredTerminalType; @@ -1074,7 +1074,7 @@ TEST_CASE("API Model") { for (auto const& mt_type : mt_types) { CAPTURE(mt_type); sym_power_sensor_measured_terminal_type[0] = mt_type; - CHECK_THROWS_WITH_AS(construct_model(), "Wrong type for object with id 3\n", PowerGridRegularError); + CHECK_THROWS_WITH_AS(construct_model(), "Wrong type for object with id 3\n", PowerGridDataError); } } } diff --git a/tests/native_api_tests/test_api_model_multi_dimension.cpp b/tests/native_api_tests/test_api_model_multi_dimension.cpp index 7d56ba09be..b0e0bde1d3 100644 --- a/tests/native_api_tests/test_api_model_multi_dimension.cpp +++ b/tests/native_api_tests/test_api_model_multi_dimension.cpp @@ -108,10 +108,10 @@ TEST_CASE("API Model Multi-Dimension") { } } SUBCASE("Linked list item referring to itself is not allowed") { - CHECK_THROWS_AS(batch_u_ref.set_next_cartesian_product_dimension(batch_u_ref), PowerGridRegularError); + CHECK_THROWS_AS(batch_u_ref.set_next_cartesian_product_dimension(batch_u_ref), PowerGridDatasetError); } SUBCASE("Cyclic linked list is not allowed") { - CHECK_THROWS_AS(batch_q_specified.set_next_cartesian_product_dimension(batch_u_ref), PowerGridRegularError); + CHECK_THROWS_AS(batch_q_specified.set_next_cartesian_product_dimension(batch_u_ref), PowerGridDatasetError); } } diff --git a/tests/native_api_tests/test_api_model_update.cpp b/tests/native_api_tests/test_api_model_update.cpp index dd10efba45..59de62d2aa 100644 --- a/tests/native_api_tests/test_api_model_update.cpp +++ b/tests/native_api_tests/test_api_model_update.cpp @@ -645,7 +645,7 @@ TEST_CASE("API model - incomplete input") { SUBCASE("Target dataset") { CHECK_THROWS_WITH_AS(test_model.calculate(get_default_options(symmetry, PGM_linear), test_result_data), doctest::Contains("Sparse matrix error, possibly singular matrix!"), - PowerGridRegularError); + PowerGridCalculationError); } SUBCASE("Empty single scenario update dataset") { DatasetConst const empty_update_data{"update", true, 1}; @@ -653,13 +653,13 @@ TEST_CASE("API model - incomplete input") { test_model.update(empty_update_data); CHECK_THROWS_WITH_AS( test_model.calculate(get_default_options(symmetry, PGM_linear), test_result_data), - doctest::Contains("Sparse matrix error, possibly singular matrix!"), PowerGridRegularError); + doctest::Contains("Sparse matrix error, possibly singular matrix!"), PowerGridCalculationError); } SUBCASE("Batch") { CHECK_THROWS_WITH_AS(test_model.calculate(get_default_options(symmetry, PGM_linear), test_result_data, empty_update_data), doctest::Contains("Sparse matrix error, possibly singular matrix!"), - PowerGridRegularError); + PowerGridCalculationError); } } SUBCASE("Incomplete update dataset") { @@ -670,7 +670,7 @@ TEST_CASE("API model - incomplete input") { CHECK_NOTHROW(test_model.update(incomplete_update_data)); CHECK_THROWS_WITH_AS( test_model.calculate(get_default_options(symmetry, PGM_linear), test_result_data), - doctest::Contains("Sparse matrix error, possibly singular matrix!"), PowerGridRegularError); + doctest::Contains("Sparse matrix error, possibly singular matrix!"), PowerGridCalculationError); } SUBCASE("Batch") { CHECK_THROWS_AS(test_model.calculate(get_default_options(symmetry, PGM_linear), test_result_data, diff --git a/tests/native_api_tests/test_api_validation.cpp b/tests/native_api_tests/test_api_validation.cpp index 3b8f76dded..b729d5e5d2 100644 --- a/tests/native_api_tests/test_api_validation.cpp +++ b/tests/native_api_tests/test_api_validation.cpp @@ -60,7 +60,7 @@ TEST_CASE("C++ validation requires experimental features to be enabled") { Options const options{}; CHECK_THROWS_WITH_AS((ValidationReport{make_single_node_input_dataset(1, 110.0), options}), - doctest::Contains("experimental"), PowerGridRegularError); + doctest::Contains("experimental"), PowerGridBadRequest); } TEST_CASE("C++ input validation returns a valid report") { From af331d77e25b70feb821d961738bc61b20d057c2 Mon Sep 17 00:00:00 2001 From: Martijn Govers Date: Fri, 13 Nov 2026 14:03:45 +0100 Subject: [PATCH 2/6] enable subcodes to C API users Signed-off-by: Martijn Govers --- .../include/power_grid_model_c/handle.h | 12 +++++++ .../power_grid_model_c/src/handle.cpp | 31 +++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/power_grid_model_c/power_grid_model_c/include/power_grid_model_c/handle.h b/power_grid_model_c/power_grid_model_c/include/power_grid_model_c/handle.h index 5d76d6eb01..c2a62e9f46 100644 --- a/power_grid_model_c/power_grid_model_c/include/power_grid_model_c/handle.h +++ b/power_grid_model_c/power_grid_model_c/include/power_grid_model_c/handle.h @@ -115,6 +115,18 @@ PGM_API void PGM_clear_error(PGM_Handle* handle) PGM_NOEXCEPT; */ PGM_API char const* PGM_version(void) PGM_NOEXCEPT; +/** + * @brief Determine whether a PGM_ErrorCode error code represents a subcode of a user-specified error code. + * + * See also #PGM_ErrorCode. + * + * @param handle The pointer to the handle. + * @param error_code The #PGM_ErrorCode error code to be checked. + * @param base_error_code The #PGM_ErrorCode base error code of which the error_code may be a subcode. + * @return 1 if the error_code is a subcode of base_error_code, 0 if it is not. + */ +PGM_API PGM_Idx PGM_error_code_is_subcode_of(PGM_Idx error_code, PGM_Idx base_error_code) PGM_NOEXCEPT; + #ifdef __cplusplus } #endif diff --git a/power_grid_model_c/power_grid_model_c/src/handle.cpp b/power_grid_model_c/power_grid_model_c/src/handle.cpp index f02c427114..aa59e08ae1 100644 --- a/power_grid_model_c/power_grid_model_c/src/handle.cpp +++ b/power_grid_model_c/power_grid_model_c/src/handle.cpp @@ -66,3 +66,34 @@ char const** PGM_batch_errors(PGM_Handle const* handle) noexcept { } void PGM_clear_error(PGM_Handle* handle) noexcept { clear_error(handle); } char const* PGM_version(void) noexcept { return version; } +namespace { +using underlying_error_code_t = std::underlying_type_t; + +bool is_sub_error_code_of(underlying_error_code_t derived, underlying_error_code_t base) noexcept { + using limits = std::numeric_limits; + constexpr auto width = + compile_time_safe_cast(power_grid_model::power_grid_error_code_level_width); + constexpr auto max_width = + compile_time_safe_cast(power_grid_model::power_grid_error_code_max_width); + + static_assert(std::is_unsigned_v); + static_assert(limits::digits == max_width); + static_assert(width > 0 && max_width % width == 0); // guarantees the shift below stays within [0, digits) + + // the root code (0) only has itself as sub code + if (base == 0u) { + return derived == 0u; + } + // keep as many low levels as base occupies; base != 0 implies n_levels in [1, max_width / width] + auto const n_levels = static_cast((std::bit_width(base) + width - 1u) / width); + auto const mask = static_cast(limits::max() >> (limits::digits - n_levels * width)); + return (derived & mask) == base; +} +} // namespace + +PGM_Idx PGM_error_code_is_subcode_of(PGM_Idx error_code, PGM_Idx base_error_code) noexcept { + auto const safe_error_code = optional_safe_cast(error_code); + auto const safe_base_error_code = optional_safe_cast(base_error_code); + return to_c_bool(safe_error_code.has_value() && safe_base_error_code.has_value() && + is_sub_error_code_of(*safe_error_code, *safe_base_error_code)); +} From 3de43310154c6dc1f740cfad49a2d5387684fe70 Mon Sep 17 00:00:00 2001 From: Martijn Govers Date: Fri, 13 Nov 2026 14:12:19 +0100 Subject: [PATCH 3/6] fix Signed-off-by: Martijn Govers --- power_grid_model_c/power_grid_model_c/src/handle.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/power_grid_model_c/power_grid_model_c/src/handle.cpp b/power_grid_model_c/power_grid_model_c/src/handle.cpp index aa59e08ae1..f8bbbb7484 100644 --- a/power_grid_model_c/power_grid_model_c/src/handle.cpp +++ b/power_grid_model_c/power_grid_model_c/src/handle.cpp @@ -21,6 +21,8 @@ using power_grid_model_c::clear_error; using power_grid_model_c::compile_time_safe_cast; using power_grid_model_c::create; using power_grid_model_c::destroy; +using power_grid_model_c::optional_safe_cast; +using power_grid_model_c::to_c_bool; constexpr char const* version = PGM_VERSION; } // namespace From 4caf0669a9b8e6f9a1bb18f21311afbc03bea460 Mon Sep 17 00:00:00 2001 From: Martijn Govers Date: Fri, 13 Nov 2026 15:30:28 +0100 Subject: [PATCH 4/6] fix bit-width macos Signed-off-by: Martijn Govers --- power_grid_model_c/power_grid_model_c/src/handle.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/power_grid_model_c/power_grid_model_c/src/handle.cpp b/power_grid_model_c/power_grid_model_c/src/handle.cpp index f8bbbb7484..de05718d4c 100644 --- a/power_grid_model_c/power_grid_model_c/src/handle.cpp +++ b/power_grid_model_c/power_grid_model_c/src/handle.cpp @@ -12,6 +12,7 @@ #include "safe_memory_handling.hpp" #include +#include #include namespace { From 2b5db6e4cb4bfb01612fa34507730e20be7e94a6 Mon Sep 17 00:00:00 2001 From: Martijn Govers Date: Mon, 16 Nov 2026 13:51:52 +0100 Subject: [PATCH 5/6] format Signed-off-by: Martijn Govers --- .../include/power_grid_model_cpp/handle.hpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/power_grid_model_c/power_grid_model_cpp/include/power_grid_model_cpp/handle.hpp b/power_grid_model_c/power_grid_model_cpp/include/power_grid_model_cpp/handle.hpp index 4e1024ef5d..c644ad37ac 100644 --- a/power_grid_model_c/power_grid_model_cpp/include/power_grid_model_cpp/handle.hpp +++ b/power_grid_model_c/power_grid_model_cpp/include/power_grid_model_cpp/handle.hpp @@ -105,7 +105,7 @@ class Handle { Handle() { if (get() == nullptr) { throw PowerGridError{"Failed to create handle. This usually points to a severe system issue, such " - "as insufficient or corrupted memory."}; + "as insufficient or corrupted memory."}; } } From cd4f14e82707a5f91d64b5e0a66de589f15bdd99 Mon Sep 17 00:00:00 2001 From: Martijn Govers Date: Tue, 17 Nov 2026 08:35:37 +0100 Subject: [PATCH 6/6] fix clang-tidy Signed-off-by: Martijn Govers --- power_grid_model_c/power_grid_model_c/src/handle.cpp | 7 ++++++- tests/native_api_tests/test_api_validation.cpp | 1 + 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/power_grid_model_c/power_grid_model_c/src/handle.cpp b/power_grid_model_c/power_grid_model_c/src/handle.cpp index de05718d4c..977f6c2e9c 100644 --- a/power_grid_model_c/power_grid_model_c/src/handle.cpp +++ b/power_grid_model_c/power_grid_model_c/src/handle.cpp @@ -11,9 +11,13 @@ #include "input_sanitization.hpp" #include "safe_memory_handling.hpp" +#include + #include #include #include +#include +#include namespace { using namespace power_grid_model; @@ -89,7 +93,8 @@ bool is_sub_error_code_of(underlying_error_code_t derived, underlying_error_code } // keep as many low levels as base occupies; base != 0 implies n_levels in [1, max_width / width] auto const n_levels = static_cast((std::bit_width(base) + width - 1u) / width); - auto const mask = static_cast(limits::max() >> (limits::digits - n_levels * width)); + auto const shift = static_cast(max_width - n_levels * width) % max_width; + auto const mask = static_cast(limits::max() >> shift); return (derived & mask) == base; } } // namespace diff --git a/tests/native_api_tests/test_api_validation.cpp b/tests/native_api_tests/test_api_validation.cpp index b729d5e5d2..b84a4095b2 100644 --- a/tests/native_api_tests/test_api_validation.cpp +++ b/tests/native_api_tests/test_api_validation.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include