Repository navigation
[Fix] Make generated template projects import without Kit (no eager omni.ext) (#5941) - #5993
Conversation
…mni.ext) (isaac-sim#5941) ## 1. Summary - Generated template projects could not be imported headless (e.g. Gym registration before `SimulationApp`): `import <project>` failed with `ModuleNotFoundError: No module named 'omni.ext'`. The package root no longer imports the example UI extension, so it stays omni-free. (NVBug 6251247) - Hardened the generator to fail loudly when a requested agent-config template is missing, instead of silently emitting a project whose Gym registration points at a non-existent config. - Self-contained on `develop`. Includes the template-generator test scaffolding (also proposed in isaac-sim#5885, commit preserved) plus new regression coverage — 15 tests. ## 2. Changes ### 2.1 Generator (`tools/template`) - `templates/extension/__init__ext`: drop the eager `from .ui_extension_example import *` from the package root. - `templates/extension/config/extension.toml`: register `<name>.ui_extension_example` as its own `[[python.module]]` so Kit still loads the UI extension (Kit imports each `python.module` by name and scans it for `omni.ext.IExt`). - `templates/extension/ui_extension_example.py`: add the missing `import omni.ui`. - `generator.py`: raise (instead of silently `continue`-ing) when an `agents/<rl_library>_<algorithm>_cfg` template is missing. ### 2.2 Tests - Existing scaffolding: algorithm discovery, single/multi-agent registry entry points, launch configs. - New regressions: omni/pxr import-safety of the generated package, `extension.toml` UI-module registration, generated-`.py` `ast`/`compile` validity, no top-level backend imports in generated env modules, per-library agent-config completeness. ## 3. Design note: why not lazy-import `omni.ext` - `omni.ext` / `ExampleExtension` are consumed only by Kit's extension manager (via `[[python.module]]`), never on the headless path. The correct fix is to not import it at the package root, not to defer it. ## 4. Out of scope / known limitations - AMP on the generated single-agent template (NVBug 6257353) is intentionally left as a known limitation (tracked on the ticket), not changed here: AMP requires task-specific reference motion data (a `MotionLoader` + `collect_reference_motions` + AMP observations) that a generic generated env cannot provide — see `contrib/humanoid_amp`. PPO trains as-generated. - The `free()` / `omni.UsdMdl TfNotice` startup crashes (NVBug 6257159, 6251258) are a separate core issue already fixed by deferring pxr (isaac-sim#5826) and cherry-picked to `release/3.0.0-beta2`. ## 5. Test plan - [x] `./isaaclab.sh -p -m pytest source/isaaclab_rl/test/test_template_generator.py` → 15 passed - [x] Import-safety + UI-module tests fail without the `__init__ext`/`extension.toml` fix (verified by reverting) - [x] Generator raises on a missing agent template (verified) - [x] `./isaaclab.sh -f` (pre-commit) clean --------- Co-authored-by: Kelly Guo <[email protected]>
There was a problem hiding this comment.
🤖 IsaacLab Review Bot — PR #5993
Cherry-pick of #5941 → release/3.0.0-beta2
📋 Summary
This PR fixes generated template projects failing to import in headless mode (before SimulationApp) due to an eager from .ui_extension_example import * that pulls omni.ext. The fix properly separates the UI extension lifecycle from the package import path.
✅ Architecture & Design
Approach is correct and well-reasoned. The design note in the commit message is spot-on: since omni.ext/ExampleExtension is only consumed by Kit's extension manager via [[python.module]], the right fix is to not import it at the package root, rather than lazy-loading it.
Key architectural decisions:
extension.tomldual-module registration — Kit discovers the UI extension via its own[[python.module]]entry ({{ name }}.ui_extension_example), decoupling it from package import. ✅ Clean separation of concerns.lazy_export()for MDP module — Themdp/__init__.pytemplate switches from eagerfrom isaaclab.envs.mdp import *+from .rewards import *tolazy_export()with a.pyistub. This prevents pullingpxr/omnitransitively through the MDP re-exports at config-resolution time. ✅ Correct for the deferred-launch pattern.TYPE_CHECKINGguard inrewards.py— Movesfrom isaaclab.assets import ArticulationbehindTYPE_CHECKINGsince it's only needed for type annotations, not at runtime. ✅ Standard pattern.- Per-workflow
__init__.pycreation moved into_generate_tasks()— Ensures internal tasks also get discoverable workflow dirs (needed after core/contrib split #5891). ✅ Fixes both internal and external paths in one place.
🔍 Implementation Correctness
| Area | Status | Notes |
|---|---|---|
No eager omni.ext in __init__ext |
✅ | Import removed, replaced with explanatory comment |
extension.toml UI module entry |
✅ | Second [[python.module]] entry correctly references {{ name }}.ui_extension_example |
ui_extension_example.py adds import omni.ui |
✅ | Needed since it's no longer imported transitively through the package root; module must be self-contained |
lazy_export() in mdp/__init__.py |
✅ | Requires isaaclab.utils.module.lazy_export to exist in the target branch — assumed available |
.pyi stub for IDE support |
✅ | Properly declares __all__ and re-exports for type checkers |
| Generator error on missing template | ✅ | FileNotFoundError with actionable message replaces silent continue |
workflow_init only created if missing |
✅ | if not os.path.exists(workflow_init) prevents clobbering existing packages |
One minor observation: The lazy_export() pattern assumes this utility exists and works correctly on release/3.0.0-beta2. If it was only introduced in develop and not yet cherry-picked, this would break. However, given the PR author is from the core team and CI is passing pre-commit, this is likely already available.
⚠️ Silent Failure Risks
-
lazy_export()masking import errors — Ifisaaclab.envs.mdphas a genuine import error,lazy_export()would defer it to first attribute access rather than surfacing it at import time. This is an acceptable trade-off for the deferred-launch pattern (configs load before SimulationApp), and the.pyistub ensures IDE tooling still works. Risk: Low. -
Kit not discovering the UI extension — If the
[[python.module]]mechanism doesn't handle dotted submodule names ({{ name }}.ui_extension_example), the extension silently won't load. However, this is a documented Kit feature for extension sub-modules. Risk: Low. -
No runtime check that
lazy_export()is available — If this utility is missing, the import would fail withImportError: cannot import name 'lazy_export'. This is a loud failure (not silent), so acceptable. Risk: None (fails visibly).
🧪 Test Coverage
Excellent. 590 lines of new test coverage (15 tests) with strong regression guarantees:
| Test | What it validates |
|---|---|
test_generated_package_import_is_omni_and_pxr_free |
Direct regression test — imports generated package with omni/pxr blocked via sys.meta_path |
test_generated_manager_based_env_cfg_resolution_is_omni_and_pxr_free |
Config instantiation doesn't pull runtime modules |
test_extension_toml_registers_ui_extension_as_separate_module |
Both halves of the fix (toml entry + no import in __init__) |
test_generated_env_modules_have_no_forbidden_top_level_imports |
AST-based check for forbidden imports at module scope |
test_generated_python_is_syntactically_valid |
All generated .py files parse and compile |
test_each_requested_agent_cfg_file_is_generated |
No silently missing configs |
test_generated_internal_task_workflow_dirs_are_importable_packages |
pkgutil.iter_modules discovers workflow dirs |
test_generated_external_project_registers_tasks_on_import |
End-to-end task registration |
The subprocess-based tests with _Blocker meta-path hook are particularly well-designed — they faithfully reproduce the headless import scenario without needing the full Isaac Sim runtime.
📝 Minor Notes (Non-blocking)
- The
changelog.d/jichuanh-fix-template-generator.skipfile is empty (0 additions/deletions) — presumably intentional to skip changelog generation for a cherry-pick. - CI shows some checks still pending (Installation Tests, Docker builds, license-check) at review time. Pre-commit and Build Wheel have passed.
🏁 Verdict
Well-structured fix with clear design rationale, correct implementation, and thorough test coverage. The approach of separating the UI extension lifecycle from the package import path is the right architectural choice. No blocking concerns identified.
Greptile SummaryThis cherry-pick fixes headless-import crashes in generated template projects by removing two sources of eager
Confidence Score: 4/5Safe to merge; the core template fixes are sound and well-tested by subprocess-level import guards. The two root-cause fixes are correct and verified by both static AST analysis tests and subprocess-level blockers. The generator refactor is straightforward. The only concerns are test-quality gaps: the static import-safety check does not scan mdp/ files, and the UI-extension test uses ast.walk that would flag a hypothetical future TYPE_CHECKING-guarded import incorrectly. Neither affects runtime correctness of the generated projects. source/isaaclab_rl/test/test_template_generator.py and tools/template/templates/tasks/manager-based_single-agent/mdp/init.pyi deserve a second look for the coverage gap and narrow all noted in comments. Important Files Changed
Sequence DiagramsequenceDiagram
participant Train as TrainingScript
participant Pkg as ProjectInit
participant Tasks as TasksInit
participant MDP as MdpInit_lazy_export
participant IsaacMDP as isaaclab_envs_mdp
participant Rewards as mdp_rewards
participant SimApp as SimulationApp
Train->>Pkg: import project
Pkg->>Tasks: from .tasks import star
Tasks->>MDP: lazy_export registers getattr
MDP->>IsaacMDP: importlib.import_module safe lazy init
Note over MDP,IsaacMDP: omni/pxr NOT loaded yet
Train->>SimApp: launch_simulation
SimApp-->>Train: Kit running
Train->>IsaacMDP: mdp.JointEffortActionCfg via getattr
IsaacMDP-->>Train: config object omni/pxr now safe
Train->>Rewards: mdp.joint_pos_target_l2 lazy stub
Rewards-->>Train: reward function
Reviews (1): Last reviewed commit: "[Fix] Make generated template projects i..." | Re-trigger Greptile |
| def test_generated_env_modules_have_no_forbidden_top_level_imports(tmp_path, monkeypatch, external): | ||
| """Generated ``*_env.py`` / ``*_env_cfg.py`` must not import backend runtime modules at module scope. | ||
|
|
||
| Config loading runs before ``SimulationApp``; a top-level ``pxr``/``omni``/``carb``/``isaacsim`` import there | ||
| causes the pre-SimulationApp crashes (e.g. ``free(): invalid pointer``, ``TfNotice`` wrapper not created). This | ||
| catches such an import being (re)introduced into the env templates; deferred / ``TYPE_CHECKING`` imports are fine. | ||
| """ | ||
| project_name = f"template_imports_{'external' if external else 'internal'}" | ||
| root_dir = tmp_path / ("external_root" if external else "internal_tasks") | ||
| monkeypatch.setattr(generator, "_setup_git_repo", lambda project_dir: None) | ||
| if not external: | ||
| monkeypatch.setattr(generator, "TASKS_DIR", str(root_dir)) | ||
|
|
||
| specification = { | ||
| "external": external, | ||
| "name": project_name, | ||
| "workflows": [ | ||
| {"name": "direct", "type": "single-agent"}, | ||
| {"name": "manager-based", "type": "single-agent"}, | ||
| {"name": "direct", "type": "multi-agent"}, | ||
| ], | ||
| "rl_libraries": _all_libraries(), | ||
| } | ||
| if external: | ||
| specification["path"] = str(root_dir) | ||
|
|
||
| generate(specification) | ||
|
|
||
| env_modules = list(root_dir.rglob("*_env.py")) + list(root_dir.rglob("*_env_cfg.py")) | ||
| assert env_modules, "generator produced no env modules" | ||
| for module_file in env_modules: | ||
| forbidden = _top_level_imported_roots(module_file.read_text()) & _FORBIDDEN_RUNTIME_MODULES | ||
| assert not forbidden, ( | ||
| f"{module_file} imports {sorted(forbidden)} at module top level (load before SimulationApp)" | ||
| ) | ||
|
|
||
|
|
||
| def test_each_requested_agent_cfg_file_is_generated(tmp_path, monkeypatch): | ||
| """Every requested (RL library, algorithm) agent config is generated; a missing template raises, not skips.""" | ||
| project_name = "template_agents" | ||
| root_dir = tmp_path / "external_root" | ||
| monkeypatch.setattr(generator, "_setup_git_repo", lambda project_dir: None) | ||
|
|
||
| workflows = [ |
There was a problem hiding this comment.
Forbidden-import check misses
mdp/ files
test_generated_env_modules_have_no_forbidden_top_level_imports only globs *_env.py and *_env_cfg.py. The mdp/__init__.py and mdp/rewards.py are part of the same static import chain: when env_cfg does from . import mdp, both files execute. If a future template change reintroduces a top-level omni/pxr import in mdp/rewards.py, this static test won't catch it. The subprocess test in test_generated_manager_based_env_cfg_resolution_is_omni_and_pxr_free provides a runtime safety net, but extending the glob to root_dir.rglob("*.py") (excluding the agents/ YAML configs) would give the static check the same breadth as the subprocess test.
|
|
||
| The generated package ``__init__`` runs Gym registration (``import_packages``) on import; if it eagerly | ||
| imports the example UI extension (``omni.ext``) or any pxr-loading module, ``import <project>`` crashes | ||
| before Isaac Sim starts. We import the generated package in a subprocess with ``omni``/``pxr`` blocked. | ||
| """ |
There was a problem hiding this comment.
ast.walk traverses into TYPE_CHECKING blocks — potential future false positive
ast.walk(init_tree) descends into every conditional, including if TYPE_CHECKING: branches. The intent documented in the comment is to block eager imports of ui_extension_example. If a developer ever adds a legitimate type-only annotation import like from .ui_extension_example import ExampleExtension inside if TYPE_CHECKING:, this assertion will fire even though that import never executes at runtime. Limiting the traversal to top-level body nodes (as _top_level_imported_roots does elsewhere in this file) would avoid the false positive without weakening the guard.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| # Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md). | ||
| # All rights reserved. | ||
| # | ||
| # SPDX-License-Identifier: BSD-3-Clause | ||
|
|
||
| __all__ = [ | ||
| "joint_pos_target_l2", | ||
| ] | ||
|
|
||
| # Forward stable MDP terms lazily, then override with environment-specific terms below. | ||
| from isaaclab.envs.mdp import * # noqa: F401, F403 | ||
|
|
||
| from .rewards import joint_pos_target_l2 |
There was a problem hiding this comment.
Narrow
__all__ in stub may confuse IDEs and from .mdp import * consumers
lazy_export() resolves names not in the stub via the isaaclab.envs.mdp fallback package, so attribute access like mdp.joint_pos_rel works at runtime. However, the module-level __all__ set by lazy.attach_stub from the filtered stub is exactly ["joint_pos_target_l2"]. Any file that does from <project>.tasks.manager_based.<task>.mdp import * will only receive joint_pos_target_l2 — not the full isaaclab.envs.mdp surface. The env_cfg template uses from . import mdp (attribute access), so the generated project itself is unaffected, but it's an unexpected contract for downstream consumers and IDE autocompletion. Adding a brief comment here noting that the wildcard import expands via __getattr__ at access time (not via __all__) would help maintainers avoid surprises.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Cherry-picks #5941 from develop to release/3.0.0-beta2.
The generated template project pulled Kit/pxr eagerly, so importing it headless (Gym registration before SimulationApp) failed with
ModuleNotFoundError: No module named 'omni.ext'andTfNotice ... has not been created yet. The fix loads the UI extension via its ownconfig/extension.tomlentry, switches the generatedmdppackage tolazy_export()with a.pyistub, guards type-only imports underTYPE_CHECKING, creates the per-workflow__init__.pyso internal tasks register after the core/contrib split, and makes the generator fail loudly on a missing agent template. Adds template-generator CI regression coverage.Validation: