From f9be7b6d22ccfe69ec34252a3ebb93f30d578da7 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Fri, 13 Nov 2026 16:43:04 -0600 Subject: [PATCH 01/28] feat(model)!: validate identifiers and drop empty-name defaults - Make `identifier` reject names that are not an ASCII letter followed by letters, digits, or underscores. This also covers the `_idq` literal and the empty string. - Delete the default constructor of `identifier`. Empty-capable plugin names use `identifier_or_empty`, and an absent product creator is an `std::optional`. - Reject empty algorithm names and empty layer names. Provider layers that are not resolved are routed through a dedicated index-set node. - Make `layer_path` build its list by walking the parent chain. - In the Python plugin, check identifiers and suffixes when modules and providers are registered. Report errors as `ValueError` or `RuntimeError` instead of letting C++ exceptions escape. - Update tests for the stricter rules, with new identifier validation and move-semantics coverage. Rename names that contain hyphens or digits in test fixtures. --- form/form_module.cpp | 2 +- form/form_source.cpp | 2 +- phlex/configuration.cpp | 11 +- phlex/core/consumer.cpp | 3 - phlex/core/detail/make_algorithm_name.cpp | 3 +- phlex/core/index_router.cpp | 11 +- phlex/core/index_router.hpp | 5 +- phlex/core/producer_catalog.cpp | 6 +- phlex/core/producer_catalog.hpp | 2 +- phlex/core/product_selector.cpp | 7 +- phlex/core/product_selector.hpp | 7 +- phlex/core/provider_node.cpp | 14 ++- phlex/core/registration_api.hpp | 2 +- phlex/model/algorithm_name.cpp | 16 +-- phlex/model/algorithm_name.hpp | 8 +- phlex/model/data_cell_index.cpp | 14 +-- phlex/model/data_cell_index.hpp | 1 + phlex/model/handle.hpp | 8 +- phlex/model/identifier.cpp | 17 ++- phlex/model/identifier.hpp | 41 ++++-- phlex/model/product_specification.cpp | 21 +++- phlex/model/product_specification.hpp | 22 ++-- phlex/model/product_store.cpp | 2 +- plugins/python/src/modulewrap.cpp | 118 +++++++++++++----- test/config_test.cpp | 6 +- test/core_misc_test.cpp | 5 - test/data_cell_index_test.cpp | 3 +- test/data_layer_hierarchy_test.cpp | 6 +- test/identifier_test.cpp | 75 +++++++++-- test/max-parallelism/CMakeLists.txt | 2 +- .../check_stage_cli_over_config.jsonnet | 4 +- .../check_stage_config.jsonnet | 4 +- test/multilayer_join_test.cpp | 2 +- test/product_selector_test.cpp | 26 ++-- test/transform_node_test.cpp | 4 +- 35 files changed, 323 insertions(+), 157 deletions(-) diff --git a/form/form_module.cpp b/form/form_module.cpp index 1143e4cd8..336bad747 100644 --- a/form/form_module.cpp +++ b/form/form_module.cpp @@ -175,7 +175,7 @@ namespace { std::cout << " Product: " << product_spec.to_string() << "\n"; // Create FORM product with metadata - products.emplace_back(product_spec.suffix().trans_get_string(), // label, from map key + products.emplace_back(std::string{product_spec.suffix().text()}, // label, from map key product_ptr->address(), // data, from phlex product_base &product_ptr->type() // type, from phlex product_base ); diff --git a/form/form_source.cpp b/form/form_source.cpp index 9243cae2d..922a5db30 100644 --- a/form/form_source.cpp +++ b/form/form_source.cpp @@ -103,7 +103,7 @@ namespace { for (auto const& name : products_) { product_specification spec{ - algorithm_name::create(advertised_creator_), identifier{name}, selector.type}; + algorithm_name::create(advertised_creator_), suffix_t{name}, selector.type}; // Read and provide products at the configured stage. identifier const selector_layer = selector.layer; diff --git a/phlex/configuration.cpp b/phlex/configuration.cpp index be391140d..fcaaa23ae 100644 --- a/phlex/configuration.cpp +++ b/phlex/configuration.cpp @@ -69,10 +69,15 @@ namespace phlex { } auto creator = value_if_exists(query_object, "creator"); auto layer = value_if_exists(query_object, "layer"); - auto suffix = value_if_exists(query_object, "suffix"); + std::optional suffix; + if (query_object.contains("suffix")) { + suffix.emplace(std::string_view{query_object.at("suffix").as_string()}); + } auto stage = value_if_exists(query_object, "stage"); - return product_selector{ - .creator = std::move(creator), .layer = std::move(layer), .suffix = suffix, .stage = stage}; + return product_selector{.creator = std::move(creator), + .layer = std::move(layer), + .suffix = std::move(suffix), + .stage = stage}; } experimental::identifier experimental::tag_invoke(boost::json::value_to_tag const&, diff --git a/phlex/core/consumer.cpp b/phlex/core/consumer.cpp index 0e80d64c1..c8e21a157 100644 --- a/phlex/core/consumer.cpp +++ b/phlex/core/consumer.cpp @@ -19,14 +19,11 @@ namespace { std::vector layers_from(phlex::product_selectors const& queries) { - using namespace phlex::experimental::literals; std::vector result; result.reserve(queries.size()); for (auto const& query : queries) { if (query.layer) { result.push_back(query.layer); - } else { - result.push_back("*"_id); } } return result; diff --git a/phlex/core/detail/make_algorithm_name.cpp b/phlex/core/detail/make_algorithm_name.cpp index e4e49d3d4..7f6f85d3f 100644 --- a/phlex/core/detail/make_algorithm_name.cpp +++ b/phlex/core/detail/make_algorithm_name.cpp @@ -9,7 +9,8 @@ namespace phlex::experimental::internal { algorithm_name make_algorithm_name(configuration const* config, std::string_view name) { - return {config ? identifier(config->get("module_label")) : ""_id, + return {config ? identifier_or_empty(identifier(config->get("module_label"))) + : identifier_or_empty{}, identifier(name)}; } } diff --git a/phlex/core/index_router.cpp b/phlex/core/index_router.cpp index 623b29801..bbbd33c9d 100644 --- a/phlex/core/index_router.cpp +++ b/phlex/core/index_router.cpp @@ -262,7 +262,14 @@ namespace phlex::detail { provider_input_ports_t provider_input_ports) { for (auto& [input_product, provider_port] : provider_input_ports | std::views::values) { - auto [it, _] = index_set_nodes_.emplace(input_product.layer ? *input_product.layer : "*"_id, + if (!input_product.layer) { + if (!unresolved_index_set_node_) { + unresolved_index_set_node_ = std::make_shared(g); + } + make_edge(*unresolved_index_set_node_, *provider_port); + continue; + } + auto [it, _] = index_set_nodes_.emplace(*input_product.layer, std::make_shared(g)); make_edge(*it->second, *provider_port); } @@ -302,7 +309,7 @@ namespace phlex::detail { node_slots.flush_specs.push_back( {.counting_layer = effective_counting_layer, .flush_port = flush_port}); } - multilayer_join_slots_.emplace(identifier{node_name}, std::move(node_slots)); + multilayer_join_slots_.emplace(node_name, std::move(node_slots)); } } diff --git a/phlex/core/index_router.hpp b/phlex/core/index_router.hpp index 0cb2d6ede..6afe6ebe4 100644 --- a/phlex/core/index_router.hpp +++ b/phlex/core/index_router.hpp @@ -179,6 +179,8 @@ namespace phlex::detail { // The first map is from layer name to the corresponding index-set node. tbb::concurrent_unordered_map index_set_nodes_; + // Unresolved provider layers do not match a concrete layer path. + internal::index_set_node_ptr unresolved_index_set_node_; // The second map is a cache from a layer hash to an index-set node, to avoid // repeated lookups for the same layer. tbb::concurrent_unordered_map index_set_node_cache_; @@ -186,8 +188,7 @@ namespace phlex::detail { // ========================================================================================== // Routing to multi-layer join nodes // Maps from join-node name to the multilayer slots for that node. - tbb::concurrent_unordered_map - multilayer_join_slots_; + tbb::concurrent_unordered_map multilayer_join_slots_; // This struct lets multilayer_slots_for return message slots and end-token entries together, // instead of passing concurrent_hash_map accessors as output parameters. End-token entries diff --git a/phlex/core/producer_catalog.cpp b/phlex/core/producer_catalog.cpp index 85fdfcb5a..a758cddbe 100644 --- a/phlex/core/producer_catalog.cpp +++ b/phlex/core/producer_catalog.cpp @@ -84,7 +84,7 @@ namespace { void check_postconditions(product_selector const& query, std::vector const& candidates, - std::set const& suffixes, + std::set const& suffixes, std::set const& creators, std::set const& types) { @@ -167,12 +167,12 @@ namespace phlex::detail { if (b == e) { spdlog::debug( "Failed to find an algorithm that creates {} products. Assuming it comes from a provider", - query.suffix.value_or("*"_id)); + query.suffix ? query.suffix->text() : "*"); return {}; } std::vector candidates; - std::set suffixes; + std::set suffixes; if (query.suffix.has_value()) { suffixes.insert(*query.suffix); } diff --git a/phlex/core/producer_catalog.hpp b/phlex/core/producer_catalog.hpp index e34036326..867c651ec 100644 --- a/phlex/core/producer_catalog.hpp +++ b/phlex/core/producer_catalog.hpp @@ -17,7 +17,7 @@ namespace phlex::detail { class producer; - using product_suffix_t = phlex::experimental::identifier; + using product_suffix_t = phlex::experimental::suffix_t; class PHLEX_CORE_EXPORT producer_catalog { public: diff --git a/phlex/core/product_selector.cpp b/phlex/core/product_selector.cpp index 87515d8d7..e38a98dae 100644 --- a/phlex/core/product_selector.cpp +++ b/phlex/core/product_selector.cpp @@ -38,7 +38,7 @@ namespace phlex { // Check if a product_specification satisfies this query bool product_selector::match(experimental::product_specification const& spec) const { - if (!creator_match(spec.creator())) { + if (creator && (!spec.creator() || !creator_match(*spec.creator()))) { return false; } if (type.valid() && type != spec.type()) { @@ -76,15 +76,14 @@ namespace phlex { return true; // empty creator matches everything } experimental::identifier const& creator{*(this->creator)}; - return alg.plugin() == creator || alg.algorithm() == creator; + return (alg.plugin().named() && *alg.plugin().named() == creator) || alg.algorithm() == creator; } std::string product_selector::to_string() const { // Will generate <:: by (of ) in > using experimental::identifier; - std::string_view suffix_str = - suffix.transform(&identifier::operator std::string_view).value_or("[ANY]"); + std::string_view suffix_str = suffix ? suffix->text() : "[ANY]"; std::string type_str = this->type.valid() ? fmt::format("<{}>", this->type) : "[UNSET TYPE]"; // will later be concept auto layer_str = std::string_view(layer); diff --git a/phlex/core/product_selector.hpp b/phlex/core/product_selector.hpp index 00a6e8cab..b468ee28c 100644 --- a/phlex/core/product_selector.hpp +++ b/phlex/core/product_selector.hpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -42,9 +43,9 @@ namespace phlex { operator bool() const noexcept { return content_.has_value(); } experimental::identifier const& operator*() const noexcept { return content_.operator*(); } - friend experimental::identifier format_as(creator_name const& me) noexcept + friend std::string_view format_as(creator_name const& me) noexcept { - return me.content_.value_or("[ANY]"); + return me.content_ ? std::string_view(*me.content_) : "[ANY]"; } auto operator<=>(creator_name const&) const noexcept = default; @@ -109,7 +110,7 @@ namespace phlex { /// folds and unfolds; products from other layers are not delivered. detail::layer_name layer; /// Product suffix, as given to @c output_product_suffixes(...). - std::optional suffix; + std::optional suffix; /// Stage that created the product; @c "CURRENT" means the job's own stage. std::optional stage; /// Product type; set by the framework from the algorithm's parameter type. diff --git a/phlex/core/provider_node.cpp b/phlex/core/provider_node.cpp index 77e11797f..65133739b 100644 --- a/phlex/core/provider_node.cpp +++ b/phlex/core/provider_node.cpp @@ -11,11 +11,23 @@ #include #include #include +#include #include +namespace { + phlex::experimental::algorithm_name provider_creator( + phlex::experimental::product_specification const& spec) + { + if (!spec.creator()) { + throw std::runtime_error("Cannot create a provider without a product creator."); + } + return *spec.creator(); + } +} + namespace phlex::detail { provider_node::provider_node(tbb::flow::graph& g, provider_bundle bundle) : - provider_node{bundle.spec.creator(), + provider_node{provider_creator(bundle.spec), bundle.max_concurrency.value, g, std::move(bundle.provider_function), diff --git a/phlex/core/registration_api.hpp b/phlex/core/registration_api.hpp index c89e4865a..20a9bd46b 100644 --- a/phlex/core/registration_api.hpp +++ b/phlex/core/registration_api.hpp @@ -202,7 +202,7 @@ namespace phlex::detail { } auto output_product(phlex::experimental::algorithm_name creator, - phlex::experimental::identifier suffix, + phlex::experimental::suffix_t suffix, phlex::experimental::identifier output_layer, phlex::experimental::identifier stage = "CURRENT"_id) { diff --git a/phlex/model/algorithm_name.cpp b/phlex/model/algorithm_name.cpp index 6571e7eb2..bada95d3b 100644 --- a/phlex/model/algorithm_name.cpp +++ b/phlex/model/algorithm_name.cpp @@ -5,7 +5,6 @@ #include #include -#include #include #include #include @@ -36,15 +35,13 @@ namespace { } namespace phlex::experimental { - algorithm_name::algorithm_name() = default; - algorithm_name::algorithm_name(char const* spec) : algorithm_name{std::string_view{spec}} {} algorithm_name::algorithm_name(std::string const& spec) : algorithm_name{std::string_view{spec}} { } - algorithm_name::algorithm_name(std::string_view spec) { *this = create(spec); } + algorithm_name::algorithm_name(std::string_view spec) : algorithm_name{create(spec)} {} - algorithm_name::algorithm_name(identifier plugin, identifier algorithm) : + algorithm_name::algorithm_name(identifier_or_empty plugin, identifier algorithm) : plugin_{std::move(plugin)}, algorithm_{std::move(algorithm)} { } @@ -63,9 +60,8 @@ namespace phlex::experimental { algorithm_name algorithm_name::create(char const* spec) { return create(std::string_view{spec}); } algorithm_name algorithm_name::create(std::string_view spec) { - // Empty spec means nothing is specified if (spec.empty()) { - return {}; + throw std::runtime_error("Cannot create an empty algorithm name."); } // Do we have a colon? If so, have both plugin and algorithm @@ -77,11 +73,11 @@ namespace phlex::experimental { std::string_view const plugin = spec.substr(0, colon_pos); std::string_view const algorithm = spec.substr(colon_pos + 1); // +1 OK, : not at end - if (!words_only(plugin) or !words_only(algorithm)) { + if (plugin.empty() || !words_only(plugin) || !words_only(algorithm)) { throw std::runtime_error( fmt::format("The specification '{}' is not a valid algorithm name.", spec)); } - return {identifier(plugin), identifier(algorithm)}; + return {identifier_or_empty(plugin), identifier(algorithm)}; } // No colon -- could be plugin or algorithm @@ -89,6 +85,6 @@ namespace phlex::experimental { throw std::runtime_error( fmt::format("The specification '{}' is not a valid algorithm name.", spec)); } - return {"", identifier(spec)}; + return {empty_string{}, identifier(spec)}; } } diff --git a/phlex/model/algorithm_name.hpp b/phlex/model/algorithm_name.hpp index 43772960f..ce82065ec 100644 --- a/phlex/model/algorithm_name.hpp +++ b/phlex/model/algorithm_name.hpp @@ -9,17 +9,15 @@ namespace phlex::experimental { class PHLEX_MODEL_EXPORT algorithm_name { public: - algorithm_name(); - // NOLINTBEGIN(google-explicit-constructor) - Implicit conversion is intentional algorithm_name(char const* spec); algorithm_name(std::string const& spec); algorithm_name(std::string_view spec); // NOLINTEND(google-explicit-constructor) - algorithm_name(identifier plugin, identifier algorithm); + algorithm_name(identifier_or_empty plugin, identifier algorithm); std::string to_string() const; - identifier const& plugin() const noexcept { return plugin_; } + identifier_or_empty const& plugin() const noexcept { return plugin_; } identifier const& algorithm() const noexcept { return algorithm_; } bool match(algorithm_name const& other) const; @@ -29,7 +27,7 @@ namespace phlex::experimental { static algorithm_name create(std::string_view spec); private: - identifier plugin_; + identifier_or_empty plugin_; identifier algorithm_; }; diff --git a/phlex/model/data_cell_index.cpp b/phlex/model/data_cell_index.cpp index 3dcc83332..5b4254e12 100644 --- a/phlex/model/data_cell_index.cpp +++ b/phlex/model/data_cell_index.cpp @@ -49,7 +49,6 @@ namespace phlex { depth_{parent_->depth_ + 1}, hash_{phlex::detail::hash(parent_->hash_, number_, layer_hash_)} { - // TODO: Should it be an error to create an ID with an empty name? } data_cell_index_ptr data_cell_index::job() @@ -65,14 +64,14 @@ namespace phlex { experimental::layer_path data_cell_index::layer_path() const { - // We know how deep we are so we can pre-allocate and fill in reverse - std::vector layers(depth_ + 1); + std::vector layers; + layers.reserve(depth_ + 1); auto const* ptr = this; - for (auto& layer : std::views::reverse(layers)) { - assert(ptr); - layer = ptr->layer_name(); + while (ptr) { + layers.push_back(ptr->layer_name()); ptr = ptr->parent_.get(); } + std::ranges::reverse(layers); return experimental::layer_path{std::move(layers)}; } @@ -144,9 +143,6 @@ namespace phlex { std::string data_cell_index::to_string_this_layer() const { - if (layer_name_.empty()) { - return std::to_string(number_); - } return fmt::format("{}:{}", layer_name_, number_); } diff --git a/phlex/model/data_cell_index.hpp b/phlex/model/data_cell_index.hpp index 12257bbb7..e93848777 100644 --- a/phlex/model/data_cell_index.hpp +++ b/phlex/model/data_cell_index.hpp @@ -21,6 +21,7 @@ namespace phlex { static data_cell_index_ptr job(); using hash_type = std::size_t; + /// The child layer must have a valid, non-empty identifier as its name. data_cell_index_ptr make_child(std::string layer_name, std::size_t data_cell_number) const; experimental::identifier const& layer_name() const noexcept; experimental::layer_path layer_path() const; diff --git a/phlex/model/handle.hpp b/phlex/model/handle.hpp index 3c126402c..0f5e4fd34 100644 --- a/phlex/model/handle.hpp +++ b/phlex/model/handle.hpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -90,9 +91,12 @@ namespace phlex { // Product specification information algorithm_name_view creator() const noexcept { - return {std::string_view(spec_->plugin()), std::string_view(spec_->algorithm())}; + if (auto const& creator = spec_->creator()) { + return {creator->plugin().text(), std::string_view(creator->algorithm())}; + } + return {}; } - std::string_view suffix() const noexcept { return std::string_view(spec_->suffix()); } + std::string_view suffix() const noexcept { return spec_->suffix().text(); } std::string_view layer() const noexcept { return std::string_view(index_->layer_name()); } std::string_view stage() const noexcept { return std::string_view(*stage_); } std::string layer_path() const { return index_->layer_path().to_string(); } diff --git a/phlex/model/identifier.cpp b/phlex/model/identifier.cpp index 716304b94..a90276368 100644 --- a/phlex/model/identifier.cpp +++ b/phlex/model/identifier.cpp @@ -2,13 +2,28 @@ #include #include +#include #include #include namespace phlex::experimental { - identifier::identifier(std::string_view str) : content_(str), hash_(hash_string(content_)) {} + namespace { + void validate_identifier(std::string_view str) + { + if (!phlex::detail::valid_identifier(str)) { + throw std::invalid_argument{"Invalid identifier: expected an ASCII letter followed by " + "ASCII letters, digits, or underscores"}; + } + } + } + + identifier::identifier(std::string_view str) : content_(str), hash_(hash_string(content_)) + { + validate_identifier(content_); + } identifier::identifier(std::string&& str) : content_(std::move(str)), hash_(hash_string(content_)) { + validate_identifier(content_); } identifier::operator std::string_view() const noexcept { return std::string_view(content_); } diff --git a/phlex/model/identifier.hpp b/phlex/model/identifier.hpp index 15314858f..35b4c56b0 100644 --- a/phlex/model/identifier.hpp +++ b/phlex/model/identifier.hpp @@ -16,6 +16,24 @@ #include #include +namespace phlex::detail { + // This implementation does not use std::regex for the validation because + // std::regex does not support compile-time regular expressions. + constexpr bool valid_identifier(std::string_view text) noexcept + { + auto const letter = [](char c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); }; + if (text.empty() || !letter(text.front())) { + return false; + } + for (char const c : text) { + if (!letter(c) && !(c >= '0' && c <= '9') && c != '_') { + return false; + } + } + return true; + } +} + namespace phlex::experimental { /// If you're comparing to an identifier you know at compile time, you're probably not going to need /// to print it. @@ -26,8 +44,8 @@ namespace phlex::experimental { bool operator()(identifier const& id) const noexcept; }; - /// Carries around the string itself (as a shared_ptr to string to make copies lighter) - /// along with a precomputed hash used for all comparisons + /// A non-empty ASCII name beginning with a letter and containing only letters, digits, + /// and underscores, together with a precomputed hash. class PHLEX_MODEL_EXPORT identifier { public: static constexpr std::uint64_t hash_string(std::string_view str) @@ -38,11 +56,9 @@ namespace phlex::experimental { hash_append(h, {}, str); return h.result(); } - // The default constructor is necessary so other classes containing identifiers - // can have default constructors. - identifier() = default; + identifier() = delete; identifier(identifier const& other) = default; - identifier(identifier&& other) noexcept = default; + identifier(identifier&& other) : identifier(static_cast(other)) {} explicit identifier(std::string_view str); @@ -55,7 +71,7 @@ namespace phlex::experimental { identifier(char const* lit) : identifier(std::string_view(lit)) {} identifier& operator=(identifier const& rhs) = default; - identifier& operator=(identifier&& rhs) noexcept = default; + identifier& operator=(identifier&& rhs) { return *this = static_cast(rhs); } ~identifier() = default; @@ -81,7 +97,7 @@ namespace phlex::experimental { private: std::string content_; - std::uint64_t hash_{hash_string("")}; + std::uint64_t hash_; }; // Identifier UDL @@ -89,6 +105,9 @@ namespace phlex::experimental { PHLEX_MODEL_EXPORT identifier operator""_id(char const* lit, std::size_t len); consteval PHLEX_MODEL_EXPORT identifier_query operator""_idq(char const* lit, std::size_t len) { + if (!phlex::detail::valid_identifier(std::string_view(lit, len))) { + throw "Invalid identifier query"; + } return {identifier::hash_string(std::string_view(lit, len))}; } @@ -114,7 +133,7 @@ namespace phlex::experimental { /// /// Value semantics: /// - Equality holds only between two empty values or two named values with equal text. - /// An empty value never equals a named value, even one whose text is empty. + /// An empty value never equals a named value. /// - Ordering places every empty value before every named value; named values are ordered by /// `identifier`'s ordering. /// - Hashing gives all empty values the same hash, and named values the hash of their @@ -124,7 +143,7 @@ namespace phlex::experimental { /// /// The lasting textual construction policy mirrors `identifier`: C strings convert implicitly, /// while `std::string` and `std::string_view` require explicit construction. Empty text produces - /// `empty_string`; non-empty text is passed to `identifier`, including its validation when enabled. + /// `empty_string`; non-empty text is validated as an `identifier`. /// C strings must be non-null and null-terminated; only text before the first NUL is consumed. /// Length-bearing inputs retain their full length and are never routed through a C-string boundary. class PHLEX_MODEL_EXPORT identifier_or_empty { @@ -138,7 +157,7 @@ namespace phlex::experimental { identifier_or_empty(identifier const& id) : value_{id} {} // NOLINTNEXTLINE(google-explicit-constructor) - Implicit conversion is intentional - identifier_or_empty(identifier&& id) noexcept : value_{std::move(id)} {} + identifier_or_empty(identifier&& id) : value_{std::move(id)} {} explicit identifier_or_empty(std::string_view str) { diff --git a/phlex/model/product_specification.cpp b/phlex/model/product_specification.cpp index cd7f63e4a..f1f959825 100644 --- a/phlex/model/product_specification.cpp +++ b/phlex/model/product_specification.cpp @@ -7,6 +7,7 @@ #include #include +#include #include #include #include @@ -26,18 +27,23 @@ namespace phlex::experimental { product_specification::product_specification(std::string_view name) { *this = create(name); } product_specification::product_specification(experimental::algorithm_name creator, - experimental::identifier suffix, + experimental::suffix_t suffix, type_id type) : creator_{std::move(creator)}, suffix_{std::move(suffix)}, type_id_{std::move(type)} { } + product_specification::product_specification(std::nullopt_t, suffix_t suffix, type_id type) : + suffix_{std::move(suffix)}, type_id_{std::move(type)} + { + } + std::string product_specification::to_string() const { - if (creator_.plugin().empty() && creator_.algorithm().empty()) { + if (!creator_) { return fmt::format("{}", suffix_); } - return fmt::format("{}/{}", creator_.to_string(), suffix_); + return fmt::format("{}/{}", creator_->to_string(), suffix_); } product_specification product_specification::create(char const* c) @@ -49,11 +55,14 @@ namespace phlex::experimental { { auto forward_slash = s.find('/'); if (forward_slash != std::string_view::npos) { + if (forward_slash == 0) { + return {std::nullopt, suffix_t(s.substr(1)), type_id{}}; + } return {experimental::algorithm_name::create(s.substr(0, forward_slash)), - experimental::identifier(s.substr(forward_slash + 1)), + experimental::suffix_t(s.substr(forward_slash + 1)), type_id{}}; } - return {experimental::algorithm_name::create(""), experimental::identifier(s), type_id{}}; + return {std::nullopt, experimental::suffix_t(s), type_id{}}; } } @@ -81,7 +90,7 @@ namespace phlex::detail { return std::views::zip(output_suffixes, output_types) | std::views::transform([&algo_name](auto const& p) { return experimental::product_specification{ - algo_name, experimental::identifier(std::get<0>(p)), std::get<1>(p)}; + algo_name, experimental::suffix_t(std::get<0>(p)), std::get<1>(p)}; }) | std::ranges::to(); } diff --git a/phlex/model/product_specification.hpp b/phlex/model/product_specification.hpp index f9f8d2f3a..75bcbe11f 100644 --- a/phlex/model/product_specification.hpp +++ b/phlex/model/product_specification.hpp @@ -8,6 +8,7 @@ #include +#include #include #include #include @@ -25,13 +26,12 @@ namespace phlex::experimental { product_specification(std::string const& name); product_specification(std::string_view name); // NOLINTEND(google-explicit-constructor) - product_specification(algorithm_name creator, identifier suffix, type_id type); + product_specification(algorithm_name creator, suffix_t suffix, type_id type); + product_specification(std::nullopt_t, suffix_t suffix, type_id type); std::string to_string() const; - algorithm_name const& creator() const noexcept { return creator_; } - identifier const& plugin() const noexcept { return creator_.plugin(); } - identifier const& algorithm() const noexcept { return creator_.algorithm(); } - identifier const& suffix() const noexcept { return suffix_; } + std::optional const& creator() const noexcept { return creator_; } + suffix_t const& suffix() const noexcept { return suffix_; } type_id type() const noexcept { return type_id_; } void set_type(type_id&& type) { type_id_ = std::move(type); } @@ -44,8 +44,8 @@ namespace phlex::experimental { friend struct std::hash; private: - experimental::algorithm_name creator_; - experimental::identifier suffix_; // Default suffix is empty string + std::optional creator_; + experimental::suffix_t suffix_; type_id type_id_{}; }; @@ -64,8 +64,12 @@ template <> struct std::hash { std::size_t operator()(phlex::experimental::product_specification const& spec) const noexcept { - std::size_t hash = spec.creator_.plugin().hash(); - boost::hash_combine(hash, spec.creator_.algorithm().hash()); + std::size_t hash = 0; + boost::hash_combine(hash, spec.creator_.has_value()); + if (spec.creator_) { + boost::hash_combine(hash, spec.creator_->plugin().hash()); + boost::hash_combine(hash, spec.creator_->algorithm().hash()); + } boost::hash_combine(hash, spec.suffix_.hash()); boost::hash_combine(hash, phlex::experimental::hash_value(spec.type_id_)); return hash; diff --git a/phlex/model/product_store.cpp b/phlex/model/product_store.cpp index 510a4a92d..338c50c49 100644 --- a/phlex/model/product_store.cpp +++ b/phlex/model/product_store.cpp @@ -53,7 +53,7 @@ namespace phlex::experimental { algorithm_name product_store::default_source() { - static algorithm_name const def = algorithm_name::create("[Source]"); + static algorithm_name const def = algorithm_name::create("Source"); return def; } } diff --git a/plugins/python/src/modulewrap.cpp b/plugins/python/src/modulewrap.cpp index 0f55e1718..77c00b110 100644 --- a/plugins/python/src/modulewrap.cpp +++ b/plugins/python/src/modulewrap.cpp @@ -116,7 +116,17 @@ namespace { inline std::string converted_suffix(product_selector const& sel) { - return "py_" + (sel.suffix ? std::string{static_cast(*sel.suffix)} : ""); + return "py_" + (sel.suffix ? std::string{sel.suffix->text()} : ""); + } + + PyObject* translate_exception(std::exception const& e) + { + if (!PyErr_Occurred()) { + PyErr_SetString(dynamic_cast(&e) ? PyExc_ValueError + : PyExc_RuntimeError, + e.what()); + } + return nullptr; } inline PyObject* import_attr(char const* module, char const* attr) @@ -277,9 +287,8 @@ namespace { using jit_callback = jit_callback_impl>; // input/output validation helpers - inline std::optional try_item(PyObject* pysel, - std::string const& item, - bool allow_optionals) + template + std::optional try_item(PyObject* pysel, std::string const& item, bool allow_optionals) { PyObject* pyii = PyDict_GetItemString(pysel, item.c_str()); if ((!pyii && !allow_optionals) || (pyii && !PyUnicode_Check(pyii))) { @@ -287,10 +296,14 @@ namespace { return std::nullopt; } if (!pyii) { - PyErr_Clear(); return std::nullopt; } - return std::optional{PyUnicode_AsUTF8(pyii)}; + Py_ssize_t size = 0; + char const* text = PyUnicode_AsUTF8AndSize(pyii, &size); + if (!text) { + return std::nullopt; + } + return T{std::string_view{text, static_cast(size)}}; } inline std::optional validate_selector(PyObject* pysel, @@ -301,13 +314,16 @@ namespace { return std::nullopt; } - std::optional c = try_item(pysel, "creator", allow_optionals); - std::optional l = try_item(pysel, "layer", allow_optionals); - if (!allow_optionals && !(c.has_value() && l.has_value())) { + auto c = try_item(pysel, "creator", allow_optionals); + if (PyErr_Occurred()) { return std::nullopt; } - std::optional const s = try_item(pysel, "suffix", true); // always optional - if (!s.has_value() && PyErr_Occurred()) { + auto l = try_item(pysel, "layer", allow_optionals); + if (PyErr_Occurred()) { + return std::nullopt; + } + auto s = try_item(pysel, "suffix", true); // always optional + if (PyErr_Occurred()) { return std::nullopt; } @@ -316,7 +332,7 @@ namespace { // move for its contructor // "suffix" is an optional itself, so can pass directly return std::optional{ - product_selector{.creator = std::move(c), .layer = std::move(l), .suffix = s}}; + product_selector{.creator = std::move(c), .layer = std::move(l), .suffix = std::move(s)}}; } template @@ -372,7 +388,9 @@ namespace { if (!p) { return std::nullopt; } - return std::string(p, static_cast(sz)); + std::string result(p, static_cast(sz)); + suffix_t const checked{result}; + return result; }); } @@ -920,8 +938,15 @@ namespace { Py_INCREF(pyname); } - functor_name = PyUnicode_AsUTF8(pyname); + Py_ssize_t name_size = 0; + char const* name_text = PyUnicode_AsUTF8AndSize(pyname, &name_size); + if (!name_text) { + Py_DECREF(pyname); + return nullptr; + } + functor_name.assign(name_text, static_cast(name_size)); Py_DECREF(pyname); + identifier const checked_name{std::string_view{functor_name}}; if (!input) { PyErr_SetString(PyExc_TypeError, "an input is required"); @@ -1161,7 +1186,7 @@ namespace { std::string const suffix = converted_suffix(selector); return {.creator = identifier(input_converter_name(name, index)), .layer = selector.layer, - .suffix = identifier(suffix)}; + .suffix = suffix_t(suffix)}; } template @@ -1197,10 +1222,10 @@ namespace { { // Only a single output is supported until typed tuple conversion is implemented. std::string const pyname = "py_" + name; - std::string const pyoutput = output_suffix + "_py"; + std::string const pyoutput = output_suffix.empty() ? "py" : output_suffix + "_py"; auto output_selector = product_selector{.creator = identifier(pyname), .layer = std::move(output_layer), - .suffix = identifier(pyoutput)}; + .suffix = suffix_t(pyoutput)}; auto register_n_args = [&](std::index_sequence) { constexpr std::size_t n = sizeof...(Is); @@ -1225,7 +1250,7 @@ namespace { } PyObject* md_transform(py_phlex_module* mod, PyObject* args, PyObject* kwds) - { + try { // Register a python algorithm by adding the necessary intermediate converter // nodes going from C++ to PyObject* and back. @@ -1288,11 +1313,16 @@ namespace { } Py_RETURN_NONE; + } catch (std::exception const& e) { + return translate_exception(e); + } catch (...) { + PyErr_SetString(PyExc_RuntimeError, "Unknown C++ exception in transform registration"); + return nullptr; } // NOLINTNEXTLINE(readability-function-size) PyObject* md_observe(py_phlex_module* mod, PyObject* args, PyObject* kwds) - { + try { // Register a python observer by adding the necessary intermediate converter // nodes going from C++ to PyObject* and back. @@ -1350,6 +1380,11 @@ namespace { } Py_RETURN_NONE; + } catch (std::exception const& e) { + return translate_exception(e); + } catch (...) { + PyErr_SetString(PyExc_RuntimeError, "Unknown C++ exception in observer registration"); + return nullptr; } // PyMethodDef arrays must be non-const; tp_methods in PyTypeObject takes a non-const pointer. @@ -1474,12 +1509,13 @@ namespace { } else { Py_INCREF(pyname); } - char const* name_text = PyUnicode_AsUTF8(pyname); + Py_ssize_t name_size = 0; + char const* name_text = PyUnicode_AsUTF8AndSize(pyname, &name_size); if (!name_text) { Py_DECREF(pyname); return std::nullopt; } - std::string const name = name_text; + std::string const name{name_text, static_cast(name_size)}; Py_DECREF(pyname); std::vector input_types; @@ -1498,6 +1534,7 @@ namespace { PyErr_SetString(PyExc_TypeError, "a provider must have an output"); return std::nullopt; } + identifier const checked_name{std::string_view{name}}; return provider_registration{ .callable = callable, .output = output, .name = name, .output_type = output_types[0]}; } @@ -1506,7 +1543,7 @@ namespace { std::string const& name, PyObject* callable, algorithm_name const& creator, - identifier const& suffix, + suffix_t const& suffix, identifier const& layer, std::string const& output_type) { @@ -1518,7 +1555,7 @@ namespace { } PyObject* sc_provide(py_phlex_source* src, PyObject* args, PyObject* kwds) - { + try { auto registration = parse_provider_registration(args, kwds); if (!registration) { return nullptr; @@ -1530,21 +1567,33 @@ namespace { // translate and validate the output "selectors" // Since a selector in Python is just a dictionary, it isn't called out in the user // API as a selector - auto opq = validate_selector(registration->output, false); - if (!opq.has_value()) { - // validate_selector has set a python exception with details about the error + if (!PyDict_Check(registration->output)) { + PyErr_SetString(PyExc_TypeError, "selector should be a product specification"); + return nullptr; + } + auto creator = try_item(registration->output, "creator", false); + if (PyErr_Occurred()) { + return nullptr; + } + auto layer = try_item(registration->output, "layer", false); + if (PyErr_Occurred()) { + return nullptr; + } + auto suffix = try_item(registration->output, "suffix", true); + if (PyErr_Occurred()) { return nullptr; } - - algorithm_name const creator = algorithm_name::create(std::string_view(*opq.value().creator)); - identifier const layer = opq.value().layer; - identifier const suffix = opq.value().suffix.value_or(""); // Provider callbacks retain the callable for the graph lifetime. A translator node // cannot be used here because sources do not have a module for adding one. // TODO: callable cleanup is deferred until a Phlex shutdown procedure exists. - bool const registered = register_provider( - src, registration->name, callable.get(), creator, suffix, layer, registration->output_type); + bool const registered = register_provider(src, + registration->name, + callable.get(), + *creator, + suffix.value_or(suffix_t{}), + *layer, + registration->output_type); if (!registered) { if (!PyErr_Occurred()) { PyErr_Format( @@ -1554,6 +1603,11 @@ namespace { } Py_RETURN_NONE; + } catch (std::exception const& e) { + return translate_exception(e); + } catch (...) { + PyErr_SetString(PyExc_RuntimeError, "Unknown C++ exception in provider registration"); + return nullptr; } // PyMethodDef arrays must be non-const; tp_methods in PyTypeObject takes a non-const pointer. diff --git a/test/config_test.cpp b/test/config_test.cpp index ed8d0fad2..7f84dcac4 100644 --- a/test/config_test.cpp +++ b/test/config_test.cpp @@ -80,11 +80,11 @@ TEST_CASE("Retrieve product_selector", "[config]") ContainsSubstring("not a string")); CHECK_THROWS_WITH(config.get("malformed2"), ContainsSubstring("Error retrieving parameter 'malformed2'") && - ContainsSubstring("Cannot specify the empty string as a data layer.")); + ContainsSubstring("Invalid identifier")); CHECK_THROWS_WITH(config.get("malformed3"), ContainsSubstring("Error retrieving parameter 'malformed3'") && - ContainsSubstring("Cannot specify product with empty creator name.")); + ContainsSubstring("Invalid identifier")); CHECK_THROWS_WITH(config.get("malformed4"), ContainsSubstring("Error retrieving parameter 'malformed4'") && - ContainsSubstring("Product selector contains unrecognized keys")); + ContainsSubstring("Product selector contains unrecognized keys")); } diff --git a/test/core_misc_test.cpp b/test/core_misc_test.cpp index 5312b6f6a..73a676d1c 100644 --- a/test/core_misc_test.cpp +++ b/test/core_misc_test.cpp @@ -21,11 +21,6 @@ TEST_CASE("algorithm_name tests", "[model]") using namespace phlex::detail; using namespace phlex::experimental; - SECTION("Default constructor") - { - algorithm_name const an; - CHECK(an.to_string().empty()); - } SECTION("Create from string with colon") { auto an = algorithm_name::create("plugin:algo"); diff --git a/test/data_cell_index_test.cpp b/test/data_cell_index_test.cpp index 1811d32c9..d05aedd36 100644 --- a/test/data_cell_index_test.cpp +++ b/test/data_cell_index_test.cpp @@ -50,8 +50,7 @@ TEST_CASE("data_cell_index methods", "[data model]") CHECK(subrun->to_string() == "[run:0, subrun:5]"); CHECK(base->to_string() == "[]"); - auto nameless = base->make_child("", 10); - CHECK(nameless->to_string() == "[10]"); + CHECK_THROWS(base->make_child("", 10)); } SECTION("Parent lookup") diff --git a/test/data_layer_hierarchy_test.cpp b/test/data_layer_hierarchy_test.cpp index 30e2f9bcc..cf34ca549 100644 --- a/test/data_layer_hierarchy_test.cpp +++ b/test/data_layer_hierarchy_test.cpp @@ -33,13 +33,13 @@ TEST_CASE("Data layer hierarchy with ambiguous layer names", "[data model]") CHECK(h.count_for("/job/run/spill") == 2); } -TEST_CASE("Data layer hierarchy with unnamed layer", "[data model]") +TEST_CASE("Data layer hierarchy requires named layers", "[data model]") { data_layer_hierarchy h; auto job_index = data_cell_index::job(); CHECK_NOTHROW(h.increment_count(job_index)); - CHECK_NOTHROW(h.increment_count(job_index->make_child("", 0))); - CHECK(h.to_string() == "\n\nSeen layers:\n\n job\n │\n └ (unnamed): 1\n"); + CHECK_THROWS(job_index->make_child("", 0)); + CHECK_NOTHROW(h.to_string()); } TEST_CASE("Data layer hierarchy layout", "[data model]") diff --git a/test/identifier_test.cpp b/test/identifier_test.cpp index 5d5bf583f..98c1bf62a 100644 --- a/test/identifier_test.cpp +++ b/test/identifier_test.cpp @@ -22,8 +22,70 @@ using namespace phlex::experimental; using namespace phlex::experimental::literals; using namespace std::string_view_literals; +TEST_CASE("Identifier rejects punctuation", "[identifier]") +{ + CHECK_THROWS(identifier{"run-name"}); + CHECK_THROWS(identifier{"run.name"}); + CHECK_THROWS(identifier{"run/name"}); + CHECK_THROWS(identifier{"run:name"}); +} + +TEST_CASE("Identifier must begin with a letter", "[identifier]") +{ + CHECK_THROWS(identifier{""}); + CHECK_THROWS(identifier{"_run"}); + CHECK_THROWS(identifier{"2run"}); +} + +TEST_CASE("Identifier rejects non-ASCII and non-name characters", "[identifier]") +{ + CHECK_THROWS(identifier{"run name"}); + CHECK_THROWS(identifier{std::string{"run\0name", 8}}); + CHECK_THROWS(identifier{"run\xc3\xa9"}); +} + +TEST_CASE("Identifier accepts ASCII letters, digits, and underscores", "[identifier]") +{ + for (auto const name : {"A"sv, "z"sv, "AbC_012"sv, "class"sv, "CURRENT"sv}) { + identifier const from_view{name}; + identifier const from_string{std::string{name}}; + CHECK(std::string_view{from_view} == name); + CHECK(from_view == from_string); + CHECK(from_view.hash() == from_string.hash()); + CHECK(fmt::format("{}", from_view) == name); + } + CHECK(std::string_view{"AbC_012"_id} == "AbC_012"sv); + CHECK("AbC_012"_id == "AbC_012"_idq); +} + +TEST_CASE("Identifier validates every length-bearing construction path", "[identifier]") +{ + CHECK_THROWS(identifier{"bad name"sv}); + CHECK_THROWS(identifier{std::string{"bad name"}}); + CHECK_THROWS("bad name"_id); + CHECK_THROWS("abc\0def"_id); + CHECK_THROWS(identifier_or_empty{"bad name"sv}); + CHECK_THROWS(suffix_t{std::string{"abc\0def", 7}}); + CHECK(identifier_or_empty{""}.empty()); +} + +TEST_CASE("Moved identifiers remain valid names", "[identifier]") +{ + identifier original{"hits"}; + identifier moved{std::move(original)}; + CHECK(std::string_view{moved} == "hits"sv); + CHECK(std::string_view{original} == "hits"sv); + CHECK(original == "hits"_idq); + CHECK(identifier_or_empty{std::move(original)}.text() == "hits"sv); + identifier assigned{"other"}; + assigned = std::move(original); + CHECK(assigned == "hits"_idq); + CHECK(std::string_view{original} == "hits"sv); +} + TEST_CASE("Identifier equality and inequality", "[identifier]") { + STATIC_CHECK_FALSE(std::is_default_constructible_v); identifier a = "a"_id; identifier a_copy = a; identifier a2 = "a"_id; @@ -50,7 +112,7 @@ TEST_CASE("Identifier reassignment", "[identifier]") { identifier a = "a"_id; identifier a_copy = a; - a = "new a"_id; + a = "new_a"_id; a_copy = a; CHECK(a == a_copy); } @@ -58,14 +120,14 @@ TEST_CASE("Identifier reassignment", "[identifier]") TEST_CASE("Identifier sorting is not lexical", "[identifier]") { std::array strings{ - "a"sv, "b"sv, "c"sv, "d"sv, "e"sv, "long-id-1"sv, "long-id-2"sv, "test"sv, "other_test"sv}; + "a"sv, "b"sv, "c"sv, "d"sv, "e"sv, "long_id_1"sv, "long_id_2"sv, "test"sv, "other_test"sv}; std::array identifiers{"a"_id, "b"_id, "c"_id, "d"_id, "e"_id, - "long-id-1"_id, - "long-id-2"_id, + "long_id_1"_id, + "long_id_2"_id, "test"_id, "other_test"_id}; std::ranges::sort(identifiers); @@ -193,13 +255,8 @@ TEST_CASE("identifier_or_empty equality distinguishes empty from named", "[ident { identifier_or_empty const empty{}; identifier_or_empty const hits{"hits"_id}; - // A named value holding an identifier with empty text is still not equal to an empty value. - identifier_or_empty const named_with_empty_text{identifier{}}; - CHECK(empty != hits); CHECK(hits != empty); - CHECK(empty != named_with_empty_text); - CHECK(named_with_empty_text != empty); } TEST_CASE("identifier_or_empty hash of empty values is shared", "[identifier]") diff --git a/test/max-parallelism/CMakeLists.txt b/test/max-parallelism/CMakeLists.txt index 244da04ac..d898be746 100644 --- a/test/max-parallelism/CMakeLists.txt +++ b/test/max-parallelism/CMakeLists.txt @@ -95,7 +95,7 @@ cet_test( phlex::phlex TEST_ARGS -c ${CMAKE_CURRENT_BINARY_DIR}/check_stage_cli_over_config.jsonnet - --stage command-line-stage + --stage command_line_stage TEST_PROPERTIES ENVIRONMENT "PHLEX_PLUGIN_PATH=${PROJECT_BINARY_DIR}/${phlex_LIBRARY_DIR}" diff --git a/test/max-parallelism/check_stage_cli_over_config.jsonnet b/test/max-parallelism/check_stage_cli_over_config.jsonnet index 98948ba3f..53088e8dc 100644 --- a/test/max-parallelism/check_stage_cli_over_config.jsonnet +++ b/test/max-parallelism/check_stage_cli_over_config.jsonnet @@ -1,10 +1,10 @@ local base = import 'check_parallelism_default.jsonnet'; base { - stage: 'configured-stage', + stage: 'configured_stage', modules+: { verify+: { - expected_stage: 'command-line-stage', + expected_stage: 'command_line_stage', }, }, } diff --git a/test/max-parallelism/check_stage_config.jsonnet b/test/max-parallelism/check_stage_config.jsonnet index e7bb3c591..81baf1c73 100644 --- a/test/max-parallelism/check_stage_config.jsonnet +++ b/test/max-parallelism/check_stage_config.jsonnet @@ -1,10 +1,10 @@ local base = import 'check_parallelism_default.jsonnet'; base { - stage: 'configured-stage', + stage: 'configured_stage', modules+: { verify+: { - expected_stage: 'configured-stage', + expected_stage: 'configured_stage', }, }, } diff --git a/test/multilayer_join_test.cpp b/test/multilayer_join_test.cpp index 379678191..7103aa1f3 100644 --- a/test/multilayer_join_test.cpp +++ b/test/multilayer_join_test.cpp @@ -33,7 +33,7 @@ namespace { template product_specification spec(algorithm_name const& creator) { - return {creator, ""_id, make_type_id()}; + return {creator, suffix_t{}, make_type_id()}; } template diff --git a/test/product_selector_test.cpp b/test/product_selector_test.cpp index 4eab694e2..d2eeece62 100644 --- a/test/product_selector_test.cpp +++ b/test/product_selector_test.cpp @@ -12,9 +12,7 @@ using namespace phlex; TEST_CASE("Empty creator name", "[data model]") { - CHECK_THROWS_WITH( - (product_selector{.creator = "", .layer = "layer"}), - Catch::Matchers::ContainsSubstring("Cannot specify product with empty creator name.")); + CHECK_THROWS((product_selector{.creator = "", .layer = "layer"})); } TEST_CASE("Creator name formatting", "[data model]") @@ -25,9 +23,7 @@ TEST_CASE("Creator name formatting", "[data model]") TEST_CASE("Empty layer name", "[data model]") { - CHECK_THROWS_WITH( - (product_selector{.creator = "creator", .layer = ""}), - Catch::Matchers::ContainsSubstring("Cannot specify the empty string as a data layer.")); + CHECK_THROWS((product_selector{.creator = "creator", .layer = ""})); } TEST_CASE("Retrieving a non-existent layer name", "[data model]") @@ -45,21 +41,21 @@ TEST_CASE("Product name with data layer", "[data model]") CHECK(*label.layer == "event"_idq); CHECK(label.suffix == "product"_id); // Mismatched creator - CHECK(!product_selector{.creator = "1", .layer = "event", .suffix = "prod"}.match( - product_selector{.creator = "2", .layer = "event", .suffix = "prod"})); + CHECK(!product_selector{.creator = "one", .layer = "event", .suffix = "prod"}.match( + product_selector{.creator = "two", .layer = "event", .suffix = "prod"})); // Missing creator matches any creator CHECK(product_selector{.layer = "event", .suffix = "prod"}.match( - product_selector{.creator = "2", .layer = "event", .suffix = "prod"})); + product_selector{.creator = "two", .layer = "event", .suffix = "prod"})); // Mismatched layer - CHECK(!product_selector{.creator = "1", .layer = "event", .suffix = "prod"}.match( - product_selector{.creator = "1", .layer = "event1", .suffix = "prod"})); + CHECK(!product_selector{.creator = "one", .layer = "event", .suffix = "prod"}.match( + product_selector{.creator = "one", .layer = "event1", .suffix = "prod"})); // Mismatched suffix - CHECK(!product_selector{.creator = "1", .layer = "event", .suffix = "prod"}.match( - product_selector{.creator = "1", .layer = "event", .suffix = "prod1"})); + CHECK(!product_selector{.creator = "one", .layer = "event", .suffix = "prod"}.match( + product_selector{.creator = "one", .layer = "event", .suffix = "prod1"})); // Mismatched stage - CHECK(!product_selector{.creator = "1", .layer = "event", .suffix = "prod", .stage = "stage"_id} + CHECK(!product_selector{.creator = "one", .layer = "event", .suffix = "prod", .stage = "stage"_id} .match(product_selector{ - .creator = "1", .layer = "event", .suffix = "prod", .stage = "stage1"_id})); + .creator = "one", .layer = "event", .suffix = "prod", .stage = "stage1"_id})); // Here for no reason other than to satisfy codecov CHECK(label == label); CHECK((label <=> label) == std::strong_ordering::equal); diff --git a/test/transform_node_test.cpp b/test/transform_node_test.cpp index 124d1c862..ab566f911 100644 --- a/test/transform_node_test.cpp +++ b/test/transform_node_test.cpp @@ -76,7 +76,7 @@ namespace { template product_specification spec(algorithm_name const& creator) { - return {creator, ""_id, make_type_id()}; + return {creator, suffix_t{}, make_type_id()}; } template @@ -128,7 +128,7 @@ TEST_CASE("transform_node directly transforms one input product", "[transform_no auto const& output_specs = transform.output(); REQUIRE(output_specs.size() == 1u); CHECK(output_specs[0].creator() == algorithm_name{"double_value"}); - CHECK(output_specs[0].suffix() == identifier{""}); + CHECK(output_specs[0].suffix() == suffix_t{}); CHECK(output_specs[0].type() == make_type_id()); oneapi::tbb::flow::queue_node sink{graph}; From 5da8941b59bf042c59c37d26f0c4936108b35659 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Sat, 14 Nov 2026 11:29:09 -0600 Subject: [PATCH 02/28] perf!: make identifier moves noexcept and non-copying Address clang-tidy issues. Replace the copy-forwarding move constructor and move assignment with defaulted noexcept versions, so moving an identifier no longer copies its name. Simplify the identifier validation loop to std::ranges::all_of with unchanged behavior. Update identifier tests to verify the moved-to value, hash, formatting, nothrow traits, and identifier_or_empty wrapping, and drop assertions about moved-from state. BREAKING CHANGE: moved-from identifiers are only guaranteed to be safely destructible; they no longer retain their name. --- phlex/model/identifier.hpp | 16 ++++++---------- test/identifier_test.cpp | 37 +++++++++++++++++++++++++------------ 2 files changed, 31 insertions(+), 22 deletions(-) diff --git a/phlex/model/identifier.hpp b/phlex/model/identifier.hpp index 35b4c56b0..469a345c1 100644 --- a/phlex/model/identifier.hpp +++ b/phlex/model/identifier.hpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -25,12 +26,8 @@ namespace phlex::detail { if (text.empty() || !letter(text.front())) { return false; } - for (char const c : text) { - if (!letter(c) && !(c >= '0' && c <= '9') && c != '_') { - return false; - } - } - return true; + return std::ranges::all_of( + text, [letter](char c) { return letter(c) || (c >= '0' && c <= '9') || c == '_'; }); } } @@ -46,6 +43,7 @@ namespace phlex::experimental { /// A non-empty ASCII name beginning with a letter and containing only letters, digits, /// and underscores, together with a precomputed hash. + /// Moved-from identifiers are only guaranteed to be safely destructible. class PHLEX_MODEL_EXPORT identifier { public: static constexpr std::uint64_t hash_string(std::string_view str) @@ -58,7 +56,7 @@ namespace phlex::experimental { } identifier() = delete; identifier(identifier const& other) = default; - identifier(identifier&& other) : identifier(static_cast(other)) {} + identifier(identifier&& other) noexcept = default; explicit identifier(std::string_view str); @@ -71,7 +69,7 @@ namespace phlex::experimental { identifier(char const* lit) : identifier(std::string_view(lit)) {} identifier& operator=(identifier const& rhs) = default; - identifier& operator=(identifier&& rhs) { return *this = static_cast(rhs); } + identifier& operator=(identifier&& rhs) noexcept = default; ~identifier() = default; @@ -81,9 +79,7 @@ namespace phlex::experimental { bool operator==(identifier const& rhs) const noexcept; std::strong_ordering operator<=>(identifier const& rhs) const noexcept; - // check if empty bool empty() const noexcept { return content_.empty(); } - // get hash std::size_t hash() const noexcept { return hash_; } // transitional access to contained string diff --git a/test/identifier_test.cpp b/test/identifier_test.cpp index 98c1bf62a..bc7ebf5af 100644 --- a/test/identifier_test.cpp +++ b/test/identifier_test.cpp @@ -17,6 +17,7 @@ #include #include #include +#include using namespace phlex::experimental; using namespace phlex::experimental::literals; @@ -69,18 +70,30 @@ TEST_CASE("Identifier validates every length-bearing construction path", "[ident CHECK(identifier_or_empty{""}.empty()); } -TEST_CASE("Moved identifiers remain valid names", "[identifier]") -{ - identifier original{"hits"}; - identifier moved{std::move(original)}; - CHECK(std::string_view{moved} == "hits"sv); - CHECK(std::string_view{original} == "hits"sv); - CHECK(original == "hits"_idq); - CHECK(identifier_or_empty{std::move(original)}.text() == "hits"sv); - identifier assigned{"other"}; - assigned = std::move(original); - CHECK(assigned == "hits"_idq); - CHECK(std::string_view{original} == "hits"sv); +TEST_CASE("Moving identifiers preserves the destination value", "[identifier]") +{ + STATIC_CHECK(std::is_nothrow_move_constructible_v); + STATIC_CHECK(std::is_nothrow_move_assignable_v); + for (auto const name : {"hits"sv, "a_long_identifier_that_requires_heap_storage"sv}) { + identifier const expected{name}; + identifier original{name}; + identifier moved{std::move(original)}; + CHECK(std::string_view{moved} == name); + CHECK(moved == expected); + CHECK(moved.hash() == expected.hash()); + CHECK(fmt::format("{}", moved) == name); + identifier assigned{"other"}; + assigned = std::move(moved); + CHECK(assigned == expected); + CHECK(std::string_view{assigned} == name); + CHECK(assigned.hash() == expected.hash()); + CHECK(fmt::format("{}", assigned) == name); + identifier_or_empty const wrapped{std::move(assigned)}; + CHECK(wrapped == identifier_or_empty{expected}); + CHECK(wrapped.text() == name); + CHECK(wrapped.hash() == expected.hash()); + CHECK(fmt::format("{}", wrapped) == name); + } } TEST_CASE("Identifier equality and inequality", "[identifier]") From 08755400580e13b09c8f0afe924aad554e204289 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Sat, 14 Nov 2026 12:16:53 -0600 Subject: [PATCH 03/28] fix(plugins): use checked access for provider selector optionals Replace unchecked dereference of the optional creator and layer selectors with value(), so an empty optional raises std::bad_optional_access (translated to a Python error by the existing catch handler) instead of undefined behavior. Include for the std::exception handler used in this file. --- plugins/python/src/modulewrap.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/plugins/python/src/modulewrap.cpp b/plugins/python/src/modulewrap.cpp index 77c00b110..6de3d6b19 100644 --- a/plugins/python/src/modulewrap.cpp +++ b/plugins/python/src/modulewrap.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -1590,9 +1591,9 @@ namespace { bool const registered = register_provider(src, registration->name, callable.get(), - *creator, + creator.value(), suffix.value_or(suffix_t{}), - *layer, + layer.value(), registration->output_type); if (!registered) { if (!PyErr_Occurred()) { From ebfe1532f8e008979648e77f05d775398120b0b3 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Sat, 14 Nov 2026 15:12:12 -0600 Subject: [PATCH 04/28] test(model): cover default product store source Add a test case checking that the default source reports the name "Source", has the matching algorithm identifier, has an empty plugin, and compares equal across calls. --- test/product_store_test.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/test/product_store_test.cpp b/test/product_store_test.cpp index 9ad38e8e5..972b54298 100644 --- a/test/product_store_test.cpp +++ b/test/product_store_test.cpp @@ -21,6 +21,15 @@ using namespace phlex::experimental; using namespace phlex::experimental::literals; +TEST_CASE("Product store default source", "[data model]") +{ + auto const source = product_store::default_source(); + CHECK(source.to_string() == "Source"); + CHECK(source.algorithm() == "Source"_id); + CHECK(source.plugin().empty()); + CHECK(product_store::default_source() == source); +} + TEST_CASE("Product store insertion", "[data model]") { auto const creator = algorithm_name::create("test_algorithm"); From ed7a81cb2a9630440a681a575fcfa0012b13ef3e Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Sat, 14 Nov 2026 15:17:17 -0600 Subject: [PATCH 05/28] refactor(core): remove unreachable suffix fallback in producer log Replace the wildcard fallback in the producer catalog debug message with direct access to the query suffix. The empty-catalog check returns early, so reaching the b == e branch implies a specified suffix. The previous wildcard branch was therefore unreachable and could not be covered by tests, leaving an artificial gap in patch coverage. Suppress the unchecked-optional lint warning at the call site with a comment explaining the invariant. Add a direct test that find_producers returns no producers for an unknown suffix in a nonempty catalog, exercising this return path. --- phlex/core/producer_catalog.cpp | 3 ++- test/producer_catalog_test.cpp | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/phlex/core/producer_catalog.cpp b/phlex/core/producer_catalog.cpp index a758cddbe..e299502b4 100644 --- a/phlex/core/producer_catalog.cpp +++ b/phlex/core/producer_catalog.cpp @@ -167,7 +167,8 @@ namespace phlex::detail { if (b == e) { spdlog::debug( "Failed to find an algorithm that creates {} products. Assuming it comes from a provider", - query.suffix ? query.suffix->text() : "*"); + // The empty catalog returned above, so b == e implies a specified suffix. + query.suffix->text()); // NOLINT(bugprone-unchecked-optional-access) return {}; } std::vector candidates; diff --git a/test/producer_catalog_test.cpp b/test/producer_catalog_test.cpp index 5beaa8351..287502159 100644 --- a/test/producer_catalog_test.cpp +++ b/test/producer_catalog_test.cpp @@ -35,6 +35,19 @@ namespace { }; } +TEST_CASE("producer_catalog returns no producers for an unknown suffix", "[producer_catalog]") +{ + tbb::flow::graph graph; + test_producer node{graph}; + std::vector producers{&node}; + producer_catalog const catalog{producers}; + + phlex::product_selector const query{.suffix = identifier{"nonexistent"}}; + auto const matches = + catalog.find_producers(query, algorithm_name{"consumer"}, identifier{"test_stage"}); + CHECK(matches.empty()); +} + TEST_CASE("producer_catalog registers all products from a producer", "[producer_catalog]") { tbb::flow::graph graph; From f07fa972ec505a3e2e2ede005eb25b1c5d218d47 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Sat, 14 Nov 2026 15:20:28 -0600 Subject: [PATCH 06/28] test(model): cover empty algorithm name error Add a Catch2 section asserting that `algorithm_name::create("")` throws `std::runtime_error` with the message "Cannot create an empty algorithm name." Include `catch2/matchers/catch_matchers.hpp` for `CHECK_THROWS_WITH`. --- test/core_misc_test.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/core_misc_test.cpp b/test/core_misc_test.cpp index 73a676d1c..cc8c44a60 100644 --- a/test/core_misc_test.cpp +++ b/test/core_misc_test.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -41,6 +42,11 @@ TEST_CASE("algorithm_name tests", "[model]") { CHECK_THROWS_AS(algorithm_name::create("plugin:"), std::runtime_error); } + SECTION("Create error - empty name") + { + CHECK_THROWS_AS(algorithm_name::create(""), std::runtime_error); + CHECK_THROWS_WITH(algorithm_name::create(""), "Cannot create an empty algorithm name."); + } SECTION("Match both") { algorithm_name const an = algorithm_name::create("p:a"); From d7fe7d0ac23d3b2b1cf7a24fc7a00c39af67ea60 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Sat, 14 Nov 2026 15:22:31 -0600 Subject: [PATCH 07/28] add: cover product specification hash and equality Add a Catch2 test case for `product_specification` covering `std::hash` and equality. It checks that named and unnamed specifications with identical fields hash equally, that duplicate insertions into an `std::unordered_set` are rejected, and that lookups distinguish differing creator, name, or type. Includes `product_specification.hpp`, ``, ``, and `` as needed. --- test/product_store_test.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/test/product_store_test.cpp b/test/product_store_test.cpp index 972b54298..0992a19d2 100644 --- a/test/product_store_test.cpp +++ b/test/product_store_test.cpp @@ -5,6 +5,7 @@ #include "phlex/model/handle.hpp" #include "phlex/model/identifier.hpp" #include "phlex/model/product_store.hpp" +#include "phlex/model/product_specification.hpp" #include "phlex/model/type_id.hpp" #include @@ -12,15 +13,44 @@ #include #include +#include #include +#include #include #include #include +#include #include using namespace phlex::experimental; using namespace phlex::experimental::literals; +TEST_CASE("Product specification hash and equality", "[data model]") +{ + auto const creator = algorithm_name::create("plugin:producer"); + product_specification const named{creator, "number"_id, make_type_id()}; + product_specification const unnamed{std::nullopt, "number"_id, make_type_id()}; + std::hash const hash; + + CHECK(hash(named) == hash(product_specification{creator, "number"_id, make_type_id()})); + CHECK(hash(unnamed) == + hash(product_specification{std::nullopt, "number"_id, make_type_id()})); + + std::unordered_set specs; + CHECK(specs.insert(named).second); + CHECK(specs.insert(unnamed).second); + CHECK_FALSE(specs.insert(product_specification{creator, "number"_id, make_type_id()}).second); + CHECK_FALSE( + specs.insert(product_specification{std::nullopt, "number"_id, make_type_id()}).second); + CHECK(specs.size() == 2u); + CHECK(specs.contains(product_specification{creator, "number"_id, make_type_id()})); + CHECK(specs.contains(product_specification{std::nullopt, "number"_id, make_type_id()})); + CHECK_FALSE(specs.contains(product_specification{creator, "other"_id, make_type_id()})); + CHECK_FALSE(specs.contains(product_specification{creator, "number"_id, make_type_id()})); + CHECK_FALSE(specs.contains(product_specification{ + algorithm_name::create("plugin:other"), "number"_id, make_type_id()})); +} + TEST_CASE("Product store default source", "[data model]") { auto const source = product_store::default_source(); From e5ccd97bd51175ccb65d7d7439d7e9431845238d Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Sat, 14 Nov 2026 15:24:58 -0600 Subject: [PATCH 08/28] add: cover leading-slash product specification without creator Add a test case verifying that `product_specification::create` with a leading-slash name yields no creator, the suffix as the given name, and an invalid type. --- test/product_store_test.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/product_store_test.cpp b/test/product_store_test.cpp index 0992a19d2..a3a400acb 100644 --- a/test/product_store_test.cpp +++ b/test/product_store_test.cpp @@ -25,6 +25,14 @@ using namespace phlex::experimental; using namespace phlex::experimental::literals; +TEST_CASE("Product specification leading slash omits the creator", "[data model]") +{ + auto const spec = product_specification::create("/number"); + CHECK_FALSE(spec.creator().has_value()); + CHECK(spec.suffix() == "number"_id); + CHECK_FALSE(spec.type().valid()); +} + TEST_CASE("Product specification hash and equality", "[data model]") { auto const creator = algorithm_name::create("plugin:producer"); From 538b0ab405d465b1b6b05093e6aa0043edac6724 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Sat, 14 Nov 2026 15:32:53 -0600 Subject: [PATCH 09/28] add tests for provider routing and product creator validation Add an index router test confirming unresolved provider layers receive no concrete indices, a product handle test for absent creator metadata, and a provider node test asserting that specifications without a creator throw std::runtime_error --- test/index_router_test.cpp | 31 +++++++++++++++++++++++++++++++ test/product_handle_test.cpp | 11 +++++++++++ test/provider_test.cpp | 19 +++++++++++++++++++ 3 files changed, 61 insertions(+) diff --git a/test/index_router_test.cpp b/test/index_router_test.cpp index a3445683c..d9d8536cf 100644 --- a/test/index_router_test.cpp +++ b/test/index_router_test.cpp @@ -18,6 +18,37 @@ using namespace phlex; +TEST_CASE("Unresolved provider layers do not receive concrete indices", "[graph]") +{ + tbb::flow::graph graph; + tbb::flow::queue_node first_unresolved{graph}; + tbb::flow::queue_node second_unresolved{graph}; + tbb::flow::queue_node resolved{graph}; + detail::index_router router{graph}; + router.finalize( + graph, + {experimental::layer_path{"/job/run"}}, + {}, + {{"first_unresolved", {.input_product = {}, .port = &first_unresolved}}, + {"second_unresolved", {.input_product = {}, .port = &second_unresolved}}, + {"resolved", {.input_product = {.layer = "run"}, .port = &resolved}}}, + {}, + {}); + + auto const job = data_cell_index::job(); + auto const run = job->make_child("run", 0); + router.route(job, {}); + router.route(run, {}); + graph.wait_for_all(); + + detail::index_message message; + REQUIRE(resolved.try_get(message)); + CHECK(message.index == run); + CHECK_FALSE(resolved.try_get(message)); + CHECK_FALSE(first_unresolved.try_get(message)); + CHECK_FALSE(second_unresolved.try_get(message)); +} + TEST_CASE("Index routing requires an explicit driver hierarchy", "[graph]") { tbb::flow::graph graph; diff --git a/test/product_handle_test.cpp b/test/product_handle_test.cpp index 590fcedbf..452b1c140 100644 --- a/test/product_handle_test.cpp +++ b/test/product_handle_test.cpp @@ -133,6 +133,17 @@ TEST_CASE("Retrieve product specification from handle", "[data model]") CHECK(h.stage() == "test_stage"); } +TEST_CASE("Retrieve absent creator from handle", "[data model]") +{ + int const number{3}; + spec_t const spec{"three"}; + auto const h = make_handle(number, *data_cell_index::job(), spec); + + CHECK(h.creator().plugin.empty()); + CHECK(h.creator().algorithm.empty()); + CHECK(h.suffix() == "three"); +} + TEST_CASE("Retrieve stage from handle", "[data model]") { int const number{3}; diff --git a/test/provider_test.cpp b/test/provider_test.cpp index f340a4203..c2b268077 100644 --- a/test/provider_test.cpp +++ b/test/provider_test.cpp @@ -14,10 +14,13 @@ #include #include #include +#include #include #include #include +#include +#include #include #include @@ -95,6 +98,22 @@ namespace { unsigned pass_on(vertex_collection const& vertices) { return vertices.data; } } +TEST_CASE("Provider nodes reject product specifications without a creator") +{ + tbb::flow::graph graph; + provider_bundle const bundle{ + .provider_function = give_me_vertices_erased, + .max_concurrency = concurrency::unlimited, + .spec = experimental::product_specification{ + std::nullopt, "happy_vertices", experimental::make_type_id()}, + .layer = "spill", + .stage = "previous_process"}; + + CHECK_THROWS_AS((detail::provider_node{graph, bundle}), std::runtime_error); + CHECK_THROWS_WITH((detail::provider_node{graph, bundle}), + "Cannot create a provider without a product creator."); +} + TEST_CASE("Explicit providers") { constexpr auto num_spills{3u}; From 5d6188b66cbbc947983e3f2459bb630104844252 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Sat, 14 Nov 2026 17:58:28 -0600 Subject: [PATCH 10/28] style: reformat finalize and product spec calls in tests --- test/index_router_test.cpp | 17 ++++++++--------- test/provider_test.cpp | 5 +++-- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/test/index_router_test.cpp b/test/index_router_test.cpp index d9d8536cf..662efa9e7 100644 --- a/test/index_router_test.cpp +++ b/test/index_router_test.cpp @@ -25,15 +25,14 @@ TEST_CASE("Unresolved provider layers do not receive concrete indices", "[graph] tbb::flow::queue_node second_unresolved{graph}; tbb::flow::queue_node resolved{graph}; detail::index_router router{graph}; - router.finalize( - graph, - {experimental::layer_path{"/job/run"}}, - {}, - {{"first_unresolved", {.input_product = {}, .port = &first_unresolved}}, - {"second_unresolved", {.input_product = {}, .port = &second_unresolved}}, - {"resolved", {.input_product = {.layer = "run"}, .port = &resolved}}}, - {}, - {}); + router.finalize(graph, + {experimental::layer_path{"/job/run"}}, + {}, + {{"first_unresolved", {.input_product = {}, .port = &first_unresolved}}, + {"second_unresolved", {.input_product = {}, .port = &second_unresolved}}, + {"resolved", {.input_product = {.layer = "run"}, .port = &resolved}}}, + {}, + {}); auto const job = data_cell_index::job(); auto const run = job->make_child("run", 0); diff --git a/test/provider_test.cpp b/test/provider_test.cpp index c2b268077..a9b7f2c9b 100644 --- a/test/provider_test.cpp +++ b/test/provider_test.cpp @@ -104,8 +104,9 @@ TEST_CASE("Provider nodes reject product specifications without a creator") provider_bundle const bundle{ .provider_function = give_me_vertices_erased, .max_concurrency = concurrency::unlimited, - .spec = experimental::product_specification{ - std::nullopt, "happy_vertices", experimental::make_type_id()}, + .spec = experimental::product_specification{std::nullopt, + "happy_vertices", + experimental::make_type_id()}, .layer = "spill", .stage = "previous_process"}; From 09fd8dba41a1f391746643b4a25679d736916ecd Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Sun, 15 Nov 2026 16:13:42 -0600 Subject: [PATCH 11/28] style: sort product store test includes and wrap product spec check --- test/product_store_test.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/product_store_test.cpp b/test/product_store_test.cpp index a3a400acb..72ca5c63c 100644 --- a/test/product_store_test.cpp +++ b/test/product_store_test.cpp @@ -4,8 +4,8 @@ #include "phlex/model/algorithm_name.hpp" #include "phlex/model/handle.hpp" #include "phlex/model/identifier.hpp" -#include "phlex/model/product_store.hpp" #include "phlex/model/product_specification.hpp" +#include "phlex/model/product_store.hpp" #include "phlex/model/type_id.hpp" #include @@ -47,7 +47,8 @@ TEST_CASE("Product specification hash and equality", "[data model]") std::unordered_set specs; CHECK(specs.insert(named).second); CHECK(specs.insert(unnamed).second); - CHECK_FALSE(specs.insert(product_specification{creator, "number"_id, make_type_id()}).second); + CHECK_FALSE( + specs.insert(product_specification{creator, "number"_id, make_type_id()}).second); CHECK_FALSE( specs.insert(product_specification{std::nullopt, "number"_id, make_type_id()}).second); CHECK(specs.size() == 2u); From 2da74a395ce6389859d0a566d340da57479df766 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Mon, 16 Nov 2026 11:38:53 -0600 Subject: [PATCH 12/28] chore: Allow unguarded optional value() calls in clang-tidy Set bugprone-unchecked-optional-access.IgnoreValueCalls to true in .clang-tidy so calls to std::optional::value() no longer trigger warnings when they lack a preceding has_value() guard. --- .clang-tidy | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.clang-tidy b/.clang-tidy index 56c579b75..4b40d4dd1 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -41,6 +41,10 @@ WarningsAsErrors: '' HeaderFilterRegex: '.*/(phlex|form)/.*\.(h|hpp)$' CheckOptions: + # Allow calls to optional::value() without guards + - key: bugprone-unchecked-optional-access.IgnoreValueCalls + value: 'true' + # Naming conventions - key: readability-identifier-naming.NamespaceCase value: lower_case From 82be2d9a97565f5e028a428e96a1b43dcde7b533 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Mon, 16 Nov 2026 16:04:36 -0600 Subject: [PATCH 13/28] refactor(model): make identifier_or_empty move constructor noexcept Moving an identifier never allocates, so the `identifier&&` constructor of identifier_or_empty can be declared noexcept. This lets callers and standard containers rely on the non-throwing move. Add comments noting that the `identifier const&` copy constructor is intentionally not noexcept, because copying the underlying string may allocate and throw. --- phlex/model/identifier.hpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/phlex/model/identifier.hpp b/phlex/model/identifier.hpp index 469a345c1..9960ab6af 100644 --- a/phlex/model/identifier.hpp +++ b/phlex/model/identifier.hpp @@ -149,11 +149,13 @@ namespace phlex::experimental { // NOLINTNEXTLINE(google-explicit-constructor) - Implicit conversion is intentional identifier_or_empty(empty_string) noexcept : value_{empty_string{}} {} + // Not noexcept: copying an identifier copies its string, which may allocate and throw. // NOLINTNEXTLINE(google-explicit-constructor) - Implicit conversion is intentional identifier_or_empty(identifier const& id) : value_{id} {} + // noexcept: moving an identifier is itself noexcept and never allocates. // NOLINTNEXTLINE(google-explicit-constructor) - Implicit conversion is intentional - identifier_or_empty(identifier&& id) : value_{std::move(id)} {} + identifier_or_empty(identifier&& id) noexcept : value_{std::move(id)} {} explicit identifier_or_empty(std::string_view str) { From fcbeabaf5aaa0011d700702301a9f7410da643a3 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Mon, 16 Nov 2026 16:07:09 -0600 Subject: [PATCH 14/28] refactor(model): use optional identifier for algorithm_name plugin Replace the identifier_or_empty plugin qualifier in algorithm_name with std::optional, where an absent value means the name is unqualified. The constructor, plugin() accessor and to_string() now use the optional directly. Adapt the callers: - make_algorithm_name leaves the plugin absent when there is no configuration and otherwise uses the module label. - product_selector compares the optional plugin to the creator identifier. - product handle creator() builds its view from an empty string_view when the plugin is absent. - the product_specification hash mixes in whether a plugin is present before hashing it, so qualified and unqualified creators stay distinct. - the product_store default source test checks has_value() instead of empty(). Add tests for the optional plugin states, construction from typed components, parse rejection of ":algo", "plugin:", multiple colons and malformed components, and make_algorithm_name with and without a configuration. --- phlex/core/detail/make_algorithm_name.cpp | 10 +++- phlex/core/product_selector.cpp | 2 +- phlex/model/algorithm_name.cpp | 12 ++-- phlex/model/algorithm_name.hpp | 11 +++- phlex/model/handle.hpp | 4 +- phlex/model/product_specification.hpp | 6 +- test/core_misc_test.cpp | 71 +++++++++++++++++++++++ test/product_store_test.cpp | 2 +- 8 files changed, 102 insertions(+), 16 deletions(-) diff --git a/phlex/core/detail/make_algorithm_name.cpp b/phlex/core/detail/make_algorithm_name.cpp index 7f6f85d3f..06cd1f3c9 100644 --- a/phlex/core/detail/make_algorithm_name.cpp +++ b/phlex/core/detail/make_algorithm_name.cpp @@ -4,13 +4,17 @@ #include "phlex/model/algorithm_name.hpp" #include "phlex/model/identifier.hpp" +#include #include +#include namespace phlex::experimental::internal { algorithm_name make_algorithm_name(configuration const* config, std::string_view name) { - return {config ? identifier_or_empty(identifier(config->get("module_label"))) - : identifier_or_empty{}, - identifier(name)}; + std::optional plugin; + if (config) { + plugin.emplace(config->get("module_label")); + } + return {std::move(plugin), identifier(name)}; } } diff --git a/phlex/core/product_selector.cpp b/phlex/core/product_selector.cpp index e38a98dae..9c20bd45e 100644 --- a/phlex/core/product_selector.cpp +++ b/phlex/core/product_selector.cpp @@ -76,7 +76,7 @@ namespace phlex { return true; // empty creator matches everything } experimental::identifier const& creator{*(this->creator)}; - return (alg.plugin().named() && *alg.plugin().named() == creator) || alg.algorithm() == creator; + return alg.plugin() == creator || alg.algorithm() == creator; } std::string product_selector::to_string() const diff --git a/phlex/model/algorithm_name.cpp b/phlex/model/algorithm_name.cpp index bada95d3b..a38e894ef 100644 --- a/phlex/model/algorithm_name.cpp +++ b/phlex/model/algorithm_name.cpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -41,17 +42,16 @@ namespace phlex::experimental { } algorithm_name::algorithm_name(std::string_view spec) : algorithm_name{create(spec)} {} - algorithm_name::algorithm_name(identifier_or_empty plugin, identifier algorithm) : + algorithm_name::algorithm_name(std::optional plugin, identifier algorithm) : plugin_{std::move(plugin)}, algorithm_{std::move(algorithm)} { } std::string algorithm_name::to_string() const { - if (!plugin_.empty()) { - return fmt::format("{}:{}", plugin_, algorithm_); + if (plugin_) { + return fmt::format("{}:{}", *plugin_, algorithm_); } - // This will stay after trans_get_string is removed return fmt::format("{}", algorithm_); } @@ -77,7 +77,7 @@ namespace phlex::experimental { throw std::runtime_error( fmt::format("The specification '{}' is not a valid algorithm name.", spec)); } - return {identifier_or_empty(plugin), identifier(algorithm)}; + return {std::optional{identifier(plugin)}, identifier(algorithm)}; } // No colon -- could be plugin or algorithm @@ -85,6 +85,6 @@ namespace phlex::experimental { throw std::runtime_error( fmt::format("The specification '{}' is not a valid algorithm name.", spec)); } - return {empty_string{}, identifier(spec)}; + return {std::nullopt, identifier(spec)}; } } diff --git a/phlex/model/algorithm_name.hpp b/phlex/model/algorithm_name.hpp index ce82065ec..e8890192a 100644 --- a/phlex/model/algorithm_name.hpp +++ b/phlex/model/algorithm_name.hpp @@ -5,6 +5,9 @@ #include "phlex/phlex_model_export.hpp" #include +#include +#include +#include namespace phlex::experimental { class PHLEX_MODEL_EXPORT algorithm_name { @@ -14,10 +17,12 @@ namespace phlex::experimental { algorithm_name(std::string const& spec); algorithm_name(std::string_view spec); // NOLINTEND(google-explicit-constructor) - algorithm_name(identifier_or_empty plugin, identifier algorithm); + /// Constructs a name from an optional plugin qualifier and a required algorithm. + /// An unqualified name is represented by `std::nullopt`. + algorithm_name(std::optional plugin, identifier algorithm); std::string to_string() const; - identifier_or_empty const& plugin() const noexcept { return plugin_; } + std::optional const& plugin() const noexcept { return plugin_; } identifier const& algorithm() const noexcept { return algorithm_; } bool match(algorithm_name const& other) const; @@ -27,7 +32,7 @@ namespace phlex::experimental { static algorithm_name create(std::string_view spec); private: - identifier_or_empty plugin_; + std::optional plugin_; identifier algorithm_; }; diff --git a/phlex/model/handle.hpp b/phlex/model/handle.hpp index 0f5e4fd34..c13d52422 100644 --- a/phlex/model/handle.hpp +++ b/phlex/model/handle.hpp @@ -92,7 +92,9 @@ namespace phlex { algorithm_name_view creator() const noexcept { if (auto const& creator = spec_->creator()) { - return {creator->plugin().text(), std::string_view(creator->algorithm())}; + auto const& plugin = creator->plugin(); + return {plugin ? std::string_view(*plugin) : std::string_view{}, + std::string_view(creator->algorithm())}; } return {}; } diff --git a/phlex/model/product_specification.hpp b/phlex/model/product_specification.hpp index 75bcbe11f..5401808c3 100644 --- a/phlex/model/product_specification.hpp +++ b/phlex/model/product_specification.hpp @@ -67,7 +67,11 @@ struct std::hash { std::size_t hash = 0; boost::hash_combine(hash, spec.creator_.has_value()); if (spec.creator_) { - boost::hash_combine(hash, spec.creator_->plugin().hash()); + auto const& plugin = spec.creator_->plugin(); + boost::hash_combine(hash, plugin.has_value()); + if (plugin) { + boost::hash_combine(hash, plugin->hash()); + } boost::hash_combine(hash, spec.creator_->algorithm().hash()); } boost::hash_combine(hash, spec.suffix_.hash()); diff --git a/test/core_misc_test.cpp b/test/core_misc_test.cpp index cc8c44a60..5166cdbf7 100644 --- a/test/core_misc_test.cpp +++ b/test/core_misc_test.cpp @@ -1,5 +1,6 @@ #include "phlex/configuration.hpp" #include "phlex/core/declared_output.hpp" +#include "phlex/core/detail/make_algorithm_name.hpp" #include "phlex/core/glue.hpp" #include "phlex/core/registrar.hpp" #include "phlex/model/algorithm_name.hpp" @@ -12,6 +13,7 @@ #include #include +#include #include #include #include @@ -21,6 +23,7 @@ TEST_CASE("algorithm_name tests", "[model]") { using namespace phlex::detail; using namespace phlex::experimental; + using namespace phlex::experimental::literals; SECTION("Create from string with colon") { @@ -38,10 +41,50 @@ TEST_CASE("algorithm_name tests", "[model]") auto an = algorithm_name::create("ptr:algo"); CHECK(an.to_string() == "ptr:algo"); } + SECTION("Unqualified name has no plugin") + { + auto const an = algorithm_name::create("algo"); + CHECK_FALSE(an.plugin().has_value()); + CHECK(an.algorithm() == "algo"_id); + } + SECTION("Qualified name has plugin and algorithm") + { + auto const an = algorithm_name::create("plugin:algo"); + REQUIRE(an.plugin().has_value()); + CHECK(*an.plugin() == "plugin"_id); + CHECK(an.algorithm() == "algo"_id); + } + SECTION("Construct from typed components") + { + algorithm_name const unqualified{std::nullopt, "algo"_id}; + CHECK_FALSE(unqualified.plugin().has_value()); + CHECK(unqualified.to_string() == "algo"); + CHECK(unqualified == algorithm_name::create("algo")); + + algorithm_name const qualified{"plugin"_id, "algo"_id}; + REQUIRE(qualified.plugin().has_value()); + CHECK(qualified.to_string() == "plugin:algo"); + CHECK(qualified == algorithm_name::create("plugin:algo")); + CHECK(qualified != unqualified); + } SECTION("Create error - trailing colon") { CHECK_THROWS_AS(algorithm_name::create("plugin:"), std::runtime_error); } + SECTION("Create error - leading colon") + { + CHECK_THROWS_AS(algorithm_name::create(":algo"), std::runtime_error); + } + SECTION("Create error - multiple colons") + { + CHECK_THROWS_AS(algorithm_name::create("a:b:c"), std::runtime_error); + } + SECTION("Create error - malformed components") + { + CHECK_THROWS(algorithm_name::create("1plugin:algo")); + CHECK_THROWS(algorithm_name::create("plugin:1algo")); + CHECK_THROWS(algorithm_name::create("pl ugin:algo")); + } SECTION("Create error - empty name") { CHECK_THROWS_AS(algorithm_name::create(""), std::runtime_error); @@ -66,6 +109,34 @@ TEST_CASE("algorithm_name tests", "[model]") } } +TEST_CASE("make_algorithm_name tests", "[core]") +{ + using namespace phlex::experimental; + using namespace phlex::experimental::literals; + using internal::make_algorithm_name; + + SECTION("Without configuration the plugin is absent") + { + auto const name = make_algorithm_name(nullptr, "my_algorithm"); + CHECK_FALSE(name.plugin().has_value()); + CHECK(name.algorithm() == "my_algorithm"_id); + } + + SECTION("With configuration the module label is the plugin") + { + boost::json::object obj; + obj["module_label"] = "my_module"; + phlex::configuration const config{obj}; + + auto const name = make_algorithm_name(&config, "my_algorithm"); + REQUIRE(name.plugin().has_value()); + CHECK(*name.plugin() == "my_module"_id); + CHECK(name.to_string() == "my_module:my_algorithm"); + } + + SECTION("An empty algorithm name is rejected") { CHECK_THROWS(make_algorithm_name(nullptr, "")); } +} + TEST_CASE("verify_name tests", "[core]") { using namespace phlex::detail::internal; diff --git a/test/product_store_test.cpp b/test/product_store_test.cpp index 72ca5c63c..2d19c4e64 100644 --- a/test/product_store_test.cpp +++ b/test/product_store_test.cpp @@ -65,7 +65,7 @@ TEST_CASE("Product store default source", "[data model]") auto const source = product_store::default_source(); CHECK(source.to_string() == "Source"); CHECK(source.algorithm() == "Source"_id); - CHECK(source.plugin().empty()); + CHECK_FALSE(source.plugin().has_value()); CHECK(product_store::default_source() == source); } From 2b45c001576020ccc2c98bbcc5c326f2198473e1 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Mon, 16 Nov 2026 16:07:38 -0600 Subject: [PATCH 15/28] refactor(model)!: require a creator in product_specification A product_specification now always names its creator. The creator is a plain algorithm_name instead of std::optional, so every specification identifies the algorithm that produced it. Default construction and the creator-less (std::nullopt, suffix, type) constructor are removed. The text form must be `creator/suffix`. `creator/` denotes an explicit empty suffix. Bare text, `/suffix`, `/` and the empty string now throw std::runtime_error with a message that describes the expected form. Previously these were accepted as creator-less specifications. The text constructor now delegates to create() rather than assigning from it. Equality and std::hash cover the creator, suffix and type. The hash no longer mixes in a has-creator flag, because the creator is always present. Adapt callers to the non-optional creator: - provider_node copies the creator before the spec is moved and drops its creator-presence check, which can no longer fail. - product_selector matches against the always-present creator. - The product handle creator() view no longer needs an empty fallback. Tests are added for the following: - Constructibility and creator type. - Text parsing, including the rejected forms. - Round-tripping of `creator/`. - set_type mutation. - Hash and equality across all components. - Selector matching by creator, suffix and type. - Handle creator views. - Provider node naming. Existing tests are migrated to `creator/suffix` specifications. BREAKING CHANGE: product_specification no longer has a default constructor or a std::nullopt creator constructor. creator() returns algorithm_name const& rather than std::optional const&. Text specifications without a creator (e.g. "number", "/number") now throw std::runtime_error and must be written as "creator/number". --- phlex/core/product_selector.cpp | 2 +- phlex/core/provider_node.cpp | 14 +-- phlex/model/handle.hpp | 11 +-- phlex/model/product_specification.cpp | 42 ++++----- phlex/model/product_specification.hpp | 25 +++-- test/accumulator_test.cpp | 16 +++- test/product_handle_test.cpp | 31 +++++-- test/product_selector_test.cpp | 44 +++++++++ test/product_store_test.cpp | 126 ++++++++++++++++++++++---- test/provider_test.cpp | 27 +++--- test/repeater_node_test.cpp | 2 +- 11 files changed, 235 insertions(+), 105 deletions(-) diff --git a/phlex/core/product_selector.cpp b/phlex/core/product_selector.cpp index 9c20bd45e..46ac6c2b3 100644 --- a/phlex/core/product_selector.cpp +++ b/phlex/core/product_selector.cpp @@ -38,7 +38,7 @@ namespace phlex { // Check if a product_specification satisfies this query bool product_selector::match(experimental::product_specification const& spec) const { - if (creator && (!spec.creator() || !creator_match(*spec.creator()))) { + if (creator && !creator_match(spec.creator())) { return false; } if (type.valid() && type != spec.type()) { diff --git a/phlex/core/provider_node.cpp b/phlex/core/provider_node.cpp index 65133739b..c2cf7f1a3 100644 --- a/phlex/core/provider_node.cpp +++ b/phlex/core/provider_node.cpp @@ -11,23 +11,11 @@ #include #include #include -#include #include -namespace { - phlex::experimental::algorithm_name provider_creator( - phlex::experimental::product_specification const& spec) - { - if (!spec.creator()) { - throw std::runtime_error("Cannot create a provider without a product creator."); - } - return *spec.creator(); - } -} - namespace phlex::detail { provider_node::provider_node(tbb::flow::graph& g, provider_bundle bundle) : - provider_node{provider_creator(bundle.spec), + provider_node{bundle.spec.creator(), // copied before the spec is moved below bundle.max_concurrency.value, g, std::move(bundle.provider_function), diff --git a/phlex/model/handle.hpp b/phlex/model/handle.hpp index c13d52422..15e9e406d 100644 --- a/phlex/model/handle.hpp +++ b/phlex/model/handle.hpp @@ -7,7 +7,6 @@ #include -#include #include #include #include @@ -91,12 +90,10 @@ namespace phlex { // Product specification information algorithm_name_view creator() const noexcept { - if (auto const& creator = spec_->creator()) { - auto const& plugin = creator->plugin(); - return {plugin ? std::string_view(*plugin) : std::string_view{}, - std::string_view(creator->algorithm())}; - } - return {}; + auto const& creator = spec_->creator(); + auto const& plugin = creator.plugin(); + return {plugin ? std::string_view(*plugin) : std::string_view{}, + std::string_view(creator.algorithm())}; } std::string_view suffix() const noexcept { return spec_->suffix().text(); } std::string_view layer() const noexcept { return std::string_view(index_->layer_name()); } diff --git a/phlex/model/product_specification.cpp b/phlex/model/product_specification.cpp index f1f959825..61ff887f5 100644 --- a/phlex/model/product_specification.cpp +++ b/phlex/model/product_specification.cpp @@ -7,15 +7,14 @@ #include #include -#include #include +#include #include +#include #include #include namespace phlex::experimental { - product_specification::product_specification() = default; - product_specification::product_specification(char const* name) : product_specification{std::string_view{name}} { @@ -24,7 +23,10 @@ namespace phlex::experimental { product_specification{std::string_view{name}} { } - product_specification::product_specification(std::string_view name) { *this = create(name); } + product_specification::product_specification(std::string_view name) : + product_specification{create(name)} + { + } product_specification::product_specification(experimental::algorithm_name creator, experimental::suffix_t suffix, @@ -33,17 +35,9 @@ namespace phlex::experimental { { } - product_specification::product_specification(std::nullopt_t, suffix_t suffix, type_id type) : - suffix_{std::move(suffix)}, type_id_{std::move(type)} - { - } - std::string product_specification::to_string() const { - if (!creator_) { - return fmt::format("{}", suffix_); - } - return fmt::format("{}/{}", creator_->to_string(), suffix_); + return fmt::format("{}/{}", creator_.to_string(), suffix_); } product_specification product_specification::create(char const* c) @@ -53,16 +47,20 @@ namespace phlex::experimental { product_specification product_specification::create(std::string_view s) { - auto forward_slash = s.find('/'); - if (forward_slash != std::string_view::npos) { - if (forward_slash == 0) { - return {std::nullopt, suffix_t(s.substr(1)), type_id{}}; - } - return {experimental::algorithm_name::create(s.substr(0, forward_slash)), - experimental::suffix_t(s.substr(forward_slash + 1)), - type_id{}}; + auto const forward_slash = s.find('/'); + if (forward_slash == std::string_view::npos) { + throw std::runtime_error( + fmt::format("The specification '{}' is not a valid product specification: " + "expected the form 'creator/suffix' (use 'creator/' for an empty suffix).", + s)); + } + if (forward_slash == 0) { + throw std::runtime_error( + fmt::format("The product specification '{}' does not name a creator.", s)); } - return {std::nullopt, experimental::suffix_t(s), type_id{}}; + return {experimental::algorithm_name::create(s.substr(0, forward_slash)), + experimental::suffix_t(s.substr(forward_slash + 1)), + type_id{}}; } } diff --git a/phlex/model/product_specification.hpp b/phlex/model/product_specification.hpp index 5401808c3..bd25d90a4 100644 --- a/phlex/model/product_specification.hpp +++ b/phlex/model/product_specification.hpp @@ -8,8 +8,8 @@ #include -#include #include +#include #include #include @@ -20,20 +20,22 @@ namespace phlex::experimental { /// promoted to the stable phlex namespace. class PHLEX_MODEL_EXPORT product_specification { public: - product_specification(); + // There is no default or creator-less construction: every specification names its creator. + + // Text constructors parse the `creator/suffix` form, which must contain the slash. // NOLINTBEGIN(google-explicit-constructor) - Implicit conversion is intentional product_specification(char const* name); product_specification(std::string const& name); product_specification(std::string_view name); // NOLINTEND(google-explicit-constructor) product_specification(algorithm_name creator, suffix_t suffix, type_id type); - product_specification(std::nullopt_t, suffix_t suffix, type_id type); std::string to_string() const; - std::optional const& creator() const noexcept { return creator_; } + algorithm_name const& creator() const noexcept { return creator_; } suffix_t const& suffix() const noexcept { return suffix_; } type_id type() const noexcept { return type_id_; } + /// Sets, replaces, or clears (with a default-constructed `type_id`) the type. void set_type(type_id&& type) { type_id_ = std::move(type); } auto operator<=>(product_specification const&) const = default; @@ -44,7 +46,7 @@ namespace phlex::experimental { friend struct std::hash; private: - std::optional creator_; + experimental::algorithm_name creator_; experimental::suffix_t suffix_; type_id type_id_{}; }; @@ -65,15 +67,12 @@ struct std::hash { std::size_t operator()(phlex::experimental::product_specification const& spec) const noexcept { std::size_t hash = 0; - boost::hash_combine(hash, spec.creator_.has_value()); - if (spec.creator_) { - auto const& plugin = spec.creator_->plugin(); - boost::hash_combine(hash, plugin.has_value()); - if (plugin) { - boost::hash_combine(hash, plugin->hash()); - } - boost::hash_combine(hash, spec.creator_->algorithm().hash()); + auto const& plugin = spec.creator_.plugin(); + boost::hash_combine(hash, plugin.has_value()); + if (plugin) { + boost::hash_combine(hash, plugin->hash()); } + boost::hash_combine(hash, spec.creator_.algorithm().hash()); boost::hash_combine(hash, spec.suffix_.hash()); boost::hash_combine(hash, phlex::experimental::hash_value(spec.type_id_)); return hash; diff --git a/test/accumulator_test.cpp b/test/accumulator_test.cpp index 309757d22..654f56a74 100644 --- a/test/accumulator_test.cpp +++ b/test/accumulator_test.cpp @@ -1,9 +1,11 @@ #include "phlex/core/detail/accumulator_node.hpp" #include "phlex/core/message.hpp" +#include "phlex/model/algorithm_name.hpp" #include "phlex/model/data_cell_index.hpp" #include "phlex/model/fwd.hpp" #include "phlex/model/identifier.hpp" #include "phlex/model/product_specification.hpp" +#include "phlex/model/type_id.hpp" #include "test/ostream_logger.hpp" #include @@ -40,6 +42,14 @@ using phlex::experimental::product_specification; using phlex::experimental::product_specifications; namespace { + // The single product emitted by the accumulator: its creator is explicit and its suffix is empty. + product_specification result_specification() + { + return {phlex::experimental::algorithm_name{"accumulator"}, + phlex::experimental::suffix_t{}, + phlex::experimental::type_id{}}; + } + auto make_run_index(int run_number) { return phlex::data_cell_index::job()->make_child("run", run_number); @@ -60,7 +70,7 @@ namespace { { auto it = messages_.find(idx->hash()); assert(it != messages_.end()); - product_specification const spec{}; + auto const spec = result_specification(); return {it->second.store->get_product(gsl::make_not_null(&spec)), it->second.id}; } @@ -87,7 +97,7 @@ namespace { node_name, "test_stage"_id, "run"_id, - product_specifications(1), + product_specifications{result_specification()}, [](phlex::data_cell_index const&) { return std::make_unique(0); }}, fold_op_{g_, tbb::flow::unlimited, count_fold}, result_consumer_{g_} @@ -234,7 +244,7 @@ TEST_CASE("Test accumulator warning message if cache is not flushed", "[multithr "test_accumulator_warning", "test_stage"_id, "run"_id, - product_specifications(1), + product_specifications{result_specification()}, [](phlex::data_cell_index const&) { return std::make_unique(0); }); SECTION("Partition received, no flush") diff --git a/test/product_handle_test.cpp b/test/product_handle_test.cpp index 452b1c140..4df2942fa 100644 --- a/test/product_handle_test.cpp +++ b/test/product_handle_test.cpp @@ -58,8 +58,8 @@ TEST_CASE("Handle copies and moves", "[data model]") { int const two{2}; int const four{4}; - spec_t const two_spec{"two"}; - spec_t const four_spec{"four"}; + spec_t const two_spec{"creator/two"}; + spec_t const four_spec{"creator/four"}; auto job_data_cell = data_cell_index::job(); auto subrun_6_data_cell = job_data_cell->make_child("subrun", 6); @@ -88,8 +88,8 @@ TEST_CASE("Handle comparisons", "[data model]") { int const seventeen{17}; int const eighteen{18}; - spec_t const seventeen_spec{"seventeen"}; - spec_t const eighteen_spec{"eighteen"}; + spec_t const seventeen_spec{"creator/seventeen"}; + spec_t const eighteen_spec{"creator/eighteen"}; auto const h17 = make_handle(seventeen, *data_cell_index::job(), seventeen_spec); auto const h18 = make_handle(eighteen, *data_cell_index::job(), eighteen_spec); CHECK(h17 == h17); @@ -105,7 +105,7 @@ TEST_CASE("Handle comparisons", "[data model]") TEST_CASE("Handle type conversions (run-time checks)", "[data model]") { int const number{3}; - spec_t const spec{"number"}; + spec_t const spec{"creator/number"}; auto const h = make_handle(number, *data_cell_index::job(), spec); CHECK(h.data_cell_index() == *data_cell_index::job()); @@ -116,7 +116,7 @@ TEST_CASE("Handle type conversions (run-time checks)", "[data model]") CHECK(*num_ptr == number); composer const elgar{"Elgar"}; - spec_t const composer_spec{"composer"}; + spec_t const composer_spec{"creator/composer"}; auto const h2 = make_handle(elgar, *data_cell_index::job(), composer_spec); CHECK(h2->name == "Elgar"); } @@ -133,17 +133,28 @@ TEST_CASE("Retrieve product specification from handle", "[data model]") CHECK(h.stage() == "test_stage"); } -TEST_CASE("Retrieve absent creator from handle", "[data model]") +TEST_CASE("Retrieve plugin-qualified creator from handle", "[data model]") { int const number{3}; - spec_t const spec{"three"}; + spec_t const spec{"plugin:creator/three"}; auto const h = make_handle(number, *data_cell_index::job(), spec); - CHECK(h.creator().plugin.empty()); - CHECK(h.creator().algorithm.empty()); + CHECK(h.creator().plugin == "plugin"); + CHECK(h.creator().algorithm == "creator"); CHECK(h.suffix() == "three"); } +TEST_CASE("Retrieve unqualified creator and empty suffix from handle", "[data model]") +{ + int const number{3}; + spec_t const spec{"creator/"}; + auto const h = make_handle(number, *data_cell_index::job(), spec); + + CHECK(h.creator().plugin.empty()); + CHECK(h.creator().algorithm == "creator"); + CHECK(h.suffix().empty()); +} + TEST_CASE("Retrieve stage from handle", "[data model]") { int const number{3}; diff --git a/test/product_selector_test.cpp b/test/product_selector_test.cpp index d2eeece62..6b1c3e144 100644 --- a/test/product_selector_test.cpp +++ b/test/product_selector_test.cpp @@ -1,5 +1,8 @@ #include "phlex/core/product_selector.hpp" +#include "phlex/model/algorithm_name.hpp" #include "phlex/model/identifier.hpp" +#include "phlex/model/product_specification.hpp" +#include "phlex/model/type_id.hpp" #include #include @@ -85,3 +88,44 @@ TEST_CASE("Selectors do not move from lvalue arguments", "[data model]") CHECK(layer_string == "event"); CHECK(from_string.layer == second.layer); } + +TEST_CASE("Selectors match product specifications by creator, suffix, and type", "[data model]") +{ + using experimental::make_type_id; + using experimental::product_specification; + using experimental::suffix_t; + using experimental::type_id; + + product_specification const qualified{ + experimental::algorithm_name::create("plugin:algo"), "prod"_id, make_type_id()}; + product_specification const unqualified{ + experimental::algorithm_name::create("algo"), "prod"_id, make_type_id()}; + product_specification const empty_suffix{ + experimental::algorithm_name::create("algo"), suffix_t{}, type_id{}}; + + SECTION("A creator selects by plugin or by algorithm") + { + CHECK(product_selector{.creator = "plugin"}.match(qualified)); + CHECK(product_selector{.creator = "algo"}.match(qualified)); + CHECK(product_selector{.creator = "algo"}.match(unqualified)); + CHECK_FALSE(product_selector{.creator = "plugin"}.match(unqualified)); + CHECK_FALSE(product_selector{.creator = "other"}.match(qualified)); + } + SECTION("An omitted creator or suffix is a wildcard") + { + CHECK(product_selector{}.match(qualified)); + CHECK(product_selector{}.match(empty_suffix)); + CHECK(product_selector{.creator = "algo"}.match(empty_suffix)); + } + SECTION("An explicit empty suffix selects only the empty suffix") + { + CHECK(product_selector{.suffix = suffix_t{}}.match(empty_suffix)); + CHECK_FALSE(product_selector{.suffix = suffix_t{}}.match(unqualified)); + CHECK_FALSE(product_selector{.suffix = "prod"_id}.match(empty_suffix)); + } + SECTION("A selector type must equal a specified specification type") + { + CHECK(product_selector{.type = make_type_id()}.match(unqualified)); + CHECK_FALSE(product_selector{.type = make_type_id()}.match(unqualified)); + } +} diff --git a/test/product_store_test.cpp b/test/product_store_test.cpp index 2d19c4e64..aaf74520d 100644 --- a/test/product_store_test.cpp +++ b/test/product_store_test.cpp @@ -18,42 +18,128 @@ #include #include #include +#include #include +#include #include +#include #include using namespace phlex::experimental; using namespace phlex::experimental::literals; -TEST_CASE("Product specification leading slash omits the creator", "[data model]") +TEST_CASE("Product specification requires a creator", "[data model]") { - auto const spec = product_specification::create("/number"); - CHECK_FALSE(spec.creator().has_value()); - CHECK(spec.suffix() == "number"_id); + STATIC_CHECK_FALSE(std::is_default_constructible_v); + STATIC_CHECK_FALSE( + std::is_constructible_v); + STATIC_CHECK( + std::is_same_v().creator())>, + algorithm_name>); +} + +TEST_CASE("Product specification text requires creator and slash", "[data model]") +{ + SECTION("Creator with a named suffix") + { + auto const spec = product_specification::create("creator/number"); + CHECK(spec.creator() == algorithm_name::create("creator")); + CHECK_FALSE(spec.creator().plugin().has_value()); + CHECK(spec.suffix() == "number"_id); + CHECK_FALSE(spec.type().valid()); + CHECK(spec.to_string() == "creator/number"); + } + SECTION("Plugin-qualified creator") + { + auto const spec = product_specification::create("plugin:creator/number"); + CHECK(spec.creator() == algorithm_name::create("plugin:creator")); + CHECK(spec.suffix() == "number"_id); + CHECK(spec.to_string() == "plugin:creator/number"); + } + SECTION("Trailing slash means an explicit empty suffix") + { + auto const spec = product_specification::create("creator/"); + CHECK(spec.creator() == algorithm_name::create("creator")); + CHECK(spec.suffix() == suffix_t{}); + CHECK(spec.suffix().empty()); + CHECK(spec.to_string() == "creator/"); + CHECK(product_specification::create(spec.to_string()) == spec); + } + SECTION("Implicit conversion from text") + { + product_specification const from_literal{"plugin:creator/number"}; + CHECK(from_literal == product_specification::create("plugin:creator/number")); + product_specification const from_string{std::string{"creator/"}}; + CHECK(from_string == product_specification::create("creator/")); + product_specification const from_view{std::string_view{"creator/number"}}; + CHECK(from_view == product_specification::create("creator/number")); + } + SECTION("Invalid forms are rejected") + { + CHECK_THROWS(product_specification::create("")); + CHECK_THROWS(product_specification::create("number")); + CHECK_THROWS(product_specification::create("creator")); + CHECK_THROWS(product_specification::create("/number")); + CHECK_THROWS(product_specification::create("/")); + CHECK_THROWS(product_specification::create("plugin:/number")); + CHECK_THROWS(product_specification::create(":creator/number")); + CHECK_THROWS(product_specification::create("creator/a/b")); + CHECK_THROWS(product_specification{"number"}); + CHECK_THROWS(product_specification{std::string{"/number"}}); + } +} + +TEST_CASE("Product specification type mutation", "[data model]") +{ + auto spec = product_specification::create("creator/number"); + REQUIRE_FALSE(spec.type().valid()); + + spec.set_type(make_type_id()); + CHECK(spec.type() == make_type_id()); + + spec.set_type(make_type_id()); + CHECK(spec.type() == make_type_id()); + + spec.set_type(type_id{}); CHECK_FALSE(spec.type().valid()); + CHECK(spec == product_specification::create("creator/number")); + CHECK(spec.creator() == algorithm_name::create("creator")); + CHECK(spec.suffix() == "number"_id); } TEST_CASE("Product specification hash and equality", "[data model]") { auto const creator = algorithm_name::create("plugin:producer"); + auto const unqualified = algorithm_name::create("producer"); product_specification const named{creator, "number"_id, make_type_id()}; - product_specification const unnamed{std::nullopt, "number"_id, make_type_id()}; + product_specification const unqualified_spec{unqualified, "number"_id, make_type_id()}; + product_specification const untyped{creator, "number"_id, type_id{}}; + product_specification const empty_suffix{creator, suffix_t{}, make_type_id()}; std::hash const hash; CHECK(hash(named) == hash(product_specification{creator, "number"_id, make_type_id()})); - CHECK(hash(unnamed) == - hash(product_specification{std::nullopt, "number"_id, make_type_id()})); + CHECK(hash(untyped) == hash(product_specification{creator, "number"_id, type_id{}})); + CHECK(hash(empty_suffix) == + hash(product_specification{creator, suffix_t{}, make_type_id()})); + + // Every component participates in identity; an unspecified type is not a wildcard. + CHECK(named != unqualified_spec); + CHECK(named != untyped); + CHECK(named != empty_suffix); + CHECK(named != product_specification{creator, "other"_id, make_type_id()}); + CHECK(named != product_specification{creator, "number"_id, make_type_id()}); std::unordered_set specs; CHECK(specs.insert(named).second); - CHECK(specs.insert(unnamed).second); + CHECK(specs.insert(unqualified_spec).second); + CHECK(specs.insert(untyped).second); + CHECK(specs.insert(empty_suffix).second); CHECK_FALSE( specs.insert(product_specification{creator, "number"_id, make_type_id()}).second); - CHECK_FALSE( - specs.insert(product_specification{std::nullopt, "number"_id, make_type_id()}).second); - CHECK(specs.size() == 2u); + CHECK_FALSE(specs.insert(product_specification{creator, "number"_id, type_id{}}).second); + CHECK(specs.size() == 4u); CHECK(specs.contains(product_specification{creator, "number"_id, make_type_id()})); - CHECK(specs.contains(product_specification{std::nullopt, "number"_id, make_type_id()})); + CHECK(specs.contains(product_specification{unqualified, "number"_id, make_type_id()})); CHECK_FALSE(specs.contains(product_specification{creator, "other"_id, make_type_id()})); CHECK_FALSE(specs.contains(product_specification{creator, "number"_id, make_type_id()})); CHECK_FALSE(specs.contains(product_specification{ @@ -82,11 +168,11 @@ TEST_CASE("Product store insertion", "[data model]") constexpr int number = 4; std::vector many_numbers{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; - store->add_product("number", number); - store->add_product("numbers", many_numbers); - product_specification const number_spec{"number"}; - product_specification const numbers_spec{"numbers"}; - product_specification const wrong_spec{"wrong_key"}; + store->add_product("test_algorithm/number", number); + store->add_product("test_algorithm/numbers", many_numbers); + product_specification const number_spec{"test_algorithm/number"}; + product_specification const numbers_spec{"test_algorithm/numbers"}; + product_specification const wrong_spec{"test_algorithm/wrong_key"}; // Check number of products CHECK(store->size() == 2ull); @@ -94,10 +180,10 @@ TEST_CASE("Product store insertion", "[data model]") CHECK_THROWS_WITH( store->get_product(gsl::make_not_null(&number_spec)), Catch::Matchers::ContainsSubstring( - "Cannot get product 'number' with type 'double' -- must specify type 'int'.")); + "Cannot get product 'test_algorithm/number' with type 'double' -- must specify type 'int'.")); - auto const matcher = - Catch::Matchers::ContainsSubstring("No product exists with the specification 'wrong_key'."); + auto const matcher = Catch::Matchers::ContainsSubstring( + "No product exists with the specification 'test_algorithm/wrong_key'."); CHECK_THROWS_WITH(store->get_handle(gsl::make_not_null(&wrong_spec)), matcher); CHECK(store->get_product(gsl::make_not_null(&number_spec)) == number); diff --git a/test/provider_test.cpp b/test/provider_test.cpp index a9b7f2c9b..472afa0b9 100644 --- a/test/provider_test.cpp +++ b/test/provider_test.cpp @@ -19,8 +19,6 @@ #include #include -#include -#include #include #include @@ -98,21 +96,20 @@ namespace { unsigned pass_on(vertex_collection const& vertices) { return vertices.data; } } -TEST_CASE("Provider nodes reject product specifications without a creator") +TEST_CASE("Provider nodes take their name from the advertised product creator") { tbb::flow::graph graph; - provider_bundle const bundle{ - .provider_function = give_me_vertices_erased, - .max_concurrency = concurrency::unlimited, - .spec = experimental::product_specification{std::nullopt, - "happy_vertices", - experimental::make_type_id()}, - .layer = "spill", - .stage = "previous_process"}; - - CHECK_THROWS_AS((detail::provider_node{graph, bundle}), std::runtime_error); - CHECK_THROWS_WITH((detail::provider_node{graph, bundle}), - "Cannot create a provider without a product creator."); + experimental::product_specification const spec{ + "reco:vertices_maker", "happy_vertices", experimental::make_type_id()}; + provider_bundle const bundle{.provider_function = give_me_vertices_erased, + .max_concurrency = concurrency::unlimited, + .spec = spec, + .layer = "spill", + .stage = "previous_process"}; + + detail::provider_node const node{graph, bundle}; + CHECK(node.name() == spec.creator()); + CHECK(node.output_product() == spec); } TEST_CASE("Explicit providers") diff --git a/test/repeater_node_test.cpp b/test/repeater_node_test.cpp index b7fb4af95..5eb383cae 100644 --- a/test/repeater_node_test.cpp +++ b/test/repeater_node_test.cpp @@ -38,7 +38,7 @@ namespace { auto index = make_run_index(run_number); auto store = std::make_shared( index, gsl::not_null{&dummy_creator_name}, gsl::not_null{&dummy_stage_name}); - store->add_product("value", value); + store->add_product("test_algorithm/value", value); return std::pair{index, store}; } From 8f979d9cf607c46c5c13ab36247136613504598e Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Tue, 17 Nov 2026 14:20:25 -0600 Subject: [PATCH 16/28] refactor(model)!: validate algorithm names once with uniform errors Algorithm-name text was checked twice by different rules. A private character precheck accepted `[A-Za-z0-9_[]]`, and the identifier constructor then re-validated with the stricter identifier grammar, so `_x`, `1p:a` and `a[0]` passed the first check and failed the second, with different exception types and unrelated messages. The identifier grammar is now the only character rule. The precheck is deleted. algorithm_name::create(text) parses structure and delegates to a new public create(optional plugin, string_view algorithm) overload, which constructs the identifiers, catches their failure, and rethrows with the composed name, the failing part (plugin label or algorithm), and the rule. make_algorithm_name uses the same overload, and the separate verify_name empty-name check is removed. All malformed algorithm-name text now throws std::invalid_argument, which the Python bindings report as ValueError. Messages quote the offending text with fmt's `{:?}`, shortened to 64 characters, through one private helper that identifier and algorithm_name share. Report the field at each parse boundary: - Product selectors read from configuration or Python name the field (creator, layer, suffix, stage) that held the bad text. - Python provider outputs name the field the same way. - form_source parses its `creator` parameter once at registration and stores the algorithm_name instead of reparsing it per product. - load_module and load_source check the configuration label, which becomes the plugin label of everything the entry registers, and name the `modules` or `sources` section. Remove identifier::empty(). An identifier is never empty, so its only production uses were unreachable checks in creator_name and layer_name, which are deleted along with their messages. Add nothrow STATIC_CHECKs for identifier_or_empty. Tests cover create and its overload, make_algorithm_name, product_specification::create, the config boundaries, label validation, and Python ValueError reports. BREAKING CHANGE: malformed algorithm names throw std::invalid_argument instead of std::runtime_error, characters `[` and `]` are no longer accepted in a name, identifier::empty() is removed, and a module or source label that is not a valid identifier is rejected when loaded. --- form/form_source.cpp | 19 ++-- phlex/app/plugin_loading.cpp | 16 +++ phlex/configuration.cpp | 25 ++++- phlex/core/CMakeLists.txt | 1 - phlex/core/detail/make_algorithm_name.cpp | 8 +- phlex/core/glue.cpp | 25 ----- phlex/core/glue.hpp | 9 -- phlex/core/product_selector.hpp | 12 --- phlex/model/algorithm_name.cpp | 87 ++++++++-------- phlex/model/algorithm_name.hpp | 16 ++- phlex/model/detail/excerpt.hpp | 28 ++++++ phlex/model/identifier.cpp | 9 +- phlex/model/identifier.hpp | 6 +- plugins/python/src/modulewrap.cpp | 15 ++- test/adjust_config_test.cpp | 18 ++++ test/config_test.cpp | 17 +++- test/core_misc_test.cpp | 115 ++++++++++++++++------ test/form/CMakeLists.txt | 18 ++++ test/form/form_source_bad_creator.jsonnet | 17 ++++ test/identifier_test.cpp | 29 ++++++ test/product_selector_test.cpp | 5 +- test/product_store_test.cpp | 5 + test/python/CMakeLists.txt | 12 +++ test/python/badname.py | 27 +++++ test/python/pybadname.jsonnet | 18 ++++ test/python/pyprovide.py | 21 ++++ test/python/suffix.py | 14 +++ 27 files changed, 449 insertions(+), 143 deletions(-) delete mode 100644 phlex/core/glue.cpp create mode 100644 phlex/model/detail/excerpt.hpp create mode 100644 test/form/form_source_bad_creator.jsonnet create mode 100644 test/python/badname.py create mode 100644 test/python/pybadname.jsonnet diff --git a/form/form_source.cpp b/form/form_source.cpp index 922a5db30..1456f4a52 100644 --- a/form/form_source.cpp +++ b/form/form_source.cpp @@ -77,7 +77,7 @@ namespace { form_input_source(form::experimental::config::item_config const& input_cfg, form::experimental::config::tech_setting_config const& tech_cfg, std::string actual_creator, - std::string advertised_creator, + phlex::experimental::algorithm_name advertised_creator, std::string stage, std::vector const& products) : reader_(std::make_shared(input_cfg, tech_cfg)), @@ -102,8 +102,7 @@ namespace { } for (auto const& name : products_) { - product_specification spec{ - algorithm_name::create(advertised_creator_), suffix_t{name}, selector.type}; + product_specification spec{advertised_creator_, suffix_t{name}, selector.type}; // Read and provide products at the configured stage. identifier const selector_layer = selector.layer; @@ -167,7 +166,7 @@ namespace { private: std::shared_ptr reader_; std::string actual_creator_; - std::string advertised_creator_; + phlex::experimental::algorithm_name advertised_creator_; std::string stage_; std::vector products_; }; @@ -178,12 +177,20 @@ PHLEX_REGISTER_SOURCE(s, config) std::cout << "Registering FORM input source...\n"; auto const input_file = config.get("input_file"); - auto const advertised_creator = config.get("creator"); + auto const creator_text = config.get("creator"); + // Parse the creator once, here, where its parameter name is known. + auto const advertised_creator = [&creator_text] { + try { + return phlex::experimental::algorithm_name::create(creator_text); + } catch (std::invalid_argument const& e) { + throw std::invalid_argument{std::string{"Invalid parameter 'creator': "} + e.what()}; + } + }(); auto const module_label = config.get("module_label", "form_source"); auto const products = config.get>("products"); auto const stage = config.get("stage"); - std::string actual_creator = advertised_creator; + std::string actual_creator = creator_text; auto const algorithm = config.get_if_present("algorithm"); auto const plugin = config.get_if_present("plugin"); if (algorithm && plugin && !algorithm->empty() && !plugin->empty()) { diff --git a/phlex/app/plugin_loading.cpp b/phlex/app/plugin_loading.cpp index 389756e7d..820e6f8f6 100644 --- a/phlex/app/plugin_loading.cpp +++ b/phlex/app/plugin_loading.cpp @@ -5,6 +5,7 @@ #include "phlex/core/graph_proxy.hpp" #include "phlex/driver.hpp" #include "phlex/metaprogramming/type_deduction.hpp" +#include "phlex/model/identifier.hpp" #include "phlex/module.hpp" #include "phlex/resource.hpp" #include "phlex/source.hpp" @@ -32,6 +33,19 @@ namespace phlex::detail { namespace { constexpr std::string_view pymodule_name{"pymodule"}; + // The label of a module or source becomes the plugin label of every algorithm that it + // registers. Checking it where the user wrote it lets the message name the configuration + // section, which the algorithm-name error raised later could not. + void verify_label(std::string_view section, std::string const& label) + { + try { + experimental::identifier const checked{label}; + } catch (std::invalid_argument const&) { + throw std::invalid_argument{fmt::format( + "Invalid label {:?} for an entry in \"{}\": it {}", label, section, identifier_rule)}; + } + } + // The shared_library member in each wrapper struct keeps the loaded .so // alive for the lifetime of the wrapper. If it goes out of scope, the // library is unloaded and the stored function pointer becomes invalid. @@ -143,6 +157,7 @@ namespace phlex::detail { void load_module(framework_graph& g, std::string const& label, boost::json::object raw_config) { + verify_label("modules", label); auto const adjusted_config = internal::adjust_config(label, std::move(raw_config)); auto const& spec = value_to(adjusted_config.at("cpp")); @@ -173,6 +188,7 @@ namespace phlex::detail { void load_source(framework_graph& g, std::string const& label, boost::json::object raw_config) { + verify_label("sources", label); auto const adjusted_config = internal::adjust_config(label, std::move(raw_config)); auto const& spec = value_to(adjusted_config.at("cpp")); diff --git a/phlex/configuration.cpp b/phlex/configuration.cpp index fcaaa23ae..988471a8d 100644 --- a/phlex/configuration.cpp +++ b/phlex/configuration.cpp @@ -34,6 +34,20 @@ namespace phlex::detail { } namespace phlex { + namespace { + // Reports a malformed value together with the name of the product selector field that held it. + template + auto in_selector_field(std::string_view field, Convert&& convert) + { + try { + return std::forward(convert)(); + } catch (std::invalid_argument const& e) { + throw std::invalid_argument{ + fmt::format("Invalid product selector field \"{}\": {}", field, e.what())}; + } + } + } + std::vector configuration::keys() const { std::vector result; @@ -67,13 +81,16 @@ namespace phlex { throw std::runtime_error( fmt::format("Product selector contains unrecognized keys: {}", unrecognized_keys)); } - auto creator = value_if_exists(query_object, "creator"); - auto layer = value_if_exists(query_object, "layer"); + auto creator = + in_selector_field("creator", [&] { return value_if_exists(query_object, "creator"); }); + auto layer = in_selector_field("layer", [&] { return value_if_exists(query_object, "layer"); }); std::optional suffix; if (query_object.contains("suffix")) { - suffix.emplace(std::string_view{query_object.at("suffix").as_string()}); + suffix = in_selector_field("suffix", [&] { + return experimental::suffix_t{std::string_view{query_object.at("suffix").as_string()}}; + }); } - auto stage = value_if_exists(query_object, "stage"); + auto stage = in_selector_field("stage", [&] { return value_if_exists(query_object, "stage"); }); return product_selector{.creator = std::move(creator), .layer = std::move(layer), .suffix = std::move(suffix), diff --git a/phlex/core/CMakeLists.txt b/phlex/core/CMakeLists.txt index 37d37dc75..5eafa0b55 100644 --- a/phlex/core/CMakeLists.txt +++ b/phlex/core/CMakeLists.txt @@ -17,7 +17,6 @@ cet_make_library( detail/repeater_node.cpp filter.cpp framework_graph.cpp - glue.cpp index_router.cpp make_computational_edges.cpp message.cpp diff --git a/phlex/core/detail/make_algorithm_name.cpp b/phlex/core/detail/make_algorithm_name.cpp index 06cd1f3c9..8bc7f2d0c 100644 --- a/phlex/core/detail/make_algorithm_name.cpp +++ b/phlex/core/detail/make_algorithm_name.cpp @@ -2,19 +2,17 @@ #include "phlex/configuration.hpp" #include "phlex/model/algorithm_name.hpp" -#include "phlex/model/identifier.hpp" #include #include -#include namespace phlex::experimental::internal { algorithm_name make_algorithm_name(configuration const* config, std::string_view name) { - std::optional plugin; + std::optional plugin_label; if (config) { - plugin.emplace(config->get("module_label")); + plugin_label = config->get("module_label"); } - return {std::move(plugin), identifier(name)}; + return algorithm_name::create(plugin_label, name); } } diff --git a/phlex/core/glue.cpp b/phlex/core/glue.cpp deleted file mode 100644 index 6637d3b64..000000000 --- a/phlex/core/glue.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "phlex/core/glue.hpp" - -#include "phlex/configuration.hpp" - -#include -#include -#include - -namespace phlex::detail::internal { - void verify_name(std::string_view name, configuration const* config) - { - if (not name.empty()) { - return; - } - - std::string msg{"Cannot specify algorithm with no name"}; - std::string const module = config ? config->get("module_label") : ""; - if (!module.empty()) { - msg += " (module: '"; - msg += module; - msg += "')"; - } - throw std::runtime_error{msg}; - } -} diff --git a/phlex/core/glue.hpp b/phlex/core/glue.hpp index ae63b33b8..a7aef3f7c 100644 --- a/phlex/core/glue.hpp +++ b/phlex/core/glue.hpp @@ -28,9 +28,6 @@ namespace phlex { namespace phlex::detail { struct node_catalog; - namespace internal { - PHLEX_CORE_EXPORT void verify_name(std::string_view name, configuration const* config); - } // ============================================================================== // Registering user functions @@ -73,7 +70,6 @@ namespace phlex::detail { std::string partition, InitArgs&&... init_args) { - internal::verify_name(name, config_); return fold_api{config_, name, stage_, @@ -94,7 +90,6 @@ namespace phlex::detail { FT f, // NOLINT(performance-unnecessary-value-param) concurrency c) { - internal::verify_name(name, config_); return make_registration( config_, name, @@ -114,7 +109,6 @@ namespace phlex::detail { FT f, // NOLINT(performance-unnecessary-value-param) concurrency c) { - internal::verify_name(name, config_); return provider_api{config_, name, stage_, @@ -133,7 +127,6 @@ namespace phlex::detail { FT f, // NOLINT(performance-unnecessary-value-param) concurrency c) { - internal::verify_name(name, config_); return make_registration( config_, name, @@ -153,7 +146,6 @@ namespace phlex::detail { FT f, // NOLINT(performance-unnecessary-value-param) concurrency c) { - internal::verify_name(name, config_); return make_registration( config_, name, @@ -173,7 +165,6 @@ namespace phlex::detail { std::string destination_data_layer) { assert(!bound_obj_); - internal::verify_name(name, config_); return unfold_api{ config_, name, diff --git a/phlex/core/product_selector.hpp b/phlex/core/product_selector.hpp index b468ee28c..08b48f111 100644 --- a/phlex/core/product_selector.hpp +++ b/phlex/core/product_selector.hpp @@ -27,18 +27,12 @@ namespace phlex { creator_name() = default; creator_name(std::optional&& content) : content_{std::move(content)} { - if (content_ && content_.value().empty()) { - throw std::runtime_error("Cannot specify product with empty creator name."); - } } template requires std::constructible_from // NOLINTNEXTLINE(google-explicit-constructor) - Implicit conversion is intentional creator_name(U&& rhs) : content_(std::forward(rhs)) { - if (content_.value().empty()) { - throw std::runtime_error("Cannot specify product with empty creator name."); - } } operator bool() const noexcept { return content_.has_value(); } @@ -58,18 +52,12 @@ namespace phlex { layer_name() = default; layer_name(std::optional&& content) : content_{std::move(content)} { - if (content_ && content_.value().empty()) { - throw std::runtime_error("Cannot specify the empty string as a data layer."); - } } template requires std::constructible_from // NOLINTNEXTLINE(google-explicit-constructor) - Implicit conversion is intentional layer_name(U&& rhs) : content_(std::forward(rhs)) { - if (content_.value().empty()) { - throw std::runtime_error("Cannot specify the empty string as a data layer."); - } } // NOLINTNEXTLINE(google-explicit-constructor) - Implicit conversion is intentional diff --git a/phlex/model/algorithm_name.cpp b/phlex/model/algorithm_name.cpp index a38e894ef..f6d81d0c3 100644 --- a/phlex/model/algorithm_name.cpp +++ b/phlex/model/algorithm_name.cpp @@ -1,10 +1,10 @@ #include "phlex/model/algorithm_name.hpp" +#include "phlex/model/detail/excerpt.hpp" #include "phlex/model/identifier.hpp" #include -#include #include #include #include @@ -12,27 +12,29 @@ #include namespace { - // Check if a char is a word (\w) char - // Only care about C locale (ASCII) for now - bool is_word(char c) + constexpr std::string_view expected_forms{R"(Expected "algorithm" or "plugin_label:algorithm".)"}; + + [[noreturn]] void throw_invalid(std::string_view name, std::string_view reason) { - if ('0' <= c && c <= '9') { - return true; - } - if ('A' <= c && c <= 'Z') { - return true; - } - if ('a' <= c && c <= 'z') { - return true; - } - if (c == '_' || c == '[' || c == ']') { - return true; - } - return false; + throw std::invalid_argument{ + fmt::format("Invalid algorithm name {}: {}", phlex::detail::excerpt(name), reason)}; } - // Check that a string_view only contains word chars - bool words_only(std::string_view str) { return std::ranges::all_of(str, is_word); } + // Constructing an identifier is the one place where character rules are checked. The + // identifier's own message is replaced with one that says which part of the name is at fault. + phlex::experimental::identifier make_identifier(std::string_view name, + std::string_view part, + std::string_view text) + { + try { + return phlex::experimental::identifier{text}; + } catch (std::invalid_argument const&) { + throw_invalid( + name, + fmt::format( + "{} {} {}", part, phlex::detail::excerpt(text), phlex::detail::identifier_rule)); + } + } } namespace phlex::experimental { @@ -58,33 +60,40 @@ namespace phlex::experimental { bool algorithm_name::match(algorithm_name const& other) const { return operator==(other); } algorithm_name algorithm_name::create(char const* spec) { return create(std::string_view{spec}); } + algorithm_name algorithm_name::create(std::string_view spec) { - if (spec.empty()) { - throw std::runtime_error("Cannot create an empty algorithm name."); + auto const colon = spec.find(':'); + if (colon == std::string_view::npos) { + return create(std::nullopt, spec); } + auto const algorithm = spec.substr(colon + 1); + if (algorithm.contains(':')) { + throw_invalid(spec, fmt::format("it contains more than one ':'. {}", expected_forms)); + } + return create(spec.substr(0, colon), algorithm); + } - // Do we have a colon? If so, have both plugin and algorithm - if (spec.contains(':')) { - if (spec.ends_with(':')) { - throw std::runtime_error("Cannot create an algorithm name that ends with a colon (':')"); - } - auto const colon_pos = spec.find(':'); - std::string_view const plugin = spec.substr(0, colon_pos); - std::string_view const algorithm = spec.substr(colon_pos + 1); // +1 OK, : not at end + algorithm_name algorithm_name::create(std::optional plugin, + std::string_view algorithm) + { + auto const name = plugin ? fmt::format("{}:{}", *plugin, algorithm) : std::string{algorithm}; - if (plugin.empty() || !words_only(plugin) || !words_only(algorithm)) { - throw std::runtime_error( - fmt::format("The specification '{}' is not a valid algorithm name.", spec)); - } - return {std::optional{identifier(plugin)}, identifier(algorithm)}; + if (!plugin && algorithm.empty()) { + throw_invalid(name, fmt::format("it is empty. {}", expected_forms)); + } + if (plugin && plugin->empty()) { + throw_invalid(name, + fmt::format("the plugin label before ':' is missing. {}", expected_forms)); + } + if (plugin && algorithm.empty()) { + throw_invalid(name, fmt::format("the algorithm after ':' is missing. {}", expected_forms)); } - // No colon -- could be plugin or algorithm - if (!words_only(spec)) { - throw std::runtime_error( - fmt::format("The specification '{}' is not a valid algorithm name.", spec)); + std::optional plugin_label; + if (plugin) { + plugin_label.emplace(make_identifier(name, "plugin label", *plugin)); } - return {std::nullopt, identifier(spec)}; + return {std::move(plugin_label), make_identifier(name, "algorithm", algorithm)}; } } diff --git a/phlex/model/algorithm_name.hpp b/phlex/model/algorithm_name.hpp index e8890192a..41300ce02 100644 --- a/phlex/model/algorithm_name.hpp +++ b/phlex/model/algorithm_name.hpp @@ -17,7 +17,7 @@ namespace phlex::experimental { algorithm_name(std::string const& spec); algorithm_name(std::string_view spec); // NOLINTEND(google-explicit-constructor) - /// Constructs a name from an optional plugin qualifier and a required algorithm. + /// Constructs a name from an optional plugin label and a required algorithm. /// An unqualified name is represented by `std::nullopt`. algorithm_name(std::optional plugin, identifier algorithm); @@ -28,9 +28,23 @@ namespace phlex::experimental { bool match(algorithm_name const& other) const; auto operator<=>(algorithm_name const&) const noexcept = default; + /// Parses `spec`, which is either `algorithm` or `plugin_label:algorithm`. + /// + /// Throws `std::invalid_argument` if `spec` is malformed. The message quotes the offending + /// text and says which part of the name is invalid and why. Only the first problem found is + /// reported. static algorithm_name create(char const* spec); static algorithm_name create(std::string_view spec); + /// Validates the components of a name and constructs it. This is the single place where + /// the text of an algorithm name is checked: the character rules are those of `identifier`, + /// and failures are reported as described for `create(std::string_view)`. + /// + /// An unqualified name is represented by `std::nullopt`. An empty `plugin` is not the same + /// as `std::nullopt`; it is rejected. + static algorithm_name create(std::optional plugin, + std::string_view algorithm); + private: std::optional plugin_; identifier algorithm_; diff --git a/phlex/model/detail/excerpt.hpp b/phlex/model/detail/excerpt.hpp new file mode 100644 index 000000000..069165ae3 --- /dev/null +++ b/phlex/model/detail/excerpt.hpp @@ -0,0 +1,28 @@ +#ifndef PHLEX_MODEL_DETAIL_EXCERPT_HPP +#define PHLEX_MODEL_DETAIL_EXCERPT_HPP + +// Private to the phlex_model library; this header is intentionally not installed. + +#include + +#include +#include +#include + +namespace phlex::detail { + /// The longest amount of user-supplied text quoted in an error message. + inline constexpr std::size_t max_excerpt_length{64}; + + /// Quotes and escapes `text` for an error message, shortening it with a trailing `...` + /// inside the quotes when it exceeds `max_excerpt_length` characters. + inline std::string excerpt(std::string_view text) + { + std::string shown{text.substr(0, max_excerpt_length)}; + if (text.size() > max_excerpt_length) { + shown += "..."; + } + return fmt::format("{:?}", shown); + } +} + +#endif // PHLEX_MODEL_DETAIL_EXCERPT_HPP diff --git a/phlex/model/identifier.cpp b/phlex/model/identifier.cpp index a90276368..b8e5d4ac0 100644 --- a/phlex/model/identifier.cpp +++ b/phlex/model/identifier.cpp @@ -1,5 +1,9 @@ #include "phlex/model/identifier.hpp" +#include "phlex/model/detail/excerpt.hpp" + +#include + #include #include #include @@ -11,8 +15,9 @@ namespace phlex::experimental { void validate_identifier(std::string_view str) { if (!phlex::detail::valid_identifier(str)) { - throw std::invalid_argument{"Invalid identifier: expected an ASCII letter followed by " - "ASCII letters, digits, or underscores"}; + throw std::invalid_argument{fmt::format("Invalid identifier {}: it {}", + phlex::detail::excerpt(str), + phlex::detail::identifier_rule)}; } } } diff --git a/phlex/model/identifier.hpp b/phlex/model/identifier.hpp index 9960ab6af..3460fcdef 100644 --- a/phlex/model/identifier.hpp +++ b/phlex/model/identifier.hpp @@ -18,6 +18,11 @@ #include namespace phlex::detail { + /// The rule enforced by `valid_identifier`, phrased to follow a subject (for example, + /// "it" or `algorithm "x"`) in error messages. + inline constexpr std::string_view identifier_rule{ + "must start with an ASCII letter and contain only ASCII letters, digits, or underscores"}; + // This implementation does not use std::regex for the validation because // std::regex does not support compile-time regular expressions. constexpr bool valid_identifier(std::string_view text) noexcept @@ -79,7 +84,6 @@ namespace phlex::experimental { bool operator==(identifier const& rhs) const noexcept; std::strong_ordering operator<=>(identifier const& rhs) const noexcept; - bool empty() const noexcept { return content_.empty(); } std::size_t hash() const noexcept { return hash_; } // transitional access to contained string diff --git a/plugins/python/src/modulewrap.cpp b/plugins/python/src/modulewrap.cpp index 6de3d6b19..de077ce8e 100644 --- a/plugins/python/src/modulewrap.cpp +++ b/plugins/python/src/modulewrap.cpp @@ -304,7 +304,13 @@ namespace { if (!text) { return std::nullopt; } - return T{std::string_view{text, static_cast(size)}}; + try { + return T{std::string_view{text, static_cast(size)}}; + } catch (std::invalid_argument const& e) { + // Name the dictionary key so that the user can tell which field is at fault. + throw std::invalid_argument{ + fmt::format("Invalid product selector field \"{}\": {}", item, e.what())}; + } } inline std::optional validate_selector(PyObject* pysel, @@ -390,6 +396,9 @@ namespace { return std::nullopt; } std::string result(p, static_cast(sz)); + // Validate the text where it arrives from the user. Names derived from it later (for + // example, with a "_py" suffix) are valid by construction, so this is the one check that + // can quote exactly what the user wrote. suffix_t const checked{result}; return result; }); @@ -947,6 +956,9 @@ namespace { } functor_name.assign(name_text, static_cast(name_size)); Py_DECREF(pyname); + // Validate the name where it arrives from the user. Names derived from it later (for + // example, "_arg0_py") are valid by construction, so this is the one check that can + // quote exactly what the user wrote. identifier const checked_name{std::string_view{functor_name}}; if (!input) { @@ -1535,7 +1547,6 @@ namespace { PyErr_SetString(PyExc_TypeError, "a provider must have an output"); return std::nullopt; } - identifier const checked_name{std::string_view{name}}; return provider_registration{ .callable = callable, .output = output, .name = name, .output_type = output_types[0]}; } diff --git a/test/adjust_config_test.cpp b/test/adjust_config_test.cpp index c1f37b195..a11f17974 100644 --- a/test/adjust_config_test.cpp +++ b/test/adjust_config_test.cpp @@ -1,12 +1,15 @@ #include "phlex/app/plugin_loading.hpp" #include "phlex/app/run.hpp" #include "phlex/core/framework_graph.hpp" +#include "phlex/model/identifier.hpp" #include #include #include #include +#include +#include #include using namespace phlex::detail::internal; @@ -74,6 +77,21 @@ TEST_CASE("Loading resources requires a cpp parameter", "[config]") "Missing 'cpp' parameter for my_resource -- only C++ resources are supported.")); } +TEST_CASE("Module and source labels must be valid identifiers", "[config]") +{ + auto graph = phlex::detail::framework_graph::without_driver("test"); + auto const rule = std::string{phlex::detail::identifier_rule}; + + CHECK_THROWS_AS(phlex::detail::load_module(graph, "my-module", {}), std::invalid_argument); + CHECK_THROWS_WITH(phlex::detail::load_module(graph, "my-module", {}), + "Invalid label \"my-module\" for an entry in \"modules\": it " + rule); + CHECK_THROWS_AS(phlex::detail::load_source(graph, "1source", {}), std::invalid_argument); + CHECK_THROWS_WITH(phlex::detail::load_source(graph, "1source", {}), + "Invalid label \"1source\" for an entry in \"sources\": it " + rule); + CHECK_THROWS_WITH(phlex::detail::load_source(graph, "", {}), + "Invalid label \"\" for an entry in \"sources\": it " + rule); +} + TEST_CASE("A stage is required to run phlex", "[config]") { CHECK_THROWS_WITH( diff --git a/test/config_test.cpp b/test/config_test.cpp index 7f84dcac4..3dedd0c89 100644 --- a/test/config_test.cpp +++ b/test/config_test.cpp @@ -60,6 +60,10 @@ TEST_CASE("Retrieve product_selector", "[config]") boost::json::object malformed_input4 = input; malformed_input4["stag"] = "simulation"; + boost::json::object malformed_input5; + malformed_input5["creator"] = "hits"; + malformed_input5["suffix"] = "bad name"; + boost::json::object underlying_config; underlying_config["input"] = std::move(input); underlying_config["unconstrained"] = std::move(unconstrained_input); @@ -67,6 +71,7 @@ TEST_CASE("Retrieve product_selector", "[config]") underlying_config["malformed2"] = std::move(malformed_input2); underlying_config["malformed3"] = std::move(malformed_input3); underlying_config["malformed4"] = std::move(malformed_input4); + underlying_config["malformed5"] = std::move(malformed_input5); configuration const config{underlying_config}; auto input_query = config.get("input"); @@ -80,11 +85,17 @@ TEST_CASE("Retrieve product_selector", "[config]") ContainsSubstring("not a string")); CHECK_THROWS_WITH(config.get("malformed2"), ContainsSubstring("Error retrieving parameter 'malformed2'") && - ContainsSubstring("Invalid identifier")); + ContainsSubstring("Invalid product selector field \"layer\": " + "Invalid identifier \"\": it must start with")); CHECK_THROWS_WITH(config.get("malformed3"), ContainsSubstring("Error retrieving parameter 'malformed3'") && - ContainsSubstring("Invalid identifier")); + ContainsSubstring("Invalid product selector field \"creator\": " + "Invalid identifier \"\": it must start with")); CHECK_THROWS_WITH(config.get("malformed4"), ContainsSubstring("Error retrieving parameter 'malformed4'") && - ContainsSubstring("Product selector contains unrecognized keys")); + ContainsSubstring("Product selector contains unrecognized keys")); + CHECK_THROWS_WITH(config.get("malformed5"), + ContainsSubstring("Error retrieving parameter 'malformed5'") && + ContainsSubstring("Invalid product selector field \"suffix\": " + "Invalid identifier \"bad name\": it must start with")); } diff --git a/test/core_misc_test.cpp b/test/core_misc_test.cpp index 5166cdbf7..8d7044a50 100644 --- a/test/core_misc_test.cpp +++ b/test/core_misc_test.cpp @@ -10,12 +10,14 @@ #include #include #include +#include #include #include #include #include #include +#include #include #include @@ -67,28 +69,64 @@ TEST_CASE("algorithm_name tests", "[model]") CHECK(qualified == algorithm_name::create("plugin:algo")); CHECK(qualified != unqualified); } - SECTION("Create error - trailing colon") + SECTION("Create error - structural problems are reported as invalid_argument") { - CHECK_THROWS_AS(algorithm_name::create("plugin:"), std::runtime_error); - } - SECTION("Create error - leading colon") - { - CHECK_THROWS_AS(algorithm_name::create(":algo"), std::runtime_error); + auto const forms = R"( Expected "algorithm" or "plugin_label:algorithm".)"; + auto const message = [forms](std::string_view text, std::string_view reason) { + return std::string{"Invalid algorithm name \""} + std::string{text} + + "\": " + std::string{reason} + forms; + }; + + CHECK_THROWS_AS(algorithm_name::create(""), std::invalid_argument); + CHECK_THROWS_WITH(algorithm_name::create(""), message("", "it is empty.")); + CHECK_THROWS_WITH(algorithm_name::create("plugin:"), + message("plugin:", "the algorithm after ':' is missing.")); + CHECK_THROWS_WITH(algorithm_name::create(":algo"), + message(":algo", "the plugin label before ':' is missing.")); + CHECK_THROWS_WITH(algorithm_name::create(":"), + message(":", "the plugin label before ':' is missing.")); + CHECK_THROWS_WITH(algorithm_name::create("a:b:c"), + message("a:b:c", "it contains more than one ':'.")); } - SECTION("Create error - multiple colons") + SECTION("Create error - malformed components are reported as invalid_argument") { - CHECK_THROWS_AS(algorithm_name::create("a:b:c"), std::runtime_error); + auto const rule = std::string{phlex::detail::identifier_rule}; + + CHECK_THROWS_AS(algorithm_name::create("_x"), std::invalid_argument); + CHECK_THROWS_WITH(algorithm_name::create("_x"), + "Invalid algorithm name \"_x\": algorithm \"_x\" " + rule); + CHECK_THROWS_WITH(algorithm_name::create("a[0]"), + "Invalid algorithm name \"a[0]\": algorithm \"a[0]\" " + rule); + CHECK_THROWS_WITH(algorithm_name::create("a b"), + "Invalid algorithm name \"a b\": algorithm \"a b\" " + rule); + CHECK_THROWS_WITH(algorithm_name::create("1p:a"), + "Invalid algorithm name \"1p:a\": plugin label \"1p\" " + rule); + CHECK_THROWS_WITH(algorithm_name::create("pl ugin:algo"), + "Invalid algorithm name \"pl ugin:algo\": plugin label \"pl ugin\" " + rule); + CHECK_THROWS_WITH(algorithm_name::create("p:1a"), + "Invalid algorithm name \"p:1a\": algorithm \"1a\" " + rule); + // Only the first problem is reported, and the plugin label is checked first. + CHECK_THROWS_WITH(algorithm_name::create("1p:1a"), + "Invalid algorithm name \"1p:1a\": plugin label \"1p\" " + rule); } - SECTION("Create error - malformed components") + SECTION("Create error - long text is shortened in the message") { - CHECK_THROWS(algorithm_name::create("1plugin:algo")); - CHECK_THROWS(algorithm_name::create("plugin:1algo")); - CHECK_THROWS(algorithm_name::create("pl ugin:algo")); + std::string const text = std::string(100, 'a') + "-"; + std::string const shown = std::string(64, 'a') + "..."; + CHECK_THROWS_WITH(algorithm_name::create(text), + Catch::Matchers::ContainsSubstring("\"" + shown + "\"") && + !Catch::Matchers::ContainsSubstring(text)); } - SECTION("Create error - empty name") + SECTION("Create from optional plugin and algorithm") { - CHECK_THROWS_AS(algorithm_name::create(""), std::runtime_error); - CHECK_THROWS_WITH(algorithm_name::create(""), "Cannot create an empty algorithm name."); + CHECK(algorithm_name::create(std::nullopt, "algo") == algorithm_name::create("algo")); + CHECK(algorithm_name::create("plugin", "algo") == algorithm_name::create("plugin:algo")); + // An empty plugin is not the same as an absent plugin. + CHECK_THROWS_AS(algorithm_name::create("", "algo"), std::invalid_argument); + CHECK_THROWS_AS(algorithm_name::create(std::nullopt, ""), std::invalid_argument); + CHECK_THROWS_AS(algorithm_name::create("plugin", ""), std::invalid_argument); + // The overload does not split on colons, so a colon in a component violates the character rule. + CHECK_THROWS_AS(algorithm_name::create(std::nullopt, "a:b"), std::invalid_argument); } SECTION("Match both") { @@ -134,30 +172,45 @@ TEST_CASE("make_algorithm_name tests", "[core]") CHECK(name.to_string() == "my_module:my_algorithm"); } - SECTION("An empty algorithm name is rejected") { CHECK_THROWS(make_algorithm_name(nullptr, "")); } -} + SECTION("An empty algorithm name is rejected with the same message as create") + { + CHECK_THROWS_AS(make_algorithm_name(nullptr, ""), std::invalid_argument); + CHECK_THROWS_WITH( + make_algorithm_name(nullptr, ""), + Catch::Matchers::ContainsSubstring("Invalid algorithm name \"\": it is empty")); -TEST_CASE("verify_name tests", "[core]") -{ - using namespace phlex::detail::internal; + boost::json::object obj; + obj["module_label"] = "my_module"; + phlex::configuration const config{obj}; + CHECK_THROWS_WITH( + make_algorithm_name(&config, ""), + Catch::Matchers::ContainsSubstring( + "Invalid algorithm name \"my_module:\": the algorithm after ':' is missing")); + } - SECTION("non-empty name does nothing") { CHECK_NOTHROW(verify_name("valid_name", nullptr)); } + SECTION("A malformed algorithm name is reported with the composed name") + { + boost::json::object obj; + obj["module_label"] = "my_module"; + phlex::configuration const config{obj}; - SECTION("empty name throws") { CHECK_THROWS_AS(verify_name("", nullptr), std::runtime_error); } + CHECK_THROWS_AS(make_algorithm_name(&config, "my-algorithm"), std::invalid_argument); + CHECK_THROWS_WITH(make_algorithm_name(&config, "my-algorithm"), + Catch::Matchers::ContainsSubstring("Invalid algorithm name " + "\"my_module:my-algorithm\": algorithm " + "\"my-algorithm\" must start with")); + CHECK_THROWS_AS(make_algorithm_name(nullptr, "a[0]"), std::invalid_argument); + } - SECTION("empty name with config includes module label") + SECTION("A malformed module label is reported as a bad plugin label") { boost::json::object obj; - obj["module_label"] = "my_module"; + obj["module_label"] = "1module"; phlex::configuration const config{obj}; - try { - verify_name("", &config); - FAIL("Should have thrown"); - } catch (std::runtime_error const& e) { - std::string const msg = e.what(); - CHECK(msg.contains("my_module")); - } + CHECK_THROWS_WITH( + make_algorithm_name(&config, "my_algorithm"), + Catch::Matchers::ContainsSubstring("plugin label \"1module\" must start with")); } } diff --git a/test/form/CMakeLists.txt b/test/form/CMakeLists.txt index 5e3a7d191..219c8ed38 100644 --- a/test/form/CMakeLists.txt +++ b/test/form/CMakeLists.txt @@ -380,6 +380,24 @@ if(FORM_USE_ROOT_STORAGE) "PHLEX_PLUGIN_PATH=${PROJECT_BINARY_DIR}/${phlex_LIBRARY_DIR}:${CMAKE_BINARY_DIR}/form" ) endforeach() + + # A malformed creator is rejected when form_source is registered, naming the parameter. + cet_test( + job:form_source_bad_creator + HANDBUILT + TEST_EXEC + phlex::phlex + TEST_ARGS + -c + ${CMAKE_CURRENT_SOURCE_DIR}/form_source_bad_creator.jsonnet + --stage + test + TEST_PROPERTIES + PASS_REGULAR_EXPRESSION + "Invalid parameter 'creator': Invalid algorithm name \"bad creator\": algorithm \"bad creator\" must start with" + ENVIRONMENT + "PHLEX_PLUGIN_PATH=${PROJECT_BINARY_DIR}/${phlex_LIBRARY_DIR}:${CMAKE_BINARY_DIR}/form" + ) endif() if(FORM_USE_ROOT_STORAGE AND FORM_USE_RNTUPLE_STORAGE) diff --git a/test/form/form_source_bad_creator.jsonnet b/test/form/form_source_bad_creator.jsonnet new file mode 100644 index 000000000..5e2bb23eb --- /dev/null +++ b/test/form/form_source_bad_creator.jsonnet @@ -0,0 +1,17 @@ +{ + driver: { + cpp: 'generate_layers', + layers: { + event: { parent: 'job', total: 1, starting_number: 0 }, + }, + }, + sources: { + sums_from_form: { + cpp: 'form_source', + stage: 'test', + input_file: 'does_not_matter.root', + creator: 'bad creator', + products: ['sums'], + }, + }, +} diff --git a/test/identifier_test.cpp b/test/identifier_test.cpp index bc7ebf5af..28e32df5c 100644 --- a/test/identifier_test.cpp +++ b/test/identifier_test.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -13,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -31,6 +33,24 @@ TEST_CASE("Identifier rejects punctuation", "[identifier]") CHECK_THROWS(identifier{"run:name"}); } +TEST_CASE("Identifier errors quote the offending text and state the rule", "[identifier]") +{ + auto const rule = std::string{phlex::detail::identifier_rule}; + CHECK_THROWS_AS(identifier{"run-name"}, std::invalid_argument); + CHECK_THROWS_WITH(identifier{"run-name"}, "Invalid identifier \"run-name\": it " + rule); + CHECK_THROWS_WITH(identifier{""}, "Invalid identifier \"\": it " + rule); + CHECK_THROWS_WITH(identifier{std::string{"a\nb"}}, "Invalid identifier \"a\\nb\": it " + rule); + CHECK_THROWS_WITH(suffix_t{"bad name"sv}, "Invalid identifier \"bad name\": it " + rule); +} + +TEST_CASE("Identifier errors shorten very long text", "[identifier]") +{ + std::string const text = std::string(100, 'a') + "-"; + CHECK_THROWS_WITH(identifier{text}, + "Invalid identifier \"" + std::string(64, 'a') + "...\": it " + + std::string{phlex::detail::identifier_rule}); +} + TEST_CASE("Identifier must begin with a letter", "[identifier]") { CHECK_THROWS(identifier{""}); @@ -70,6 +90,15 @@ TEST_CASE("Identifier validates every length-bearing construction path", "[ident CHECK(identifier_or_empty{""}.empty()); } +TEST_CASE("identifier_or_empty exception specifications", "[identifier]") +{ + // Moving an identifier never allocates; copying one may. + STATIC_CHECK(std::is_nothrow_constructible_v); + STATIC_CHECK_FALSE(std::is_nothrow_constructible_v); + STATIC_CHECK(std::is_nothrow_move_constructible_v); + STATIC_CHECK(std::is_nothrow_move_assignable_v); +} + TEST_CASE("Moving identifiers preserves the destination value", "[identifier]") { STATIC_CHECK(std::is_nothrow_move_constructible_v); diff --git a/test/product_selector_test.cpp b/test/product_selector_test.cpp index 6b1c3e144..2a53f2ade 100644 --- a/test/product_selector_test.cpp +++ b/test/product_selector_test.cpp @@ -71,6 +71,7 @@ TEST_CASE("Product name with data layer", "[data model]") TEST_CASE("Selectors do not move from lvalue arguments", "[data model]") { experimental::identifier const expected_creator{"creator"}; + experimental::identifier const expected_layer{"event"}; experimental::identifier creator{"creator"}; experimental::identifier layer{"event"}; std::string layer_string{"event"}; @@ -78,8 +79,8 @@ TEST_CASE("Selectors do not move from lvalue arguments", "[data model]") product_selector first{.creator = creator, .layer = layer, .suffix = "a"_id}; // The sources must be intact after the first use... CHECK(creator == expected_creator); - CHECK(!layer.empty()); - // ...so that reusing them does not throw an empty-name error. + CHECK(layer == expected_layer); + // ...so that reusing them still yields the original values. product_selector second{.creator = creator, .layer = layer, .suffix = "b"_id}; CHECK(first.creator == second.creator); CHECK(first.layer == second.layer); diff --git a/test/product_store_test.cpp b/test/product_store_test.cpp index aaf74520d..2e5620682 100644 --- a/test/product_store_test.cpp +++ b/test/product_store_test.cpp @@ -85,6 +85,11 @@ TEST_CASE("Product specification text requires creator and slash", "[data model] CHECK_THROWS(product_specification::create(":creator/number")); CHECK_THROWS(product_specification::create("creator/a/b")); CHECK_THROWS(product_specification{"number"}); + // Malformed creator text is reported by algorithm_name, as invalid_argument. + CHECK_THROWS_AS(product_specification::create("_x/number"), std::invalid_argument); + CHECK_THROWS_WITH(product_specification::create("1p:a/number"), + Catch::Matchers::ContainsSubstring("Invalid algorithm name \"1p:a\": " + "plugin label \"1p\" must start with")); CHECK_THROWS(product_specification{std::string{"/number"}}); } } diff --git a/test/python/CMakeLists.txt b/test/python/CMakeLists.txt index fb0d54dab..12e7ac58f 100644 --- a/test/python/CMakeLists.txt +++ b/test/python/CMakeLists.txt @@ -231,6 +231,18 @@ set_tests_properties( ) list(APPEND ACTIVE_PY_CPHLEX_TESTS py:baduint) +add_test( + NAME py:badname + COMMAND phlex::phlex -c ${CMAKE_CURRENT_SOURCE_DIR}/pybadname.jsonnet --stage test +) +set_tests_properties( + py:badname + PROPERTIES + PASS_REGULAR_EXPRESSION + "ValueError: Invalid identifier \"bad name\": it must start with an ASCII letter" +) +list(APPEND ACTIVE_PY_CPHLEX_TESTS py:badname) + add_test( NAME py:mismatch_variant COMMAND phlex::phlex -c ${CMAKE_CURRENT_SOURCE_DIR}/pymismatch_variant.jsonnet --stage test diff --git a/test/python/badname.py b/test/python/badname.py new file mode 100644 index 000000000..57ee747ca --- /dev/null +++ b/test/python/badname.py @@ -0,0 +1,27 @@ +"""A transform with a name that is not a valid identifier. + +Registration must fail with a ValueError that quotes the name exactly as written. +""" + + +def constant_one(i: int) -> int: + """Constant 1.""" + return 1 + + +def PHLEX_REGISTER_ALGORITHMS(m, config): + """Register a transform whose name is malformed. + + Args: + m (internal): Phlex registrar representation. + config (internal): Phlex configuration representation. + + Returns: + None + """ + m.transform( + constant_one, + name="bad name", + input_family=[{"creator": "input", "layer": "event", "suffix": "i"}], + output_product_suffixes=["output_one"], + ) diff --git a/test/python/pybadname.jsonnet b/test/python/pybadname.jsonnet new file mode 100644 index 000000000..de30f1aa4 --- /dev/null +++ b/test/python/pybadname.jsonnet @@ -0,0 +1,18 @@ +{ + driver: { + cpp: 'generate_layers', + layers: { + event: { parent: 'job', total: 1, starting_number: 1 }, + }, + }, + sources: { + provider: { + cpp: 'cppsource4py', + }, + }, + modules: { + badname: { + py: 'badname', + }, + }, +} diff --git a/test/python/pyprovide.py b/test/python/pyprovide.py index f884c63b7..0745ffdf6 100644 --- a/test/python/pyprovide.py +++ b/test/python/pyprovide.py @@ -134,6 +134,27 @@ def __call__(self, di): except TypeError as e: assert msg in str(e) + # malformed text in a provider output is a ValueError that names the offending field + for selector, field in [ + ({"creator": "a b", "layer": "b", "suffix": "c"}, "creator"), + ({"creator": "a:b:c", "layer": "b", "suffix": "c"}, "creator"), + ({"creator": "a", "layer": "1b", "suffix": "c"}, "layer"), + ({"creator": "a", "layer": "b", "suffix": "c d"}, "suffix"), + ]: + try: + s.provide(freq, selector) + assert not "supposed to be here" + except ValueError as e: + assert f'Invalid product selector field "{field}"' in str(e) + + # a malformed provider name is a ValueError that quotes the composed algorithm name + bad_name = Variant(lambda di: 42, {"di": "data_cell_index", "return": int}, "bad name") + try: + s.provide(bad_name, {"creator": "a", "layer": "b", "suffix": "c"}) + assert not "supposed to be here" + except ValueError as e: + assert 'Invalid algorithm name "provider:bad name"' in str(e) + def PHLEX_REGISTER_ALGORITHMS(m, config): """Register python consumers as observers to check providers' output. diff --git a/test/python/suffix.py b/test/python/suffix.py index 558ee29f8..b88f5064e 100644 --- a/test/python/suffix.py +++ b/test/python/suffix.py @@ -78,6 +78,20 @@ def PHLEX_REGISTER_ALGORITHMS(m, config): # test for the one generic part in all these errors assert "not a string" in str(e) + # malformed text in an input selector is a ValueError that names the offending field + for input_query, field in ( + ({"creator": "bad creator", "layer": "event", "suffix": "i"}, "creator"), + ({"creator": "input", "layer": "event layer", "suffix": "i"}, "layer"), + ({"creator": "input", "layer": "event", "suffix": "bad suffix"}, "suffix"), + ): + try: + m.transform( + constant_one, input_family=[input_query], output_product_suffixes=["output_one"] + ) + assert not "supposed to be here" + except ValueError as e: + assert f'Invalid product selector field "{field}"' in str(e) + # transforms with suffix to be used without suffix m.transform( constant_one, From 24b17c068150ea5907f5750626fbd4a48fdc10d2 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Wed, 18 Nov 2026 18:12:22 -0600 Subject: [PATCH 17/28] refactor(test): prefer optional::value() over operator* Read the plugin label in algorithm_name tests through value() instead of operator*. Both are guarded by a preceding REQUIRE(has_value()), so behavior is unchanged, and value() reports an error on an empty optional rather than being undefined. Also declare the expected-forms string in the structural-error test as a const pointer, matching the surrounding test style. --- test/core_misc_test.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/core_misc_test.cpp b/test/core_misc_test.cpp index 8d7044a50..14c965ac1 100644 --- a/test/core_misc_test.cpp +++ b/test/core_misc_test.cpp @@ -53,7 +53,7 @@ TEST_CASE("algorithm_name tests", "[model]") { auto const an = algorithm_name::create("plugin:algo"); REQUIRE(an.plugin().has_value()); - CHECK(*an.plugin() == "plugin"_id); + CHECK(an.plugin().value() == "plugin"_id); CHECK(an.algorithm() == "algo"_id); } SECTION("Construct from typed components") @@ -71,7 +71,7 @@ TEST_CASE("algorithm_name tests", "[model]") } SECTION("Create error - structural problems are reported as invalid_argument") { - auto const forms = R"( Expected "algorithm" or "plugin_label:algorithm".)"; + auto const *const forms = R"( Expected "algorithm" or "plugin_label:algorithm".)"; auto const message = [forms](std::string_view text, std::string_view reason) { return std::string{"Invalid algorithm name \""} + std::string{text} + "\": " + std::string{reason} + forms; @@ -168,7 +168,7 @@ TEST_CASE("make_algorithm_name tests", "[core]") auto const name = make_algorithm_name(&config, "my_algorithm"); REQUIRE(name.plugin().has_value()); - CHECK(*name.plugin() == "my_module"_id); + CHECK(name.plugin().value() == "my_module"_id); CHECK(name.to_string() == "my_module:my_algorithm"); } From 4f5eb3dfeddaa6f32d687f9b81a9cca8dbf9dcc1 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Fri, 20 Nov 2026 12:24:30 -0600 Subject: [PATCH 18/28] fix(model): clarify identifier validation error messages Identifier errors now say "an identifier" instead of "it" and state that an empty value is rejected, so the message no longer implies that an empty name is accepted when it does not start with a letter. The shared identifier_rule text is updated, and the error messages built from it change accordingly. Update the affected C++, Python, and CMake test expectations to match the new message text. --- phlex/model/identifier.cpp | 2 +- phlex/model/identifier.hpp | 3 ++- test/config_test.cpp | 9 ++++++--- test/core_misc_test.cpp | 16 +++++++++------- test/form/CMakeLists.txt | 2 +- test/identifier_test.cpp | 13 ++++++++----- test/product_selector_test.cpp | 8 ++++++-- test/product_store_test.cpp | 8 +++++--- test/python/CMakeLists.txt | 2 +- 9 files changed, 39 insertions(+), 24 deletions(-) diff --git a/phlex/model/identifier.cpp b/phlex/model/identifier.cpp index b8e5d4ac0..c1431fd22 100644 --- a/phlex/model/identifier.cpp +++ b/phlex/model/identifier.cpp @@ -15,7 +15,7 @@ namespace phlex::experimental { void validate_identifier(std::string_view str) { if (!phlex::detail::valid_identifier(str)) { - throw std::invalid_argument{fmt::format("Invalid identifier {}: it {}", + throw std::invalid_argument{fmt::format("Invalid identifier {}: an identifier {}", phlex::detail::excerpt(str), phlex::detail::identifier_rule)}; } diff --git a/phlex/model/identifier.hpp b/phlex/model/identifier.hpp index 3460fcdef..cde01f687 100644 --- a/phlex/model/identifier.hpp +++ b/phlex/model/identifier.hpp @@ -21,7 +21,8 @@ namespace phlex::detail { /// The rule enforced by `valid_identifier`, phrased to follow a subject (for example, /// "it" or `algorithm "x"`) in error messages. inline constexpr std::string_view identifier_rule{ - "must start with an ASCII letter and contain only ASCII letters, digits, or underscores"}; + "must not be empty and must start with an ASCII letter and contain only ASCII letters, digits, " + "or underscores"}; // This implementation does not use std::regex for the validation because // std::regex does not support compile-time regular expressions. diff --git a/test/config_test.cpp b/test/config_test.cpp index 3dedd0c89..e96519d01 100644 --- a/test/config_test.cpp +++ b/test/config_test.cpp @@ -86,16 +86,19 @@ TEST_CASE("Retrieve product_selector", "[config]") CHECK_THROWS_WITH(config.get("malformed2"), ContainsSubstring("Error retrieving parameter 'malformed2'") && ContainsSubstring("Invalid product selector field \"layer\": " - "Invalid identifier \"\": it must start with")); + "Invalid identifier \"\": an identifier " + + std::string{phlex::detail::identifier_rule})); CHECK_THROWS_WITH(config.get("malformed3"), ContainsSubstring("Error retrieving parameter 'malformed3'") && ContainsSubstring("Invalid product selector field \"creator\": " - "Invalid identifier \"\": it must start with")); + "Invalid identifier \"\": an identifier " + + std::string{phlex::detail::identifier_rule})); CHECK_THROWS_WITH(config.get("malformed4"), ContainsSubstring("Error retrieving parameter 'malformed4'") && ContainsSubstring("Product selector contains unrecognized keys")); CHECK_THROWS_WITH(config.get("malformed5"), ContainsSubstring("Error retrieving parameter 'malformed5'") && ContainsSubstring("Invalid product selector field \"suffix\": " - "Invalid identifier \"bad name\": it must start with")); + "Invalid identifier \"bad name\": an identifier " + + std::string{phlex::detail::identifier_rule})); } diff --git a/test/core_misc_test.cpp b/test/core_misc_test.cpp index 14c965ac1..514eaf410 100644 --- a/test/core_misc_test.cpp +++ b/test/core_misc_test.cpp @@ -195,10 +195,12 @@ TEST_CASE("make_algorithm_name tests", "[core]") phlex::configuration const config{obj}; CHECK_THROWS_AS(make_algorithm_name(&config, "my-algorithm"), std::invalid_argument); - CHECK_THROWS_WITH(make_algorithm_name(&config, "my-algorithm"), - Catch::Matchers::ContainsSubstring("Invalid algorithm name " - "\"my_module:my-algorithm\": algorithm " - "\"my-algorithm\" must start with")); + CHECK_THROWS_WITH( + make_algorithm_name(&config, "my-algorithm"), + Catch::Matchers::ContainsSubstring("Invalid algorithm name " + "\"my_module:my-algorithm\": algorithm " + "\"my-algorithm\" " + + std::string{phlex::detail::identifier_rule})); CHECK_THROWS_AS(make_algorithm_name(nullptr, "a[0]"), std::invalid_argument); } @@ -208,9 +210,9 @@ TEST_CASE("make_algorithm_name tests", "[core]") obj["module_label"] = "1module"; phlex::configuration const config{obj}; - CHECK_THROWS_WITH( - make_algorithm_name(&config, "my_algorithm"), - Catch::Matchers::ContainsSubstring("plugin label \"1module\" must start with")); + CHECK_THROWS_WITH(make_algorithm_name(&config, "my_algorithm"), + Catch::Matchers::ContainsSubstring( + "plugin label \"1module\" " + std::string{phlex::detail::identifier_rule})); } } diff --git a/test/form/CMakeLists.txt b/test/form/CMakeLists.txt index 219c8ed38..ab25da523 100644 --- a/test/form/CMakeLists.txt +++ b/test/form/CMakeLists.txt @@ -394,7 +394,7 @@ if(FORM_USE_ROOT_STORAGE) test TEST_PROPERTIES PASS_REGULAR_EXPRESSION - "Invalid parameter 'creator': Invalid algorithm name \"bad creator\": algorithm \"bad creator\" must start with" + "Invalid parameter 'creator': Invalid algorithm name \"bad creator\": algorithm \"bad creator\" must not be empty and must start with" ENVIRONMENT "PHLEX_PLUGIN_PATH=${PROJECT_BINARY_DIR}/${phlex_LIBRARY_DIR}:${CMAKE_BINARY_DIR}/form" ) diff --git a/test/identifier_test.cpp b/test/identifier_test.cpp index 28e32df5c..b0a591936 100644 --- a/test/identifier_test.cpp +++ b/test/identifier_test.cpp @@ -37,17 +37,20 @@ TEST_CASE("Identifier errors quote the offending text and state the rule", "[ide { auto const rule = std::string{phlex::detail::identifier_rule}; CHECK_THROWS_AS(identifier{"run-name"}, std::invalid_argument); - CHECK_THROWS_WITH(identifier{"run-name"}, "Invalid identifier \"run-name\": it " + rule); - CHECK_THROWS_WITH(identifier{""}, "Invalid identifier \"\": it " + rule); - CHECK_THROWS_WITH(identifier{std::string{"a\nb"}}, "Invalid identifier \"a\\nb\": it " + rule); - CHECK_THROWS_WITH(suffix_t{"bad name"sv}, "Invalid identifier \"bad name\": it " + rule); + CHECK_THROWS_WITH(identifier{"run-name"}, + "Invalid identifier \"run-name\": an identifier " + rule); + CHECK_THROWS_WITH(identifier{""}, "Invalid identifier \"\": an identifier " + rule); + CHECK_THROWS_WITH(identifier{std::string{"a\nb"}}, + "Invalid identifier \"a\\nb\": an identifier " + rule); + CHECK_THROWS_WITH(suffix_t{"bad name"sv}, + "Invalid identifier \"bad name\": an identifier " + rule); } TEST_CASE("Identifier errors shorten very long text", "[identifier]") { std::string const text = std::string(100, 'a') + "-"; CHECK_THROWS_WITH(identifier{text}, - "Invalid identifier \"" + std::string(64, 'a') + "...\": it " + + "Invalid identifier \"" + std::string(64, 'a') + "...\": an identifier " + std::string{phlex::detail::identifier_rule}); } diff --git a/test/product_selector_test.cpp b/test/product_selector_test.cpp index 2a53f2ade..29bf3db39 100644 --- a/test/product_selector_test.cpp +++ b/test/product_selector_test.cpp @@ -15,7 +15,9 @@ using namespace phlex; TEST_CASE("Empty creator name", "[data model]") { - CHECK_THROWS((product_selector{.creator = "", .layer = "layer"})); + CHECK_THROWS_WITH((product_selector{.creator = "", .layer = "layer"}), + "Invalid identifier \"\": an identifier " + + std::string{phlex::detail::identifier_rule}); } TEST_CASE("Creator name formatting", "[data model]") @@ -26,7 +28,9 @@ TEST_CASE("Creator name formatting", "[data model]") TEST_CASE("Empty layer name", "[data model]") { - CHECK_THROWS((product_selector{.creator = "creator", .layer = ""})); + CHECK_THROWS_WITH((product_selector{.creator = "creator", .layer = ""}), + "Invalid identifier \"\": an identifier " + + std::string{phlex::detail::identifier_rule}); } TEST_CASE("Retrieving a non-existent layer name", "[data model]") diff --git a/test/product_store_test.cpp b/test/product_store_test.cpp index 2e5620682..0c77c84ed 100644 --- a/test/product_store_test.cpp +++ b/test/product_store_test.cpp @@ -87,9 +87,11 @@ TEST_CASE("Product specification text requires creator and slash", "[data model] CHECK_THROWS(product_specification{"number"}); // Malformed creator text is reported by algorithm_name, as invalid_argument. CHECK_THROWS_AS(product_specification::create("_x/number"), std::invalid_argument); - CHECK_THROWS_WITH(product_specification::create("1p:a/number"), - Catch::Matchers::ContainsSubstring("Invalid algorithm name \"1p:a\": " - "plugin label \"1p\" must start with")); + CHECK_THROWS_WITH( + product_specification::create("1p:a/number"), + Catch::Matchers::ContainsSubstring("Invalid algorithm name \"1p:a\": " + "plugin label \"1p\" " + + std::string{phlex::detail::identifier_rule})); CHECK_THROWS(product_specification{std::string{"/number"}}); } } diff --git a/test/python/CMakeLists.txt b/test/python/CMakeLists.txt index 12e7ac58f..f67f6cb3e 100644 --- a/test/python/CMakeLists.txt +++ b/test/python/CMakeLists.txt @@ -239,7 +239,7 @@ set_tests_properties( py:badname PROPERTIES PASS_REGULAR_EXPRESSION - "ValueError: Invalid identifier \"bad name\": it must start with an ASCII letter" + "ValueError: Invalid identifier \"bad name\": an identifier must not be empty and must start with an ASCII letter" ) list(APPEND ACTIVE_PY_CPHLEX_TESTS py:badname) From 1bd60fa0c9311dca9f7b6feb5e1ca89c080b5b4f Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Fri, 20 Nov 2026 12:37:34 -0600 Subject: [PATCH 19/28] refactor(core): drop redundant creator guard in product match `creator_match()` already returns true when no creator is set, so the explicit `creator &&` check in `product_selector::match()` was redundant. Behavior is unchanged. --- phlex/core/product_selector.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/phlex/core/product_selector.cpp b/phlex/core/product_selector.cpp index 46ac6c2b3..70ac5c1d2 100644 --- a/phlex/core/product_selector.cpp +++ b/phlex/core/product_selector.cpp @@ -38,7 +38,7 @@ namespace phlex { // Check if a product_specification satisfies this query bool product_selector::match(experimental::product_specification const& spec) const { - if (creator && !creator_match(spec.creator())) { + if (!creator_match(spec.creator())) { return false; } if (type.valid() && type != spec.type()) { From 1d0ecc5cb549f743f7057634d2c9cde218ce4b73 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Fri, 20 Nov 2026 12:40:19 -0600 Subject: [PATCH 20/28] chore(model): assert layer path depth matches index depth --- phlex/model/data_cell_index.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/phlex/model/data_cell_index.cpp b/phlex/model/data_cell_index.cpp index 5b4254e12..0bdb507a9 100644 --- a/phlex/model/data_cell_index.cpp +++ b/phlex/model/data_cell_index.cpp @@ -71,6 +71,7 @@ namespace phlex { layers.push_back(ptr->layer_name()); ptr = ptr->parent_.get(); } + assert(layers.size() == depth_ + 1); std::ranges::reverse(layers); return experimental::layer_path{std::move(layers)}; } From 78aaa5f0b33aa295c9e668684c2ba57b1ff313ea Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Fri, 20 Nov 2026 12:41:22 -0600 Subject: [PATCH 21/28] test(identifier): split constructor and embedded NUL tests Separate invalid-name constructor checks from embedded-NUL checks on explicitly sized input, and give the empty identifier_or_empty case its own test. The NUL test comment explains why these constructors are exercised with the full byte sequence. --- test/identifier_test.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/test/identifier_test.cpp b/test/identifier_test.cpp index b0a591936..56ecb67fe 100644 --- a/test/identifier_test.cpp +++ b/test/identifier_test.cpp @@ -82,14 +82,26 @@ TEST_CASE("Identifier accepts ASCII letters, digits, and underscores", "[identif CHECK("AbC_012"_id == "AbC_012"_idq); } -TEST_CASE("Identifier validates every length-bearing construction path", "[identifier]") +TEST_CASE("Identifier constructors, literals, and optional wrappers reject invalid names", + "[identifier]") { CHECK_THROWS(identifier{"bad name"sv}); CHECK_THROWS(identifier{std::string{"bad name"}}); CHECK_THROWS("bad name"_id); - CHECK_THROWS("abc\0def"_id); CHECK_THROWS(identifier_or_empty{"bad name"sv}); +} + +// The following tests the constructors that process the whole series of bytes because they +// are not using any functions that make use of null-terminated character arrays. +TEST_CASE("Identifier literals and suffixes reject embedded NULs in explicitly sized input", + "[identifier]") +{ + CHECK_THROWS("abc\0def"_id); CHECK_THROWS(suffix_t{std::string{"abc\0def", 7}}); +} + +TEST_CASE("identifier_or_empty accepts an empty name", "[identifier]") +{ CHECK(identifier_or_empty{""}.empty()); } From 5788acc4e7d21e4677e7c166ab0b07c8fb4f8b60 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Fri, 20 Nov 2026 12:59:28 -0600 Subject: [PATCH 22/28] refactor: replace text create factories with constructors Remove the static `algorithm_name::create(char const*)` and `algorithm_name::create(std::string_view)` overloads, and the matching `product_specification::create` overloads. The text constructors now parse their argument directly, so `algorithm_name{spec}` and `product_specification{spec}` replace the removed factories. The `algorithm_name::create(plugin, algorithm)` overload remains as the validation point. Parsing, error messages, and exception types are unchanged. Callers in form, model, and tests are updated to use the constructors. --- form/form_source.cpp | 2 +- phlex/model/algorithm_name.cpp | 34 ++++++++------- phlex/model/algorithm_name.hpp | 16 +++---- phlex/model/product_specification.cpp | 47 ++++++++++---------- phlex/model/product_specification.hpp | 7 ++- phlex/model/product_store.cpp | 2 +- test/core_misc_test.cpp | 63 +++++++++++++-------------- test/filter_impl_test.cpp | 4 +- test/multilayer_join_test.cpp | 4 +- test/product_selector_test.cpp | 6 +-- test/product_store_test.cpp | 60 ++++++++++++------------- test/repeater_node_test.cpp | 3 +- test/transform_node_test.cpp | 8 ++-- 13 files changed, 124 insertions(+), 132 deletions(-) diff --git a/form/form_source.cpp b/form/form_source.cpp index 1456f4a52..6e970b4a5 100644 --- a/form/form_source.cpp +++ b/form/form_source.cpp @@ -181,7 +181,7 @@ PHLEX_REGISTER_SOURCE(s, config) // Parse the creator once, here, where its parameter name is known. auto const advertised_creator = [&creator_text] { try { - return phlex::experimental::algorithm_name::create(creator_text); + return phlex::experimental::algorithm_name{creator_text}; } catch (std::invalid_argument const& e) { throw std::invalid_argument{std::string{"Invalid parameter 'creator': "} + e.what()}; } diff --git a/phlex/model/algorithm_name.cpp b/phlex/model/algorithm_name.cpp index f6d81d0c3..98547d7c9 100644 --- a/phlex/model/algorithm_name.cpp +++ b/phlex/model/algorithm_name.cpp @@ -38,11 +38,28 @@ namespace { } namespace phlex::experimental { + namespace { + // Splits `spec` into an optional plugin label and an algorithm, then validates them through + // the component overload of `algorithm_name::create`. + algorithm_name parse(std::string_view spec) + { + auto const colon = spec.find(':'); + if (colon == std::string_view::npos) { + return algorithm_name::create(std::nullopt, spec); + } + auto const algorithm = spec.substr(colon + 1); + if (algorithm.contains(':')) { + throw_invalid(spec, fmt::format("it contains more than one ':'. {}", expected_forms)); + } + return algorithm_name::create(spec.substr(0, colon), algorithm); + } + } + algorithm_name::algorithm_name(char const* spec) : algorithm_name{std::string_view{spec}} {} algorithm_name::algorithm_name(std::string const& spec) : algorithm_name{std::string_view{spec}} { } - algorithm_name::algorithm_name(std::string_view spec) : algorithm_name{create(spec)} {} + algorithm_name::algorithm_name(std::string_view spec) : algorithm_name{parse(spec)} {} algorithm_name::algorithm_name(std::optional plugin, identifier algorithm) : plugin_{std::move(plugin)}, algorithm_{std::move(algorithm)} @@ -59,21 +76,6 @@ namespace phlex::experimental { bool algorithm_name::match(algorithm_name const& other) const { return operator==(other); } - algorithm_name algorithm_name::create(char const* spec) { return create(std::string_view{spec}); } - - algorithm_name algorithm_name::create(std::string_view spec) - { - auto const colon = spec.find(':'); - if (colon == std::string_view::npos) { - return create(std::nullopt, spec); - } - auto const algorithm = spec.substr(colon + 1); - if (algorithm.contains(':')) { - throw_invalid(spec, fmt::format("it contains more than one ':'. {}", expected_forms)); - } - return create(spec.substr(0, colon), algorithm); - } - algorithm_name algorithm_name::create(std::optional plugin, std::string_view algorithm) { diff --git a/phlex/model/algorithm_name.hpp b/phlex/model/algorithm_name.hpp index 41300ce02..c1dc20bcd 100644 --- a/phlex/model/algorithm_name.hpp +++ b/phlex/model/algorithm_name.hpp @@ -12,6 +12,11 @@ namespace phlex::experimental { class PHLEX_MODEL_EXPORT algorithm_name { public: + /// Parse text that is either `algorithm` or `plugin_label:algorithm`. + /// + /// Throws `std::invalid_argument` if `spec` is malformed. The message quotes the offending + /// text and says which part of the name is invalid and why. Only the first problem found is + /// reported. // NOLINTBEGIN(google-explicit-constructor) - Implicit conversion is intentional algorithm_name(char const* spec); algorithm_name(std::string const& spec); @@ -28,17 +33,10 @@ namespace phlex::experimental { bool match(algorithm_name const& other) const; auto operator<=>(algorithm_name const&) const noexcept = default; - /// Parses `spec`, which is either `algorithm` or `plugin_label:algorithm`. - /// - /// Throws `std::invalid_argument` if `spec` is malformed. The message quotes the offending - /// text and says which part of the name is invalid and why. Only the first problem found is - /// reported. - static algorithm_name create(char const* spec); - static algorithm_name create(std::string_view spec); - /// Validates the components of a name and constructs it. This is the single place where /// the text of an algorithm name is checked: the character rules are those of `identifier`, - /// and failures are reported as described for `create(std::string_view)`. + /// and failures are reported as described for the text constructors, which parse their + /// argument and then call this function. /// /// An unqualified name is represented by `std::nullopt`. An empty `plugin` is not the same /// as `std::nullopt`; it is rejected. diff --git a/phlex/model/product_specification.cpp b/phlex/model/product_specification.cpp index 61ff887f5..0014e28fc 100644 --- a/phlex/model/product_specification.cpp +++ b/phlex/model/product_specification.cpp @@ -15,6 +15,27 @@ #include namespace phlex::experimental { + namespace { + // Parses the `creator/suffix` form. The specification's type is left unspecified. + product_specification parse(std::string_view s) + { + auto const forward_slash = s.find('/'); + if (forward_slash == std::string_view::npos) { + throw std::runtime_error( + fmt::format("The specification '{}' is not a valid product specification: " + "expected the form 'creator/suffix' (use 'creator/' for an empty suffix).", + s)); + } + if (forward_slash == 0) { + throw std::runtime_error( + fmt::format("The product specification '{}' does not name a creator.", s)); + } + return {algorithm_name{s.substr(0, forward_slash)}, + suffix_t(s.substr(forward_slash + 1)), + type_id{}}; + } + } + product_specification::product_specification(char const* name) : product_specification{std::string_view{name}} { @@ -24,7 +45,7 @@ namespace phlex::experimental { { } product_specification::product_specification(std::string_view name) : - product_specification{create(name)} + product_specification{parse(name)} { } @@ -39,30 +60,6 @@ namespace phlex::experimental { { return fmt::format("{}/{}", creator_.to_string(), suffix_); } - - product_specification product_specification::create(char const* c) - { - return create(std::string_view{c}); - } - - product_specification product_specification::create(std::string_view s) - { - auto const forward_slash = s.find('/'); - if (forward_slash == std::string_view::npos) { - throw std::runtime_error( - fmt::format("The specification '{}' is not a valid product specification: " - "expected the form 'creator/suffix' (use 'creator/' for an empty suffix).", - s)); - } - if (forward_slash == 0) { - throw std::runtime_error( - fmt::format("The product specification '{}' does not name a creator.", s)); - } - return {experimental::algorithm_name::create(s.substr(0, forward_slash)), - experimental::suffix_t(s.substr(forward_slash + 1)), - type_id{}}; - } - } namespace phlex::detail { diff --git a/phlex/model/product_specification.hpp b/phlex/model/product_specification.hpp index bd25d90a4..9797121e1 100644 --- a/phlex/model/product_specification.hpp +++ b/phlex/model/product_specification.hpp @@ -22,7 +22,9 @@ namespace phlex::experimental { public: // There is no default or creator-less construction: every specification names its creator. - // Text constructors parse the `creator/suffix` form, which must contain the slash. + // Text constructors parse the `creator/suffix` form, which must contain the slash. Structural + // errors throw `std::runtime_error`; an invalid creator or suffix throws + // `std::invalid_argument`. // NOLINTBEGIN(google-explicit-constructor) - Implicit conversion is intentional product_specification(char const* name); product_specification(std::string const& name); @@ -40,9 +42,6 @@ namespace phlex::experimental { auto operator<=>(product_specification const&) const = default; - static product_specification create(char const* c); - static product_specification create(std::string_view s); - friend struct std::hash; private: diff --git a/phlex/model/product_store.cpp b/phlex/model/product_store.cpp index 338c50c49..ae44d860c 100644 --- a/phlex/model/product_store.cpp +++ b/phlex/model/product_store.cpp @@ -53,7 +53,7 @@ namespace phlex::experimental { algorithm_name product_store::default_source() { - static algorithm_name const def = algorithm_name::create("Source"); + static algorithm_name const def = algorithm_name{"Source"}; return def; } } diff --git a/test/core_misc_test.cpp b/test/core_misc_test.cpp index 514eaf410..836804139 100644 --- a/test/core_misc_test.cpp +++ b/test/core_misc_test.cpp @@ -29,29 +29,29 @@ TEST_CASE("algorithm_name tests", "[model]") SECTION("Create from string with colon") { - auto an = algorithm_name::create("plugin:algo"); + auto an = algorithm_name{"plugin:algo"}; CHECK(an.to_string() == "plugin:algo"); } SECTION("Create from string without colon") { - auto an = algorithm_name::create("algo"); + auto an = algorithm_name{"algo"}; // For 'either' cases, the word is stored as algorithm_ CHECK(an.to_string() == "algo"); } SECTION("Create from char pointer") { - auto an = algorithm_name::create("ptr:algo"); + auto an = algorithm_name{"ptr:algo"}; CHECK(an.to_string() == "ptr:algo"); } SECTION("Unqualified name has no plugin") { - auto const an = algorithm_name::create("algo"); + auto const an = algorithm_name{"algo"}; CHECK_FALSE(an.plugin().has_value()); CHECK(an.algorithm() == "algo"_id); } SECTION("Qualified name has plugin and algorithm") { - auto const an = algorithm_name::create("plugin:algo"); + auto const an = algorithm_name{"plugin:algo"}; REQUIRE(an.plugin().has_value()); CHECK(an.plugin().value() == "plugin"_id); CHECK(an.algorithm() == "algo"_id); @@ -61,66 +61,64 @@ TEST_CASE("algorithm_name tests", "[model]") algorithm_name const unqualified{std::nullopt, "algo"_id}; CHECK_FALSE(unqualified.plugin().has_value()); CHECK(unqualified.to_string() == "algo"); - CHECK(unqualified == algorithm_name::create("algo")); + CHECK(unqualified == algorithm_name{"algo"}); algorithm_name const qualified{"plugin"_id, "algo"_id}; REQUIRE(qualified.plugin().has_value()); CHECK(qualified.to_string() == "plugin:algo"); - CHECK(qualified == algorithm_name::create("plugin:algo")); + CHECK(qualified == algorithm_name{"plugin:algo"}); CHECK(qualified != unqualified); } SECTION("Create error - structural problems are reported as invalid_argument") { - auto const *const forms = R"( Expected "algorithm" or "plugin_label:algorithm".)"; + auto const* const forms = R"( Expected "algorithm" or "plugin_label:algorithm".)"; auto const message = [forms](std::string_view text, std::string_view reason) { return std::string{"Invalid algorithm name \""} + std::string{text} + "\": " + std::string{reason} + forms; }; - CHECK_THROWS_AS(algorithm_name::create(""), std::invalid_argument); - CHECK_THROWS_WITH(algorithm_name::create(""), message("", "it is empty.")); - CHECK_THROWS_WITH(algorithm_name::create("plugin:"), + CHECK_THROWS_AS(algorithm_name{""}, std::invalid_argument); + CHECK_THROWS_WITH(algorithm_name{""}, message("", "it is empty.")); + CHECK_THROWS_WITH(algorithm_name{"plugin:"}, message("plugin:", "the algorithm after ':' is missing.")); - CHECK_THROWS_WITH(algorithm_name::create(":algo"), + CHECK_THROWS_WITH(algorithm_name{":algo"}, message(":algo", "the plugin label before ':' is missing.")); - CHECK_THROWS_WITH(algorithm_name::create(":"), - message(":", "the plugin label before ':' is missing.")); - CHECK_THROWS_WITH(algorithm_name::create("a:b:c"), - message("a:b:c", "it contains more than one ':'.")); + CHECK_THROWS_WITH(algorithm_name{":"}, message(":", "the plugin label before ':' is missing.")); + CHECK_THROWS_WITH(algorithm_name{"a:b:c"}, message("a:b:c", "it contains more than one ':'.")); } SECTION("Create error - malformed components are reported as invalid_argument") { auto const rule = std::string{phlex::detail::identifier_rule}; - CHECK_THROWS_AS(algorithm_name::create("_x"), std::invalid_argument); - CHECK_THROWS_WITH(algorithm_name::create("_x"), + CHECK_THROWS_AS(algorithm_name{"_x"}, std::invalid_argument); + CHECK_THROWS_WITH(algorithm_name{"_x"}, "Invalid algorithm name \"_x\": algorithm \"_x\" " + rule); - CHECK_THROWS_WITH(algorithm_name::create("a[0]"), + CHECK_THROWS_WITH(algorithm_name{"a[0]"}, "Invalid algorithm name \"a[0]\": algorithm \"a[0]\" " + rule); - CHECK_THROWS_WITH(algorithm_name::create("a b"), + CHECK_THROWS_WITH(algorithm_name{"a b"}, "Invalid algorithm name \"a b\": algorithm \"a b\" " + rule); - CHECK_THROWS_WITH(algorithm_name::create("1p:a"), + CHECK_THROWS_WITH(algorithm_name{"1p:a"}, "Invalid algorithm name \"1p:a\": plugin label \"1p\" " + rule); - CHECK_THROWS_WITH(algorithm_name::create("pl ugin:algo"), + CHECK_THROWS_WITH(algorithm_name{"pl ugin:algo"}, "Invalid algorithm name \"pl ugin:algo\": plugin label \"pl ugin\" " + rule); - CHECK_THROWS_WITH(algorithm_name::create("p:1a"), + CHECK_THROWS_WITH(algorithm_name{"p:1a"}, "Invalid algorithm name \"p:1a\": algorithm \"1a\" " + rule); // Only the first problem is reported, and the plugin label is checked first. - CHECK_THROWS_WITH(algorithm_name::create("1p:1a"), + CHECK_THROWS_WITH(algorithm_name{"1p:1a"}, "Invalid algorithm name \"1p:1a\": plugin label \"1p\" " + rule); } SECTION("Create error - long text is shortened in the message") { std::string const text = std::string(100, 'a') + "-"; std::string const shown = std::string(64, 'a') + "..."; - CHECK_THROWS_WITH(algorithm_name::create(text), + CHECK_THROWS_WITH(algorithm_name{text}, Catch::Matchers::ContainsSubstring("\"" + shown + "\"") && !Catch::Matchers::ContainsSubstring(text)); } SECTION("Create from optional plugin and algorithm") { - CHECK(algorithm_name::create(std::nullopt, "algo") == algorithm_name::create("algo")); - CHECK(algorithm_name::create("plugin", "algo") == algorithm_name::create("plugin:algo")); + CHECK(algorithm_name::create(std::nullopt, "algo") == algorithm_name{"algo"}); + CHECK(algorithm_name::create("plugin", "algo") == algorithm_name{"plugin:algo"}); // An empty plugin is not the same as an absent plugin. CHECK_THROWS_AS(algorithm_name::create("", "algo"), std::invalid_argument); CHECK_THROWS_AS(algorithm_name::create(std::nullopt, ""), std::invalid_argument); @@ -130,14 +128,13 @@ TEST_CASE("algorithm_name tests", "[model]") } SECTION("Match both") { - algorithm_name const an = algorithm_name::create("p:a"); - CHECK(an.match(algorithm_name::create("p:a"))); - CHECK_FALSE(an.match(algorithm_name::create("p:b"))); + algorithm_name const an = algorithm_name{"p:a"}; + CHECK(an.match(algorithm_name{"p:a"})); + CHECK_FALSE(an.match(algorithm_name{"p:b"})); } SECTION("Bulleted list of algorithm_name") { - std::vector const ans = {algorithm_name::create("p:a1"), - algorithm_name::create("p:a2")}; + std::vector const ans = {algorithm_name{"p:a1"}, algorithm_name{"p:a2"}}; CHECK(bulleted_list(ans) == " - p:a1\n - p:a2"); } SECTION("Empty bulleted list") @@ -237,7 +234,7 @@ TEST_CASE("Moving a registrar transfers node creation", "[core]") int creations = 0; auto creator = [&](auto const&, auto const&) -> declared_output_ptr { ++creations; - return std::make_unique(phlex::experimental::algorithm_name::create("output"), + return std::make_unique(phlex::experimental::algorithm_name{"output"}, 1, std::vector{}, graph, diff --git a/test/filter_impl_test.cpp b/test/filter_impl_test.cpp index 0a0e879ac..0c5011865 100644 --- a/test/filter_impl_test.cpp +++ b/test/filter_impl_test.cpp @@ -62,7 +62,7 @@ TEST_CASE("Filter data map", "[filtering]") data_map data{data_products_to_cache}; // Stores with the data products "a" and "b" in the spill data layer - auto const creator = algorithm_name::create("input"); + auto const creator = algorithm_name{"input"}; auto const stage = "test_stage"_id; auto creator_ptr = gsl::make_not_null(&creator); auto stage_ptr = gsl::make_not_null(&stage); @@ -94,7 +94,7 @@ TEST_CASE("Data map for output only", "[filtering]") CHECK(not data.is_complete(msg_id)); // Output-only data maps accept any store (no product lookup required) - auto const creator = algorithm_name::create("output_only"); + auto const creator = algorithm_name{"output_only"}; auto const stage = "test_stage"_id; auto store = product_store::base(gsl::make_not_null(&creator), gsl::make_not_null(&stage)); diff --git a/test/multilayer_join_test.cpp b/test/multilayer_join_test.cpp index 7103aa1f3..185007459 100644 --- a/test/multilayer_join_test.cpp +++ b/test/multilayer_join_test.cpp @@ -52,8 +52,8 @@ TEST_CASE("multilayer_join_node joins multiple input products", "[join]") oneapi::tbb::flow::graph graph; auto const stage = "test_stage"_id; - auto const left_creator_name = algorithm_name::create("left_input"); - auto const right_creator_name = algorithm_name::create("right_input"); + auto const left_creator_name = algorithm_name{"left_input"}; + auto const right_creator_name = algorithm_name{"right_input"}; auto left_store = store_with_product( gsl::make_not_null(&left_creator_name), gsl::make_not_null(&stage), input_type_1{17}); diff --git a/test/product_selector_test.cpp b/test/product_selector_test.cpp index 29bf3db39..e30314cb4 100644 --- a/test/product_selector_test.cpp +++ b/test/product_selector_test.cpp @@ -102,11 +102,11 @@ TEST_CASE("Selectors match product specifications by creator, suffix, and type", using experimental::type_id; product_specification const qualified{ - experimental::algorithm_name::create("plugin:algo"), "prod"_id, make_type_id()}; + experimental::algorithm_name{"plugin:algo"}, "prod"_id, make_type_id()}; product_specification const unqualified{ - experimental::algorithm_name::create("algo"), "prod"_id, make_type_id()}; + experimental::algorithm_name{"algo"}, "prod"_id, make_type_id()}; product_specification const empty_suffix{ - experimental::algorithm_name::create("algo"), suffix_t{}, type_id{}}; + experimental::algorithm_name{"algo"}, suffix_t{}, type_id{}}; SECTION("A creator selects by plugin or by algorithm") { diff --git a/test/product_store_test.cpp b/test/product_store_test.cpp index 0c77c84ed..20cc25fcf 100644 --- a/test/product_store_test.cpp +++ b/test/product_store_test.cpp @@ -42,8 +42,8 @@ TEST_CASE("Product specification text requires creator and slash", "[data model] { SECTION("Creator with a named suffix") { - auto const spec = product_specification::create("creator/number"); - CHECK(spec.creator() == algorithm_name::create("creator")); + auto const spec = product_specification{"creator/number"}; + CHECK(spec.creator() == algorithm_name{"creator"}); CHECK_FALSE(spec.creator().plugin().has_value()); CHECK(spec.suffix() == "number"_id); CHECK_FALSE(spec.type().valid()); @@ -51,44 +51,44 @@ TEST_CASE("Product specification text requires creator and slash", "[data model] } SECTION("Plugin-qualified creator") { - auto const spec = product_specification::create("plugin:creator/number"); - CHECK(spec.creator() == algorithm_name::create("plugin:creator")); + auto const spec = product_specification{"plugin:creator/number"}; + CHECK(spec.creator() == algorithm_name{"plugin:creator"}); CHECK(spec.suffix() == "number"_id); CHECK(spec.to_string() == "plugin:creator/number"); } SECTION("Trailing slash means an explicit empty suffix") { - auto const spec = product_specification::create("creator/"); - CHECK(spec.creator() == algorithm_name::create("creator")); + auto const spec = product_specification{"creator/"}; + CHECK(spec.creator() == algorithm_name{"creator"}); CHECK(spec.suffix() == suffix_t{}); CHECK(spec.suffix().empty()); CHECK(spec.to_string() == "creator/"); - CHECK(product_specification::create(spec.to_string()) == spec); + CHECK(product_specification{spec.to_string()} == spec); } SECTION("Implicit conversion from text") { product_specification const from_literal{"plugin:creator/number"}; - CHECK(from_literal == product_specification::create("plugin:creator/number")); + CHECK(from_literal == + product_specification{algorithm_name{"plugin:creator"}, "number"_id, type_id{}}); product_specification const from_string{std::string{"creator/"}}; - CHECK(from_string == product_specification::create("creator/")); + CHECK(from_string == product_specification{algorithm_name{"creator"}, suffix_t{}, type_id{}}); product_specification const from_view{std::string_view{"creator/number"}}; - CHECK(from_view == product_specification::create("creator/number")); + CHECK(from_view == product_specification{algorithm_name{"creator"}, "number"_id, type_id{}}); } SECTION("Invalid forms are rejected") { - CHECK_THROWS(product_specification::create("")); - CHECK_THROWS(product_specification::create("number")); - CHECK_THROWS(product_specification::create("creator")); - CHECK_THROWS(product_specification::create("/number")); - CHECK_THROWS(product_specification::create("/")); - CHECK_THROWS(product_specification::create("plugin:/number")); - CHECK_THROWS(product_specification::create(":creator/number")); - CHECK_THROWS(product_specification::create("creator/a/b")); + CHECK_THROWS(product_specification{""}); CHECK_THROWS(product_specification{"number"}); + CHECK_THROWS(product_specification{"creator"}); + CHECK_THROWS(product_specification{"/number"}); + CHECK_THROWS(product_specification{"/"}); + CHECK_THROWS(product_specification{"plugin:/number"}); + CHECK_THROWS(product_specification{":creator/number"}); + CHECK_THROWS(product_specification{"creator/a/b"}); // Malformed creator text is reported by algorithm_name, as invalid_argument. - CHECK_THROWS_AS(product_specification::create("_x/number"), std::invalid_argument); + CHECK_THROWS_AS(product_specification{"_x/number"}, std::invalid_argument); CHECK_THROWS_WITH( - product_specification::create("1p:a/number"), + product_specification{"1p:a/number"}, Catch::Matchers::ContainsSubstring("Invalid algorithm name \"1p:a\": " "plugin label \"1p\" " + std::string{phlex::detail::identifier_rule})); @@ -98,7 +98,7 @@ TEST_CASE("Product specification text requires creator and slash", "[data model] TEST_CASE("Product specification type mutation", "[data model]") { - auto spec = product_specification::create("creator/number"); + auto spec = product_specification{"creator/number"}; REQUIRE_FALSE(spec.type().valid()); spec.set_type(make_type_id()); @@ -109,15 +109,15 @@ TEST_CASE("Product specification type mutation", "[data model]") spec.set_type(type_id{}); CHECK_FALSE(spec.type().valid()); - CHECK(spec == product_specification::create("creator/number")); - CHECK(spec.creator() == algorithm_name::create("creator")); + CHECK(spec == product_specification{"creator/number"}); + CHECK(spec.creator() == algorithm_name{"creator"}); CHECK(spec.suffix() == "number"_id); } TEST_CASE("Product specification hash and equality", "[data model]") { - auto const creator = algorithm_name::create("plugin:producer"); - auto const unqualified = algorithm_name::create("producer"); + auto const creator = algorithm_name{"plugin:producer"}; + auto const unqualified = algorithm_name{"producer"}; product_specification const named{creator, "number"_id, make_type_id()}; product_specification const unqualified_spec{unqualified, "number"_id, make_type_id()}; product_specification const untyped{creator, "number"_id, type_id{}}; @@ -149,8 +149,8 @@ TEST_CASE("Product specification hash and equality", "[data model]") CHECK(specs.contains(product_specification{unqualified, "number"_id, make_type_id()})); CHECK_FALSE(specs.contains(product_specification{creator, "other"_id, make_type_id()})); CHECK_FALSE(specs.contains(product_specification{creator, "number"_id, make_type_id()})); - CHECK_FALSE(specs.contains(product_specification{ - algorithm_name::create("plugin:other"), "number"_id, make_type_id()})); + CHECK_FALSE(specs.contains( + product_specification{algorithm_name{"plugin:other"}, "number"_id, make_type_id()})); } TEST_CASE("Product store default source", "[data model]") @@ -164,7 +164,7 @@ TEST_CASE("Product store default source", "[data model]") TEST_CASE("Product store insertion", "[data model]") { - auto const creator = algorithm_name::create("test_algorithm"); + auto const creator = algorithm_name{"test_algorithm"}; auto const stage = "test_stage"_id; auto creator_ptr = gsl::make_not_null(&creator); auto stage_ptr = gsl::make_not_null(&stage); @@ -206,7 +206,7 @@ TEST_CASE("Product retrieval requires exactly one match", "[data model]") { using Catch::Matchers::ContainsSubstring; - auto const creator = algorithm_name::create("test_algorithm"); + auto const creator = algorithm_name{"test_algorithm"}; auto const stage = "test_stage"_id; auto store = product_store::base(gsl::make_not_null(&creator), gsl::make_not_null(&stage)); phlex::detail::message const msg{.store = store}; @@ -258,7 +258,7 @@ TEST_CASE("Product store derivation", "[data model]") { using namespace phlex::experimental::detail; - auto const creator = algorithm_name::create("test_algorithm"); + auto const creator = algorithm_name{"test_algorithm"}; auto const stage = "test_stage"_id; auto creator_ptr = gsl::make_not_null(&creator); auto stage_ptr = gsl::make_not_null(&stage); diff --git a/test/repeater_node_test.cpp b/test/repeater_node_test.cpp index 5eb383cae..38cba1f82 100644 --- a/test/repeater_node_test.cpp +++ b/test/repeater_node_test.cpp @@ -32,8 +32,7 @@ namespace { auto make_run_with_product(int run_number, int value) { - static auto const dummy_creator_name = - phlex::experimental::algorithm_name::create("test_algorithm"); + static auto const dummy_creator_name = phlex::experimental::algorithm_name{"test_algorithm"}; static auto const dummy_stage_name = "test_stage"_id; auto index = make_run_index(run_number); auto store = std::make_shared( diff --git a/test/transform_node_test.cpp b/test/transform_node_test.cpp index ab566f911..af86975c3 100644 --- a/test/transform_node_test.cpp +++ b/test/transform_node_test.cpp @@ -106,7 +106,7 @@ namespace { TEST_CASE("transform_node directly transforms one input product", "[transform_node]") { oneapi::tbb::flow::graph graph; - auto const input_creator_name = algorithm_name::create("input"); + auto const input_creator_name = algorithm_name{"input"}; identifier const stage_name = "test_stage"_id; auto input_selector = selector(input_creator_name); auto input_store = store_with_product( @@ -153,7 +153,7 @@ TEST_CASE("transform_node directly transforms one input product", "[transform_no TEST_CASE("transform_node stores multiple output products", "[transform_node]") { oneapi::tbb::flow::graph graph; - auto const input_creator_name = algorithm_name::create("input"); + auto const input_creator_name = algorithm_name{"input"}; identifier const stage{"test_stage"}; auto input_selector = selector(input_creator_name); auto input_store = @@ -203,7 +203,7 @@ TEST_CASE("transform_node stores multiple output products", "[transform_node]") TEST_CASE("transform_node receives a resource token", "[transform_node][resource]") { oneapi::tbb::flow::graph graph; - auto const input_creator_name = algorithm_name::create("input"); + auto const input_creator_name = algorithm_name{"input"}; identifier const stage_name = "test_stage"_id; auto input_selector = selector(input_creator_name); auto input_store = store_with_product( @@ -239,7 +239,7 @@ TEST_CASE("transform_node receives a resource token", "[transform_node][resource TEST_CASE("transform_node receives an unlimited resource", "[transform_node][resource]") { oneapi::tbb::flow::graph graph; - auto const input_creator_name = algorithm_name::create("input"); + auto const input_creator_name = algorithm_name{"input"}; identifier const stage_name = "test_stage"_id; auto input_selector = selector(input_creator_name); auto input_store = store_with_product( From 985b7b4869593d56a913fb40b88f7035dc94196c Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Fri, 20 Nov 2026 13:06:11 -0600 Subject: [PATCH 23/28] refactor(model): move excerpt definition into source file Move excerpt() out of the private detail header into detail/excerpt.cpp so the fmt dependency is no longer pulled into every includer. The function's behavior is unchanged. --- phlex/model/CMakeLists.txt | 1 + phlex/model/detail/excerpt.cpp | 18 ++++++++++++++++++ phlex/model/detail/excerpt.hpp | 11 +---------- 3 files changed, 20 insertions(+), 10 deletions(-) create mode 100644 phlex/model/detail/excerpt.cpp diff --git a/phlex/model/CMakeLists.txt b/phlex/model/CMakeLists.txt index 0895b3e69..c4e82da87 100644 --- a/phlex/model/CMakeLists.txt +++ b/phlex/model/CMakeLists.txt @@ -4,6 +4,7 @@ cet_make_library( SHARED SOURCE algorithm_name.cpp + detail/excerpt.cpp data_cell_counts.cpp data_cell_tracker.cpp flush_gate.cpp diff --git a/phlex/model/detail/excerpt.cpp b/phlex/model/detail/excerpt.cpp new file mode 100644 index 000000000..6da487b8b --- /dev/null +++ b/phlex/model/detail/excerpt.cpp @@ -0,0 +1,18 @@ +#include "phlex/model/detail/excerpt.hpp" + +#include + +#include +#include +#include + +namespace phlex::detail { + std::string excerpt(std::string_view text) + { + std::string shown{text.substr(0, max_excerpt_length)}; + if (text.size() > max_excerpt_length) { + shown += "..."; + } + return fmt::format("{:?}", shown); + } +} diff --git a/phlex/model/detail/excerpt.hpp b/phlex/model/detail/excerpt.hpp index 069165ae3..9dc0fd71e 100644 --- a/phlex/model/detail/excerpt.hpp +++ b/phlex/model/detail/excerpt.hpp @@ -3,8 +3,6 @@ // Private to the phlex_model library; this header is intentionally not installed. -#include - #include #include #include @@ -15,14 +13,7 @@ namespace phlex::detail { /// Quotes and escapes `text` for an error message, shortening it with a trailing `...` /// inside the quotes when it exceeds `max_excerpt_length` characters. - inline std::string excerpt(std::string_view text) - { - std::string shown{text.substr(0, max_excerpt_length)}; - if (text.size() > max_excerpt_length) { - shown += "..."; - } - return fmt::format("{:?}", shown); - } + std::string excerpt(std::string_view text); } #endif // PHLEX_MODEL_DETAIL_EXCERPT_HPP From bf806ff236582bce106192510871094427a6f88e Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Fri, 20 Nov 2026 13:14:27 -0600 Subject: [PATCH 24/28] test: rename invalid-identifier test fixtures Rename the badname transform test and its Jsonnet config to invalid_transform_name, and replace malformed selector values with descriptive strings (bad creator, bad layer, bad suffix) so each case names the field it exercises. --- test/config_test.cpp | 4 ++-- test/python/CMakeLists.txt | 8 ++++---- test/python/{badname.py => invalid_transform_name.py} | 0 ...pybadname.jsonnet => pyinvalid_transform_name.jsonnet} | 4 ++-- test/python/pyprovide.py | 8 ++++---- test/python/suffix.py | 2 +- 6 files changed, 13 insertions(+), 13 deletions(-) rename test/python/{badname.py => invalid_transform_name.py} (100%) rename test/python/{pybadname.jsonnet => pyinvalid_transform_name.jsonnet} (77%) diff --git a/test/config_test.cpp b/test/config_test.cpp index e96519d01..4b510461a 100644 --- a/test/config_test.cpp +++ b/test/config_test.cpp @@ -62,7 +62,7 @@ TEST_CASE("Retrieve product_selector", "[config]") boost::json::object malformed_input5; malformed_input5["creator"] = "hits"; - malformed_input5["suffix"] = "bad name"; + malformed_input5["suffix"] = "bad suffix"; boost::json::object underlying_config; underlying_config["input"] = std::move(input); @@ -99,6 +99,6 @@ TEST_CASE("Retrieve product_selector", "[config]") CHECK_THROWS_WITH(config.get("malformed5"), ContainsSubstring("Error retrieving parameter 'malformed5'") && ContainsSubstring("Invalid product selector field \"suffix\": " - "Invalid identifier \"bad name\": an identifier " + + "Invalid identifier \"bad suffix\": an identifier " + std::string{phlex::detail::identifier_rule})); } diff --git a/test/python/CMakeLists.txt b/test/python/CMakeLists.txt index f67f6cb3e..cc783b8fc 100644 --- a/test/python/CMakeLists.txt +++ b/test/python/CMakeLists.txt @@ -232,16 +232,16 @@ set_tests_properties( list(APPEND ACTIVE_PY_CPHLEX_TESTS py:baduint) add_test( - NAME py:badname - COMMAND phlex::phlex -c ${CMAKE_CURRENT_SOURCE_DIR}/pybadname.jsonnet --stage test + NAME py:invalid_transform_name + COMMAND phlex::phlex -c ${CMAKE_CURRENT_SOURCE_DIR}/pyinvalid_transform_name.jsonnet --stage test ) set_tests_properties( - py:badname + py:invalid_transform_name PROPERTIES PASS_REGULAR_EXPRESSION "ValueError: Invalid identifier \"bad name\": an identifier must not be empty and must start with an ASCII letter" ) -list(APPEND ACTIVE_PY_CPHLEX_TESTS py:badname) +list(APPEND ACTIVE_PY_CPHLEX_TESTS py:invalid_transform_name) add_test( NAME py:mismatch_variant diff --git a/test/python/badname.py b/test/python/invalid_transform_name.py similarity index 100% rename from test/python/badname.py rename to test/python/invalid_transform_name.py diff --git a/test/python/pybadname.jsonnet b/test/python/pyinvalid_transform_name.jsonnet similarity index 77% rename from test/python/pybadname.jsonnet rename to test/python/pyinvalid_transform_name.jsonnet index de30f1aa4..dcf83b860 100644 --- a/test/python/pybadname.jsonnet +++ b/test/python/pyinvalid_transform_name.jsonnet @@ -11,8 +11,8 @@ }, }, modules: { - badname: { - py: 'badname', + invalid_transform_name: { + py: 'invalid_transform_name', }, }, } diff --git a/test/python/pyprovide.py b/test/python/pyprovide.py index 0745ffdf6..8e9d97fca 100644 --- a/test/python/pyprovide.py +++ b/test/python/pyprovide.py @@ -136,10 +136,10 @@ def __call__(self, di): # malformed text in a provider output is a ValueError that names the offending field for selector, field in [ - ({"creator": "a b", "layer": "b", "suffix": "c"}, "creator"), - ({"creator": "a:b:c", "layer": "b", "suffix": "c"}, "creator"), - ({"creator": "a", "layer": "1b", "suffix": "c"}, "layer"), - ({"creator": "a", "layer": "b", "suffix": "c d"}, "suffix"), + ({"creator": "bad creator", "layer": "b", "suffix": "c"}, "creator"), + ({"creator": "bad:creator:name", "layer": "b", "suffix": "c"}, "creator"), + ({"creator": "a", "layer": "1bad_layer", "suffix": "c"}, "layer"), + ({"creator": "a", "layer": "b", "suffix": "bad suffix"}, "suffix"), ]: try: s.provide(freq, selector) diff --git a/test/python/suffix.py b/test/python/suffix.py index b88f5064e..9d33ab38a 100644 --- a/test/python/suffix.py +++ b/test/python/suffix.py @@ -81,7 +81,7 @@ def PHLEX_REGISTER_ALGORITHMS(m, config): # malformed text in an input selector is a ValueError that names the offending field for input_query, field in ( ({"creator": "bad creator", "layer": "event", "suffix": "i"}, "creator"), - ({"creator": "input", "layer": "event layer", "suffix": "i"}, "layer"), + ({"creator": "input", "layer": "bad layer", "suffix": "i"}, "layer"), ({"creator": "input", "layer": "event", "suffix": "bad suffix"}, "suffix"), ): try: From fe6cc45974dde5211f72cc8e303f5c4b4f9d864a Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Fri, 20 Nov 2026 13:45:45 -0600 Subject: [PATCH 25/28] test: remove make_child empty-name throw assertion --- test/data_layer_hierarchy_test.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/test/data_layer_hierarchy_test.cpp b/test/data_layer_hierarchy_test.cpp index cf34ca549..22f8b66a2 100644 --- a/test/data_layer_hierarchy_test.cpp +++ b/test/data_layer_hierarchy_test.cpp @@ -38,7 +38,6 @@ TEST_CASE("Data layer hierarchy requires named layers", "[data model]") data_layer_hierarchy h; auto job_index = data_cell_index::job(); CHECK_NOTHROW(h.increment_count(job_index)); - CHECK_THROWS(job_index->make_child("", 0)); CHECK_NOTHROW(h.to_string()); } From 50a5eaca96f3b0e9e6f7ecdbd02575a02cd65a7a Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Fri, 20 Nov 2026 13:51:16 -0600 Subject: [PATCH 26/28] test: move product specification tests to their own file Move the product_specification test cases out of product_store_test.cpp into test/product_specification_test.cpp and register the new target in test/CMakeLists.txt. The moved test bodies are unchanged; only the includes needed by each file are adjusted. --- test/CMakeLists.txt | 3 + test/product_specification_test.cpp | 145 ++++++++++++++++++++++++++++ test/product_store_test.cpp | 132 ------------------------- 3 files changed, 148 insertions(+), 132 deletions(-) create mode 100644 test/product_specification_test.cpp diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index 920914aac..093daf3c6 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -219,6 +219,9 @@ cet_test(product_handle USE_CATCH2_MAIN SOURCE product_handle_test.cpp LIBRARIES cet_test(product_store USE_CATCH2_MAIN SOURCE product_store_test.cpp LIBRARIES phlex::core_internal ) +cet_test(product_specification USE_CATCH2_MAIN SOURCE product_specification_test.cpp LIBRARIES + phlex::model_internal +) cet_test(producer_catalog USE_CATCH2_MAIN SOURCE producer_catalog_test.cpp LIBRARIES phlex::core_internal ) diff --git a/test/product_specification_test.cpp b/test/product_specification_test.cpp new file mode 100644 index 000000000..696889a9a --- /dev/null +++ b/test/product_specification_test.cpp @@ -0,0 +1,145 @@ +#include "phlex/model/algorithm_name.hpp" +#include "phlex/model/identifier.hpp" +#include "phlex/model/product_specification.hpp" +#include "phlex/model/type_id.hpp" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace phlex::experimental; +using namespace phlex::experimental::literals; + +TEST_CASE("Product specification requires a creator", "[data model]") +{ + STATIC_CHECK_FALSE(std::is_default_constructible_v); + STATIC_CHECK_FALSE( + std::is_constructible_v); + STATIC_CHECK( + std::is_same_v().creator())>, + algorithm_name>); +} + +TEST_CASE("Product specification text requires creator and slash", "[data model]") +{ + SECTION("Creator with a named suffix") + { + auto const spec = product_specification{"creator/number"}; + CHECK(spec.creator() == algorithm_name{"creator"}); + CHECK_FALSE(spec.creator().plugin().has_value()); + CHECK(spec.suffix() == "number"_id); + CHECK_FALSE(spec.type().valid()); + CHECK(spec.to_string() == "creator/number"); + } + SECTION("Plugin-qualified creator") + { + auto const spec = product_specification{"plugin:creator/number"}; + CHECK(spec.creator() == algorithm_name{"plugin:creator"}); + CHECK(spec.suffix() == "number"_id); + CHECK(spec.to_string() == "plugin:creator/number"); + } + SECTION("Trailing slash means an explicit empty suffix") + { + auto const spec = product_specification{"creator/"}; + CHECK(spec.creator() == algorithm_name{"creator"}); + CHECK(spec.suffix() == suffix_t{}); + CHECK(spec.suffix().empty()); + CHECK(spec.to_string() == "creator/"); + CHECK(product_specification{spec.to_string()} == spec); + } + SECTION("Implicit conversion from text") + { + product_specification const from_literal{"plugin:creator/number"}; + CHECK(from_literal == + product_specification{algorithm_name{"plugin:creator"}, "number"_id, type_id{}}); + product_specification const from_string{std::string{"creator/"}}; + CHECK(from_string == product_specification{algorithm_name{"creator"}, suffix_t{}, type_id{}}); + product_specification const from_view{std::string_view{"creator/number"}}; + CHECK(from_view == product_specification{algorithm_name{"creator"}, "number"_id, type_id{}}); + } + SECTION("Invalid forms are rejected") + { + CHECK_THROWS(product_specification{""}); + CHECK_THROWS(product_specification{"number"}); + CHECK_THROWS(product_specification{"creator"}); + CHECK_THROWS(product_specification{"/number"}); + CHECK_THROWS(product_specification{"/"}); + CHECK_THROWS(product_specification{"plugin:/number"}); + CHECK_THROWS(product_specification{":creator/number"}); + CHECK_THROWS(product_specification{"creator/a/b"}); + // Malformed creator text is reported by algorithm_name, as invalid_argument. + CHECK_THROWS_AS(product_specification{"_x/number"}, std::invalid_argument); + CHECK_THROWS_WITH( + product_specification{"1p:a/number"}, + Catch::Matchers::ContainsSubstring("Invalid algorithm name \"1p:a\": " + "plugin label \"1p\" " + + std::string{phlex::detail::identifier_rule})); + CHECK_THROWS(product_specification{std::string{"/number"}}); + } +} + +TEST_CASE("Product specification type mutation", "[data model]") +{ + auto spec = product_specification{"creator/number"}; + REQUIRE_FALSE(spec.type().valid()); + + spec.set_type(make_type_id()); + CHECK(spec.type() == make_type_id()); + + spec.set_type(make_type_id()); + CHECK(spec.type() == make_type_id()); + + spec.set_type(type_id{}); + CHECK_FALSE(spec.type().valid()); + CHECK(spec == product_specification{"creator/number"}); + CHECK(spec.creator() == algorithm_name{"creator"}); + CHECK(spec.suffix() == "number"_id); +} + +TEST_CASE("Product specification hash and equality", "[data model]") +{ + auto const creator = algorithm_name{"plugin:producer"}; + auto const unqualified = algorithm_name{"producer"}; + product_specification const named{creator, "number"_id, make_type_id()}; + product_specification const unqualified_spec{unqualified, "number"_id, make_type_id()}; + product_specification const untyped{creator, "number"_id, type_id{}}; + product_specification const empty_suffix{creator, suffix_t{}, make_type_id()}; + std::hash const hash; + + CHECK(hash(named) == hash(product_specification{creator, "number"_id, make_type_id()})); + CHECK(hash(untyped) == hash(product_specification{creator, "number"_id, type_id{}})); + CHECK(hash(empty_suffix) == + hash(product_specification{creator, suffix_t{}, make_type_id()})); + + // Every component participates in identity; an unspecified type is not a wildcard. + CHECK(named != unqualified_spec); + CHECK(named != untyped); + CHECK(named != empty_suffix); + CHECK(named != product_specification{creator, "other"_id, make_type_id()}); + CHECK(named != product_specification{creator, "number"_id, make_type_id()}); + + std::unordered_set specs; + CHECK(specs.insert(named).second); + CHECK(specs.insert(unqualified_spec).second); + CHECK(specs.insert(untyped).second); + CHECK(specs.insert(empty_suffix).second); + CHECK_FALSE( + specs.insert(product_specification{creator, "number"_id, make_type_id()}).second); + CHECK_FALSE(specs.insert(product_specification{creator, "number"_id, type_id{}}).second); + CHECK(specs.size() == 4u); + CHECK(specs.contains(product_specification{creator, "number"_id, make_type_id()})); + CHECK(specs.contains(product_specification{unqualified, "number"_id, make_type_id()})); + CHECK_FALSE(specs.contains(product_specification{creator, "other"_id, make_type_id()})); + CHECK_FALSE(specs.contains(product_specification{creator, "number"_id, make_type_id()})); + CHECK_FALSE(specs.contains( + product_specification{algorithm_name{"plugin:other"}, "number"_id, make_type_id()})); +} diff --git a/test/product_store_test.cpp b/test/product_store_test.cpp index 20cc25fcf..751d7ee34 100644 --- a/test/product_store_test.cpp +++ b/test/product_store_test.cpp @@ -13,146 +13,14 @@ #include #include -#include #include -#include #include -#include -#include #include -#include -#include -#include #include using namespace phlex::experimental; using namespace phlex::experimental::literals; -TEST_CASE("Product specification requires a creator", "[data model]") -{ - STATIC_CHECK_FALSE(std::is_default_constructible_v); - STATIC_CHECK_FALSE( - std::is_constructible_v); - STATIC_CHECK( - std::is_same_v().creator())>, - algorithm_name>); -} - -TEST_CASE("Product specification text requires creator and slash", "[data model]") -{ - SECTION("Creator with a named suffix") - { - auto const spec = product_specification{"creator/number"}; - CHECK(spec.creator() == algorithm_name{"creator"}); - CHECK_FALSE(spec.creator().plugin().has_value()); - CHECK(spec.suffix() == "number"_id); - CHECK_FALSE(spec.type().valid()); - CHECK(spec.to_string() == "creator/number"); - } - SECTION("Plugin-qualified creator") - { - auto const spec = product_specification{"plugin:creator/number"}; - CHECK(spec.creator() == algorithm_name{"plugin:creator"}); - CHECK(spec.suffix() == "number"_id); - CHECK(spec.to_string() == "plugin:creator/number"); - } - SECTION("Trailing slash means an explicit empty suffix") - { - auto const spec = product_specification{"creator/"}; - CHECK(spec.creator() == algorithm_name{"creator"}); - CHECK(spec.suffix() == suffix_t{}); - CHECK(spec.suffix().empty()); - CHECK(spec.to_string() == "creator/"); - CHECK(product_specification{spec.to_string()} == spec); - } - SECTION("Implicit conversion from text") - { - product_specification const from_literal{"plugin:creator/number"}; - CHECK(from_literal == - product_specification{algorithm_name{"plugin:creator"}, "number"_id, type_id{}}); - product_specification const from_string{std::string{"creator/"}}; - CHECK(from_string == product_specification{algorithm_name{"creator"}, suffix_t{}, type_id{}}); - product_specification const from_view{std::string_view{"creator/number"}}; - CHECK(from_view == product_specification{algorithm_name{"creator"}, "number"_id, type_id{}}); - } - SECTION("Invalid forms are rejected") - { - CHECK_THROWS(product_specification{""}); - CHECK_THROWS(product_specification{"number"}); - CHECK_THROWS(product_specification{"creator"}); - CHECK_THROWS(product_specification{"/number"}); - CHECK_THROWS(product_specification{"/"}); - CHECK_THROWS(product_specification{"plugin:/number"}); - CHECK_THROWS(product_specification{":creator/number"}); - CHECK_THROWS(product_specification{"creator/a/b"}); - // Malformed creator text is reported by algorithm_name, as invalid_argument. - CHECK_THROWS_AS(product_specification{"_x/number"}, std::invalid_argument); - CHECK_THROWS_WITH( - product_specification{"1p:a/number"}, - Catch::Matchers::ContainsSubstring("Invalid algorithm name \"1p:a\": " - "plugin label \"1p\" " + - std::string{phlex::detail::identifier_rule})); - CHECK_THROWS(product_specification{std::string{"/number"}}); - } -} - -TEST_CASE("Product specification type mutation", "[data model]") -{ - auto spec = product_specification{"creator/number"}; - REQUIRE_FALSE(spec.type().valid()); - - spec.set_type(make_type_id()); - CHECK(spec.type() == make_type_id()); - - spec.set_type(make_type_id()); - CHECK(spec.type() == make_type_id()); - - spec.set_type(type_id{}); - CHECK_FALSE(spec.type().valid()); - CHECK(spec == product_specification{"creator/number"}); - CHECK(spec.creator() == algorithm_name{"creator"}); - CHECK(spec.suffix() == "number"_id); -} - -TEST_CASE("Product specification hash and equality", "[data model]") -{ - auto const creator = algorithm_name{"plugin:producer"}; - auto const unqualified = algorithm_name{"producer"}; - product_specification const named{creator, "number"_id, make_type_id()}; - product_specification const unqualified_spec{unqualified, "number"_id, make_type_id()}; - product_specification const untyped{creator, "number"_id, type_id{}}; - product_specification const empty_suffix{creator, suffix_t{}, make_type_id()}; - std::hash const hash; - - CHECK(hash(named) == hash(product_specification{creator, "number"_id, make_type_id()})); - CHECK(hash(untyped) == hash(product_specification{creator, "number"_id, type_id{}})); - CHECK(hash(empty_suffix) == - hash(product_specification{creator, suffix_t{}, make_type_id()})); - - // Every component participates in identity; an unspecified type is not a wildcard. - CHECK(named != unqualified_spec); - CHECK(named != untyped); - CHECK(named != empty_suffix); - CHECK(named != product_specification{creator, "other"_id, make_type_id()}); - CHECK(named != product_specification{creator, "number"_id, make_type_id()}); - - std::unordered_set specs; - CHECK(specs.insert(named).second); - CHECK(specs.insert(unqualified_spec).second); - CHECK(specs.insert(untyped).second); - CHECK(specs.insert(empty_suffix).second); - CHECK_FALSE( - specs.insert(product_specification{creator, "number"_id, make_type_id()}).second); - CHECK_FALSE(specs.insert(product_specification{creator, "number"_id, type_id{}}).second); - CHECK(specs.size() == 4u); - CHECK(specs.contains(product_specification{creator, "number"_id, make_type_id()})); - CHECK(specs.contains(product_specification{unqualified, "number"_id, make_type_id()})); - CHECK_FALSE(specs.contains(product_specification{creator, "other"_id, make_type_id()})); - CHECK_FALSE(specs.contains(product_specification{creator, "number"_id, make_type_id()})); - CHECK_FALSE(specs.contains( - product_specification{algorithm_name{"plugin:other"}, "number"_id, make_type_id()})); -} - TEST_CASE("Product store default source", "[data model]") { auto const source = product_store::default_source(); From 468c225cb83207a680d008ecc62952be93d9a2b2 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Fri, 20 Nov 2026 14:00:02 -0600 Subject: [PATCH 27/28] test: verify product specification hash via set deduplication Replace the direct `std::hash` equality checks with duplicate insertions into an `std::unordered_set`. Equal specifications must hash equal to be deduplicated, so the set checks cover the same contract. Add a duplicate check for an empty suffix and a comment explaining the hash/equality expectation. --- test/product_specification_test.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/test/product_specification_test.cpp b/test/product_specification_test.cpp index 696889a9a..ee968b4c2 100644 --- a/test/product_specification_test.cpp +++ b/test/product_specification_test.cpp @@ -113,12 +113,6 @@ TEST_CASE("Product specification hash and equality", "[data model]") product_specification const unqualified_spec{unqualified, "number"_id, make_type_id()}; product_specification const untyped{creator, "number"_id, type_id{}}; product_specification const empty_suffix{creator, suffix_t{}, make_type_id()}; - std::hash const hash; - - CHECK(hash(named) == hash(product_specification{creator, "number"_id, make_type_id()})); - CHECK(hash(untyped) == hash(product_specification{creator, "number"_id, type_id{}})); - CHECK(hash(empty_suffix) == - hash(product_specification{creator, suffix_t{}, make_type_id()})); // Every component participates in identity; an unspecified type is not a wildcard. CHECK(named != unqualified_spec); @@ -127,6 +121,12 @@ TEST_CASE("Product specification hash and equality", "[data model]") CHECK(named != product_specification{creator, "other"_id, make_type_id()}); CHECK(named != product_specification{creator, "number"_id, make_type_id()}); + // The duplicate insertions below test the hash/equality contract: separately constructed + // specifications with equal values must hash equal, so that they land in the same bucket and + // are recognized as duplicates. This would fail if the hash depended on object identity + // (e.g. addresses) or on anything else not determined by the specification's value. The + // default-constructed suffix and the unspecified type are included because they are edge cases + // of the component hashes. std::unordered_set specs; CHECK(specs.insert(named).second); CHECK(specs.insert(unqualified_spec).second); @@ -135,6 +135,7 @@ TEST_CASE("Product specification hash and equality", "[data model]") CHECK_FALSE( specs.insert(product_specification{creator, "number"_id, make_type_id()}).second); CHECK_FALSE(specs.insert(product_specification{creator, "number"_id, type_id{}}).second); + CHECK_FALSE(specs.insert(product_specification{creator, suffix_t{}, make_type_id()}).second); CHECK(specs.size() == 4u); CHECK(specs.contains(product_specification{creator, "number"_id, make_type_id()})); CHECK(specs.contains(product_specification{unqualified, "number"_id, make_type_id()})); From 79b6a9f860a5c97abfd42e6d461190dbb6313743 Mon Sep 17 00:00:00 2001 From: Marc Paterno Date: Fri, 20 Nov 2026 14:54:42 -0600 Subject: [PATCH 28/28] refactor: Generalize product selector field conversion Make detail::value_if_exists a header-only template that converts to any type T via boost::json::value_to, and read product selector fields through it. The suffix field is converted by a tag_invoke overload for suffix_t, so the optional and error handling of each field is shared. Malformed fields still report the field name in the error message. Update identifier_test to call the templated value_if_exists. --- phlex/configuration.cpp | 69 +++++++++++++++++++--------------------- phlex/configuration.hpp | 15 +++++++-- test/identifier_test.cpp | 2 +- 3 files changed, 45 insertions(+), 41 deletions(-) diff --git a/phlex/configuration.cpp b/phlex/configuration.cpp index 988471a8d..08355498e 100644 --- a/phlex/configuration.cpp +++ b/phlex/configuration.cpp @@ -6,7 +6,6 @@ #include #include #include -#include #include #include @@ -17,34 +16,34 @@ #include #include #include -#include #include -namespace phlex::detail { - std::optional value_if_exists( - boost::json::object const& obj, // will be used later for new product_selector - std::string_view parameter) - { - if (!obj.contains(parameter)) { - return std::nullopt; +namespace phlex::experimental { + // The unnamed namespace gives this helper internal linkage. It is inline so that its members + // are still found by argument-dependent lookup in phlex::experimental. + inline namespace { + // Boost.JSON conversion to suffix_t, used when reading a product selector's "suffix" field. + // boost::json::value_to finds tag_invoke overloads by argument-dependent lookup, which + // searches phlex::experimental, the namespace of suffix_t, and its inline namespaces. + suffix_t tag_invoke(boost::json::value_to_tag const&, boost::json::value const& jv) + { + return suffix_t{std::string_view{jv.as_string()}}; } - auto const& val = obj.at(parameter); - return boost::json::value_to(val); } } namespace phlex { namespace { - // Reports a malformed value together with the name of the product selector field that held it. - template - auto in_selector_field(std::string_view field, Convert&& convert) - { - try { - return std::forward(convert)(); - } catch (std::invalid_argument const& e) { - throw std::invalid_argument{ - fmt::format("Invalid product selector field \"{}\": {}", field, e.what())}; - } + // Returns the product selector field named `field` converted to T, or std::nullopt when it is + // absent. A malformed value is reported together with the name of the field that held it. + template + std::optional in_selector_field(boost::json::object const& query_object, + std::string_view field) + try { + return detail::value_if_exists(query_object, field); + } catch (std::invalid_argument const& e) { + throw std::invalid_argument{ + fmt::format("Invalid product selector field \"{}\": {}", field, e.what())}; } } @@ -66,11 +65,13 @@ namespace phlex { product_selector tag_invoke(boost::json::value_to_tag const&, boost::json::value const& jv) { - using detail::value_if_exists; + using experimental::identifier; + using experimental::suffix_t; using namespace std::string_view_literals; static std::set const valid_keys = { "creator"sv, "layer"sv, "suffix"sv, "stage"sv}; - auto query_object = jv.as_object(); + // A reference into `jv`: the selector is only read here, so no copy of the object is needed. + auto const& query_object = jv.as_object(); std::set unrecognized_keys = {}; for (auto const& [key, _] : query_object) { if (!valid_keys.contains(key)) { @@ -81,20 +82,14 @@ namespace phlex { throw std::runtime_error( fmt::format("Product selector contains unrecognized keys: {}", unrecognized_keys)); } - auto creator = - in_selector_field("creator", [&] { return value_if_exists(query_object, "creator"); }); - auto layer = in_selector_field("layer", [&] { return value_if_exists(query_object, "layer"); }); - std::optional suffix; - if (query_object.contains("suffix")) { - suffix = in_selector_field("suffix", [&] { - return experimental::suffix_t{std::string_view{query_object.at("suffix").as_string()}}; - }); - } - auto stage = in_selector_field("stage", [&] { return value_if_exists(query_object, "stage"); }); - return product_selector{.creator = std::move(creator), - .layer = std::move(layer), - .suffix = std::move(suffix), - .stage = stage}; + // Each field is initialized directly from the value returned by in_selector_field, so no + // field value is copied or moved through a named local. The initializers of a braced list are + // evaluated in order, so fields are read in declaration order and the first malformed field + // in that order is the one reported. + return product_selector{.creator = in_selector_field(query_object, "creator"), + .layer = in_selector_field(query_object, "layer"), + .suffix = in_selector_field(query_object, "suffix"), + .stage = in_selector_field(query_object, "stage")}; } experimental::identifier experimental::tag_invoke(boost::json::value_to_tag const&, diff --git a/phlex/configuration.hpp b/phlex/configuration.hpp index f64a6e2ce..775e292ca 100644 --- a/phlex/configuration.hpp +++ b/phlex/configuration.hpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -23,9 +24,17 @@ namespace phlex { throw std::runtime_error("Error retrieving parameter '" + key + "':\n" + e.what()); } - // Used later for product_selector - PHLEX_CONFIGURATION_INTERNAL_EXPORT std::optional value_if_exists( - boost::json::object const& obj, std::string_view parameter); + // Returns the value stored under `parameter` in `obj` converted to T with + // boost::json::value_to, or std::nullopt when `obj` has no such key. Exceptions thrown by the + // conversion propagate unchanged. + template + std::optional value_if_exists(boost::json::object const& obj, std::string_view parameter) + { + if (!obj.contains(parameter)) { + return std::nullopt; + } + return boost::json::value_to(obj.at(parameter)); + } // helper for unpacking json array template diff --git a/test/identifier_test.cpp b/test/identifier_test.cpp index 56ecb67fe..96495a8dc 100644 --- a/test/identifier_test.cpp +++ b/test/identifier_test.cpp @@ -159,7 +159,7 @@ TEST_CASE("Identifier from JSON", "[identifier]") identifier b = "b"_id; boost::json::object const parsed_json = boost::json::parse(R"( {"identifier": "b" } )").as_object(); - auto b_from_json = phlex::detail::value_if_exists(parsed_json, "identifier"); + auto b_from_json = phlex::detail::value_if_exists(parsed_json, "identifier"); REQUIRE(b_from_json); // NOLINTNEXTLINE(bugprone-unchecked-optional-access) -- `REQUIRE` protects against incorrect access CHECK(b == *b_from_json);