Skip to content

[Fix] Make generated template projects import without Kit (no eager omni.ext) (#5941) - #5993

Merged
kellyguo11 merged 1 commit into
isaac-sim:release/3.0.0-beta2from
hujc7:jichuanh/cherrypick-5941-release-3.0.0-beta2
Jun 7, 2026
Merged

kellyguo11 merged 1 commit into
isaac-sim:release/3.0.0-beta2from
hujc7:jichuanh/cherrypick-5941-release-3.0.0-beta2

Conversation

@hujc7

@hujc7 hujc7 commented Jun 5, 2026

Copy link
Copy Markdown
Collaborator

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' and TfNotice ... has not been created yet. The fix loads the UI extension via its own config/extension.toml entry, switches the generated mdp package to lazy_export() with a .pyi stub, guards type-only imports under TYPE_CHECKING, creates the per-workflow __init__.py so 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:

  • ./isaaclab.sh -f

…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]>
@hujc7
hujc7 requested a review from hhansen-bdai as a code owner June 5, 2026 16:22
@github-actions github-actions Bot added isaac-lab Related to Isaac Lab team infrastructure labels Jun 5, 2026
@hujc7
hujc7 requested review from kellyguo11 and ooctipus June 5, 2026 16:24

@isaaclab-review-bot isaaclab-review-bot Bot 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.

🤖 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:

  1. extension.toml dual-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.
  2. lazy_export() for MDP module — The mdp/__init__.py template switches from eager from isaaclab.envs.mdp import * + from .rewards import * to lazy_export() with a .pyi stub. This prevents pulling pxr/omni transitively through the MDP re-exports at config-resolution time. ✅ Correct for the deferred-launch pattern.
  3. TYPE_CHECKING guard in rewards.py — Moves from isaaclab.assets import Articulation behind TYPE_CHECKING since it's only needed for type annotations, not at runtime. ✅ Standard pattern.
  4. Per-workflow __init__.py creation 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

  1. lazy_export() masking import errors — If isaaclab.envs.mdp has 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 .pyi stub ensures IDE tooling still works. Risk: Low.

  2. 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.

  3. No runtime check that lazy_export() is available — If this utility is missing, the import would fail with ImportError: 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)

  1. The changelog.d/jichuanh-fix-template-generator.skip file is empty (0 additions/deletions) — presumably intentional to skip changelog generation for a cherry-pick.
  2. 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-apps

greptile-apps Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This cherry-pick fixes headless-import crashes in generated template projects by removing two sources of eager omni/pxr loading: the package __init__ no longer imports ui_extension_example (moved to its own [[python.module]] Kit entry), and mdp/__init__.py switches from eager from isaaclab.envs.mdp import * / from .rewards import * to lazy_export() backed by a .pyi stub. A comprehensive CI test suite (590 lines) is added to lock in the behaviour.

  • Workflow-level __init__.py creation is consolidated into _generate_tasks, covering both internal and external paths.
  • The generator now raises FileNotFoundError instead of silently skipping missing agent config templates.
  • New subprocess-based tests block omni/pxr at import time and verify that both package import and env-config instantiation remain safe before SimulationApp.

Confidence Score: 4/5

Safe 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

Filename Overview
source/isaaclab_rl/test/test_template_generator.py New 590-line test file covering template generator correctness, Gym registration, forbidden import checks, and the UI-extension separation. Several test helpers have minor coverage and false-positive risks.
tools/template/generator.py Key fix: workflow init.py creation moved into _generate_tasks (covers both internal and external paths), and missing agent template now raises instead of silently skipping.
tools/template/templates/tasks/manager-based_single-agent/mdp/init.py Switches from eager from isaaclab.envs.mdp import * to lazy_export(), deferring attribute resolution to access time so importing the package stays omni/pxr-free.
tools/template/templates/tasks/manager-based_single-agent/mdp/init.pyi New stub file driving lazy_export(); all only lists joint_pos_target_l2, while from isaaclab.envs.mdp import * establishes the lazy fallback. IDEs will see a narrow all and may not discover other mdp terms via autocomplete.
tools/template/templates/extension/__init__ext Replaces from .ui_extension_example import * with a comment explaining that Kit loads the UI module via extension.toml; directly fixes the ModuleNotFoundError on headless import.
tools/template/templates/extension/config/extension.toml Adds a second [[python.module]] entry for the ui_extension_example submodule so Kit can still discover and load the UI extension even though the package init no longer imports it.

Sequence Diagram

sequenceDiagram
    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
Loading

Reviews (1): Last reviewed commit: "[Fix] Make generated template projects i..." | Re-trigger Greptile

Comment on lines +285 to +328
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 = [

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 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.

Comment on lines +415 to +419

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.
"""

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 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!

Comment on lines +1 to +13
# 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

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 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!

@kellyguo11
kellyguo11 merged commit 527a516 into isaac-sim:release/3.0.0-beta2 Jun 7, 2026
37 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

infrastructure isaac-lab Related to Isaac Lab team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants