Skip to content

Select external environments in Experiments by class path - #1453

Closed
cvolkcvolk wants to merge 7 commits into
mainfrom
cvolk/feature/external-environment-import-paths
Closed

cvolkcvolk wants to merge 7 commits into
mainfrom
cvolk/feature/external-environment-import-paths

Conversation

@cvolkcvolk

@cvolkcvolk cvolkcvolk commented Oct 14, 2026 •

Copy link
Copy Markdown
Collaborator

Closed: replaced by three smaller PRs on top of current main: #1716 (read argparse environment configs from the registry), #1729 (replace ExampleEnvironmentBase with typed external factories) and #1730 (select external environments in Experiments by class path).

Let Arena Experiments select environments defined outside Arena by the dotted class path of their factory, and replace ExampleEnvironmentBase with the typed factory contract the built-in environments already use.

This is a draft for review and discussion. It will be split into smaller PRs afterwards.

Why this change?

Environments defined in a user's own repository could only be evaluated with policy_runner.py:

  • load_arena_experiment_from_yaml accepted an environment.type only if it was a graph-spec path or a key of the mapping built by _registered_environment_cfg_types(). Nothing imported a user's module. experiment_runner.py parses --external_environment_class_path, but neither the YAML nor the JSON loader reads it, so no Run can select that environment.
  • The documented contract, ExampleEnvironmentBase with get_env(args_cli) and add_cli_args(parser), has no typed config. ExampleEnvironmentBase.build(cfg) raised NotImplementedError, so even an imported environment could not be built from YAML.

There were also two related problems:

  • _registered_environment_cfg_types() called EnvironmentRegistry.get_environment_cfg_type for every registered name before composing any Run. If any registered environment had no config, every YAML load in that process failed with "must register a config". experiment_runner.py does not reach this, because it loads the Experiment before building any Run. In this repository it shows up as a test-ordering problem: test_external_environment_registration_callback leaves franka_table registered without a config, and the test_osmo_experiment_workflow.py tests that load an Experiment, such as test_embedded_graph_environment_experiment_composes_through_experiment_runner_loader, then fail in the same pytest process. Load typed experiments alongside external environments #1379 addresses this by filtering the lookup; this PR removes the lookup instead.
  • A factory written as ArenaEnvironmentFactory[Cfg] with @register_environment could not be loaded with --external_environment_class_path. The decorator registered it on import, and add_example_environments_cli_args and environment_registration_callback then called EnvironmentRegistry.register(cls, name) again and hit the duplicate-name assertion. No such external factory existed before this PR; this was shown with a constructed module.

What changes?

External environments use the built-in contract. An environment is an ArenaEnvironmentFactory[Cfg] subclass with build(cfg), a config dataclass that subclasses ArenaEnvironmentCfg, and @register_environment. ExampleEnvironmentBase is removed. This is a breaking change for environments defined outside Arena; the "Arena in Your Repository" docs have a migration guide. Both examples in isaaclab_arena_examples/external_environments/ are migrated, and external_environments_experiment.yaml runs them.

Experiments select a factory by class path. environment.type accepts a registered name, a graph-spec YAML path, or a dotted class path such as my_package.envs.MyEnvironment. policy.type already accepts a registered name or a dotted class path. For a name that is not registered, _resolve_environment_cfg_type_from_name_or_class_path calls import_registered_environment_factory. It imports the module after the built-in environments are registered and checks that @register_environment registered that class under its name.

Each Run resolves only the types it selects. _compose_typed_config_from_yaml_selector now calls the environment or policy resolver for the Run's selector. Before, only the policy was resolved per Run, by _build_arena_run_cfg_from_yaml_values through a one-entry mapping. _registered_environment_cfg_types() is gone, so an environment without a config elsewhere in the registry does not affect other Runs. A resolution failure is reported as "Run '' selects unknown environment type '': ". When an Experiment uses the command-line form module_path:ClassName, the error says to use module_path.ClassName.

Serialized Experiments keep the class path. serialize_arena_experiment_to_yaml writes module.ClassName for factories outside isaaclab_arena_environments, so a serialized Experiment reloads in a fresh process where only built-in environments are registered by name.

--external_environment_class_path stays for the command-line scripts. policy_runner.py, environment_runner.py, and the Isaac Lab scripts that use environment_registration_callback keep the flag with module_path:ClassName. import_external_environment replaces parse_and_return_external_environment_from_string. It imports the module and checks the registration instead of registering the class again. Repeated imports return the same factory; graph-spec Runs rebuild the parser from sys.argv for every build, so a flag on the command line is imported once per build.

add_environment_cli_args and _environment_cfg_from_cli read configs from the registry. They used a private _legacy_argparse_cfg_type attribute that repeated the config type @register_environment already registered. They now use EnvironmentRegistry.get_environment_cfg_type, and the 19 duplicate declarations are deleted. Without this, an external factory would have to set the private attribute to work with the command-line scripts.

Usage example

Before:

class ExternalFrankaTableEnvironment(ExampleEnvironmentBase):
    name: str = "franka_table"

    def get_env(self, args_cli: argparse.Namespace):
        pick_up_object = self.asset_registry.get_asset_by_name(args_cli.object)()
        ...

    @staticmethod
    def add_cli_args(parser: argparse.ArgumentParser) -> None:
        parser.add_argument("--object", type=str, default="cracker_box")
python isaaclab_arena/evaluation/policy_runner.py --policy_type zero_action --num_steps 50 \
  --external_environment_class_path my_package.envs:ExternalFrankaTableEnvironment \
  franka_table --object tomato_soup_can

After:

@dataclass
class ExternalFrankaTableEnvironmentCfg(ArenaEnvironmentCfg):
    object: str = "cracker_box"


@register_environment
class ExternalFrankaTableEnvironment(ArenaEnvironmentFactory[ExternalFrankaTableEnvironmentCfg]):
    name: str = "franka_table"

    def build(self, cfg: ExternalFrankaTableEnvironmentCfg) -> IsaacLabArenaEnvironment:
        pick_up_object = self.asset_registry.get_asset_by_name(cfg.object)()
        ...
runs:
  franka_table:
    environment:
      type: my_package.envs.ExternalFrankaTableEnvironment
      object: tomato_soup_can
    policy:
      type: zero_action
    rollout_limit:
      num_steps: 50
python isaaclab_arena/evaluation/experiment_runner.py --experiment_config my_experiment.yaml

Points for discussion

