Skip to content

feat(model)!: restrict identifiers to letters, digits, and underscores - #1068

Merged
knoepfel merged 28 commits into
mainfrom
stack/concept-registry/03a-constrain-identifier-string
Nov 20, 2026
Merged

knoepfel merged 28 commits into
mainfrom
stack/concept-registry/03a-constrain-identifier-string

Conversation

@marcpaterno

@marcpaterno marcpaterno commented Nov 14, 2026 •

Copy link
Copy Markdown
Member

Summary

PR 3a of the concept-registry stack, based on main. Inserted beneath #1002
after #1001 merged.

Make identifier a validated, never-empty name, and remove the defaults that
relied on an empty one.

identifier(text)
  valid    an ASCII letter, then ASCII letters, digits, or underscores
  invalid  -> std::invalid_argument            (includes "")
  "..."_idq with invalid text -> compile error
  default constructor deleted

values that may be empty
  plugin of an unqualified algorithm name -> identifier_or_empty
  absent product creator                  -> std::optional<algorithm_name>
  • Reject empty algorithm names, empty plugin components, and empty layer names.
  • Route providers whose layer is unresolved through a dedicated index-set node
    instead of a "*" layer key.
  • Build layer_path by walking the parent chain.
  • Rename the default source creator from [Source] to Source, which is a
    valid name.
  • In the Python plugin, check identifiers and suffixes when modules and
    providers are registered. Report failures as ValueError or RuntimeError
    instead of letting C++ exceptions escape.
  • Update tests for the stricter rule and rename fixture names it rejects.

Evidence

  • Before: on main, identifier accepts any text, including "", and has
    a default constructor. This is the API change shown by the diff, not a
    failing run.
    After: the identifier test passes. It covers rejected names
    (punctuation, a leading digit or underscore, empty text, spaces, non-ASCII
    bytes and embedded NUL) and moved-from identifiers.
  • The configured build is up to date and all 163 CTests pass.
  • All hooks pass except mypy, which reports the same 12 errors in
    plugins/python/python/phlex/_typing.py on main. This PR changes no .py
    files.

Local macOS evidence, not CI or sanitizer approval.

Merge Danger

Door: Two-way

A revert restores the permissive behaviour. #1002, #1003 and #1009 are stacked
on this PR and would need rebasing.

Blast Radius: Consumers

Breaking change. A name that is empty, starts with a character other than a
letter, or contains anything except letters, digits and underscores is now
rejected, in C++, in configuration, and in Python modules. Code that
default-constructs identifier or algorithm_name no longer compiles.

Overview

  • Restricts identifier to non-empty names that start with an ASCII letter and contain only ASCII letters, digits, or underscores.
  • Rejects invalid names, including empty names, with std::invalid_argument.
  • Deletes the default constructor of identifier.
  • Removes the default constructor of algorithm_name.
  • Adds a separate suffix_t type for product suffixes.
  • Breaking change: code that default-constructs identifier or algorithm_name no longer compiles. Previously accepted names may now be rejected.

Model (phlex/model)

  • identifier.hpp/.cpp: adds validation to both constructors. Adds a constexpr validator for _idq literals, which throw "Invalid identifier query". Documents the validation rules.
  • identifier_or_empty: its move-from-identifier constructor is no longer noexcept, per the raw summary. A later commit reportedly made identifier move operations noexcept. Confirm this against the final source.
  • algorithm_name: create(std::string_view) throws on an empty specification. The plugin argument is now identifier_or_empty. An empty plugin is allowed for colon-qualified names.
  • product_specification: stores suffix_t. Adds a std::nullopt_t constructor for specifications without a creator. creator() returns std::optional<algorithm_name>. plugin() and algorithm() are removed. suffix() returns suffix_t.
  • data_cell_index: layer_path() builds the path by walking parents. to_string_this_layer() always prints name:number. A documentation comment states that child layer names must be non-empty identifiers.
  • handle.hpp: creator() returns an empty view when no creator is set. suffix() returns a std::string_view.
  • product_store.cpp: the default source algorithm name changes from [Source] to Source.

Core (phlex/core)

  • index_router: unresolved provider inputs use a shared unresolved_index_set_node_. This replaces the "*" identifier key. multilayer_join_slots_ keys change from identifier to std::string.
  • consumer.cpp: layers_from ignores selectors without a layer. consumer::layers() therefore omits those selectors.
  • provider_node.cpp: throws std::runtime_error when the product specification has no creator.
  • product_selector: match returns false when a required creator is missing. suffix is std::optional<suffix_t>. creator_name formatting returns a std::string_view.
  • producer_catalog: product_suffix_t aliases suffix_t.
  • registration_api.hpp: output_product takes a suffix_t for the suffix.
  • make_algorithm_name.cpp: passes the module label through identifier_or_empty.

