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 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..6e970b4a5 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_), identifier{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{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 be391140d..08355498e 100644 --- a/phlex/configuration.cpp +++ b/phlex/configuration.cpp @@ -6,7 +6,6 @@ #include #include #include -#include #include #include @@ -17,23 +16,37 @@ #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 { + // 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())}; + } + } + std::vector configuration::keys() const { std::vector result; @@ -52,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)) { @@ -67,12 +82,14 @@ 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 suffix = value_if_exists(query_object, "suffix"); - auto stage = value_if_exists(query_object, "stage"); - return product_selector{ - .creator = std::move(creator), .layer = std::move(layer), .suffix = 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/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/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..8bc7f2d0c 100644 --- a/phlex/core/detail/make_algorithm_name.cpp +++ b/phlex/core/detail/make_algorithm_name.cpp @@ -2,14 +2,17 @@ #include "phlex/configuration.hpp" #include "phlex/model/algorithm_name.hpp" -#include "phlex/model/identifier.hpp" +#include #include namespace phlex::experimental::internal { algorithm_name make_algorithm_name(configuration const* config, std::string_view name) { - return {config ? identifier(config->get("module_label")) : ""_id, - identifier(name)}; + std::optional plugin_label; + if (config) { + plugin_label = config->get("module_label"); + } + 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/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..e299502b4 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,13 @@ 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)); + // The empty catalog returned above, so b == e implies a specified suffix. + query.suffix->text()); // NOLINT(bugprone-unchecked-optional-access) 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..70ac5c1d2 100644 --- a/phlex/core/product_selector.cpp +++ b/phlex/core/product_selector.cpp @@ -83,8 +83,7 @@ namespace phlex { { // 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..08b48f111 100644 --- a/phlex/core/product_selector.hpp +++ b/phlex/core/product_selector.hpp @@ -11,6 +11,7 @@ #include #include #include +#include #include #include #include @@ -26,25 +27,19 @@ 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(); } 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; @@ -57,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 @@ -109,7 +98,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..c2cf7f1a3 100644 --- a/phlex/core/provider_node.cpp +++ b/phlex/core/provider_node.cpp @@ -15,7 +15,7 @@ namespace phlex::detail { provider_node::provider_node(tbb::flow::graph& g, provider_bundle bundle) : - provider_node{bundle.spec.creator(), + 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/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/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/algorithm_name.cpp b/phlex/model/algorithm_name.cpp index 6571e7eb2..98547d7c9 100644 --- a/phlex/model/algorithm_name.cpp +++ b/phlex/model/algorithm_name.cpp @@ -1,94 +1,101 @@ #include "phlex/model/algorithm_name.hpp" +#include "phlex/model/detail/excerpt.hpp" #include "phlex/model/identifier.hpp" #include -#include -#include +#include #include #include #include #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 { - algorithm_name::algorithm_name() = default; + 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) { *this = create(spec); } + algorithm_name::algorithm_name(std::string_view spec) : algorithm_name{parse(spec)} {} - algorithm_name::algorithm_name(identifier 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_); } 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) + algorithm_name algorithm_name::create(std::optional plugin, + std::string_view algorithm) { - // Empty spec means nothing is specified - if (spec.empty()) { - return {}; - } + auto const name = plugin ? fmt::format("{}:{}", *plugin, algorithm) : std::string{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 - - if (!words_only(plugin) or !words_only(algorithm)) { - throw std::runtime_error( - fmt::format("The specification '{}' is not a valid algorithm name.", spec)); - } - return {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 {"", 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 43772960f..c1dc20bcd 100644 --- a/phlex/model/algorithm_name.hpp +++ b/phlex/model/algorithm_name.hpp @@ -5,31 +5,46 @@ #include "phlex/phlex_model_export.hpp" #include +#include +#include +#include namespace phlex::experimental { class PHLEX_MODEL_EXPORT algorithm_name { public: - algorithm_name(); - + /// 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); algorithm_name(std::string_view spec); // NOLINTEND(google-explicit-constructor) - algorithm_name(identifier plugin, identifier 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); std::string to_string() const; - identifier 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; auto operator<=>(algorithm_name const&) const noexcept = default; - 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 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. + static algorithm_name create(std::optional plugin, + std::string_view algorithm); private: - identifier plugin_; + std::optional plugin_; identifier algorithm_; }; diff --git a/phlex/model/data_cell_index.cpp b/phlex/model/data_cell_index.cpp index 3dcc83332..0bdb507a9 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,15 @@ 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(); } + assert(layers.size() == depth_ + 1); + std::ranges::reverse(layers); return experimental::layer_path{std::move(layers)}; } @@ -144,9 +144,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/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 new file mode 100644 index 000000000..9dc0fd71e --- /dev/null +++ b/phlex/model/detail/excerpt.hpp @@ -0,0 +1,19 @@ +#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 + +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. + std::string excerpt(std::string_view text); +} + +#endif // PHLEX_MODEL_DETAIL_EXCERPT_HPP diff --git a/phlex/model/handle.hpp b/phlex/model/handle.hpp index 3c126402c..15e9e406d 100644 --- a/phlex/model/handle.hpp +++ b/phlex/model/handle.hpp @@ -7,7 +7,7 @@ #include -#include +#include #include #include #include @@ -90,9 +90,12 @@ namespace phlex { // Product specification information algorithm_name_view creator() const noexcept { - return {std::string_view(spec_->plugin()), std::string_view(spec_->algorithm())}; + 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 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..c1431fd22 100644 --- a/phlex/model/identifier.cpp +++ b/phlex/model/identifier.cpp @@ -1,14 +1,34 @@ #include "phlex/model/identifier.hpp" +#include "phlex/model/detail/excerpt.hpp" + +#include + #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{fmt::format("Invalid identifier {}: an identifier {}", + phlex::detail::excerpt(str), + phlex::detail::identifier_rule)}; + } + } + } + + 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..cde01f687 100644 --- a/phlex/model/identifier.hpp +++ b/phlex/model/identifier.hpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -16,6 +17,26 @@ #include #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 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. + 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; + } + return std::ranges::all_of( + text, [letter](char c) { return letter(c) || (c >= '0' && c <= '9') || c == '_'; }); + } +} + 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 +47,9 @@ 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. + /// 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) @@ -38,9 +60,7 @@ 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; @@ -65,9 +85,6 @@ 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 @@ -81,7 +98,7 @@ namespace phlex::experimental { private: std::string content_; - std::uint64_t hash_{hash_string("")}; + std::uint64_t hash_; }; // Identifier UDL @@ -89,6 +106,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 +134,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 +144,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 { @@ -134,9 +154,11 @@ 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) noexcept : value_{std::move(id)} {} diff --git a/phlex/model/product_specification.cpp b/phlex/model/product_specification.cpp index cd7f63e4a..0014e28fc 100644 --- a/phlex/model/product_specification.cpp +++ b/phlex/model/product_specification.cpp @@ -8,12 +8,33 @@ #include #include +#include #include +#include #include #include namespace phlex::experimental { - product_specification::product_specification() = default; + 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}} @@ -23,10 +44,13 @@ 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{parse(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)} { @@ -34,28 +58,8 @@ namespace phlex::experimental { std::string product_specification::to_string() const { - if (creator_.plugin().empty() && creator_.algorithm().empty()) { - return fmt::format("{}", suffix_); - } 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 forward_slash = s.find('/'); - if (forward_slash != std::string_view::npos) { - return {experimental::algorithm_name::create(s.substr(0, forward_slash)), - experimental::identifier(s.substr(forward_slash + 1)), - type_id{}}; - } - return {experimental::algorithm_name::create(""), experimental::identifier(s), type_id{}}; - } - } namespace phlex::detail { @@ -81,7 +85,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..9797121e1 100644 --- a/phlex/model/product_specification.hpp +++ b/phlex/model/product_specification.hpp @@ -9,6 +9,7 @@ #include #include +#include #include #include @@ -19,33 +20,33 @@ 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. 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); 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); 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_; } + 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; - static product_specification create(char const* c); - static product_specification create(std::string_view s); - friend struct std::hash; private: experimental::algorithm_name creator_; - experimental::identifier suffix_; // Default suffix is empty string + experimental::suffix_t suffix_; type_id type_id_{}; }; @@ -64,7 +65,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(); + std::size_t hash = 0; + 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_)); diff --git a/phlex/model/product_store.cpp b/phlex/model/product_store.cpp index 510a4a92d..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/plugins/python/src/modulewrap.cpp b/plugins/python/src/modulewrap.cpp index 0f55e1718..de077ce8e 100644 --- a/plugins/python/src/modulewrap.cpp +++ b/plugins/python/src/modulewrap.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -116,7 +117,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 +288,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 +297,20 @@ 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; + } + 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, @@ -301,13 +321,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; + } + auto l = try_item(pysel, "layer", 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 s = try_item(pysel, "suffix", true); // always optional + if (PyErr_Occurred()) { return std::nullopt; } @@ -316,7 +339,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 +395,12 @@ namespace { if (!p) { return std::nullopt; } - return std::string(p, static_cast(sz)); + 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; }); } @@ -920,8 +948,18 @@ 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); + // 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) { PyErr_SetString(PyExc_TypeError, "an input is required"); @@ -1161,7 +1199,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 +1235,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 +1263,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 +1326,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 +1393,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 +1522,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; @@ -1506,7 +1555,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 +1567,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 +1579,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.value(), + suffix.value_or(suffix_t{}), + layer.value(), + registration->output_type); if (!registered) { if (!PyErr_Occurred()) { PyErr_Format( @@ -1554,6 +1615,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/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/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/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 ed8d0fad2..4b510461a 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 suffix"; + 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,20 @@ 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 product selector field \"layer\": " + "Invalid identifier \"\": an identifier " + + std::string{phlex::detail::identifier_rule})); CHECK_THROWS_WITH(config.get("malformed3"), ContainsSubstring("Error retrieving parameter 'malformed3'") && - ContainsSubstring("Cannot specify product with empty creator name.")); + ContainsSubstring("Invalid product selector field \"creator\": " + "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 suffix\": an identifier " + + std::string{phlex::detail::identifier_rule})); } diff --git a/test/core_misc_test.cpp b/test/core_misc_test.cpp index 5312b6f6a..836804139 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" @@ -8,11 +9,15 @@ #include #include +#include +#include #include #include +#include #include #include +#include #include #include @@ -20,42 +25,116 @@ TEST_CASE("algorithm_name tests", "[model]") { using namespace phlex::detail; using namespace phlex::experimental; + using namespace phlex::experimental::literals; - 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"); + 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("Create error - trailing colon") + SECTION("Unqualified name has no plugin") + { + auto const an = algorithm_name{"algo"}; + CHECK_FALSE(an.plugin().has_value()); + CHECK(an.algorithm() == "algo"_id); + } + SECTION("Qualified name has plugin and algorithm") { - CHECK_THROWS_AS(algorithm_name::create("plugin:"), std::runtime_error); + auto const an = algorithm_name{"plugin:algo"}; + REQUIRE(an.plugin().has_value()); + CHECK(an.plugin().value() == "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{"algo"}); + + algorithm_name const qualified{"plugin"_id, "algo"_id}; + REQUIRE(qualified.plugin().has_value()); + CHECK(qualified.to_string() == "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 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{""}, 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{":algo"}, + message(":algo", "the plugin label before ':' is missing.")); + 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{"_x"}, std::invalid_argument); + CHECK_THROWS_WITH(algorithm_name{"_x"}, + "Invalid algorithm name \"_x\": algorithm \"_x\" " + rule); + CHECK_THROWS_WITH(algorithm_name{"a[0]"}, + "Invalid algorithm name \"a[0]\": algorithm \"a[0]\" " + rule); + CHECK_THROWS_WITH(algorithm_name{"a b"}, + "Invalid algorithm name \"a b\": algorithm \"a b\" " + rule); + CHECK_THROWS_WITH(algorithm_name{"1p:a"}, + "Invalid algorithm name \"1p:a\": plugin label \"1p\" " + rule); + CHECK_THROWS_WITH(algorithm_name{"pl ugin:algo"}, + "Invalid algorithm name \"pl ugin:algo\": plugin label \"pl ugin\" " + rule); + 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{"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{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{"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); + 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") { - 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") @@ -65,27 +144,72 @@ TEST_CASE("algorithm_name tests", "[model]") } } -TEST_CASE("verify_name tests", "[core]") +TEST_CASE("make_algorithm_name tests", "[core]") { - using namespace phlex::detail::internal; + using namespace phlex::experimental; + using namespace phlex::experimental::literals; + using internal::make_algorithm_name; - SECTION("non-empty name does nothing") { CHECK_NOTHROW(verify_name("valid_name", nullptr)); } + 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("empty name throws") { CHECK_THROWS_AS(verify_name("", nullptr), std::runtime_error); } + 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().value() == "my_module"_id); + CHECK(name.to_string() == "my_module:my_algorithm"); + } - SECTION("empty name with config includes module label") + 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")); + 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")); + } - 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")); - } + 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}; + + 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\" " + + std::string{phlex::detail::identifier_rule})); + CHECK_THROWS_AS(make_algorithm_name(nullptr, "a[0]"), std::invalid_argument); + } + + SECTION("A malformed module label is reported as a bad plugin label") + { + boost::json::object obj; + obj["module_label"] = "1module"; + phlex::configuration const config{obj}; + + CHECK_THROWS_WITH(make_algorithm_name(&config, "my_algorithm"), + Catch::Matchers::ContainsSubstring( + "plugin label \"1module\" " + std::string{phlex::detail::identifier_rule})); } } @@ -110,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/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..22f8b66a2 100644 --- a/test/data_layer_hierarchy_test.cpp +++ b/test/data_layer_hierarchy_test.cpp @@ -33,13 +33,12 @@ 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_NOTHROW(h.to_string()); } TEST_CASE("Data layer hierarchy layout", "[data model]") 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/form/CMakeLists.txt b/test/form/CMakeLists.txt index 5e3a7d191..ab25da523 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 not be empty and 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 5d5bf583f..96495a8dc 100644 --- a/test/identifier_test.cpp +++ b/test/identifier_test.cpp @@ -5,6 +5,7 @@ #include #include #include +#include #include #include @@ -13,17 +14,135 @@ #include #include #include +#include #include #include #include #include +#include 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 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\": 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') + "...\": an identifier " + + std::string{phlex::detail::identifier_rule}); +} + +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 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(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()); +} + +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); + 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]") { + STATIC_CHECK_FALSE(std::is_default_constructible_v); identifier a = "a"_id; identifier a_copy = a; identifier a2 = "a"_id; @@ -40,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); @@ -50,7 +169,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 +177,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 +312,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/index_router_test.cpp b/test/index_router_test.cpp index a3445683c..662efa9e7 100644 --- a/test/index_router_test.cpp +++ b/test/index_router_test.cpp @@ -18,6 +18,36 @@ 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/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..185007459 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 @@ -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/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; diff --git a/test/product_handle_test.cpp b/test/product_handle_test.cpp index 590fcedbf..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,6 +133,28 @@ TEST_CASE("Retrieve product specification from handle", "[data model]") CHECK(h.stage() == "test_stage"); } +TEST_CASE("Retrieve plugin-qualified creator from handle", "[data model]") +{ + int const number{3}; + spec_t const spec{"plugin:creator/three"}; + auto const h = make_handle(number, *data_cell_index::job(), spec); + + 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 4eab694e2..e30314cb4 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 @@ -12,9 +15,9 @@ 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_WITH((product_selector{.creator = "", .layer = "layer"}), + "Invalid identifier \"\": an identifier " + + std::string{phlex::detail::identifier_rule}); } TEST_CASE("Creator name formatting", "[data model]") @@ -25,9 +28,9 @@ 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_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]") @@ -45,21 +48,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); @@ -72,6 +75,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"}; @@ -79,8 +83,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); @@ -89,3 +93,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{"plugin:algo"}, "prod"_id, make_type_id()}; + product_specification const unqualified{ + experimental::algorithm_name{"algo"}, "prod"_id, make_type_id()}; + product_specification const empty_suffix{ + experimental::algorithm_name{"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_specification_test.cpp b/test/product_specification_test.cpp new file mode 100644 index 000000000..ee968b4c2 --- /dev/null +++ b/test/product_specification_test.cpp @@ -0,0 +1,146 @@ +#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()}; + + // 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()}); + + // 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); + 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_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()})); + 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 9ad38e8e5..751d7ee34 100644 --- a/test/product_store_test.cpp +++ b/test/product_store_test.cpp @@ -4,6 +4,7 @@ #include "phlex/model/algorithm_name.hpp" #include "phlex/model/handle.hpp" #include "phlex/model/identifier.hpp" +#include "phlex/model/product_specification.hpp" #include "phlex/model/product_store.hpp" #include "phlex/model/type_id.hpp" @@ -14,16 +15,24 @@ #include #include -#include #include #include 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_FALSE(source.plugin().has_value()); + CHECK(product_store::default_source() == source); +} + 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); @@ -34,11 +43,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); @@ -46,10 +55,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); @@ -65,7 +74,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}; @@ -117,7 +126,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/provider_test.cpp b/test/provider_test.cpp index f340a4203..472afa0b9 100644 --- a/test/provider_test.cpp +++ b/test/provider_test.cpp @@ -14,6 +14,7 @@ #include #include #include +#include #include #include @@ -95,6 +96,22 @@ namespace { unsigned pass_on(vertex_collection const& vertices) { return vertices.data; } } +TEST_CASE("Provider nodes take their name from the advertised product creator") +{ + tbb::flow::graph graph; + 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") { constexpr auto num_spills{3u}; diff --git a/test/python/CMakeLists.txt b/test/python/CMakeLists.txt index fb0d54dab..cc783b8fc 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:invalid_transform_name + COMMAND phlex::phlex -c ${CMAKE_CURRENT_SOURCE_DIR}/pyinvalid_transform_name.jsonnet --stage test +) +set_tests_properties( + 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:invalid_transform_name) + add_test( NAME py:mismatch_variant COMMAND phlex::phlex -c ${CMAKE_CURRENT_SOURCE_DIR}/pymismatch_variant.jsonnet --stage test diff --git a/test/python/invalid_transform_name.py b/test/python/invalid_transform_name.py new file mode 100644 index 000000000..57ee747ca --- /dev/null +++ b/test/python/invalid_transform_name.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/pyinvalid_transform_name.jsonnet b/test/python/pyinvalid_transform_name.jsonnet new file mode 100644 index 000000000..dcf83b860 --- /dev/null +++ b/test/python/pyinvalid_transform_name.jsonnet @@ -0,0 +1,18 @@ +{ + driver: { + cpp: 'generate_layers', + layers: { + event: { parent: 'job', total: 1, starting_number: 1 }, + }, + }, + sources: { + provider: { + cpp: 'cppsource4py', + }, + }, + modules: { + invalid_transform_name: { + py: 'invalid_transform_name', + }, + }, +} diff --git a/test/python/pyprovide.py b/test/python/pyprovide.py index f884c63b7..8e9d97fca 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": "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) + 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..9d33ab38a 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": "bad 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, diff --git a/test/repeater_node_test.cpp b/test/repeater_node_test.cpp index b7fb4af95..38cba1f82 100644 --- a/test/repeater_node_test.cpp +++ b/test/repeater_node_test.cpp @@ -32,13 +32,12 @@ 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( 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}; } diff --git a/test/transform_node_test.cpp b/test/transform_node_test.cpp index 124d1c862..af86975c3 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 @@ -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( @@ -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}; @@ -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(