Known limitations and follow-ups

  • Graph-spec Runs and unsupported field types. build_arena_builder_from_legacy_graph builds its parser with get_isaaclab_arena_environments_cli_parser, which reads sys.argv and adds an argparse subcommand for every registered environment. An external config with a field type that add_dataclass_cli_args does not support, such as tuple[float, float, float], therefore breaks graph-spec Runs in the same Experiment. No such config exists in this repository; this was shown with a constructed config. The fix is to build that parser from the Run's own arguments.
  • Import order. register_environment keeps the first class registered under a name and only prints a warning for later ones. If user code imports its module before Arena registers the built-in environments, a factory with a built-in name replaces the built-in environment instead of being rejected. This was shown with a constructed module.
  • Stale tutorials. The four example_workflows/*/step_1_environment_setup.rst pages still show first-party environments as ExampleEnvironmentBase subclasses. Those snippets were already out of date before this PR.
  • OSMO. OSMO submission of Experiments that use code from a user's own repository is not addressed.

Validation

  • CI passed while the PR was ready for review: Run tests, Run tests with subprocess, GR00T closed-loop E2E, the docs build, and pre-commit.
  • Locally in the Arena Docker container, the changed test files and the subprocess tests for test_external_environment.py, test_experiment_runner.py, test_policy_runner.py, test_variations_in_policy_runner.py, and test_osmo_experiment_workflow.py pass. Five of the subprocess tests needed a rerun after CUDA out-of-memory errors on a GPU shared with other jobs. The tests include the new experiment_runner.py run of both example environments by class path, and the Isaac Lab callback test with the migrated example.
  • sphinx-build -b html finishes without warnings.

The argparse adapter looked up each factory's config through a private
_legacy_argparse_cfg_type attribute that repeated the config type
already registered by @register_environment. Read it from
EnvironmentRegistry instead and drop the 19 duplicate declarations.

A typed factory defined outside isaaclab_arena_environments can now
use the argparse paths without setting the private attribute.

Signed-off-by: Clemens Volk <cvolk@nvidia.com>
External environments now use the same contract as built-in ones: an
ArenaEnvironmentFactory[Cfg] subclass with build(cfg), decorated with
@register_environment. ExampleEnvironmentBase and its argparse-only
get_env()/add_cli_args() path are removed. This is a breaking change
for environments defined outside Arena.

--external_environment_class_path now imports the module and checks
that the decorator registered the class under its name, instead of
registering it a second time without a config. Repeated imports
return the same factory, and a factory that reuses a built-in name is
rejected.

Migrate both examples in isaaclab_arena_examples/external_environments
to typed factories.

Signed-off-by: Clemens Volk <cvolk@nvidia.com>
environment.type now accepts the dotted Python class path of an
environment factory, the same rule policy.type already follows. When
the name is not registered, the loader imports the module after the
built-in environments are registered, and checks that the factory's
@register_environment decorator registered it under its name.

The loader resolves only the environment types its Runs select,
instead of looking up every registered environment. A registered
environment without a config no longer breaks loading Experiments
that do not use it.

The serializer writes the class path for factories outside
isaaclab_arena_environments, so a serialized Experiment reloads in a
fresh process where only built-in environments are registered by
name.

Add an example Experiment for the two external environment examples
and run it through experiment_runner.py in the subprocess tests,
replacing the policy_runner.py tests.

Signed-off-by: Clemens Volk <cvolk@nvidia.com>
Rewrite the Arena in Your Repository pages for the typed factory
contract: a config dataclass, an ArenaEnvironmentFactory[Cfg] subclass
with build(cfg), and @register_environment. Show how an Experiment
selects the factory by its dotted class path, how command-line scripts
keep using --external_environment_class_path, and how to migrate an
environment from ExampleEnvironmentBase.

The Policy Runner is no longer needed for external environments.
Update the runner note in the Experiments concept page, the
run-experiment skill, and the catalog pages that described
environments as ExampleEnvironmentBase subclasses.

Signed-off-by: Clemens Volk <cvolk@nvidia.com>
Resolving environment.type before composition dropped the Run name
from the error, so a typo in one Run of a long Experiment did not say
which Run was wrong. _compose_typed_config_from_yaml_selector now calls
the resolver itself and reports a failure as a ValueError that names
the Run, the section, and the selector, which the loader extends with
the Experiment path. This also removes the "Available types" check
that could no longer fail.

Point out the command-line form module_path:ClassName when it is used
as an environment.type, since Experiments use module_path.ClassName.

Signed-off-by: Clemens Volk <cvolk@nvidia.com>
The removed Policy Runner subprocess tests were the only coverage of
--external_environment_class_path through the environment subcommand
parser that environment_runner.py and graph-YAML builds use. Parse the
flag, the environment name, and a generated config flag through
get_isaaclab_arena_environments_cli_parser instead.

Drop comments that still referred to the removed per-environment
add_cli_args() and get_env() adapters.

Signed-off-by: Clemens Volk <cvolk@nvidia.com>
- List the dotted class path as a form of environment.type on the
  Experiments concept page.
- Add a migration step for values that get_env() read from shared
  runner flags such as num_envs.
- List the field types that command-line flags can be generated for.
- State when a factory with a built-in name is rejected.
- Add a rollout limit to the example docstring Experiments so they run
  as shown.

Signed-off-by: Clemens Volk <cvolk@nvidia.com>
@cvolkcvolk
cvolkcvolk marked this pull request as ready for review October 15, 2026 22:25
@greptile-apps

greptile-apps Bot commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[High impact] Refactors how environments are selected and loaded in experiments.

The PR appears safe to merge, with a non-blocking saved-YAML issue for nested external factories.

Findings

  1. P2 Saved nested factories cannot reload ▶

Summary

Experiments can select external environment factories by dotted class path.

  • Experiment Runs can select outside environments by their factory class path.
  • Each Experiment Run resolves its selected environment and policy as it is composed.
  • External and built-in environments use one typed factory contract.

Acknowledged by cvolkcvolk:

  • Removing ExampleEnvironmentBase intentionally breaks the old external contract; a migration guide is included.
  • Graph-YAML Runs with unsupported external config field types are deferred.
  • Duplicate-name behavior when user modules import before built-ins is unchanged.
  • Four stale workflow tutorials are known and deferred.
  • OSMO support for code in a user’s repository is outside this change.
  • Open PRs #887, #635, and #1386 need updates for the removed API.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Run environment.type] --> B{Selector form}
    B -->|Graph YAML path| C[Graph configuration]
    B -->|Registered name| D[Registered factory]
    B -->|Dotted class path| E[Import factory module]
    E --> F[Check registered class matches]
    F --> D
    D --> G[Resolve registered config]
    G --> H[Compose typed Run]
    C --> H
    H --> I[Build environment]
Loading

Reviews (1) · Last reviewed commit: "Clarify the external environment docs" · Reviewed by Greptile

environment_selector = environment_type.name
# Only built-in environments are registered by name when a fresh process loads the YAML.
if not environment_type.__module__.startswith("isaaclab_arena_environments."):
environment_selector = f"{environment_type.__module__}.{environment_type.__qualname__}"

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.

P2 Saved nested factories cannot reload

A nested factory can load through a module-level alias, but saving it writes its dotted __qualname__. For example, my_envs.Factory may point to Group.Factory; saving writes my_envs.Group.Factory. The loader then tries to import my_envs.Group as a module and fails, so the saved Experiment cannot reload.

Make the loader resolve nested class names, or check that the generated path can be imported before writing it.

pass
def test_external_environment_flag_adds_the_registered_factory_subcommand(monkeypatch):
"""Select an external typed factory through the environment subcommand parser used by runner scripts."""
from isaaclab_arena_examples.external_environments.basic import (

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.

🟡 Flag test passes without the flag

This import runs @register_environment, so franka_table is registered before the parser reads --external_environment_class_path. If the import_external_environment(environment) call in add_example_environments_cli_args were removed, this test would still pass. The same import (and the class-path test in test_arena_experiment_config_loader.py) runs earlier in the Phase 1 process, so test_external_environment_registration_callback no longer proves the flag works either. The Policy Runner subprocess tests that used the flag are removed.

Could this test use a module that only the flag imports, for example one written to tmp_path with monkeypatch.syspath_prepend, and assert the name is not registered before parsing? The callback test could select advanced:ExternalFrankaTableWithTaskEnvironment, which no Phase 1 test imports.

ensure_environments_registered()
environment_factory_type = getattr(importlib.import_module(module_path), class_name)
factory_class_path = f"{module_path}.{class_name}"
environment_name = getattr(environment_factory_type, "name", None)

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.

🔵 Check the factory type instead of reading name with getattr

If the selected class is not a factory, for example the config class ...basic.ExternalFrankaTableEnvironmentCfg, this reports "not registered. Decorate it with @register_environment", and following that advice fails inside the decorator because the config has no name. ArenaEnvironmentFactory declares name, so could we check the type and then read it directly? The registration assert below still covers an undecorated factory.

Suggested change
environment_name = getattr(environment_factory_type, "name", None)
assert isinstance(environment_factory_type, type) and issubclass(
environment_factory_type, ArenaEnvironmentFactory
), f"{factory_class_path} is not an ArenaEnvironmentFactory subclass."
environment_name = environment_factory_type.name

cfg_type = cfg_type_resolver(selector)
except (AssertionError, ImportError, AttributeError) as exc:
# Resolvers do not know which Run selected the type; add it so multi-Run Experiments point at the bad Run.
raise ValueError(f"Run '{run_name}' selects unknown {section_name} type '{selector}': {exc}") from exc

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.

🔵 "unknown" is misleading when the type exists

The resolver also imports the user's module and runs the registration checks, so a missing dependency inside that module, or the duplicate-name check in import_registered_environment_factory, is reported as "selects unknown environment type" even though the type exists. The original message is kept after the colon, so only the wording is off. Could it be neutral? The regex in test_unknown_environment_type_names_the_run would need the same change.

Suggested change
raise ValueError(f"Run '{run_name}' selects unknown {section_name} type '{selector}': {exc}") from exc
raise ValueError(f"Run '{run_name}' could not resolve {section_name} type '{selector}': {exc}") from exc

Comment on lines +145 to +147
The fields of the environment's configuration become command-line flags. Flags can be generated
for fields of type ``bool``, ``int``, ``float``, ``str``, an ``Enum`` or ``Literal``, an optional
of these, or a list of these:

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.

🔵 Listed field types are broader than what works

add_dataclass_cli_args handles fewer types than this lists. A plain Enum rejects every value, because argparse compares the converted member with the member.value choices; only class Mode(str, Enum) works. list[Literal[...]] rejects every value, and list[bool] parses False as True. Types such as tuple[...] or dict[...] fail while the parser is built, and because the parser adds a subcommand for every registered environment, that breaks these scripts for all environments once the module is imported. Could the sentence list only what works and say what happens otherwise?

Suggested change
The fields of the environment's configuration become command-line flags. Flags can be generated
for fields of type ``bool``, ``int``, ``float``, ``str``, an ``Enum`` or ``Literal``, an optional
of these, or a list of these:
The fields of the environment's configuration become command-line flags. Flags can be generated
for fields of type ``bool``, ``int``, ``float``, ``str``, a ``Literal``, a string-valued enum such
as ``class Mode(str, Enum)``, an optional of these, or a list of ``int``, ``float``, or ``str``.
Other field types, such as ``tuple[...]``, stop these scripts from building their parser once
your module is imported:

Comment on lines +175 to +178
#. Replace Policy Runner commands that used ``--external_environment_class_path`` with an
Experiment that selects the factory by its class path, as shown above. Note that the
Experiment uses a dotted path (``module_path.ClassName``), while the command-line flag uses
``module_path:ClassName``.

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.

🔵 torchrun runs can't follow this step

The Experiment Runner rejects --distributed, and the Experiments concept page still sends torchrun runs to the Policy Runner, which keeps accepting --external_environment_class_path. Could this step say so?

Suggested change
#. Replace Policy Runner commands that used ``--external_environment_class_path`` with an
Experiment that selects the factory by its class path, as shown above. Note that the
Experiment uses a dotted path (``module_path.ClassName``), while the command-line flag uses
``module_path:ClassName``.
#. Replace Policy Runner commands that used ``--external_environment_class_path`` with an
Experiment that selects the factory by its class path, as shown above. Note that the
Experiment uses a dotted path (``module_path.ClassName``), while the command-line flag uses
``module_path:ClassName``. Multi-GPU runs with ``torchrun`` still use the Policy Runner,
which keeps accepting ``--external_environment_class_path``.

@arena-review-bot

Copy link
Copy Markdown
Contributor

🤖 Isaac Lab-Arena Review Bot

Summary

This PR moves external environments onto the typed ArenaEnvironmentFactory[Cfg] + @register_environment contract, lets Experiments select them by dotted class path the same way policy.type works, and makes the loader resolve only the types each Run selects. The main gap is test coverage for --external_environment_class_path: the tests that remain would still pass if the flag stopped importing the module. The other comments are small fixes to code and docs.

Findings

🔵 Improvement: isaaclab_arena_environments/cli.py:51: check that the imported object is an ArenaEnvironmentFactory subclass instead of reading name with getattr(..., "name", None). A non-factory class, such as the config class, currently gets "decorate it with @register_environment" advice that fails when followed.
🔵 Improvement: isaaclab_arena/hydra/typed_experiment_loader.py:377: "selects unknown type" also labels import errors in the user's module and the duplicate-name rejection, where the type exists.
🔵 Improvement: docs/pages/arena_in_your_repo/external_environments.rst:146: the list of field types that get command-line flags includes plain Enum, list[Literal], and list[bool], which don't parse correctly. It also doesn't say that types like tuple[...] stop the parser from being built.
🔵 Improvement: docs/pages/arena_in_your_repo/external_environments.rst:175: the migration step should note that torchrun runs still need the Policy Runner.

Test Coverage and CI Cost

🟡 Warning: isaaclab_arena/tests/test_environment_cfgs.py:172: test_external_environment_flag_adds_the_registered_factory_subcommand imports the example module before parsing, so franka_table is already registered and the test passes even if the flag does nothing. Two Phase 1 tests run before test_external_environment.py in the same process and import the same module: this one and test_typed_experiment_selects_external_environment_by_class_path. That masks test_external_environment_registration_callback the same way. The Policy Runner subprocess tests that used the flag are removed, so CI no longer checks that the flag imports the module. A module that only the flag imports would close the gap (details inline). Replacing the two Policy Runner subprocess runs with one Experiment Runner run for both environments is a good reduction in CI cost.

Verdict

Minor fixes needed

@cvolkcvolk
cvolkcvolk marked this pull request as draft October 16, 2026 08:39
@cvolkcvolk cvolkcvolk closed this Nov 20, 2026
cvolkcvolk added a commit that referenced this pull request Nov 27, 2026
Read each typed environment's argparse config from `EnvironmentRegistry`
and remove the `_legacy_argparse_cfg_type` attribute from the 19
environment factories.

## Why this change?

The argparse adapter in `isaaclab_arena_environments/cli.py` found a
factory's config through a private `_legacy_argparse_cfg_type` class
attribute. Each factory already declares its config in its
`ArenaEnvironmentFactory[Cfg]` base, and `@register_environment` records
it in `EnvironmentRegistry`, so the attribute repeated it.

A typed factory registered with `@register_environment` but without the
attribute broke the environment CLI. `add_example_environments_cli_args`
builds a subparser for every registered environment, so that one factory
made the build assert for all of them.

This is the first of three PRs that replace #1453 and let an Experiment
select an external environment by class path. The next one, #1729, turns
the external environment examples into typed factories, which will not
set the private attribute. The third, #1730, adds the class path to
Experiments.

## What changes?

- `_registered_environment_cfg_type` in `cli.py` reads the config from
`EnvironmentRegistry.get_environment_cfg_types()` by the factory's
`name`. `add_environment_cli_args` and `_environment_cfg_from_cli` use
it.
- The 19 first-party factories drop `_legacy_argparse_cfg_type`.
- `test_every_registered_cli_adapter_uses_its_typed_cfg_defaults` no
longer compares the attribute with the registry. It still checks that
every registered factory gets its registered config back from the CLI.

`--external_environment_class_path` still registers its class without a
config, so a typed factory loaded through that flag gets no CLI flags
yet. Building the environment subcommands then fails with an error
saying that the flag does not support typed factories yet. This includes
a subclass of a first-party factory, which on `main` inherited
`_legacy_argparse_cfg_type` and worked. The next PR, #1729, makes the
flag use the factory's own `@register_environment` registration.

## Validation

- For all 19 registered environments, the registry lookup returns the
same config class as the removed attribute on `main`.
- In the Arena Docker image, the related tests pass when run locally:
`test_environment_cfgs.py`, `test_environment_registry.py`,
`test_legacy_graph_environment_cli.py`, `test_arena_env_graph_spec.py`,
`test_isaaclab_interop.py`, `test_arena_experiment_config_loader.py`,
`test_asset_registry.py`, `test_environment_runner.py`, and
`test_all_environments_have_default_args`.

- Rebased onto `main` at `a170ca3610` (2026-11-27). No
`_legacy_argparse_cfg_type` is left. The same tests and
`test_external_environment.py` pass locally.

---------

Signed-off-by: Clemens Volk <cvolk@nvidia.com>
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.

1 participant