Configuration and FORM

  • configuration.cpp: parses suffix directly as a string. It creates an optional suffix_t only when the key exists.
  • form/form_module.cpp: derives product labels from suffix().text().
  • form/form_source.cpp: builds specifications with suffix_t{name}.

Python plugin (plugins/python/src/modulewrap.cpp)

  • Reads selector and algorithm strings with explicit UTF-8 lengths.
  • Validates identifiers and output suffixes. Requires creator and layer fields. An omitted provider suffix defaults to empty.
  • Transform output suffixes use an empty value directly when the declared suffix is empty. Otherwise they still append "_py".
  • Maps std::invalid_argument to Python ValueError. Maps other standard exceptions to RuntimeError. Unknown exceptions produce registration-specific RuntimeError messages.
  • No .py files change.

Tests

  • identifier_test.cpp: adds validation, ASCII-name, construction, and move tests. Checks that identifier is not default-constructible. Switches fixtures to underscores.
  • config_test.cpp: expects Invalid identifier for empty layer or creator.
  • core_misc_test.cpp: removes the algorithm_name default-constructor test.
  • data_cell_index_test.cpp and data_layer_hierarchy_test.cpp: expect make_child("", …) to throw.
  • product_selector_test.cpp: empty-name tests check only that construction throws. Creator values change from "1"/"2" to "one"/"two".
  • multilayer_join_test.cpp and transform_node_test.cpp: use suffix_t{}.
  • max-parallelism test files: rename command-line-stage and configured-stage to command_line_stage and configured_stage.

Verification status

  • The author reports that all 163 CTests pass on local macOS. This was not verified here and is not CI evidence.
  • The author reports that all pre-commit hooks pass except mypy. The mypy failure is 12 errors in plugins/python/python/phlex/_typing.py, which also fail on main.
  • No CI results are available for this review.

Reviewer notes

  • Stacked PRs #1002, #1003, and #1009 need rebasing if this change is reverted.
  • Check identifier_or_empty move noexcept behavior against the final source before merge.

@coderabbitai

coderabbitai Bot commented Nov 14, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Important

Review skipped

Auto incremental reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: ASSERTIVE
  • Plan: Advanced
  • Run ID: 804e9fde-8533-4b7e-a57a-17c9e7173844

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The change validates identifier names and updates product specifications to represent optional creators and suffixes with dedicated types. Selector matching, provider routing, FORM handling, and Python registration now use the updated representations.

Changes: Product identity and registration

Layer / File(s) Summary
Identifier and name rules
phlex/model/identifier.*, phlex/model/algorithm_name.*, phlex/model/data_cell_index.*, test/identifier_test.cpp, test/data_cell_index_test.cpp, test/data_layer_hierarchy_test.cpp, test/core_misc_test.cpp, test/max-parallelism/*
Identifiers now reject invalid names, and algorithm_name no longer has a default constructor. Child layer names must be non-empty. Related tests and stage-name fixtures use valid names.
Product specification and suffix types
phlex/model/product_specification.*, phlex/model/handle.hpp, phlex/model/product_store.cpp, phlex/core/registration_api.hpp, form/form_*, test/multilayer_join_test.cpp, test/transform_node_test.cpp
Product specifications store an optional creator and a suffix_t. Accessors, output registration, FORM product handling, and related tests use the updated suffix representation.
Selector matching and provider routing
phlex/configuration.cpp, phlex/core/consumer.cpp, phlex/core/detail/make_algorithm_name.cpp, phlex/core/index_router.*, phlex/core/producer_catalog.*, phlex/core/product_selector.*, phlex/core/provider_node.cpp, test/config_test.cpp, test/product_selector_test.cpp
Selectors use suffix_t and handle absent creators. Consumer layer collection omits unspecified layers, and provider routing uses a shared unresolved-layer node for inputs without a specified layer.
Python registration and suffix conversion
plugins/python/src/modulewrap.cpp
Python registration parses typed selector values, validates names and suffixes, and translates C++ exceptions into Python errors.

Estimated code review effort: 4 (Complex) | ~45 minutes

Change: Feature

Suggested reviewers: knoepfel, beojan, greenc-fnal

Merge Risk: Minimal · previous review 78070

This change tightens identifier validation and removes empty-name defaults, which is a deliberate breaking change for consumers. No concrete defects were found in the supplied code, and the reported test results are local only. The main merge-readiness note is that downstream consumers must adopt the stricter naming rules.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: identifiers are restricted to letters, digits, and underscores. The changeset enforces this in identifier validation (identifier.cpp/hpp), and the rest of the diff fol…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title names the main change: identifiers are restricted to letters, digits, and underscores. The changeset enforces this in identifier validation (identifier.cpp/hpp), and the rest of the diff follows from it: empty-capable values move to identifier_or_empty or std::optional, the default constructor is deleted, and tests are updated. The title is specific, uses a conventional type prefix, and flags the breaking change with '!'. It omits the wider effects (algorithm_name, product_specification, layer handling, Python validation), which is acceptable for a title.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@marcpaterno
marcpaterno added this pull request to stack #1069 November 14, 2026 16:12
@codecov

codecov Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.14778% with 20 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
plugins/python/src/modulewrap.cpp 73.33% 13 Missing and 7 partials ⚠️
@@            Coverage Diff             @@
##             main    #1068      +/-   ##
==========================================
+ Coverage   91.19%   91.39%   +0.19%     
==========================================
  Files         184      184              
  Lines        5986     6054      +68     
  Branches      962      972      +10     
==========================================
+ Hits         5459     5533      +74     
+ Misses        337      331       -6     
  Partials      190      190              
Flag Coverage Δ
amd64 91.39% <90.14%> (+0.19%) ⬆️
arm64 91.39% <90.14%> (+0.19%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
form/form_module.cpp 93.90% <100.00%> (ø)
form/form_source.cpp 58.16% <100.00%> (+2.24%) ⬆️
phlex/app/plugin_loading.cpp 91.42% <100.00%> (+0.95%) ⬆️
phlex/configuration.cpp 100.00% <100.00%> (ø)
phlex/configuration.hpp 100.00% <100.00%> (ø)
phlex/core/consumer.cpp 100.00% <ø> (ø)
phlex/core/detail/make_algorithm_name.cpp 100.00% <100.00%> (ø)
phlex/core/glue.hpp 100.00% <ø> (ø)
phlex/core/index_router.cpp 97.77% <100.00%> (+0.41%) ⬆️
phlex/core/index_router.hpp 100.00% <ø> (ø)
... and 18 more

... and 3 files with indirect coverage changes


Continue to review full report in Codecov by Harness.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 14446db...79b6a9f. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@marcpaterno
marcpaterno marked this pull request as ready for review November 14, 2026 17:37
@knoepfel
knoepfel self-requested a review November 16, 2026 18:06
@knoepfel knoepfel linked an issue Nov 16, 2026 that may be closed by this pull request
beojan
beojan previously requested changes Nov 16, 2026

@beojan beojan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! I didn't see anything glaring, but Gemini caught a few issues due to residual code:

  1. Algorithm names get validated twice (once in algorithm_name::create and then again here) and sometimes make it through the first validation, but fail the second.

  2. identifier::empty() still exists

  3. If a stage name is given as a command line argument and it fails validation, you don't get a nice error message.

It also complains about identifier_or_empty's move constructor from identifier not being noexcept any more.

I'd say this PR is big enough that 1 and 2 are in scope.

Comment thread phlex/model/algorithm_name.hpp Resolved
Comment thread phlex/model/algorithm_name.hpp Resolved
Comment thread phlex/model/product_specification.hpp Resolved
Comment thread phlex/model/product_specification.hpp Resolved
@marcpaterno

Copy link
Copy Markdown
Member Author

@phlexbot coverage

@github-actions

Copy link
Copy Markdown
Contributor

Coverage workflow completed.

Result: ✅ Coverage analysis passed.

See the workflow run for detailed results.

@marcpaterno marcpaterno reopened this Nov 18, 2026
@marcpaterno
marcpaterno force-pushed the stack/concept-registry/03a-constrain-identifier-string branch from 09782e4 to bf61f97 Compare November 18, 2026 22:41
@marcpaterno
marcpaterno requested a review from knoepfel November 18, 2026 22:45
Comment thread phlex/core/product_selector.cpp Resolved
Comment thread phlex/core/product_selector.cpp Resolved
Comment thread phlex/core/product_selector.hpp Resolved
Comment thread phlex/core/product_selector.hpp Resolved
Comment thread phlex/model/detail/excerpt.hpp Resolved
Comment thread phlex/model/data_cell_index.cpp Resolved
Comment thread test/data_layer_hierarchy_test.cpp Resolved
Comment thread phlex/model/identifier.cpp Resolved
Comment thread phlex/model/identifier.hpp Resolved
Comment thread phlex/configuration.cpp Resolved
Comment thread phlex/configuration.cpp Resolved
Comment thread phlex/model/algorithm_name.hpp Resolved
Comment thread test/python/suffix.py Resolved
Add a test case checking that the default source reports the name
"Source", has the matching algorithm identifier, has an empty plugin,
and compares equal across calls.
Replace the wildcard fallback in the producer catalog debug message with
direct access to the query suffix. The empty-catalog check returns early,
so reaching the b == e branch implies a specified suffix. The previous
wildcard branch was therefore unreachable and could not be covered by
tests, leaving an artificial gap in patch coverage.

Suppress the unchecked-optional lint warning at the call site with a
comment explaining the invariant.

Add a direct test that find_producers returns no producers for an unknown
suffix in a nonempty catalog, exercising this return path.
Add a Catch2 section asserting that `algorithm_name::create("")` throws
`std::runtime_error` with the message "Cannot create an empty algorithm
name." Include `catch2/matchers/catch_matchers.hpp` for `CHECK_THROWS_WITH`.
Add a Catch2 test case for `product_specification` covering `std::hash`
and equality. It checks that named and unnamed specifications with
identical fields hash equally, that duplicate insertions into an
`std::unordered_set` are rejected, and that lookups distinguish
differing creator, name, or type. Includes `product_specification.hpp`,
`<functional>`, `<optional>`, and `<unordered_set>` as needed.
Add a test case verifying that `product_specification::create` with a
leading-slash name yields no creator, the suffix as the given name, and
an invalid type.
Add an index router test confirming unresolved provider layers receive no
concrete indices, a product handle test for absent creator metadata, and
a provider node test asserting that specifications without a creator
throw std::runtime_error
Set bugprone-unchecked-optional-access.IgnoreValueCalls to true in
.clang-tidy so calls to std::optional::value() no longer trigger
warnings when they lack a preceding has_value() guard.
Moving an identifier never allocates, so the `identifier&&` constructor
of identifier_or_empty can be declared noexcept. This lets callers and
standard containers rely on the non-throwing move.

Add comments noting that the `identifier const&` copy constructor is
intentionally not noexcept, because copying the underlying string may
allocate and throw.
Replace the identifier_or_empty plugin qualifier in algorithm_name with
std::optional<identifier>, where an absent value means the name is
unqualified. The constructor, plugin() accessor and to_string() now use
the optional directly.

Adapt the callers:
- make_algorithm_name leaves the plugin absent when there is no
  configuration and otherwise uses the module label.
- product_selector compares the optional plugin to the creator
  identifier.
- product handle creator() builds its view from an empty string_view
  when the plugin is absent.
- the product_specification hash mixes in whether a plugin is present
  before hashing it, so qualified and unqualified creators stay
  distinct.
- the product_store default source test checks has_value() instead of
  empty().

Add tests for the optional plugin states, construction from typed
components, parse rejection of ":algo", "plugin:", multiple colons and
malformed components, and make_algorithm_name with and without a
configuration.
A product_specification now always names its creator. The creator is a
plain algorithm_name instead of std::optional<algorithm_name>, so every
specification identifies the algorithm that produced it.

Default construction and the creator-less (std::nullopt, suffix, type)
constructor are removed. The text form must be `creator/suffix`.
`creator/` denotes an explicit empty suffix. Bare text, `/suffix`, `/`
and the empty string now throw std::runtime_error with a message that
describes the expected form. Previously these were accepted as
creator-less specifications. The text constructor now delegates to
create() rather than assigning from it.

Equality and std::hash cover the creator, suffix and type. The hash no
longer mixes in a has-creator flag, because the creator is always
present.

Adapt callers to the non-optional creator:
- provider_node copies the creator before the spec is moved and drops
  its creator-presence check, which can no longer fail.
- product_selector matches against the always-present creator.
- The product handle creator() view no longer needs an empty fallback.

Tests are added for the following:
- Constructibility and creator type.
- Text parsing, including the rejected forms.
- Round-tripping of `creator/`.
- set_type mutation.
- Hash and equality across all components.
- Selector matching by creator, suffix and type.
- Handle creator views.
- Provider node naming.

Existing tests are migrated to `creator/suffix` specifications.

BREAKING CHANGE: product_specification no longer has a default
constructor or a std::nullopt creator constructor. creator() returns
algorithm_name const& rather than std::optional<algorithm_name> const&.
Text specifications without a creator (e.g. "number", "/number") now
throw std::runtime_error and must be written as "creator/number".
Algorithm-name text was checked twice by different rules. A private
character precheck accepted `[A-Za-z0-9_[]]`, and the identifier
constructor then re-validated with the stricter identifier grammar, so
`_x`, `1p:a` and `a[0]` passed the first check and failed the second,
with different exception types and unrelated messages.

The identifier grammar is now the only character rule. The precheck is
deleted. algorithm_name::create(text) parses structure and delegates to
a new public create(optional<string_view> plugin, string_view algorithm)
overload, which constructs the identifiers, catches their failure, and
rethrows with the composed name, the failing part (plugin label or
algorithm), and the rule. make_algorithm_name uses the same overload, and
the separate verify_name empty-name check is removed.

All malformed algorithm-name text now throws std::invalid_argument,
which the Python bindings report as ValueError. Messages quote the
offending text with fmt's `{:?}`, shortened to 64 characters, through one
private helper that identifier and algorithm_name share.

Report the field at each parse boundary:
- Product selectors read from configuration or Python name the field
  (creator, layer, suffix, stage) that held the bad text.
- Python provider outputs name the field the same way.
- form_source parses its `creator` parameter once at registration and
  stores the algorithm_name instead of reparsing it per product.
- load_module and load_source check the configuration label, which
  becomes the plugin label of everything the entry registers, and name
  the `modules` or `sources` section.

Remove identifier::empty(). An identifier is never empty, so its only
production uses were unreachable checks in creator_name and layer_name,
which are deleted along with their messages.

Add nothrow STATIC_CHECKs for identifier_or_empty. Tests cover create
and its overload, make_algorithm_name, product_specification::create,
the config boundaries, label validation, and Python ValueError reports.

BREAKING CHANGE: malformed algorithm names throw std::invalid_argument
instead of std::runtime_error, characters `[` and `]` are no longer
accepted in a name, identifier::empty() is removed, and a module or
source label that is not a valid identifier is rejected when loaded.
Read the plugin label in algorithm_name tests through value() instead of
operator*. Both are guarded by a preceding REQUIRE(has_value()), so
behavior is unchanged, and value() reports an error on an empty optional
rather than being undefined. Also declare the expected-forms string in
the structural-error test as a const pointer, matching the surrounding
test style.
Identifier errors now say "an identifier" instead of "it" and state that
an empty value is rejected, so the message no longer implies that an
empty name is accepted when it does not start with a letter. The shared
identifier_rule text is updated, and the error messages built from it
change accordingly.

Update the affected C++, Python, and CMake test expectations to match
the new message text.
`creator_match()` already returns true when no creator is set, so the
explicit `creator &&` check in `product_selector::match()` was redundant.
Behavior is unchanged.
Separate invalid-name constructor checks from embedded-NUL checks on
explicitly sized input, and give the empty identifier_or_empty case its
own test. The NUL test comment explains why these constructors are
exercised with the full byte sequence.
Remove the static `algorithm_name::create(char const*)` and
`algorithm_name::create(std::string_view)` overloads, and the matching
`product_specification::create` overloads. The text constructors now
parse their argument directly, so `algorithm_name{spec}` and
`product_specification{spec}` replace the removed factories. The
`algorithm_name::create(plugin, algorithm)` overload remains as the
validation point.

Parsing, error messages, and exception types are unchanged. Callers in
form, model, and tests are updated to use the constructors.
Move excerpt() out of the private detail header into detail/excerpt.cpp
so the fmt dependency is no longer pulled into every includer. The
function's behavior is unchanged.
Rename the badname transform test and its Jsonnet config to
invalid_transform_name, and replace malformed selector values with
descriptive strings (bad creator, bad layer, bad suffix) so each case
names the field it exercises.
Move the product_specification test cases out of product_store_test.cpp
into test/product_specification_test.cpp and register the new target in
test/CMakeLists.txt. The moved test bodies are unchanged; only the
includes needed by each file are adjusted.
Replace the direct `std::hash` equality checks with duplicate
insertions into an `std::unordered_set`. Equal specifications must hash
equal to be deduplicated, so the set checks cover the same contract. Add
a duplicate check for an empty suffix and a comment explaining the
hash/equality expectation.
Make detail::value_if_exists a header-only template that converts to
any type T via boost::json::value_to, and read product selector fields
through it. The suffix field is converted by a tag_invoke overload for
suffix_t, so the optional and error handling of each field is shared.
Malformed fields still report the field name in the error message.

Update identifier_test to call the templated value_if_exists<identifier>.
@marcpaterno
marcpaterno force-pushed the stack/concept-registry/03a-constrain-identifier-string branch from 64865f8 to 79b6a9f Compare November 20, 2026 22:20
@knoepfel
knoepfel dismissed beojan’s stale review November 20, 2026 22:33

All of @beojan's requested changes have been implemented.

@knoepfel
knoepfel merged commit 5234656 into main Nov 20, 2026
45 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Valid characters in algorithm names (and identifiers in general)

3 participants