a valid preset selection."""
+ presets = {"env": {"": {"default": None, "fast": None}}, "agent": {}}
+ _, sel, _, _ = parse_overrides(["env=fast"], presets)
+ assert sel == [("env", "", "fast")]
+
+
+# =============================================================================
+# Tests: _parse_val
+# =============================================================================
+
+
+def test_parse_val_types():
+ """_parse_val converts strings to correct Python types."""
+ from isaaclab_tasks.utils.hydra import _parse_val
+
+ assert _parse_val("true") is True
+ assert _parse_val("True") is True
+ assert _parse_val("false") is False
+ assert _parse_val("none") is None
+ assert _parse_val("null") is None
+ assert _parse_val("42") == 42
+ assert isinstance(_parse_val("42"), int)
+ assert _parse_val("3.14") == 3.14
+ assert isinstance(_parse_val("3.14"), float)
+ assert _parse_val("hello") == "hello"
+ assert _parse_val('"quoted"') == "quoted"
+ assert _parse_val("'single'") == "single"
+
+
+# =============================================================================
+# Tests: scalar override within preset path
+# =============================================================================
+
+
+def test_scalar_override_within_preset_path(class_presets):
+ """Scalar overrides within preset paths are applied on top of the preset."""
+ env_cfg, agent_cfg, presets = class_presets
+ env_cfg = resolve_preset_defaults(env_cfg)
+ agent_cfg = resolve_preset_defaults(agent_cfg)
+ hydra_cfg = {"env": env_cfg.to_dict(), "agent": agent_cfg.to_dict()}
+ apply_overrides(
+ env_cfg,
+ agent_cfg,
+ hydra_cfg,
+ [],
+ [("env", "backend", "newton")],
+ [("env.backend.dt", "0.001")],
+ presets,
+ )
+ assert isinstance(env_cfg.backend, NewtonCfg)
+ assert env_cfg.backend.dt == 0.001 # overridden from 0.002
+ assert env_cfg.backend.substeps == 4 # untouched
+
+
+# =============================================================================
+# Tests: resolve_preset_defaults idempotency
+# =============================================================================
+
+
+def test_resolve_preset_defaults_idempotent():
+ """Calling resolve_preset_defaults twice yields the same result."""
+ cfg = PresetCfgEnvCfg()
+ first = resolve_preset_defaults(cfg)
+ second = resolve_preset_defaults(first)
+ assert isinstance(second.backend, PhysxCfg)
+ assert isinstance(second.observations, NoiselessObservationsCfg)
+ assert second.backend.dt == first.backend.dt
diff --git a/source/isaaclab_tasks/test/test_lazy_export_stubs.py b/source/isaaclab_tasks/test/test_lazy_export_stubs.py
index 7a13dba6c6b0..b7e9a824d727 100644
--- a/source/isaaclab_tasks/test/test_lazy_export_stubs.py
+++ b/source/isaaclab_tasks/test/test_lazy_export_stubs.py
@@ -3,7 +3,7 @@
#
# SPDX-License-Identifier: BSD-3-Clause
-"""Verify that lazy_export() call sites use no arguments.
+"""Verify lazy_export() call-site conventions and _parse_stub behaviour.
Every ``__init__.py`` that calls ``lazy_export()`` should pass no arguments.
Fallback packages and wildcard re-exports are inferred from the ``.pyi``
@@ -15,10 +15,13 @@
import ast
import os
+import tempfile
from pathlib import Path
import pytest
+from isaaclab.utils.module import _parse_stub
+
_SOURCE_ROOT = Path(__file__).resolve().parent.parent.parent
@@ -80,3 +83,126 @@ def test_no_lazy_export_violations_found():
if f == "__init__.py" and "lazy_export" in (Path(root) / f).read_text(errors="ignore")
)
assert init_count > 0, "No __init__.py files with lazy_export() found — discovery may be broken"
+
+
+# ---------------------------------------------------------------------------
+# _parse_stub unit tests
+# ---------------------------------------------------------------------------
+
+
+def _write_stub(content: str) -> str:
+ """Write *content* to a temporary ``.pyi`` file and return its path."""
+ fd, path = tempfile.mkstemp(suffix=".pyi")
+ with os.fdopen(fd, "w") as f:
+ f.write(content)
+ return path
+
+
+def test_parse_stub_single_absolute_named_import():
+ """Test single absolute named import extraction."""
+ stub = _write_stub("from some.package import alpha, beta\n")
+ try:
+ _, _, _, absolute_named = _parse_stub(stub)
+ finally:
+ os.unlink(stub)
+
+ assert "some.package" in absolute_named
+ assert absolute_named["some.package"] == ["alpha", "beta"]
+
+
+def test_parse_stub_multiple_absolute_named_imports():
+ """Test multiple absolute named imports from different packages."""
+ stub = _write_stub("from pkg_a import foo\nfrom pkg_b import bar, baz\n")
+ try:
+ _, _, _, absolute_named = _parse_stub(stub)
+ finally:
+ os.unlink(stub)
+
+ assert absolute_named["pkg_a"] == ["foo"]
+ assert absolute_named["pkg_b"] == ["bar", "baz"]
+
+
+def test_parse_stub_same_package_multiple_lines_accumulates():
+ """Test that imports from the same package on multiple lines accumulate."""
+ stub = _write_stub("from pkg import a\nfrom pkg import b, c\n")
+ try:
+ _, _, _, absolute_named = _parse_stub(stub)
+ finally:
+ os.unlink(stub)
+
+ assert absolute_named["pkg"] == ["a", "b", "c"]
+
+
+def test_parse_stub_absolute_wildcard_not_in_absolute_named():
+ """Test that absolute wildcard imports go to fallbacks, not absolute_named."""
+ stub = _write_stub("from some.package import *\n")
+ try:
+ _, fallbacks, _, absolute_named = _parse_stub(stub)
+ finally:
+ os.unlink(stub)
+
+ assert "some.package" in fallbacks
+ assert absolute_named == {}
+
+
+def test_parse_stub_relative_import_not_in_absolute_named():
+ """Test that relative imports are not included in absolute_named."""
+ stub = _write_stub("from .sub import foo, bar\n")
+ try:
+ _, _, _, absolute_named = _parse_stub(stub)
+ finally:
+ os.unlink(stub)
+
+ assert absolute_named == {}
+
+
+def test_parse_stub_mixed_import_kinds():
+ """All four import kinds in one stub are routed correctly."""
+ stub = _write_stub(
+ "from .local import thing\nfrom .wildmod import *\nfrom abs.pkg import *\nfrom abs.other import x, y\n"
+ )
+ try:
+ filtered_path, fallbacks, rel_wildcards, absolute_named = _parse_stub(stub)
+ finally:
+ if filtered_path is not None:
+ os.unlink(filtered_path)
+ os.unlink(stub)
+
+ assert fallbacks == ["abs.pkg"]
+ assert rel_wildcards == ["wildmod"]
+ assert absolute_named == {"abs.other": ["x", "y"]}
+ assert filtered_path is not None
+
+
+def test_parse_stub_no_imports_returns_empty():
+ """Test that a stub with no imports returns empty collections."""
+ stub = _write_stub("X: int\n")
+ try:
+ filtered_path, fallbacks, rel_wildcards, absolute_named = _parse_stub(stub)
+ finally:
+ os.unlink(stub)
+
+ assert filtered_path is None
+ assert fallbacks == []
+ assert rel_wildcards == []
+ assert absolute_named == {}
+
+
+def test_parse_stub_filtered_stub_excludes_absolute_named():
+ """Absolute named imports must not leak into the filtered stub.
+
+ The filtered stub is passed to lazy_loader which only handles relative named imports.
+ """
+ stub = _write_stub("from .local import thing\nfrom abs.pkg import alpha\n")
+ try:
+ filtered_path, _, _, _ = _parse_stub(stub)
+ assert filtered_path is not None
+ with open(filtered_path) as f:
+ content = f.read()
+ assert "alpha" not in content
+ assert "abs" not in content
+ assert "thing" in content
+ finally:
+ if filtered_path is not None:
+ os.unlink(filtered_path)
+ os.unlink(stub)
diff --git a/source/isaaclab_tasks/test/test_rendering_correctness.py b/source/isaaclab_tasks/test/test_rendering_correctness.py
index 6f196ce38083..695f7dbfc2a6 100644
--- a/source/isaaclab_tasks/test/test_rendering_correctness.py
+++ b/source/isaaclab_tasks/test/test_rendering_correctness.py
@@ -6,9 +6,10 @@
"""Tests for rendering correctness.
Each test builds an environment with a given (physics_backend, renderer, data_type),
-steps once, then asserts that camera outputs are not blank (at least one non-zero
-pixel). Env-specific fixtures use parametrized combinations; a separate test
-covers a list of registered task IDs that use camera-based observations.
+steps once, then checks if camera outputs are not blank (at least one non-zero
+pixel) and consistent with golden images. Env-specific fixtures use parametrized
+combinations; a separate test covers a list of registered task IDs that use
+camera-based observations.
"""
# Launch Isaac Sim Simulator first.
@@ -17,11 +18,15 @@
app_launcher = AppLauncher(headless=True, enable_cameras=True)
simulation_app = app_launcher.app
-from typing import Any
+import os # noqa: E402
+from datetime import datetime # noqa: E402
+from typing import Any # noqa: E402
import gymnasium as gym # noqa: E402
+import numpy as np # noqa: E402
import pytest # noqa: E402
import torch # noqa: E402
+from PIL import Image, ImageChops # noqa: E402
from isaaclab.envs.utils.spaces import sample_space # noqa: E402
from isaaclab.sim import SimulationContext # noqa: E402
@@ -33,6 +38,36 @@
)
from isaaclab_tasks.utils.parse_cfg import parse_env_cfg # noqa: E402
+# ---------------------------------------------------------------------------
+# Constants
+# ---------------------------------------------------------------------------
+
+# Directory containing golden images.
+_GOLDEN_IMAGES_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), "golden_images")
+
+# Pixel L2 norm difference threshold. L2 norm difference is the Euclidean distance between two pixels:
+#
+# d = sqrt((R1 - R2)^2 + (G1 - G2)^2 + (B1 - B2)^2)
+#
+# If the difference between two pixels is less than this threshold, consider them "equal" (i.e. within the tolerance).
+#
+_PIXEL_L2_NORM_DIFFERENCE_THRESHOLD = 10.0
+
+_OVRTX_DISABLED = pytest.mark.skip(
+ reason="OVRTX is optional and experimental feature and temporarily is excluded from testing."
+)
+
+# Directory for comparison images saved during the test session.
+# Located under the pytest output root so it gets copied alongside test reports.
+_COMPARISON_IMAGES_DIR = os.path.join(os.getcwd(), "tests", "comparison-images")
+
+# Collects comparison scores from all golden-image comparisons during the session.
+# Each entry: {"test": str, "backend": str, "renderer": str, "aov": str,
+# "ssim": float, "diff_pct": float, "passed": bool,
+# "img_result_path": str | None, "img_golden_path": str | None}
+_COMPARISON_SCORES: list[dict] = []
+
+
# ---------------------------------------------------------------------------
# Fixtures
# ---------------------------------------------------------------------------
@@ -52,19 +87,51 @@ def cleanup_simulation_context():
SimulationContext.clear_instance()
+@pytest.fixture(scope="session", autouse=True)
+def _generate_comparison_html_report():
+ """Generate an HTML comparison report after all tests in the session complete."""
+ yield
+ try:
+ _generate_html_report()
+ except Exception as exc: # noqa: BLE001
+ import warnings
+
+ warnings.warn(f"Failed to generate HTML comparison report: {exc}", stacklevel=1)
+
+
+@pytest.fixture(autouse=True)
+def _attach_comparison_properties(request):
+ """Attach pixel-diff, SSIM scores, and failure images as JUnit XML properties."""
+ initial_count = len(_COMPARISON_SCORES)
+ yield
+ for entry in _COMPARISON_SCORES[initial_count:]:
+ label = f"{entry['backend']}-{entry['renderer']}-{entry['aov']}"
+ request.node.user_properties.append((f"diff_pct:{label}", f"{entry['diff_pct']:.2f}"))
+ request.node.user_properties.append((f"ssim:{label}", f"{entry['ssim']:.4f}"))
+ request.node.user_properties.append((f"threshold:{label}", f"{entry['threshold']:.1f}"))
+ if entry.get("img_result_path"):
+ request.node.user_properties.append((f"img_result:{label}", entry["img_result_path"]))
+ request.node.user_properties.append((f"img_golden:{label}", entry["img_golden_path"]))
+
+
# ---------------------------------------------------------------------------
# Parametrization: (physics_backend, renderer, data_type)
# ---------------------------------------------------------------------------
-_OVRTX_DISABLED = pytest.mark.skip(
- reason="OVRTX is optional and experimental feature and temporarily is excluded from testing."
-)
-
_PHYSICS_RENDERER_AOV_COMBINATIONS = [
# physx + isaacsim_rtx_renderer
- pytest.param(("physx", "isaacsim_rtx_renderer", "rgb"), id="physx-isaacsim_rtx-rgb"),
- pytest.param(("physx", "isaacsim_rtx_renderer", "albedo"), id="physx-isaacsim_rtx-albedo"),
- pytest.param(("physx", "isaacsim_rtx_renderer", "depth"), id="physx-isaacsim_rtx-depth"),
+ pytest.param(
+ ("physx", "isaacsim_rtx_renderer", "rgb"),
+ id="physx-isaacsim_rtx-rgb",
+ ),
+ pytest.param(
+ ("physx", "isaacsim_rtx_renderer", "albedo"),
+ id="physx-isaacsim_rtx-albedo",
+ ),
+ pytest.param(
+ ("physx", "isaacsim_rtx_renderer", "depth"),
+ id="physx-isaacsim_rtx-depth",
+ ),
pytest.param(
("physx", "isaacsim_rtx_renderer", "simple_shading_constant_diffuse"),
id="physx-isaacsim_rtx-simple_shading_constant_diffuse",
@@ -77,12 +144,28 @@ def cleanup_simulation_context():
("physx", "isaacsim_rtx_renderer", "simple_shading_full_mdl"),
id="physx-isaacsim_rtx-simple_shading_full_mdl",
),
+ pytest.param(
+ ("physx", "isaacsim_rtx_renderer", "semantic_segmentation"),
+ id="physx-isaacsim_rtx-semantic_segmentation",
+ ),
# physx + newton_renderer (warp)
- pytest.param(("physx", "newton_renderer", "rgb"), id="physx-newton_warp-rgb"),
- pytest.param(("physx", "newton_renderer", "depth"), id="physx-newton_warp-depth"),
+ pytest.param(
+ ("physx", "newton_renderer", "rgb"),
+ id="physx-newton_warp-rgb",
+ ),
+ pytest.param(
+ ("physx", "newton_renderer", "depth"),
+ id="physx-newton_warp-depth",
+ ),
# newton + isaacsim_rtx_renderer
- pytest.param(("newton", "isaacsim_rtx_renderer", "rgb"), id="newton-isaacsim_rtx-rgb"),
- pytest.param(("newton", "isaacsim_rtx_renderer", "albedo"), id="newton-isaacsim_rtx-albedo"),
+ pytest.param(
+ ("newton", "isaacsim_rtx_renderer", "rgb"),
+ id="newton-isaacsim_rtx-rgb",
+ ),
+ pytest.param(
+ ("newton", "isaacsim_rtx_renderer", "albedo"),
+ id="newton-isaacsim_rtx-albedo",
+ ),
pytest.param(
("newton", "isaacsim_rtx_renderer", "depth"),
id="newton-isaacsim_rtx-depth",
@@ -99,8 +182,15 @@ def cleanup_simulation_context():
("newton", "isaacsim_rtx_renderer", "simple_shading_full_mdl"),
id="newton-isaacsim_rtx-simple_shading_full_mdl",
),
+ pytest.param(
+ ("newton", "isaacsim_rtx_renderer", "semantic_segmentation"),
+ id="newton-isaacsim_rtx-semantic_segmentation",
+ ),
# newton + newton_renderer (warp)
- pytest.param(("newton", "newton_renderer", "rgb"), id="newton-newton_warp-rgb"),
+ pytest.param(
+ ("newton", "newton_renderer", "rgb"),
+ id="newton-newton_warp-rgb",
+ ),
pytest.param(
("newton", "newton_renderer", "depth"),
id="newton-newton_warp-depth",
@@ -136,6 +226,11 @@ def cleanup_simulation_context():
id="newton-ovrtx-simple_shading_full_mdl",
marks=_OVRTX_DISABLED,
),
+ pytest.param(
+ ("newton", "ovrtx_renderer", "semantic_segmentation"),
+ id="newton-ovrtx-semantic_segmentation",
+ marks=_OVRTX_DISABLED,
+ ),
]
@@ -161,21 +256,335 @@ def _apply_overrides_to_env_cfg(env_cfg: Any, override_args: list[str]) -> Any:
return env_cfg
-def _assert_camera_outputs_are_not_blank(label: str, camera_outputs: dict[str, dict[str, torch.Tensor]]) -> None:
- """Assert each camera output has at least one non-zero pixel.
+def _normalize_tensor(tensor: torch.Tensor, data_type: str) -> torch.Tensor:
+ """Convert camera output tensor to [0, 1] float32 for conversion to image.
+
+ Args:
+ tensor: Camera output tensor.
+ data_type: Data type of the camera output.
+
+ Returns:
+ Normalized tensor.
+ """
+ normalized = tensor.float()
+
+ if data_type in ["depth", "distance_to_camera", "distance_to_image_plane"]:
+ max_val = normalized.max()
+ if max_val > 0:
+ normalized = normalized / max_val
+ elif data_type in {"albedo"}:
+ normalized = normalized[..., :3] / 255.0
+ else:
+ normalized = normalized / 255.0
+
+ return normalized
+
+
+def _save_comparison_image(img: Image.Image, filename: str) -> str:
+ """Save a PIL image to the comparison-images/images directory.
Args:
- label: Label for error messages.
- camera_outputs: Nested dict: sensor name -> {data_type -> tensor}.
+ img: PIL Image to save.
+ filename: File name (e.g. ``"test-backend-renderer-aov-result.png"``).
+
+ Returns:
+ Absolute path to the saved file.
+ """
+ path = os.path.join(_COMPARISON_IMAGES_DIR, "images", filename)
+ os.makedirs(os.path.dirname(path), exist_ok=True)
+ img.save(path, format="PNG")
+ return path
+
+
+def _generate_html_report() -> None:
+ """Generate an HTML report of all comparison scores and save it alongside the comparison images.
+
+ The report is written to ``<_COMPARISON_IMAGES_DIR>/_report_.html`` and includes a table of
+ all image comparison results sorted by PixelDiff % descending, with thumbnail links to actual
+ and golden images where available.
"""
- assert len(camera_outputs) > 0, f"[{label}] No camera outputs; env may have no cameras or wrong structure."
- for sensor_name, output in camera_outputs.items():
- for data_type, tensor in output.items():
- invalid = torch.logical_or(torch.isinf(tensor), torch.isnan(tensor))
- corrected = torch.where(invalid, torch.zeros_like(tensor), tensor)
- assert corrected.max() > 0, (
- f"[{label}] Sensor '{sensor_name}' output '{data_type}' has no non-zero pixels. "
- f"Shape: {corrected.shape}, dtype: {corrected.dtype}."
+ if not _COMPARISON_SCORES:
+ return
+
+ os.makedirs(_COMPARISON_IMAGES_DIR, exist_ok=True)
+ report_path = os.path.join(_COMPARISON_IMAGES_DIR, "_report_.html")
+
+ sorted_scores = sorted(_COMPARISON_SCORES, key=lambda e: -e["diff_pct"])
+
+ rows = []
+ for entry in sorted_scores:
+ status_class = "pass" if entry["passed"] else "fail"
+ status_text = status_class.upper()
+
+ actual_img_html = ""
+ golden_img_html = ""
+ if entry.get("img_result_path"):
+ actual_fname = os.path.relpath(entry["img_result_path"], _COMPARISON_IMAGES_DIR)
+ golden_fname = os.path.relpath(entry["img_golden_path"], _COMPARISON_IMAGES_DIR)
+ actual_img_html = f'
'
+ golden_img_html = f'
'
+
+ rows.append(
+ f''
+ f"| {entry['test']} | "
+ f"{entry['backend']} | "
+ f"{entry['renderer']} | "
+ f"{entry['aov']} | "
+ f"{entry['diff_pct']:.2f} | "
+ f"{entry['threshold']:.1f} | "
+ f"{entry['ssim']:.4f} | "
+ f'{status_text} | '
+ f"{actual_img_html} | "
+ f"{golden_img_html} | "
+ "
"
+ )
+
+ html = (
+ "\n"
+ "\n"
+ "\n"
+ '\n'
+ "Rendering Correctness — Image Comparison Report\n"
+ "\n"
+ "\n"
+ "\n"
+ "Rendering Correctness — Image Comparison Report
\n"
+ f"Sorted by PixelDiff % (desc) — {len(sorted_scores)} total.
\n"
+ "\n"
+ ""
+ "| Test | "
+ "Backend | "
+ "Renderer | "
+ "AOV | "
+ "PixelDiff % | "
+ "Threshold % | "
+ "SSIM | "
+ "Status | "
+ "ACTUAL | "
+ "GOLDEN | "
+ "
\n"
+ "\n" + "\n".join(rows) + "\n\n
\n\n\n"
+ )
+
+ with open(report_path, "w", encoding="utf-8") as f:
+ f.write(html)
+
+
+def _make_grid(images: torch.Tensor) -> torch.Tensor:
+ """Make a grid of images from a tensor of shape (B, H, W, C).
+
+ Args:
+ images: A tensor of shape (B, H, W, C) containing the images.
+
+ Returns:
+ A tensor of shape (H, W, C) containing the grid of images.
+ """
+ from torchvision.utils import make_grid
+
+ return make_grid(torch.swapaxes(images.unsqueeze(1), 1, -1).squeeze(-1), nrow=round(images.shape[0] ** 0.5))
+
+
+def _ssim(img1: torch.Tensor, img2: torch.Tensor, window_size: int = 11) -> float:
+ """Compute mean SSIM between two (1, C, H, W) float tensors in [0, 1].
+
+ https://en.wikipedia.org/wiki/Structural_similarity_index_measure
+
+ Uses a uniform averaging window and the standard SSIM constants (K1=0.01, K2=0.03,
+ data_range=1.0).
+
+ Args:
+ img1: First image tensor of shape (1, C, H, W) in [0, 1].
+ img2: Second image tensor of shape (1, C, H, W) in [0, 1].
+ window_size: Side length of the square averaging window.
+
+ Returns:
+ Mean SSIM score (1.0 = identical).
+ """
+ c1 = 0.01**2
+ c2 = 0.03**2
+ channels = img1.shape[1]
+ pad = window_size // 2
+
+ kernel = torch.ones(channels, 1, window_size, window_size, device=img1.device, dtype=img1.dtype) / (
+ window_size * window_size
+ )
+
+ mu1 = torch.nn.functional.conv2d(img1, kernel, padding=pad, groups=channels)
+ mu2 = torch.nn.functional.conv2d(img2, kernel, padding=pad, groups=channels)
+
+ mu1_sq = mu1 * mu1
+ mu2_sq = mu2 * mu2
+ mu1_mu2 = mu1 * mu2
+
+ sigma1_sq = torch.nn.functional.conv2d(img1 * img1, kernel, padding=pad, groups=channels) - mu1_sq
+ sigma2_sq = torch.nn.functional.conv2d(img2 * img2, kernel, padding=pad, groups=channels) - mu2_sq
+ sigma12 = torch.nn.functional.conv2d(img1 * img2, kernel, padding=pad, groups=channels) - mu1_mu2
+
+ ssim_map = ((2 * mu1_mu2 + c1) * (2 * sigma12 + c2)) / ((mu1_sq + mu2_sq + c1) * (sigma1_sq + sigma2_sq + c2))
+ return ssim_map.mean().item()
+
+
+def _pixel_diff_percentage(
+ result_image: Image.Image,
+ golden_image: Image.Image,
+ pixel_diff_threshold: float = _PIXEL_L2_NORM_DIFFERENCE_THRESHOLD,
+) -> float:
+ """Compute the percentage of pixels whose L2 norm difference exceeds a threshold.
+
+ Args:
+ result_image: Result image as PIL Image.
+ golden_image: Golden image as PIL Image (must be same size/mode).
+ pixel_diff_threshold: Pixel L2 norm difference threshold.
+
+ Returns:
+ Percentage of pixels that differ beyond the threshold.
+ """
+ diff_array = np.array(ImageChops.difference(result_image, golden_image))
+ l2_norm_array = np.linalg.norm(diff_array, axis=2)
+ num_different_pixels = np.sum(l2_norm_array > pixel_diff_threshold)
+ return 100.0 * num_different_pixels / l2_norm_array.size
+
+
+def _compare_images(
+ result_image: Image.Image,
+ golden_image: Image.Image,
+ max_different_pixels_percentage: float,
+) -> tuple[bool, str | None, float, float]:
+ """Compare result and golden images using pixel L2 norm (pass/fail) and SSIM (reference).
+
+ Args:
+ result_image: Result image as PIL Image to compare with golden image.
+ golden_image: Golden image as PIL Image to compare with result image.
+ max_different_pixels_percentage: Maximum percentage of pixels allowed to exceed pixel_diff_threshold.
+
+ Returns:
+ (passed, error_message_or_None, diff_percentage, ssim_score).
+ Scores are 0.0 / 0.0 when comparison cannot be performed (size/mode mismatch).
+ """
+ if result_image.size != golden_image.size:
+ return False, f"Size mismatch: expected {golden_image.size}, got {result_image.size}.", 0.0, 0.0
+
+ if result_image.mode != golden_image.mode:
+ return False, f"Mode mismatch: expected {golden_image.mode}, got {result_image.mode}.", 0.0, 0.0
+
+ diff_pct = _pixel_diff_percentage(result_image, golden_image)
+
+ # SSIM (reference only, not used for pass/fail).
+ result_tensor = torch.from_numpy(np.array(result_image, dtype=np.float32) / 255.0).permute(2, 0, 1).unsqueeze(0)
+ golden_tensor = torch.from_numpy(np.array(golden_image, dtype=np.float32) / 255.0).permute(2, 0, 1).unsqueeze(0)
+ ssim_score = _ssim(result_tensor, golden_tensor)
+
+ if diff_pct > max_different_pixels_percentage:
+ return (
+ False,
+ f"The percentage of different pixels ({diff_pct:.2f}%) exceeds the threshold of"
+ f" {max_different_pixels_percentage:.2f}%. SSIM={ssim_score:.4f} (reference).",
+ diff_pct,
+ ssim_score,
+ )
+
+ return True, None, diff_pct, ssim_score
+
+
+def _validate_camera_outputs(
+ test_name: str,
+ physics_backend: str,
+ renderer: str,
+ camera_outputs: dict[str, torch.Tensor],
+ max_different_pixels_percentage: float,
+) -> None:
+ """Validate correctness and consistency of camera outputs.
+
+ Args:
+ test_name: Test name.
+ physics_backend: Physics backend.
+ renderer: Renderer.
+ camera_outputs: {data_type -> tensor}.
+ max_different_pixels_percentage: Maximum percentage of pixels allowed to exceed pixel_diff_threshold.
+ """
+ assert len(camera_outputs) > 0, f"[{test_name}] No camera outputs produced by {physics_backend} + {renderer}."
+
+ golden_image_dir = os.path.join(_GOLDEN_IMAGES_DIRECTORY, test_name)
+ os.makedirs(golden_image_dir, exist_ok=True)
+
+ for data_type, tensor in camera_outputs.items():
+ # Replace inf/nan with zero so they do not break comparison; ensure the tensor has at least one non-zero value.
+ condition = torch.logical_or(torch.isinf(tensor), torch.isnan(tensor))
+ corrected = torch.where(condition, torch.zeros_like(tensor), tensor)
+ max_val = corrected.max()
+ assert max_val > 0, (
+ f"[{test_name}] Camera output '{data_type}' has no non-zero pixels. "
+ f"Shape: {corrected.shape}, dtype: {corrected.dtype}."
+ )
+
+ # convert tensors to a tiled image.
+ normalized = _normalize_tensor(corrected, data_type)
+ grid = _make_grid(normalized)
+
+ # permute(1, 2, 0) is there to change the tensor layout from channel-first to channel-last so it matches what
+ # PIL expects.
+ ndarr = grid.mul(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to("cpu", torch.uint8).numpy()
+ result_image = Image.fromarray(ndarr)
+
+ # first run creates baseline and fails; second run validates.
+ golden_path = os.path.join(golden_image_dir, f"{physics_backend}-{renderer}-{data_type}.png")
+ if not os.path.exists(golden_path):
+ result_image.save(golden_path)
+ pytest.fail(
+ f"[{test_name}] Golden image not found at {golden_path}. Saved result image to {golden_path}. "
+ "Please run the test again to validate the consistency of rendering outputs."
+ )
+
+ try:
+ golden_image = Image.open(golden_path)
+ except Exception as e:
+ pytest.fail(f"Error opening golden image: {e}")
+
+ # validate the consistency of rendering outputs.
+ succeeded, error_message, diff_pct, ssim_score = _compare_images(
+ result_image, golden_image, max_different_pixels_percentage
+ )
+
+ entry = {
+ "test": test_name,
+ "backend": physics_backend,
+ "renderer": renderer,
+ "aov": data_type,
+ "diff_pct": diff_pct,
+ "ssim": ssim_score,
+ "threshold": max_different_pixels_percentage,
+ "passed": succeeded,
+ "img_result_path": None,
+ "img_golden_path": None,
+ }
+
+ if diff_pct > 0:
+ prefix = f"{test_name}-{physics_backend}-{renderer}-{data_type}"
+ entry["img_result_path"] = _save_comparison_image(result_image, f"{prefix}-actual.png")
+ entry["img_golden_path"] = _save_comparison_image(golden_image, f"{prefix}-golden.png")
+
+ _COMPARISON_SCORES.append(entry)
+
+ if not succeeded:
+ timestamp = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
+ result_path = os.path.join(golden_image_dir, f"{physics_backend}-{renderer}-{data_type}-{timestamp}.png")
+ result_image.save(result_path)
+ pytest.fail(
+ f"[{test_name}] Inconsistency detected for camera output '{data_type}': {error_message}. "
+ f"Saved result image to {result_path} for further investigation. "
+ f"If result image is correct, please replace the golden image at {golden_path} with the result image."
)
@@ -228,6 +637,7 @@ def shadow_hand_env(request):
env_cfg = _apply_overrides_to_env_cfg(env_cfg, override_args)
env_cfg.scene.num_envs = 4
+ env_cfg.seed = 42
if data_type == "depth":
# Disable CNN forward pass as it cannot be meaningfully trained from depth alone and will raise a ValueError.
@@ -245,11 +655,17 @@ def shadow_hand_env(request):
env.close()
-def test_camera_outputs_are_not_blank_for_shadow_hand(shadow_hand_env):
+def test_shadow_hand(shadow_hand_env):
"""Camera output must contain at least one non-zero pixel (Shadow Hand vision env)."""
- physics_backend, renderer, data_type, env = shadow_hand_env
- label = f"shadow_hand-{physics_backend}-{renderer}+{data_type}"
- _assert_camera_outputs_are_not_blank(label, {"tiled_camera": env._tiled_camera.data.output})
+ physics_backend, renderer, _, env = shadow_hand_env
+
+ _validate_camera_outputs(
+ "shadow_hand",
+ physics_backend,
+ renderer,
+ env._tiled_camera.data.output,
+ max_different_pixels_percentage=5.0,
+ )
# ---------------------------------------------------------------------------
@@ -271,6 +687,7 @@ def cartpole_env(request):
env_cfg = _apply_overrides_to_env_cfg(env_cfg, override_args)
env_cfg.scene.num_envs = 4
+ env_cfg.seed = 42
env = None
try:
@@ -284,11 +701,17 @@ def cartpole_env(request):
env.close()
-def test_camera_outputs_are_not_blank_for_cartpole(cartpole_env):
+def test_cartpole(cartpole_env):
"""Camera output must contain at least one non-zero pixel (Cartpole camera env)."""
- physics_backend, renderer, data_type, env = cartpole_env
- label = f"cartpole-{physics_backend}-{renderer}+{data_type}"
- _assert_camera_outputs_are_not_blank(label, {"tiled_camera": env._tiled_camera.data.output})
+ physics_backend, renderer, _, env = cartpole_env
+
+ _validate_camera_outputs(
+ "cartpole",
+ physics_backend,
+ renderer,
+ env._tiled_camera.data.output,
+ max_different_pixels_percentage=5.0,
+ )
# ---------------------------------------------------------------------------
@@ -314,6 +737,7 @@ def dexsuite_kuka_allegro_lift_env(request):
env_cfg = _apply_overrides_to_env_cfg(env_cfg, override_args)
env_cfg.scene.num_envs = 4
+ env_cfg.seed = 42
env = None
try:
@@ -327,11 +751,17 @@ def dexsuite_kuka_allegro_lift_env(request):
env.close()
-def test_camera_outputs_are_not_blank_for_dexsuite_kuka_allegro_lift(dexsuite_kuka_allegro_lift_env):
+def test_dexsuite_kuka_allegro_lift(dexsuite_kuka_allegro_lift_env):
"""Camera output must contain at least one non-zero pixel (Dexsuite Kuka-Allegro Lift, single camera)."""
- physics_backend, renderer, data_type, env = dexsuite_kuka_allegro_lift_env
- label = f"dexsuite_kuka_allegro_lift-{physics_backend}-{renderer}+{data_type}"
- _assert_camera_outputs_are_not_blank(label, {"base_camera": env.scene.sensors["base_camera"].data.output})
+ physics_backend, renderer, _, env = dexsuite_kuka_allegro_lift_env
+
+ _validate_camera_outputs(
+ "dexsuite_kuka",
+ physics_backend,
+ renderer,
+ env.scene.sensors["base_camera"].data.output,
+ max_different_pixels_percentage=10.0,
+ )
# ---------------------------------------------------------------------------
@@ -340,12 +770,7 @@ def test_camera_outputs_are_not_blank_for_dexsuite_kuka_allegro_lift(dexsuite_ku
# Task IDs that expose camera/tiled_camera image observations; each is validated for non-blank rendering.
_RENDER_CORRECTNESS_TASK_IDS = [
- "Isaac-Cartpole-RGB-Camera-Direct-v0",
"Isaac-Cartpole-Albedo-Camera-Direct-v0",
- "Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0",
- "Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0",
- "Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0",
- "Isaac-Cartpole-Depth-Camera-Direct-v0",
"Isaac-Cartpole-Camera-Presets-Direct-v0",
"Isaac-Cartpole-Camera-Showcase-Box-Box-Direct-v0",
"Isaac-Cartpole-Camera-Showcase-Box-Discrete-Direct-v0",
@@ -356,19 +781,26 @@ def test_camera_outputs_are_not_blank_for_dexsuite_kuka_allegro_lift(dexsuite_ku
"Isaac-Cartpole-Camera-Showcase-Tuple-Box-Direct-v0",
"Isaac-Cartpole-Camera-Showcase-Tuple-Discrete-Direct-v0",
"Isaac-Cartpole-Camera-Showcase-Tuple-MultiDiscrete-Direct-v0",
- "Isaac-Repose-Cube-Shadow-Vision-Direct-v0",
- "Isaac-Cartpole-RGB-v0",
+ "Isaac-Cartpole-Depth-Camera-Direct-v0",
"Isaac-Cartpole-Depth-v0",
+ "Isaac-Cartpole-RGB-Camera-Direct-v0",
"Isaac-Cartpole-RGB-ResNet18-v0",
+ "Isaac-Cartpole-RGB-v0",
+ "Isaac-Cartpole-SimpleShading-Constant-Camera-Direct-v0",
+ "Isaac-Cartpole-SimpleShading-Diffuse-Camera-Direct-v0",
+ "Isaac-Cartpole-SimpleShading-Full-Camera-Direct-v0",
+ "Isaac-Repose-Cube-Shadow-Vision-Direct-v0",
]
@pytest.mark.parametrize("task_id", _RENDER_CORRECTNESS_TASK_IDS)
-def test_camera_outputs_are_not_blank_for_registered_task(task_id):
+def test_registered_tasks(task_id):
"""Camera output must be non-empty for each registered task with camera-based observations."""
env = None
try:
env_cfg = parse_env_cfg(task_id, num_envs=4)
+ env_cfg.seed = 42
+
env = gym.make(task_id, cfg=env_cfg)
unwrapped: Any = env.unwrapped
sim = getattr(unwrapped, "sim", None)
@@ -401,8 +833,19 @@ def test_camera_outputs_are_not_blank_for_registered_task(task_id):
env.step(actions)
- camera_outputs = _collect_camera_outputs(env)
- _assert_camera_outputs_are_not_blank(task_id, camera_outputs)
+ camera_outputs_nested_dict = _collect_camera_outputs(env)
+ num_camera_outputs = len(camera_outputs_nested_dict)
+ assert num_camera_outputs == 1, f"[{task_id}] Expected 1 camera output, got {num_camera_outputs}."
+
+ camera_outputs = next(iter(camera_outputs_nested_dict.values()))
+
+ _validate_camera_outputs(
+ f"registered_tasks/{task_id}",
+ "default_physics",
+ "default_renderer",
+ camera_outputs,
+ max_different_pixels_percentage=5.0,
+ )
finally:
if env is not None:
env.close()
diff --git a/source/isaaclab_teleop/config/extension.toml b/source/isaaclab_teleop/config/extension.toml
index 547c213e91cd..48e59c25e80e 100644
--- a/source/isaaclab_teleop/config/extension.toml
+++ b/source/isaaclab_teleop/config/extension.toml
@@ -1,6 +1,6 @@
[package]
# Semantic Versioning is used: https://semver.org/
-version = "0.3.3"
+version = "0.3.4"
# Description
title = "Isaac Lab Teleop"
diff --git a/source/isaaclab_teleop/docs/CHANGELOG.rst b/source/isaaclab_teleop/docs/CHANGELOG.rst
index 8c28d8c383f2..e9545bd4b894 100644
--- a/source/isaaclab_teleop/docs/CHANGELOG.rst
+++ b/source/isaaclab_teleop/docs/CHANGELOG.rst
@@ -1,6 +1,25 @@
Changelog
---------
+0.3.4 (2026-03-17)
+~~~~~~~~~~~~~~~~~~~
+
+Added
+^^^^^
+
+* Added :attr:`~isaaclab_teleop.IsaacTeleopCfg.target_frame_prim_path` for
+ config-driven frame rebasing. When set to a USD prim path, the device
+ automatically reads the prim's world transform each frame and uses its
+ inverse as the ``target_T_world`` rebase matrix, so all output poses are
+ expressed in the target frame (e.g. robot base link for IK).
+
+* Added ``target_T_world`` parameter to
+ :meth:`~isaaclab_teleop.IsaacTeleopDevice.advance` for rebasing all output
+ poses into an arbitrary target coordinate frame (e.g. robot base link for
+ IK). Accepts :class:`numpy.ndarray`, :class:`torch.Tensor`, or
+ ``wp.array``.
+
+
0.3.3 (2026-03-13)
~~~~~~~~~~~~~~~~~~~
diff --git a/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_cfg.py b/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_cfg.py
index b2c9f303cc97..36dfb55a737c 100644
--- a/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_cfg.py
+++ b/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_cfg.py
@@ -108,5 +108,26 @@ def build_pipeline():
If ``None``, the tuning UI will not be opened.
"""
+ target_frame_prim_path: str | None = None
+ """Optional USD prim path whose world frame becomes the target coordinate
+ frame for all output poses.
+
+ When set, the device automatically reads this prim's world transform each
+ frame and uses its inverse as the ``target_T_world`` rebase matrix in
+ :meth:`~isaaclab_teleop.IsaacTeleopDevice.advance`. An explicit
+ ``target_T_world`` argument to :meth:`~isaaclab_teleop.IsaacTeleopDevice.advance`
+ takes precedence over this config.
+
+ Typical usage: set to the robot base link prim path so that an IK
+ controller receives end-effector poses in the robot's base frame.
+
+ Example::
+
+ IsaacTeleopCfg(
+ target_frame_prim_path="/World/envs/env_0/Robot/base_link",
+ ...
+ )
+ """
+
app_name: str = "IsaacLabTeleop"
"""Application name for the IsaacTeleop session."""
diff --git a/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_device.py b/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_device.py
index f7448fffd548..832f5536b28c 100644
--- a/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_device.py
+++ b/source/isaaclab_teleop/isaaclab_teleop/isaac_teleop_device.py
@@ -9,7 +9,9 @@
import logging
from collections.abc import Callable
+from typing import TYPE_CHECKING
+import numpy as np
import torch
from .command_handler import CommandHandler
@@ -17,6 +19,9 @@
from .session_lifecycle import TeleopSessionLifecycle
from .xr_anchor_manager import XrAnchorManager
+if TYPE_CHECKING:
+ from .session_lifecycle import SupportsDLPack
+
logger = logging.getLogger(__name__)
@@ -42,6 +47,24 @@ class IsaacTeleopDevice:
The device uses IsaacTeleop's TensorReorderer to flatten pipeline outputs
into a single action tensor matching the environment's action space.
+ Frame rebasing:
+ By default, all output poses are expressed in the simulation world
+ frame. When an application needs poses in a different frame (e.g.
+ robot base link for IK), there are two options:
+
+ * **Config-driven** (recommended): set
+ :attr:`~IsaacTeleopCfg.target_frame_prim_path` to the USD prim
+ whose frame the output should be expressed in. The device reads
+ the prim's world transform each frame and applies the rebase
+ automatically.
+ * **Explicit**: pass a ``target_T_world`` matrix directly to
+ :meth:`advance`.
+
+ In both cases the device composes
+ ``target_T_world @ world_T_anchor`` before feeding the matrix into
+ the retargeting pipeline, so all resulting poses are expressed in the
+ target frame.
+
Teleop commands:
The device supports callbacks for START, STOP, and RESET commands
that can be triggered via XR controller buttons or the message bus.
@@ -54,10 +77,25 @@ class IsaacTeleopDevice:
sim_device="cuda:0",
)
+ # Poses in world frame (default)
+ with IsaacTeleopDevice(cfg) as device:
+ while running:
+ action = device.advance()
+ env.step(action.repeat(num_envs, 1))
+
+ # Config-driven rebase into robot base frame
+ cfg.target_frame_prim_path = "/World/Robot/base_link"
with IsaacTeleopDevice(cfg) as device:
while running:
action = device.advance()
env.step(action.repeat(num_envs, 1))
+
+ # Explicit rebase into robot base frame
+ with IsaacTeleopDevice(cfg) as device:
+ while running:
+ robot_T_world = get_robot_base_transform()
+ action = device.advance(target_T_world=robot_T_world)
+ env.step(action.repeat(num_envs, 1))
"""
def __init__(self, cfg: IsaacTeleopCfg):
@@ -147,7 +185,7 @@ def add_callback(self, key: str, func: Callable) -> None:
"""
self._command_handler.add_callback(key, func)
- def advance(self) -> torch.Tensor | None:
+ def advance(self, target_T_world: np.ndarray | torch.Tensor | SupportsDLPack | None = None) -> torch.Tensor | None:
"""Process current device state and return control commands.
If the IsaacTeleop session has not been started yet (because the OpenXR
@@ -155,6 +193,27 @@ def advance(self) -> torch.Tensor | None:
attempt to start it on each call. Once the user clicks "Start AR" and
the handles become available, the session is created transparently.
+ Args:
+ target_T_world: Optional 4x4 transform matrix that rebases all
+ output poses into an arbitrary target coordinate frame. When
+ provided, the matrix sent to the retargeting pipeline becomes
+ ``target_T_world @ world_T_anchor`` instead of just
+ ``world_T_anchor``, so all resulting poses are expressed in
+ the target frame rather than the simulation world frame.
+
+ Typical use case: pass ``robot_base_T_world`` so that an IK
+ controller receives end-effector poses in the robot's base
+ link frame.
+
+ Accepts any object supporting the DLPack buffer protocol
+ (``__dlpack__``), including :class:`numpy.ndarray`,
+ :class:`torch.Tensor`, and ``wp.array``.
+
+ When ``None`` and
+ :attr:`~IsaacTeleopCfg.target_frame_prim_path` is set, the
+ transform is computed automatically by reading the prim's
+ world matrix from Fabric and inverting it.
+
Returns:
A flattened action :class:`torch.Tensor` ready for the Isaac Lab
environment, or ``None`` if the session has not started yet
@@ -163,9 +222,14 @@ def advance(self) -> torch.Tensor | None:
Raises:
RuntimeError: If called outside of a context manager.
"""
+ # Auto-compute target_T_world from config if not explicitly provided
+ if target_T_world is None and self._cfg.target_frame_prim_path is not None:
+ target_T_world = self._get_target_frame_T_world()
+
# Step the session (handles lazy start and action extraction)
action = self._session_lifecycle.step(
anchor_world_matrix_fn=self._anchor_manager.get_world_matrix,
+ target_T_world=target_T_world,
)
if action is not None:
@@ -174,6 +238,75 @@ def advance(self) -> torch.Tensor | None:
return action
+ # ------------------------------------------------------------------
+ # Target frame transform (config-driven rebase)
+ # ------------------------------------------------------------------
+
+ def _get_target_frame_T_world(self) -> np.ndarray | None:
+ """Read the target-frame prim's world matrix from Fabric and return its inverse.
+
+ Uses USDRT to read the prim's hierarchical world matrix, matching the
+ pattern used by :class:`XrAnchorSynchronizer` for anchor prim reads.
+
+ Returns:
+ A (4, 4) float32 :class:`numpy.ndarray` representing the inverse
+ of the prim's world transform (i.e. ``target_T_world``), or
+ ``None`` if the prim cannot be read.
+ """
+ try:
+ import omni.usd
+ import usdrt
+ from pxr import UsdUtils
+ from usdrt import Rt
+
+ stage = omni.usd.get_context().get_stage()
+ stage_cache = UsdUtils.StageCache.Get()
+ stage_id = stage_cache.GetId(stage).ToLongInt()
+ if stage_id < 0:
+ stage_id = stage_cache.Insert(stage).ToLongInt()
+ rt_stage = usdrt.Usd.Stage.Attach(stage_id)
+ if rt_stage is None:
+ return None
+
+ rt_prim = rt_stage.GetPrimAtPath(self._cfg.target_frame_prim_path)
+ if not rt_prim.IsValid():
+ return None
+
+ rt_xformable = Rt.Xformable(rt_prim)
+ if not rt_xformable.GetPrim().IsValid():
+ return None
+
+ world_matrix_attr = rt_xformable.GetFabricHierarchyWorldMatrixAttr()
+ if world_matrix_attr is None:
+ return None
+
+ rt_matrix = world_matrix_attr.Get()
+ if rt_matrix is None:
+ return None
+
+ pos = rt_matrix.ExtractTranslation()
+ rt_quat = rt_matrix.ExtractRotationQuat()
+
+ from scipy.spatial.transform import Rotation
+
+ quat_xyzw = [
+ float(rt_quat.GetImaginary()[0]),
+ float(rt_quat.GetImaginary()[1]),
+ float(rt_quat.GetImaginary()[2]),
+ float(rt_quat.GetReal()),
+ ]
+
+ R = Rotation.from_quat(quat_xyzw).as_matrix().astype(np.float32)
+ t = np.array([float(pos[0]), float(pos[1]), float(pos[2])], dtype=np.float32)
+
+ inv_mat = np.eye(4, dtype=np.float32)
+ inv_mat[:3, :3] = R.T
+ inv_mat[:3, 3] = -(R.T @ t)
+ return inv_mat
+ except Exception as e:
+ logger.warning(f"Failed to read target frame prim '{self._cfg.target_frame_prim_path}': {e}")
+ return None
+
# ------------------------------------------------------------------
# Controller button polling (glue between session and anchor manager)
# ------------------------------------------------------------------
diff --git a/source/isaaclab_teleop/isaaclab_teleop/session_lifecycle.py b/source/isaaclab_teleop/isaaclab_teleop/session_lifecycle.py
index 06c02a0205c9..8620e9d85b87 100644
--- a/source/isaaclab_teleop/isaaclab_teleop/session_lifecycle.py
+++ b/source/isaaclab_teleop/isaaclab_teleop/session_lifecycle.py
@@ -9,7 +9,7 @@
import logging
from collections.abc import Callable
-from typing import TYPE_CHECKING
+from typing import TYPE_CHECKING, Any, Protocol
import numpy as np
import torch
@@ -21,8 +21,53 @@
from .isaac_teleop_cfg import IsaacTeleopCfg
+
+class SupportsDLPack(Protocol):
+ """Duck type for objects supporting the DLPack buffer protocol.
+
+ Satisfied by :class:`torch.Tensor`, :class:`numpy.ndarray` (>= 1.22),
+ ``wp.array``, CuPy arrays, JAX arrays, and other frameworks.
+ """
+
+ def __dlpack__(self, *, stream: Any = ...) -> Any: ...
+
+ def __dlpack_device__(self) -> tuple[int, int]: ...
+
+
logger = logging.getLogger(__name__)
+_DLDEVICE_CPU = 1
+
+
+def _to_numpy_4x4(mat: np.ndarray | torch.Tensor | SupportsDLPack) -> np.ndarray:
+ """Convert a (4, 4) transform to a float32 numpy array.
+
+ Prefers the DLPack buffer protocol (``__dlpack__``) for zero-copy
+ interop with torch, warp, cupy, jax, and other frameworks.
+
+ Args:
+ mat: A (4, 4) transform matrix.
+
+ Returns:
+ A (4, 4) float32 :class:`numpy.ndarray`.
+ """
+ if isinstance(mat, np.ndarray):
+ return np.asarray(mat, dtype=np.float32)
+ if isinstance(mat, torch.Tensor):
+ return np.asarray(np.from_dlpack(mat.detach().cpu()), dtype=np.float32)
+ if hasattr(mat, "__dlpack_device__"):
+ device_type, _ = mat.__dlpack_device__()
+ if device_type == _DLDEVICE_CPU:
+ return np.asarray(np.from_dlpack(mat), dtype=np.float32)
+ # Non-CPU DLPack source (e.g. CUDA wp.array): .numpy() typically
+ # handles the device-to-host transfer internally.
+ if hasattr(mat, "numpy"):
+ return np.asarray(mat.numpy(), dtype=np.float32) # type: ignore[union-attr]
+ raise TypeError(f"Cannot convert non-CPU DLPack array of type {type(mat).__name__} to numpy")
+ if hasattr(mat, "numpy"):
+ return np.asarray(mat.numpy(), dtype=np.float32) # type: ignore[union-attr]
+ return np.asarray(mat, dtype=np.float32)
+
class TeleopSessionLifecycle:
"""Manages the IsaacTeleop session lifecycle.
@@ -306,7 +351,11 @@ def _try_start_session(self) -> bool:
# Stepping
# ------------------------------------------------------------------
- def step(self, anchor_world_matrix_fn: Callable[[], np.ndarray] | None = None) -> torch.Tensor | None:
+ def step(
+ self,
+ anchor_world_matrix_fn: Callable[[], np.ndarray] | None = None,
+ target_T_world: np.ndarray | torch.Tensor | SupportsDLPack | None = None,
+ ) -> torch.Tensor | None:
"""Execute one step of the teleop session and return the action tensor.
If the session has not been started yet (because OpenXR handles were
@@ -323,6 +372,14 @@ def step(self, anchor_world_matrix_fn: Callable[[], np.ndarray] | None = None) -
anchor_world_matrix_fn: Optional callable returning the (4, 4)
world-to-anchor transform. Used to build external inputs
for ``ValueInput`` leaf nodes in the pipeline.
+ target_T_world: Optional (4, 4) transform matrix that rebases
+ pipeline poses into a target coordinate frame. When provided,
+ the anchor matrix is left-multiplied by this transform
+ (``target_T_world @ world_T_anchor``) so all output poses
+ are expressed in the target frame. Accepts any object
+ supporting the DLPack buffer protocol (``__dlpack__``),
+ including :class:`numpy.ndarray`, :class:`torch.Tensor`,
+ and ``wp.array``.
Returns:
A flattened action :class:`torch.Tensor` ready for the Isaac Lab
@@ -342,7 +399,7 @@ def step(self, anchor_world_matrix_fn: Callable[[], np.ndarray] | None = None) -
# Build external inputs (e.g. world-to-anchor transform) if the
# pipeline contains ValueInput leaf nodes.
- external_inputs = self._build_external_inputs(anchor_world_matrix_fn)
+ external_inputs = self._build_external_inputs(anchor_world_matrix_fn, target_T_world)
# Execute one step of the teleop session.
# If the underlying OpenXR session was destroyed externally (e.g.
@@ -360,11 +417,12 @@ def step(self, anchor_world_matrix_fn: Callable[[], np.ndarray] | None = None) -
# Store the right controller TensorGroup for button polling
self._last_right_controller = result.get(self._CONTROLLER_RIGHT_KEY)
- # Extract the flattened action array from TensorReorderer output
- action_np = result["action"][0]
-
- # Convert to torch tensor and move to device
- action = torch.from_numpy(np.asarray(action_np, dtype=np.float32)).to(self._device)
+ # Extract the flattened action array (DLPack-compatible) from
+ # TensorReorderer and move to the simulation device.
+ action_array = result["action"][0]
+ action = torch.from_dlpack(action_array).to( # type: ignore[attr-defined]
+ dtype=torch.float32, device=self._device
+ )
return action
@@ -395,16 +453,27 @@ def _teardown_dead_session(self) -> None:
# External input building
# ------------------------------------------------------------------
- def _build_external_inputs(self, anchor_world_matrix_fn: Callable[[], np.ndarray] | None) -> dict | None:
+ def _build_external_inputs(
+ self,
+ anchor_world_matrix_fn: Callable[[], np.ndarray] | None,
+ target_T_world: np.ndarray | torch.Tensor | SupportsDLPack | None = None,
+ ) -> dict | None:
"""Build external inputs for non-DeviceIO leaf nodes in the pipeline.
Checks whether the active ``TeleopSession`` has external (non-DeviceIO)
leaf nodes and, for each recognized leaf, constructs the corresponding
``TensorGroup`` data.
+ When *target_T_world* is provided, the anchor matrix is left-multiplied
+ by the rebase transform so that all pipeline poses are expressed in
+ the target coordinate frame:
+ ``target_T_world @ world_T_anchor = target_T_anchor``.
+
Args:
anchor_world_matrix_fn: Callable returning the (4, 4)
world-to-anchor transform matrix.
+ target_T_world: Optional (4, 4) rebase transform. See
+ :meth:`step` for details.
Returns:
A dict suitable for ``TeleopSession.step(external_inputs=...)``,
@@ -425,6 +494,8 @@ def _build_external_inputs(self, anchor_world_matrix_fn: Callable[[], np.ndarray
anchor_matrix = anchor_world_matrix_fn()
else:
anchor_matrix = np.eye(4, dtype=np.float32)
+ if target_T_world is not None:
+ anchor_matrix = _to_numpy_4x4(target_T_world) @ anchor_matrix
xform_tg = TensorGroup(TransformMatrix())
xform_tg[0] = anchor_matrix
external_inputs[leaf_name] = {ValueInput.VALUE: xform_tg}
diff --git a/source/isaaclab_teleop/test/test_target_frame_rebase.py b/source/isaaclab_teleop/test/test_target_frame_rebase.py
new file mode 100644
index 000000000000..044b5da7d305
--- /dev/null
+++ b/source/isaaclab_teleop/test/test_target_frame_rebase.py
@@ -0,0 +1,264 @@
+# 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
+
+# pyright: reportPrivateUsage=none
+
+"""Tests for the target-frame rebase logic, _to_numpy_4x4 helper, and config-driven auto-selection.
+
+These tests exercise pure math (no Omniverse/Isaac Sim stack required).
+"""
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+import torch
+from isaaclab_teleop.session_lifecycle import _to_numpy_4x4
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+@pytest.fixture
+def identity_4x4() -> np.ndarray:
+ return np.eye(4, dtype=np.float32)
+
+
+@pytest.fixture
+def translation_matrix() -> np.ndarray:
+ """A pure translation of (1, 2, 3)."""
+ mat = np.eye(4, dtype=np.float32)
+ mat[:3, 3] = [1.0, 2.0, 3.0]
+ return mat
+
+
+@pytest.fixture
+def rotation_90z_matrix() -> np.ndarray:
+ """90-degree rotation about Z axis."""
+ mat = np.eye(4, dtype=np.float32)
+ mat[0, 0] = 0.0
+ mat[0, 1] = -1.0
+ mat[1, 0] = 1.0
+ mat[1, 1] = 0.0
+ return mat
+
+
+# ---------------------------------------------------------------------------
+# _to_numpy_4x4 conversion tests
+# ---------------------------------------------------------------------------
+
+
+class TestToNumpy4x4:
+ def test_from_ndarray_float32(self, identity_4x4: np.ndarray):
+ result = _to_numpy_4x4(identity_4x4)
+ assert isinstance(result, np.ndarray)
+ assert result.dtype == np.float32
+ np.testing.assert_array_equal(result, identity_4x4)
+
+ def test_from_ndarray_float64_casts(self):
+ mat = np.eye(4, dtype=np.float64)
+ result = _to_numpy_4x4(mat)
+ assert result.dtype == np.float32
+ np.testing.assert_array_almost_equal(result, np.eye(4, dtype=np.float32))
+
+ def test_from_torch_cpu(self, translation_matrix: np.ndarray):
+ tensor = torch.from_numpy(translation_matrix.copy())
+ result = _to_numpy_4x4(tensor)
+ assert isinstance(result, np.ndarray)
+ assert result.dtype == np.float32
+ np.testing.assert_array_almost_equal(result, translation_matrix)
+
+ @pytest.mark.skipif(not torch.cuda.is_available(), reason="CUDA not available")
+ def test_from_torch_gpu(self, translation_matrix: np.ndarray):
+ tensor = torch.from_numpy(translation_matrix.copy()).cuda()
+ result = _to_numpy_4x4(tensor)
+ assert isinstance(result, np.ndarray)
+ assert result.dtype == np.float32
+ np.testing.assert_array_almost_equal(result, translation_matrix)
+
+ def test_from_duck_typed_numpy(self, rotation_90z_matrix: np.ndarray):
+ """Simulates a wp.array or similar object with a .numpy() method."""
+
+ class FakeWarpArray:
+ def __init__(self, data: np.ndarray):
+ self._data = data
+
+ def numpy(self) -> np.ndarray:
+ return self._data
+
+ fake = FakeWarpArray(rotation_90z_matrix.copy())
+ result = _to_numpy_4x4(fake)
+ assert isinstance(result, np.ndarray)
+ assert result.dtype == np.float32
+ np.testing.assert_array_almost_equal(result, rotation_90z_matrix)
+
+ def test_from_list(self):
+ data = [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
+ result = _to_numpy_4x4(data)
+ assert isinstance(result, np.ndarray)
+ assert result.dtype == np.float32
+ np.testing.assert_array_equal(result, np.eye(4, dtype=np.float32))
+
+
+# ---------------------------------------------------------------------------
+# Matrix multiplication (rebase) tests
+# ---------------------------------------------------------------------------
+
+
+class TestRebaseMultiplication:
+ def test_rebase_identity_is_noop(self, translation_matrix: np.ndarray):
+ """target_T_world = I should leave anchor_matrix unchanged."""
+ identity = np.eye(4, dtype=np.float32)
+ result = _to_numpy_4x4(identity) @ translation_matrix
+ np.testing.assert_array_almost_equal(result, translation_matrix)
+
+ def test_rebase_translation(self, identity_4x4: np.ndarray):
+ """Rebasing by a pure translation offsets the origin."""
+ target_T_world = np.eye(4, dtype=np.float32)
+ target_T_world[:3, 3] = [10.0, 20.0, 30.0]
+
+ world_T_anchor = np.eye(4, dtype=np.float32)
+ world_T_anchor[:3, 3] = [1.0, 2.0, 3.0]
+
+ result = _to_numpy_4x4(target_T_world) @ world_T_anchor
+ np.testing.assert_array_almost_equal(result[:3, 3], [11.0, 22.0, 33.0])
+
+ def test_rebase_rotation(self, rotation_90z_matrix: np.ndarray):
+ """A 90-deg Z rotation rebase should rotate the anchor translation."""
+ world_T_anchor = np.eye(4, dtype=np.float32)
+ world_T_anchor[:3, 3] = [1.0, 0.0, 0.0]
+
+ result = _to_numpy_4x4(rotation_90z_matrix) @ world_T_anchor
+
+ # After 90-deg Z rotation: (1,0,0) -> (0,1,0)
+ np.testing.assert_array_almost_equal(result[:3, 3], [0.0, 1.0, 0.0])
+ # Rotation part should match the 90-deg Z rotation
+ np.testing.assert_array_almost_equal(result[:3, :3], rotation_90z_matrix[:3, :3])
+
+ def test_rebase_with_torch_tensor(self, translation_matrix: np.ndarray):
+ """target_T_world as a torch.Tensor should work identically."""
+ target_T_world = torch.eye(4, dtype=torch.float32)
+ target_T_world[:3, 3] = torch.tensor([5.0, 5.0, 5.0])
+
+ result = _to_numpy_4x4(target_T_world) @ translation_matrix
+
+ expected = np.eye(4, dtype=np.float32)
+ expected[:3, 3] = [6.0, 7.0, 8.0]
+ np.testing.assert_array_almost_equal(result, expected)
+
+ def test_none_target_leaves_anchor_unchanged(self, translation_matrix: np.ndarray):
+ """When target_T_world is None, the calling code should skip multiplication."""
+ target_T_world = None
+ anchor_matrix = translation_matrix.copy()
+
+ if target_T_world is not None:
+ anchor_matrix = _to_numpy_4x4(target_T_world) @ anchor_matrix
+
+ np.testing.assert_array_equal(anchor_matrix, translation_matrix)
+
+ def test_inverse_rebase_recovers_identity(self):
+ """target_T_world = inv(world_T_anchor) should yield identity."""
+ world_T_anchor = np.array(
+ [
+ [0.0, -1.0, 0.0, 3.0],
+ [1.0, 0.0, 0.0, -1.0],
+ [0.0, 0.0, 1.0, 2.0],
+ [0.0, 0.0, 0.0, 1.0],
+ ],
+ dtype=np.float32,
+ )
+ target_T_world = np.linalg.inv(world_T_anchor).astype(np.float32)
+
+ result = _to_numpy_4x4(target_T_world) @ world_T_anchor
+ np.testing.assert_array_almost_equal(result, np.eye(4, dtype=np.float32), decimal=5)
+
+
+# ---------------------------------------------------------------------------
+# Config-driven auto-selection tests
+# ---------------------------------------------------------------------------
+
+
+def _simulate_advance_selection(
+ target_T_world: np.ndarray | None,
+ target_frame_prim_path: str | None,
+ auto_read_result: np.ndarray | None = None,
+) -> tuple[np.ndarray | None, bool]:
+ """Replicate the auto-selection logic from IsaacTeleopDevice.advance().
+
+ Returns the target_T_world that would be passed to step(), and whether
+ _get_target_frame_T_world would have been called.
+ """
+ auto_read_called = False
+
+ def fake_get_target_frame_T_world():
+ nonlocal auto_read_called
+ auto_read_called = True
+ return auto_read_result
+
+ if target_T_world is None and target_frame_prim_path is not None:
+ target_T_world = fake_get_target_frame_T_world()
+
+ return target_T_world, auto_read_called
+
+
+class TestConfigDrivenAutoSelection:
+ """Tests for the advance() auto-selection logic between explicit target_T_world
+ and config-driven target_frame_prim_path.
+
+ These tests replicate the branching logic from advance() without importing
+ the full IsaacTeleopDevice (which requires Isaac Sim runtime dependencies).
+ """
+
+ def test_no_config_no_explicit_passes_none(self):
+ """When neither config nor explicit target_T_world is set, step() receives None."""
+ result, called = _simulate_advance_selection(target_T_world=None, target_frame_prim_path=None)
+ assert result is None
+ assert not called
+
+ def test_explicit_target_is_passed_through(self):
+ """An explicit target_T_world should be passed directly to step()."""
+ explicit = np.eye(4, dtype=np.float32)
+ explicit[:3, 3] = [1.0, 2.0, 3.0]
+
+ result, called = _simulate_advance_selection(target_T_world=explicit, target_frame_prim_path=None)
+ np.testing.assert_array_equal(result, explicit)
+ assert not called
+
+ def test_config_prim_triggers_auto_read(self):
+ """When target_frame_prim_path is set, _get_target_frame_T_world is called."""
+ auto_matrix = np.eye(4, dtype=np.float32)
+ auto_matrix[:3, 3] = [9.0, 8.0, 7.0]
+
+ result, called = _simulate_advance_selection(
+ target_T_world=None,
+ target_frame_prim_path="/World/Robot/base_link",
+ auto_read_result=auto_matrix,
+ )
+ assert called
+ np.testing.assert_array_equal(result, auto_matrix)
+
+ def test_explicit_overrides_config(self):
+ """An explicit target_T_world takes precedence over config prim path."""
+ explicit = np.eye(4, dtype=np.float32)
+ explicit[:3, 3] = [42.0, 0.0, 0.0]
+
+ result, called = _simulate_advance_selection(
+ target_T_world=explicit,
+ target_frame_prim_path="/World/Robot/base_link",
+ auto_read_result=np.eye(4, dtype=np.float32),
+ )
+ assert not called
+ np.testing.assert_array_equal(result, explicit)
+
+ def test_config_prim_returns_none_passes_none(self):
+ """If the prim read fails (returns None), step() receives None."""
+ result, called = _simulate_advance_selection(
+ target_T_world=None,
+ target_frame_prim_path="/World/Robot/base_link",
+ auto_read_result=None,
+ )
+ assert called
+ assert result is None
diff --git a/tools/conftest.py b/tools/conftest.py
index 82ba353ff437..ab70e5ac20a2 100644
--- a/tools/conftest.py
+++ b/tools/conftest.py
@@ -23,10 +23,19 @@ def pytest_ignore_collect(collection_path, config):
return True
+# TODO: SimulationApp.close() can hang indefinitely in some tests (especially those using
+# cameras or render products), causing CI timeouts. A fix that detects test completion via
+# the JUnit XML report file and kills the process after a grace period was prototyped in
+# https://github.com/isaac-sim/IsaacLab/pull/5097 — see commits:
+# 242315b3722 Handle hanging subprocesses causing timeouts
+# bd4953019ab Add comment explaining intentional return 0 in shutdown-hang path
+# A per-test-file conftest.py using atexit.register(os._exit) was also tried:
+# 6840e5a3aeb Force stalled test subprocesses that hang after SimulationApp.close()
def capture_test_output_with_timeout(cmd, timeout, env):
"""Run a command with timeout and capture all output while streaming in real-time."""
stdout_data = b""
stderr_data = b""
+ process = None
try:
# Use Popen to capture output in real-time
@@ -91,15 +100,29 @@ def capture_test_output_with_timeout(cmd, timeout, env):
time.sleep(0.1)
continue
- # Get any remaining output
- remaining_stdout, remaining_stderr = process.communicate()
- stdout_data += remaining_stdout
- stderr_data += remaining_stderr
+ # Drain any output the process wrote before or just after exiting.
+ # Wrapped in try/except so a pipe error doesn't discard what was already captured.
+ try:
+ remaining_stdout, remaining_stderr = process.communicate(timeout=10)
+ stdout_data += remaining_stdout
+ stderr_data += remaining_stderr
+ except Exception:
+ pass
return process.returncode, stdout_data, stderr_data, False
except Exception as e:
- return -1, str(e).encode(), b"", False
+ # Kill the process if it is still alive, then drain whatever it wrote.
+ if process is not None and process.poll() is None:
+ process.kill()
+ with contextlib.suppress(Exception):
+ rem_out, rem_err = process.communicate(timeout=5)
+ stdout_data += rem_out
+ stderr_data += rem_err
+ # Append the exception message so the caller can see what went wrong,
+ # but preserve any output already captured.
+ stdout_data += f"\n[capture error: {e}]\n".encode()
+ return -1, stdout_data, stderr_data, False
def create_timeout_test_case(test_file, timeout, stdout_data, stderr_data):
@@ -133,6 +156,7 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci):
"""Run each test file separately, ensuring one finishes before starting the next."""
failed_tests = []
test_status = {}
+ xml_reports = [] # in-memory JUnitXml objects, used to build the merged report
for test_file in test_files:
print(f"\n\n🚀 Running {test_file} independently...\n")
@@ -147,7 +171,6 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci):
# Note: Command options matter as they are used for cleanups inside AppLauncher
cmd = [
sys.executable,
- "-u",
"-m",
"pytest",
"--no-header",
@@ -178,6 +201,7 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci):
# Write timeout report
report_file = f"tests/test-reports-{str(file_name)}.xml"
timeout_report.write(report_file)
+ xml_reports.append(timeout_report)
test_status[test_file] = {
"errors": 1,
@@ -195,14 +219,46 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci):
# check report for any failures
report_file = f"tests/test-reports-{str(file_name)}.xml"
if not os.path.exists(report_file):
- print(f"Warning: Test report not found at {report_file}")
+ if returncode < 0:
+ sig = -returncode
+ reason = f"Process killed by signal {sig}"
+ if sig == 9:
+ reason += " (SIGKILL — likely OOM killed)"
+ elif sig == 6:
+ reason += " (SIGABRT)"
+ print(f"⚠️ {test_file}: {reason}")
+ else:
+ reason = f"Process exited with code {returncode} but produced no report"
+ print(f"Warning: Test report not found at {report_file}")
+
+ crash_suite = TestSuite(name=f"crash_{os.path.splitext(file_name)[0]}")
+ crash_case = TestCase(
+ name="test_execution",
+ classname=os.path.splitext(file_name)[0],
+ )
+ details = f"{reason}\n\n"
+ if stdout_data:
+ details += "=== STDOUT (last 2000 chars) ===\n"
+ details += stdout_data.decode("utf-8", errors="replace")[-2000:] + "\n"
+ if stderr_data:
+ details += "=== STDERR (last 2000 chars) ===\n"
+ details += stderr_data.decode("utf-8", errors="replace")[-2000:] + "\n"
+ error = Error(message=reason)
+ error.text = details
+ crash_case.result = error
+ crash_suite.add_testcase(crash_case)
+ crash_report = JUnitXml()
+ crash_report.add_testsuite(crash_suite)
+ crash_report.write(report_file)
+ xml_reports.append(crash_report)
+
failed_tests.append(test_file)
test_status[test_file] = {
- "errors": 1, # Assume error since we can't read the report
+ "errors": 1,
"failures": 0,
"skipped": 0,
- "tests": 0,
- "result": "FAILED",
+ "tests": 1,
+ "result": "CRASHED",
"time_elapsed": 0.0,
}
continue
@@ -219,6 +275,7 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci):
# Write the updated report back
report.write(report_file)
+ xml_reports.append(report)
# Parse the integer values with None handling
errors = int(report.errors) if report.errors is not None else 0
@@ -254,7 +311,7 @@ def run_individual_tests(test_files, workspace_root, isaacsim_ci):
print("~~~~~~~~~~~~ Finished running all tests")
- return failed_tests, test_status
+ return failed_tests, test_status, xml_reports
def _collect_test_files(
@@ -262,10 +319,8 @@ def _collect_test_files(
filter_pattern,
exclude_pattern,
include_files,
- flaky_only,
- slightly_flaky_only,
+ quarantined_only,
curobo_only,
- cuda_issue_only,
):
"""Collect test files from source directories, applying all active filters."""
test_files = []
@@ -280,18 +335,12 @@ def _collect_test_files(
continue
# Mode-exclusive filters (each bypasses TESTS_TO_SKIP)
- if flaky_only:
- if file not in test_settings.FLAKY_TESTS:
- continue
- elif slightly_flaky_only:
- if file not in test_settings.SLIGHTLY_FLAKY_TESTS:
+ if quarantined_only:
+ if file not in test_settings.QUARANTINED_TESTS:
continue
elif curobo_only:
if file not in test_settings.CUROBO_TESTS:
continue
- elif cuda_issue_only:
- if file not in test_settings.CUDA_ISSUE_TESTS:
- continue
else:
# An explicit include_files entry overrides TESTS_TO_SKIP, allowing
# dedicated jobs (e.g. test-environments-training) to run tests that
@@ -305,7 +354,7 @@ def _collect_test_files(
if filter_pattern and filter_pattern not in full_path:
print(f"Skipping {full_path} (does not match include pattern: {filter_pattern})")
continue
- if exclude_pattern and exclude_pattern in full_path:
+ if exclude_pattern and any(p.strip() in full_path for p in exclude_pattern.split(",")):
print(f"Skipping {full_path} (matches exclude pattern: {exclude_pattern})")
continue
if include_files and file not in include_files:
@@ -313,9 +362,31 @@ def _collect_test_files(
continue
test_files.append(full_path)
+
+ # Apply file-level sharding: sort deterministically, then select every Nth file.
+ # Skip when include_files is set — in that case the test's own conftest handles
+ # sharding at the test-item level (e.g. parametrized test cases).
+ shard_index = os.environ.get("TEST_SHARD_INDEX", "")
+ shard_count = os.environ.get("TEST_SHARD_COUNT", "")
+ if shard_index and shard_count and not include_files:
+ shard_index = int(shard_index)
+ shard_count = int(shard_count)
+ test_files.sort()
+ test_files = [f for i, f in enumerate(test_files) if i % shard_count == shard_index]
+ print(f"Shard {shard_index}/{shard_count}: selected {len(test_files)} test files")
+
return test_files
+def _write_empty_report():
+ """Write an empty JUnit XML report so downstream CI steps find a valid file."""
+ os.makedirs("tests", exist_ok=True)
+ result_file = os.environ.get("TEST_RESULT_FILE", "full_report.xml")
+ report = JUnitXml()
+ report.write(f"tests/{result_file}")
+ print(f"Wrote empty report to tests/{result_file}")
+
+
def pytest_sessionstart(session):
"""Intercept pytest startup to execute tests in the correct order."""
# Get the workspace root directory (one level up from tools)
@@ -329,10 +400,8 @@ def pytest_sessionstart(session):
filter_pattern = os.environ.get("TEST_FILTER_PATTERN", "")
exclude_pattern = os.environ.get("TEST_EXCLUDE_PATTERN", "")
include_files_str = os.environ.get("TEST_INCLUDE_FILES", "")
+ quarantined_only = os.environ.get("TEST_QUARANTINED_ONLY", "false") == "true"
curobo_only = os.environ.get("TEST_CUROBO_ONLY", "false") == "true"
- cuda_issue_only = os.environ.get("TEST_CUDA_ISSUE_ONLY", "false") == "true"
- flaky_only = os.environ.get("TEST_FLAKY_ONLY", "false") == "true"
- slightly_flaky_only = os.environ.get("TEST_SLIGHTLY_FLAKY_ONLY", "false") == "true"
isaacsim_ci = os.environ.get("ISAACSIM_CI_SHORT", "false") == "true"
@@ -356,17 +425,13 @@ def pytest_sessionstart(session):
print(f"Filter pattern: '{filter_pattern}'")
print(f"Exclude pattern: '{exclude_pattern}'")
print(f"Include files: {include_files if include_files else 'none'}")
+ print(f"Quarantined-only mode: {quarantined_only}")
print(f"Curobo-only mode: {curobo_only}")
- print(f"CUDA-issue-only mode: {cuda_issue_only}")
- print(f"Flaky-only mode: {flaky_only}")
- print(f"Slightly-flaky-only mode: {slightly_flaky_only}")
print(f"TEST_FILTER_PATTERN env var: '{os.environ.get('TEST_FILTER_PATTERN', 'NOT_SET')}'")
print(f"TEST_EXCLUDE_PATTERN env var: '{os.environ.get('TEST_EXCLUDE_PATTERN', 'NOT_SET')}'")
print(f"TEST_INCLUDE_FILES env var: '{os.environ.get('TEST_INCLUDE_FILES', 'NOT_SET')}'")
+ print(f"TEST_QUARANTINED_ONLY env var: '{os.environ.get('TEST_QUARANTINED_ONLY', 'NOT_SET')}'")
print(f"TEST_CUROBO_ONLY env var: '{os.environ.get('TEST_CUROBO_ONLY', 'NOT_SET')}'")
- print(f"TEST_CUDA_ISSUE_ONLY env var: '{os.environ.get('TEST_CUDA_ISSUE_ONLY', 'NOT_SET')}'")
- print(f"TEST_FLAKY_ONLY env var: '{os.environ.get('TEST_FLAKY_ONLY', 'NOT_SET')}'")
- print(f"TEST_SLIGHTLY_FLAKY_ONLY env var: '{os.environ.get('TEST_SLIGHTLY_FLAKY_ONLY', 'NOT_SET')}'")
print("=" * 50)
# Get all test files in the source directories
@@ -375,10 +440,8 @@ def pytest_sessionstart(session):
filter_pattern,
exclude_pattern,
include_files,
- flaky_only,
- slightly_flaky_only,
+ quarantined_only,
curobo_only,
- cuda_issue_only,
)
if isaacsim_ci:
@@ -390,6 +453,14 @@ def pytest_sessionstart(session):
test_files = new_test_files
if not test_files:
+ if quarantined_only:
+ print("No quarantined tests configured — nothing to run.")
+ _write_empty_report()
+ pytest.exit("No quarantined tests configured", returncode=0)
+ if filter_pattern:
+ print(f"No test files found matching filter pattern '{filter_pattern}' — nothing to run.")
+ _write_empty_report()
+ pytest.exit("No test files found for filter", returncode=0)
print("No test files found in source directory")
pytest.exit("No test files found", returncode=1)
@@ -398,21 +469,20 @@ def pytest_sessionstart(session):
print(f" - {test_file}")
# Run all tests individually
- failed_tests, test_status = run_individual_tests(test_files, workspace_root, isaacsim_ci)
+ failed_tests, test_status, xml_reports = run_individual_tests(test_files, workspace_root, isaacsim_ci)
print("failed tests:", failed_tests)
# Collect reports
print("~~~~~~~~~ Collecting final report...")
- # create new full report
+ # Merge in-memory report objects collected during the test run. Reading the
+ # on-disk files again risks losing elements if the junitparser
+ # read/write round-trip does not preserve them faithfully.
full_report = JUnitXml()
- # read all reports and merge them
- for report in os.listdir("tests"):
- if report.endswith(".xml"):
- print(report)
- report_file = JUnitXml.fromfile(f"tests/{report}")
- full_report += report_file
+ for xml_report in xml_reports:
+ print(xml_report)
+ full_report += xml_report
print("~~~~~~~~~~~~ Writing final report...")
# write content to full report
result_file = os.environ.get("TEST_RESULT_FILE", "full_report.xml")
@@ -427,6 +497,7 @@ def pytest_sessionstart(session):
num_passing = len([test_path for test_path in test_files if test_status[test_path]["result"] == "passed"])
num_failing = len([test_path for test_path in test_files if test_status[test_path]["result"] == "FAILED"])
num_timeout = len([test_path for test_path in test_files if test_status[test_path]["result"] == "TIMEOUT"])
+ num_crashed = len([test_path for test_path in test_files if test_status[test_path]["result"] == "CRASHED"])
if num_tests == 0:
passing_percentage = 100
@@ -442,6 +513,7 @@ def pytest_sessionstart(session):
summary_str += f"Total: {num_tests}\n"
summary_str += f"Passing: {num_passing}\n"
summary_str += f"Failing: {num_failing}\n"
+ summary_str += f"Crashed: {num_crashed}\n"
summary_str += f"Timeout: {num_timeout}\n"
summary_str += f"Passing Percentage: {passing_percentage:.2f}%\n"
@@ -482,4 +554,7 @@ def pytest_sessionstart(session):
print(summary_str)
# Exit pytest after custom execution to prevent normal pytest from overwriting our report
- pytest.exit("Custom test execution completed", returncode=0 if num_failing == 0 else 1)
+ pytest.exit(
+ "Custom test execution completed",
+ returncode=0 if (num_failing == 0 and num_timeout == 0 and num_crashed == 0) else 1,
+ )
diff --git a/tools/test_settings.py b/tools/test_settings.py
index a5e9505ef873..12d4bf5bcf97 100644
--- a/tools/test_settings.py
+++ b/tools/test_settings.py
@@ -15,6 +15,7 @@
DEFAULT_TIMEOUT = 1000
"""The default timeout for each test in seconds."""
+
PER_TEST_TIMEOUTS = {
"test_articulation.py": 1000,
"test_stage_in_memory.py": 1000,
@@ -46,10 +47,10 @@
"test_sb3_wrapper.py": 1000,
"test_skrl_wrapper.py": 1000,
"test_action_state_recorder_term.py": 1000,
- "test_manager_based_rl_env_obs_spaces.py": 500,
+ "test_manager_based_rl_env_obs_spaces.py": 1000,
"test_visuotactile_sensor.py": 1000,
"test_visuotactile_render.py": 1000,
- "test_rigid_object_collection.py": 1000,
+ "test_rigid_object_collection.py": 1500,
"test_outdated_sensor.py": 1000,
"test_multi_tiled_camera.py": 1000,
"test_multirotor.py": 1000,
@@ -61,60 +62,47 @@
Note: Any tests not listed here will use the default timeout.
"""
-CUROBO_TESTS = [
+CUROBO_PLANNER_TESTS = [
"test_curobo_planner_franka.py",
"test_curobo_planner_cube_stack.py",
+ "test_pink_ik.py",
+]
+"""Tests for the cuRobo motion planner and Pink IK controller.
+
+These tests are skipped in the base image CI jobs and run in the dedicated
+``test-curobo`` CI job which uses the cuRobo Docker image.
+"""
+
+SKILLGEN_TESTS = [
"test_generate_dataset_skillgen.py",
"test_environments_skillgen.py",
"test_environments_automate.py",
- "test_pink_ik.py",
]
-"""A list of tests that require cuRobo installation.
+"""SkillGen and AutoMate environment tests.
-These tests are skipped in the base image CI jobs and run separately in the
-dedicated ``test-curobo`` CI job which uses the cuRobo Docker image.
+These tests are skipped in the base image CI jobs and run in the dedicated
+``test-skillgen`` CI job which uses the cuRobo Docker image.
"""
-FLAKY_TESTS = [
- # Consistently failing or highly flaky (<60% pass rate across recent CI runs)
- "test_rigid_object_collection_iface.py", # 0%
- "test_environments_newton.py", # 5.9%
- "test_articulation_iface.py", # 7.7%
- # "test_articulation.py", # 10.5%
- "test_rigid_object_iface.py", # 23.1%
- # "test_rigid_object_collection.py", # 26.7%
- "test_physx_scene_data_provider_visualizer_contract.py", # 30.8%
- "test_shadow_hand_vision_presets.py", # 47.4%
- "test_mock_data_properties.py", # 50.0%
- # "test_rigid_object.py", # 57.7%
- # "test_contact_sensor.py", # 60.0%
- "test_robot_load_performance.py", # 60.0%
- # Failing in recent CI runs
- # "test_camera.py",
- "test_logger.py",
- "test_multirotor.py",
- "test_null_command_term.py",
- "test_sb3_wrapper.py",
- "test_selection_strategy.py",
- "test_spawn_lights.py",
+CUROBO_TESTS = [
+ *CUROBO_PLANNER_TESTS,
+ *SKILLGEN_TESTS,
]
-"""A list of tests that are known to be flaky (< 60% pass rate).
+"""A list of tests that require cuRobo installation.
-These tests are skipped in normal CI runs and executed in the dedicated
-``test-flaky`` CI job where failures do not block PR merges.
+These tests are skipped in the base image CI jobs and run separately in the
+dedicated ``test-curobo`` and ``test-skillgen`` CI jobs which use the cuRobo
+Docker image.
"""
-SLIGHTLY_FLAKY_TESTS = [
- # Mildly intermittent (96%+ pass rate across recent CI runs)
- # "test_multi_mesh_ray_caster_camera.py", # 96.2%
- # "test_ray_caster_camera.py", # 96.2%
- "test_surface_gripper.py", # 96.2%
- "test_env_cfg_no_forbidden_imports.py", # 96.4%
-]
-"""A list of tests that are mildly flaky (96%+ pass rate).
+QUARANTINED_TESTS: list[str] = []
+"""A list of tests that are quarantined due to known instability.
-These tests are skipped in normal CI runs and executed in the dedicated
-``test-slightly-flaky`` CI job where failures do not block PR merges.
+These tests are skipped in normal CI runs. When the ``test-quarantined``
+CI job is enabled (gated by the ``RUN_QUARANTINED_TESTS`` repository
+variable), they run in a dedicated job where failures do not block PR
+merges. The job is currently disabled. Add test filenames here to
+quarantine them from regular CI.
"""
TESTS_TO_SKIP = [
@@ -127,14 +115,13 @@
# lab_tasks
"test_record_video.py", # Failing
"test_tiled_camera_env.py", # Need to improve the logic
- # curobo / skillgen - require cuRobo installation; run via the test-curobo CI job
+ # curobo / skillgen - require cuRobo installation; run via test-curobo and test-skillgen CI jobs
*CUROBO_TESTS,
- # flaky tests - run in dedicated CI jobs that do not block PR merges
- *FLAKY_TESTS,
- *SLIGHTLY_FLAKY_TESTS,
+ # quarantined tests - run in dedicated CI job that does not block PR merges
+ *QUARANTINED_TESTS,
"test_environments_training.py", # Long-running RL training test; runs in dedicated CI job
]
-"""A list of tests to skip by run_tests.py"""
+"""A list of tests to skip in CI (see conftest.py)."""
TEST_RL_ENVS = [
# classic control