diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 63c581fd6dac..fc29b9ad4bc5 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -182,6 +182,7 @@ Guidelines for modifications: * Ori Gadot * Oyindamola Omotuyi * Özhan Özen +* Pablo de Heras Ciechomski * Patrick Yin * Patrick-SCH03 * Paul Reeves diff --git a/docs/source/_static/concepts/ovphysx-live-ovd-recording.png b/docs/source/_static/concepts/ovphysx-live-ovd-recording.png new file mode 100644 index 000000000000..bbea596d0255 Binary files /dev/null and b/docs/source/_static/concepts/ovphysx-live-ovd-recording.png differ diff --git a/docs/source/concepts/physics-backends/ovphysx.rst b/docs/source/concepts/physics-backends/ovphysx.rst index 6f4b9729e489..c6559828b6ed 100644 --- a/docs/source/concepts/physics-backends/ovphysx.rst +++ b/docs/source/concepts/physics-backends/ovphysx.rst @@ -341,6 +341,79 @@ readiness predicate for the current simulation context. Manager teardown release and clears this handle. Initialize and reset the current context before access, and always reacquire the handle before creating new bindings or views. +.. _ovphysx-live-ovd-recording: + +Record OVD during a running simulation +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Set ``OvPhysxCfg(ovd_recording_capable=True)`` before the first native PhysX +instance is created. The default is ``False``. Enabling capability provisions +recording resources and can affect simulation performance while output is +inactive. An explicit start selects the destination and begins recording. See +the `OVPhysX recording guide `_ +for the runtime's recording and performance details. + +The manager's handle is ``None`` until the first hard reset starts constructing +the runtime. For recording, wait until that reset has returned and the scene has +attached and warmed up. A late start snapshots the current scene. Run the +start and stop calls on the simulation's stepping thread between completed +steps. The same simulation can continue stepping after a stop and start +another capture with a new destination. + +.. image:: ../../_static/concepts/ovphysx-live-ovd-recording.png + :alt: The simulation keeps stepping before, between, and after two separate OVD captures. + +This headless example takes several steps before starting a file capture. + +.. code-block:: python + + from ovphysx import OmniPvdDestination + from pxr import UsdGeom, UsdPhysics + + from isaaclab.sim import SimulationCfg, build_simulation_context + from isaaclab_ov.physics import OvPhysxCfg + + cfg = SimulationCfg(device="cpu", physics=OvPhysxCfg(ovd_recording_capable=True)) + with build_simulation_context(sim_cfg=cfg) as sim: + cube = UsdGeom.Cube.Define(sim.stage, "/World/Cube") + cube.AddTranslateOp().Set((0.0, 0.0, 2.0)) + UsdPhysics.RigidBodyAPI.Apply(cube.GetPrim()) + UsdPhysics.CollisionAPI.Apply(cube.GetPrim()) + sim.reset() + + for _ in range(10): + sim.step(render=False) + + physx = sim.backend_manager.get_physx_instance() + physx.start_recording(OmniPvdDestination.file("captures/late.ovd")) + try: + for _ in range(20): + sim.step(render=False) + finally: + physx.stop_recording() + + for _ in range(10): + sim.step(render=False) + +A path ending in lowercase ``.ovd`` selects that filename and can replace an +existing file. A directory destination produces timestamped files and preserves +existing captures. For streaming, use ``OmniPvdDestination.tcp(address, port, +timeout_ms=...)`` with an already listening, trusted receiver. Starting a +TCP capture connects synchronously. + +The process can have one active recording at a time. Stop it on the native +instance that started it. A forced re-warm that reloads the stage or a context +close ends its capture without restarting it. Stop explicitly before teardown +to receive recording errors, and reacquire the native handle in a new context. + +The capability setting is shared process-wide and the native value persists +after the context closes. A default Isaac Lab context resets an unfrozen +``True`` to ``False``, including a value set directly through the SDK, retained +from an earlier job, or inherited from host settings. A default context raises +if an existing capable runtime has frozen the value. Match that runtime's +capability, complete native shutdown by closing all owners, or run the new +context in a fresh process with the desired value. + Reuse Isaac Lab-owned access ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/docs/source/how-to/record_animation.rst b/docs/source/how-to/record_animation.rst index 4180cf27c435..9c70f08b537a 100644 --- a/docs/source/how-to/record_animation.rst +++ b/docs/source/how-to/record_animation.rst @@ -5,8 +5,8 @@ Recording Animations of Simulations .. currentmodule:: isaaclab -Use Newton RTX to record simulation videos without Isaac Sim. The Kit-based USD animation -workflows are retained below for existing projects. +Use Newton RTX to record simulation videos or kit-less OVPhysX to capture live physics data. +Existing projects can also use the Kit recorders to export USD animations. Newton RTX video recording --------------------------- @@ -32,8 +32,7 @@ Isaac Sim / Kit USD animation (deprecated) workflows. The Stage Recorder and OVD instructions below remain available for projects that need their USD animation outputs. -Isaac Lab supports two approaches for recording animations of physics simulations: the **Stage Recorder** and the **OVD Recorder**. -Both generate USD outputs that can be played back in Omniverse, but they differ in how they work and when you’d use them. +The **Stage Recorder** and the **Isaac Sim OVD Recorder** generate USD animations for playback in Omniverse. The `Stage Recorder`_ extension listens to all motion and USD property changes in the stage during simulation and records them as **time-sampled data**. The result is a USD file that captures only the animated changes—**not** the @@ -44,8 +43,8 @@ This method is built into Isaac Lab’s UI through the :class:`~isaaclab.envs.ui However, to record the animation of a simulation, you need to disable `Fabric`_ to allow reading and writing all the changes (such as motion and USD properties) to the USD stage. -The **OVD Recorder** is designed for more scalable or automated workflows. It uses OmniPVD to capture simulated physics from a played stage -and then **bakes** that directly into an animated USD file. It works with Fabric enabled and runs with CLI arguments. +The **Isaac Sim OVD Recorder** uses OmniPVD to capture simulated physics and bake it into an animated USD file. +It works with Fabric enabled and runs with CLI arguments. The animated USD can be quickly replayed and reviewed by scrubbing through the timeline window, without simulating expensive physics operations. .. note:: @@ -123,20 +122,15 @@ See the `tutorial on layering in Omniverse`_ for more on working with layers. OVD Recorder ~~~~~~~~~~~~ -The OVD Recorder uses OmniPVD to record simulation data and bake it directly into a new USD stage. -This method is more scalable and better suited for large-scale training scenarios (e.g. multi-env RL). - -It’s not UI-controlled—the whole process is enabled through CLI flags and runs automatically. +The animation recording CLI uses the Isaac Sim PhysX backend to capture a single interval and bake it +into a new USD stage. Use ``--viz kit`` to open a window and leave ``HEADLESS`` unset or set to ``0``. .. note:: - The OVD Recorder uses OmniPVD, which only records **PhysX** simulations. If the active physics backend is not - PhysX (for example, Newton, which is the default for many tasks), Isaac Lab raises an error at startup naming - the active backend instead of recording. Select the PhysX backend by adding ``physics=isaacsim_physx`` to the - command line, as shown below. + Select Isaac Sim PhysX by adding ``physics=isaacsim_physx`` to the command line, as shown below. + Kit-less OVPhysX uses the live capture API described below. - The PhysX backend requires Isaac Sim. If it isn't installed yet, add ``--extra isaacsim`` to the ``uv run`` - command; see :ref:`installation-optional-extras` for details. + The examples include the Isaac Sim extra. See :ref:`installation-optional-extras` for details. Workflow Summary @@ -176,7 +170,8 @@ To record an animation: .. note:: - The provided ``--anim_recording_stop_time`` should be greater than the simulation time. + Set ``--anim_recording_stop_time`` greater than ``--anim_recording_start_time`` and let the process run + through the export. .. warning:: @@ -189,6 +184,38 @@ After the stop time is reached, a file will be saved to: anim_recordings//baked_animation_recording.usda +Live OVD capture with kit-less OVPhysX +-------------------------------------- + +Use ``OvPhysxCfg(ovd_recording_capable=True)`` before the first native PhysX instance is created. The +default is ``False``. After the scene's initial reset completes, get the native OVPhysX handle with +``sim.backend_manager.get_physx_instance()``. Call ``start_recording()`` with an OVD destination and +``stop_recording()`` on the stepping thread between completed steps. + +For multiple captures in a job, let the simulation code choose when to start and stop each capture. +Only one capture per process can be active at a time. After stopping, the simulation can keep stepping +and start another capture with a different destination. The live API writes OVD data, and the +``--anim_recording_*`` flags are for the Isaac Sim USD-baking workflow above. + +See :ref:`ovphysx-live-ovd-recording` for a runnable headless example, destination options, and the +recording lifetime. + +Inspect an OVPhysX capture +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A live capture is a physics recording for inspection. Use an external reader to examine the file. +With the PhysX SDK's ``ovd-inspect`` tool installed, summarize the recording to find its scenes and +completed frames. + +.. code-block:: bash + + ovd-inspect summary captures/late.ovd + +The `SDK inspection guide `_ +shows how to inspect an object's recorded values. For visual playback in a compatible Kit application, +enable the OmniPVD extension and follow its `OVD import instructions `_. + + .. _Stage Recorder: https://docs.omniverse.nvidia.com/extensions/latest/ext_animation_stage-recorder.html .. _Fabric: https://docs.omniverse.nvidia.com/kit/docs/usdrt.scenegraph/latest/usd_fabric_usdrt.html .. _Omniverse Launcher: https://docs.omniverse.nvidia.com/launcher/latest/index.html diff --git a/source/isaaclab_ov/changelog.d/ovphysx-live-recording.added.rst b/source/isaaclab_ov/changelog.d/ovphysx-live-recording.added.rst new file mode 100644 index 000000000000..e936b6de3039 --- /dev/null +++ b/source/isaaclab_ov/changelog.d/ovphysx-live-recording.added.rst @@ -0,0 +1,2 @@ +* Added opt-in ``ovd_recording_capable`` to :class:`~isaaclab_ov.physics.OvPhysxCfg` for + live OVD start and stop with the native OVPhysX handle. diff --git a/source/isaaclab_ov/changelog.d/ovphysx-live-recording.changed.rst b/source/isaaclab_ov/changelog.d/ovphysx-live-recording.changed.rst new file mode 100644 index 000000000000..680128d8118f --- /dev/null +++ b/source/isaaclab_ov/changelog.d/ovphysx-live-recording.changed.rst @@ -0,0 +1,3 @@ +* Default OVPhysX contexts set an unfrozen recording capability to ``False``, including values + set by the native SDK, retained from an earlier job, or inherited from host settings. They raise + a configuration error when a live native runtime has already frozen capability to ``True``. diff --git a/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py b/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py index 2bf317829cf7..a2f5f8115231 100644 --- a/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py +++ b/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager.py @@ -311,11 +311,48 @@ def transforms(self) -> SceneDataFormat.Transform: return self._transforms.data +def _read_ovd_recording_capability() -> bool: + try: + value = ovphysx.get_global_config(ovphysx.GlobalConfigKey.OVD_RECORDING_CAPABLE) + except (AttributeError, RuntimeError, ValueError) as exc: + raise RuntimeError( + "Cannot read ovd_recording_capable from OVPhysX. The supported runtime is ovphysx==0.8.0.43443703471." + ) from exc + if not isinstance(value, bool): + raise RuntimeError( + f"OVPhysX returned {value!r} for ovd_recording_capable. " + "The supported runtime is ovphysx==0.8.0.43443703471." + ) + return value + + +def _ovd_recording_capability_conflict(requested: bool, configured: bool) -> str: + return ( + f"OVPhysX ovd_recording_capable={requested} conflicts with the process configuration ({configured}). " + "Set ovd_recording_capable to match it, close all native owners and complete runtime shutdown, " + "or start a new process with the desired value." + ) + + class OvPhysxBackend: """Own the native OVPhysX runtime and either own or borrow its stage.""" def __init__(self, cfg: OvPhysxBackendCfg, *, scene: OvstageBackend | None = None): + requested = cfg.ovd_recording_capable + if not isinstance(requested, bool): + raise TypeError("ovd_recording_capable must be a bool.") ovphysx.bootstrap() + configured = _read_ovd_recording_capability() + # The setting survives shutdown, but the setter is frozen while the native runtime is live. + if configured != requested: + try: + ovphysx.set_global_config(ovphysx.GlobalConfigKey.OVD_RECORDING_CAPABLE, requested) + except AttributeError as exc: + raise RuntimeError( + "Cannot set ovd_recording_capable on OVPhysX. The supported runtime is ovphysx==0.8.0.43443703471." + ) from exc + except (RuntimeError, ValueError) as exc: + raise RuntimeError(_ovd_recording_capability_conflict(requested, configured)) from exc is_gpu = cfg.device.startswith("cuda:") cache_dir = cfg.cooked_collider_cache_dir if cache_dir == DEFAULT_COOKED_COLLIDER_CACHE_DIR: @@ -331,12 +368,27 @@ def __init__(self, cfg: OvPhysxBackendCfg, *, scene: OvstageBackend | None = Non carbonite_overrides.update({"/physics/suppressReadback": True, "/physics/suppressFabricUpdate": True}) # CPU scenes select CPU dynamics through their scene attributes (see _set_scene_dynamics_device). # OVPhysX's process-wide CPU-only mode is irreversible and would block later CUDA scenes. - self.physx = ovphysx.PhysX( + physx = ovphysx.PhysX( config=ovphysx.PhysXConfig( num_threads=8, cooked_collider_cache_dir=cache_dir, carbonite_overrides=carbonite_overrides ), active_cuda_gpus=cfg.device.removeprefix("cuda:") if is_gpu else None, ) + try: + # Another native owner may have selected the configuration before construction completed. + configured = _read_ovd_recording_capability() + if configured != requested: + raise RuntimeError(_ovd_recording_capability_conflict(requested, configured)) + except Exception as startup_error: + try: + physx.destroy() + except Exception as cleanup_error: + startup_error.add_note( + "OVPhysX could not confirm candidate cleanup. If native ownership remains, start a new process." + ) + raise startup_error from cleanup_error + raise + self.physx = physx self.scene = scene self.owns_scene = scene is None self.stage: Any = None @@ -791,6 +843,7 @@ def _warmup_and_load(self) -> None: OvPhysxBackendCfg( device=self._device, cooked_collider_cache_dir=self._cfg.cooked_collider_cache_dir, + ovd_recording_capable=self._cfg.ovd_recording_capable, ), scene=shared_scene, ) diff --git a/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager_cfg.py b/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager_cfg.py index c614a1834431..ffa6ec767ef8 100644 --- a/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager_cfg.py +++ b/source/isaaclab_ov/isaaclab_ov/physics/ovphysx_manager_cfg.py @@ -38,6 +38,9 @@ class OvPhysxBackendCfg(BackendCfg): cooked_collider_cache_dir: str | None = DEFAULT_COOKED_COLLIDER_CACHE_DIR """Cooked-collider cache location, fixed by the first runtime created in the process.""" + ovd_recording_capable: bool = False + """Provision process-wide OVD recording capability before the first native instance.""" + @configclass class OvPhysxCfg(PhysicsCfg): @@ -82,6 +85,13 @@ class OvPhysxCfg(PhysicsCfg): This does not disable the cooked-collider cache. """ + ovd_recording_capable: bool = field(default=False, kw_only=True) + """Provision OVD recording capability at startup, without starting a capture. + + This is shared by all native OVPhysX instances in a process. Changing it + requires full native runtime shutdown before creating the next instance. + """ + enable_enhanced_determinism: bool = False """Enable/disable improved determinism at the expense of performance. Defaults to False. diff --git a/source/isaaclab_ov/test/physics/test_ovphysx_manager_lifecycle.py b/source/isaaclab_ov/test/physics/test_ovphysx_manager_lifecycle.py index 71c218252237..7ead72968807 100644 --- a/source/isaaclab_ov/test/physics/test_ovphysx_manager_lifecycle.py +++ b/source/isaaclab_ov/test/physics/test_ovphysx_manager_lifecycle.py @@ -9,6 +9,8 @@ import ast import inspect +import json +import struct import subprocess import sys import textwrap @@ -79,6 +81,13 @@ def _fake_ovphysx_module(bootstrap): module.bootstrap = bootstrap module.PhysX = _FakePhysX module.PhysXConfig = _FakePhysXConfig + module.GlobalConfigKey = SimpleNamespace(OVD_RECORDING_CAPABLE=object()) + module.get_global_config = lambda key: False + + def reject_write(key, value): + pytest.fail("A matching native capability must not be written") + + module.set_global_config = reject_write return module @@ -496,6 +505,342 @@ def _assert_no_atexit_errors(output: str) -> None: assert "Error in atexit._run_exitfuncs" not in output, output[-8000:] +def _run_ovd_child(tmp_path: Path, checks: str) -> None: + setup = textwrap.dedent( + """ + from pathlib import Path + + import ovphysx + from pxr import UsdGeom, UsdPhysics + + from isaaclab.sim import SimulationCfg, build_simulation_context + from isaaclab_ov.physics import OvPhysxCfg + + def add_cube(sim): + cube = UsdGeom.Cube.Define(sim.stage, "/World/Cube") + cube.AddTranslateOp().Set((0.0, 0.0, 2.0)) + UsdPhysics.RigidBodyAPI.Apply(cube.GetPrim()) + UsdPhysics.CollisionAPI.Apply(cube.GetPrim()) + + def disable_check(physx, capture): + try: + physx.start_recording(ovphysx.OmniPvdDestination.file(str(capture))) + except RuntimeError as exc: + assert "INVALID_STATE" in str(exc) and "OVD_RECORDING_CAPABLE" in str(exc), exc + else: + physx.stop_recording() + raise AssertionError("A default Isaac Lab context recorded after a native SDK opt-in") + assert not physx.is_recording() and not capture.exists() + + ovphysx.bootstrap() + key = ovphysx.GlobalConfigKey.OVD_RECORDING_CAPABLE + initial = ovphysx.get_global_config(key) + """ + ) + script = setup + f"\noutput = Path({str(tmp_path)!r})\n" + textwrap.dedent(checks) + completed, output = _run_child(script) + assert completed.returncode == 0, output[-8000:] + _assert_no_atexit_errors(output) + + +def _read_recorded_cube_heights(capture: Path) -> list[tuple[int, float]]: + """Read fresh cube poses in completed frames of the single-scene test capture.""" + # The pinned OVPhysX wheel writes OmniPVD 0.4.0 without shipping a reader. + # Command layouts follow PhysX's OmniPvdReaderImpl.cpp at tag ovphysx-0.8.0. + with capture.open("rb") as stream: + + def read(size: int) -> bytes: + data = stream.read(size) + assert len(data) == size, f"Truncated OVD record in {capture}" + return data + + def unpack(fmt: str) -> tuple: + layout = struct.Struct(f"<{fmt}") + return layout.unpack(read(layout.size)) + + def read_name() -> bytes: + (size,) = unpack("H") + return read(size) + + assert unpack("III") == (0, 4, 0), "Expected an OmniPVD 0.4.0 stream" + classes = {} + attributes = {} + dynamic_objects = set() + scene = None + cube = None + frame = None + height = None + samples = [] + for opcode in iter(lambda: stream.read(1), b""): + match opcode[0]: + case 1: # Register class + class_id, _ = unpack("II") + classes[class_id] = read_name() + case 3: # Register typed attribute + class_id, attribute, datatype, elements = unpack("IIHI") + attributes[attribute] = (classes[class_id], read_name(), datatype, elements) + case 4 | 5: # Register class or list attribute + read(12 if opcode[0] == 4 else 10) + read_name() + case 6 | 7 | 8: # Set an attribute or edit a list attribute + context, obj, depth = unpack("QQB") + handles = unpack(f"{depth}I") + (size,) = unpack("I") + data = read(size) + key = (context, obj) + if opcode[0] != 6 or depth != 1 or key not in dynamic_objects: + continue + attribute = attributes.get(handles[0]) + if attribute == (b"PxActor", b"name", 10, 1) and data.rstrip(b"\x00") == b"/World/Cube": + assert cube is None or cube == key, "Expected one recorded cube" + cube = key + elif key == cube and frame is not None and attribute == (b"PxRigidActor", b"globalPose", 8, 7): + # PxTransform stores the quaternion followed by the XYZ position. + height = struct.unpack("<7f", data)[-1] + case 9: # Create object + context, class_id, obj = unpack("QIQ") + read_name() + if classes[class_id] == b"PxScene": + assert scene is None, "Expected a single scene" + scene = obj + elif classes[class_id] == b"PxRigidDynamic": + dynamic_objects.add((context, obj)) + case 10: # Destroy object + dynamic_objects.discard(unpack("QQ")) + case 11: # Start frame + context, timestamp = unpack("QQ") + assert context == scene and frame is None, "Expected one open scene frame at a time" + frame = timestamp + height = None + case 12: # Stop frame + context, timestamp = unpack("QQ") + assert context == scene and frame is not None and timestamp >= frame, "Unmatched scene frame" + if height is not None: + samples.append((frame, height)) + frame = None + case 13: # Record message + read(8) + read_name() + read_name() + read(12) + case other: + raise AssertionError(f"Unexpected OVD 0.4.0 command {other} in {capture}") + # The SDK can leave an empty frame open after the final completed step. + assert cube is not None, "Expected the existing /World/Cube rigid body" + return samples + + +@pytest.mark.kitless +@pytest.mark.integration +@pytest.mark.skipif(not _CPU_DEVICES, reason="Requires a selected CPU test device") +def test_default_ovd_capability_overrides_unfrozen_native_opt_in(tmp_path): + """A default Lab job must leave late recording disabled with a pre-set native key.""" + _run_ovd_child( + tmp_path, + """ + try: + ovphysx.set_global_config(key, True) + physics = OvPhysxCfg(cooked_collider_cache_dir=str(output / "cache")) + with build_simulation_context(sim_cfg=SimulationCfg(device="cpu", physics=physics)) as sim: + add_cube(sim) + sim.reset() + sim.step(render=False) + disable_check(sim.backend_manager.get_physx_instance(), output / "unexpected.ovd") + finally: + ovphysx.set_global_config(key, initial) + """, + ) + + +@pytest.mark.kitless +@pytest.mark.integration +@pytest.mark.skipif(not _CPU_DEVICES, reason="Requires a selected CPU test device") +def test_ovd_recording_lifecycle_and_conflicting_owner(tmp_path: Path) -> None: + """Record on a live shared stage, retain the native owner, and restore the default.""" + _run_ovd_child( + tmp_path, + """ + import json + from contextlib import closing + from unittest.mock import patch + + from isaaclab_ov.physics import OvPhysxBackendCfg + from isaaclab_ov.physics.ovphysx_manager import OvPhysxBackend + from isaaclab_ov.sim.views import OvPhysxView + from isaaclab_ov.stage import OvstageBackendCfg + + def start(physx, label): + capture = output / f"{label}.ovd" + assert not capture.exists() and not physx.is_recording() + physx.start_recording(ovphysx.OmniPvdDestination.file(str(capture))) + assert physx.is_recording() + return capture + + cache = str(output / "cache") + try: + physics = OvPhysxCfg(ovd_recording_capable=True, cooked_collider_cache_dir=cache) + with build_simulation_context(sim_cfg=SimulationCfg(device="cpu", physics=physics)) as sim: + manager = sim.backend_manager + assert manager.get_physx_instance() is None + shared = sim.get_or_create_backend(OvstageBackendCfg(populate_physics=True)) + add_cube(sim) + sim.reset() + physx = manager.get_physx_instance() + assert manager.backend.scene is shared + sim.step(render=False) + assert not list(output.glob("*.ovd")) + + conflicting = OvPhysxBackendCfg(device="cpu", cooked_collider_cache_dir=cache) + with patch.object(ovphysx, "PhysX", wraps=ovphysx.PhysX) as constructor: + try: + sim.get_or_create_backend(conflicting) + except RuntimeError as exc: + assert "ovd_recording_capable" in str(exc) + assert "False" in str(exc) and "True" in str(exc) + assert isinstance(exc.__cause__, RuntimeError), exc.__cause__ + else: + raise AssertionError("A conflicting request started while a capable native owner was live") + constructor.assert_not_called() + assert sim.get_backends(OvPhysxBackendCfg) == (manager.backend,) + + with closing(OvPhysxView(physx, pattern="/World/Cube", device="cpu")) as view: + first = start(physx, "first") + heights = [] + for _ in range(3): + sim.step(render=False) + heights.append(float(view.get_attribute("rigid_body_pose").numpy()[0, 2])) + physx.stop_recording() + assert not physx.is_recording() and first.stat().st_size > 0 + (output / "first-heights.json").write_text(json.dumps(heights), encoding="utf-8") + t = manager.get_simulation_time() + sim.step(render=False) + assert manager.get_simulation_time() > t and manager.get_physx_instance() is physx + + rewarmed = start(physx, "rewarmed") + sim.step(render=False) + manager._warmup_done = False + sim.reset() + assert manager.get_physx_instance() is physx + assert not physx.is_recording() and rewarmed.stat().st_size > 0 + t = manager.get_simulation_time() + sim.step(render=False) + assert manager.get_simulation_time() > t + + closed = start(physx, "closed") + sim.step(render=False) + assert closed.stat().st_size > 0 + + physics = OvPhysxCfg(cooked_collider_cache_dir=cache) + with build_simulation_context(sim_cfg=SimulationCfg(device="cpu", physics=physics)) as sim: + add_cube(sim) + sim.reset() + sim.step(render=False) + disable_check(sim.backend_manager.get_physx_instance(), output / "after-close.ovd") + + # A live instance freezes the startup key even before any stage attaches. + native_owner = ovphysx.PhysX() + try: + with closing(OvPhysxBackend(conflicting)) as peer: + assert peer.physx.handle != native_owner.handle + finally: + native_owner.destroy() + finally: + ovphysx.set_global_config(key, initial) + """, + ) + samples = _read_recorded_cube_heights(tmp_path / "first.ovd") + live_heights = json.loads((tmp_path / "first-heights.json").read_text(encoding="utf-8")) + assert len(samples) == len(live_heights) > 1, "Expected a recorded cube pose for each captured step" + frames, recorded_heights = zip(*samples) + assert all(later > earlier for earlier, later in zip(frames, frames[1:])) + assert recorded_heights[-1] < recorded_heights[0], "Expected the cube to fall during recording" + assert recorded_heights == pytest.approx(live_heights, abs=1e-5, rel=0) + + +@pytest.mark.parametrize(("query_fails", "cleanup_fails"), [(False, False), (True, False), (False, True)]) +def test_ovd_constructor_releases_candidate_after_failed_readback( + monkeypatch, manager_module, query_fails, cleanup_fails +): + """A backend with failed startup verification cannot escape into the registry.""" + from isaaclab_ov.physics import OvPhysxBackendCfg + + from isaaclab.sim import SimulationContext + + candidates = [] + + class Candidate(_FakePhysX): + def __init__(self, **kwargs): + super().__init__(**kwargs) + self.cleanup_attempted = False + candidates.append(self) + + def destroy(self): + self.cleanup_attempted = True + if cleanup_fails: + raise RuntimeError("Native teardown still busy") + + def configured_value(key): + if candidates and query_fails: + raise RuntimeError("Native query failed") + return False + + native = _fake_ovphysx_module(lambda: None) + native.PhysX = Candidate + native.get_global_config = configured_value + native.set_global_config = lambda key, value: None + monkeypatch.setattr(manager_module, "ovphysx", native) + sim = SimpleNamespace(_backend_registry=[]) + cfg = OvPhysxBackendCfg(device="cpu", ovd_recording_capable=True) + with pytest.raises(RuntimeError, match="ovd_recording_capable") as error: + SimulationContext.get_or_create_backend(sim, cfg) + + assert not sim._backend_registry + assert len(candidates) == 1 and candidates[0].cleanup_attempted + if cleanup_fails: + assert "Native teardown still busy" in str(error.value.__cause__) + assert any("new process" in note for note in error.value.__notes__) + + +def test_ovd_capability_preserves_positional_determinism(): + """Existing positional construction leaves recording capability off.""" + from isaaclab_ov.physics import OvPhysxCfg + + defaults = OvPhysxCfg() + args = ( + defaults.class_type, + defaults.launcher_type, + defaults.mesh_variant_source_root, + defaults.deterministic, + defaults.legacy_joint_friction_replacements, + defaults.cooked_collider_cache_dir, + True, + ) + + cfg = OvPhysxCfg(*args) + assert cfg.enable_enhanced_determinism is True + assert cfg.ovd_recording_capable is False + assert OvPhysxCfg(*args, ovd_recording_capable=True).ovd_recording_capable is True + + +def test_ovd_capability_requires_bool_before_native_startup(monkeypatch, manager_module): + """Non-bools, including integers and other boolean-like types, never reach the SDK.""" + import numpy as np + from isaaclab_ov.physics import OvPhysxBackendCfg + + def native_call(*args, **kwargs): + pytest.fail("Invalid Lab capability reached the native API") + + native = _fake_ovphysx_module(native_call) + native.PhysX = native_call + native.get_global_config = native_call + native.set_global_config = native_call + monkeypatch.setattr(manager_module, "ovphysx", native) + for value in (0, 1, "false", None, np.bool_(True)): + cfg = OvPhysxBackendCfg(device="cpu", ovd_recording_capable=value) + with pytest.raises(TypeError, match="ovd_recording_capable.*bool"): + manager_module.OvPhysxBackend(cfg) + + def test_retained_binding_preserves_uncaught_failure_exit_status(): script = _retained_binding_script() + '\nraise RuntimeError("EXPECTED_CHILD_FAILURE")\n' diff --git a/source/isaaclab_ov/test/physics/test_ovphysx_scene_data_backend.py b/source/isaaclab_ov/test/physics/test_ovphysx_scene_data_backend.py index 33368565eaed..b001588e36a8 100644 --- a/source/isaaclab_ov/test/physics/test_ovphysx_scene_data_backend.py +++ b/source/isaaclab_ov/test/physics/test_ovphysx_scene_data_backend.py @@ -118,7 +118,17 @@ def pinned_config(*, num_threads=None, cooked_collider_cache_dir=None, carbonite carbonite_overrides=carbonite_overrides, ) - runtime = SimpleNamespace(PhysX=PinnedPhysX, PhysXConfig=pinned_config, bootstrap=lambda: None) + def reject_write(key, value): + pytest.fail("A matching native capability must not be written") + + runtime = SimpleNamespace( + PhysX=PinnedPhysX, + PhysXConfig=pinned_config, + bootstrap=lambda: None, + GlobalConfigKey=SimpleNamespace(OVD_RECORDING_CAPABLE=object()), + get_global_config=lambda key: False, + set_global_config=reject_write, + ) monkeypatch.setattr(module, "ovphysx", runtime) backend = module.OvPhysxBackend(OvPhysxBackendCfg(device=device, cooked_collider_cache_dir=cache_dir))