Repository navigation
[Newton] Redesign Newton Manager [1/N] - #8711
Conversation
SimulationContext constructs the manager selected by cfg.physics.class_type and owns it as sim.physics_manager. PhysicsManager runtime methods and state (callbacks, views, sim, cfg, device, time) are per instance, so managers no longer share process-wide class state. Assets and sensors resolve the context and manager once; backend data classes take the manager at construction; MDP terms use env.sim.physics_manager. Backend factories select implementations with PhysicsManager.backend_name, and views are keyed by prim path per manager. The PhysX, OVPhysX and Newton managers, the Newton solver managers and the couplers are converted mechanically. Class-level factory hooks used before a manager exists stay classmethods; Newton solver construction takes the determinism mode as an argument.
[High impact] Converts physics managers from class-level singletons to per-instance objects. The PR appears safe to merge, with a non-blocking fix recommended for OVPhysX exit callbacks retaining closed managers. Findings
SummaryPhysics managers become simulation-owned instances across PhysX, OVPhysX, and Newton.
Review checks were static; no runtime tests were executed. Diagram%%{init: {'theme': 'neutral'}}%%
flowchart LR
C[Simulation configuration] --> S[SimulationContext]
S --> M[PhysicsManager instance]
M --> B[Native backend]
M --> V[Per-manager views and callbacks]
A[Assets and sensors] --> M
D[Asset data] --> M
T[Tasks and visualizers] --> M
Reviews (1) · Last reviewed commit: "Make physics managers instances" · Reviewed by Greptile |
| if not self._atexit_registered: | ||
| atexit.register(self._close_at_exit) | ||
| self._atexit_registered = True |
There was a problem hiding this comment.
Each warmed-up OvPhysxManager now registers its bound self._close_at_exit method, but close() never unregisters it. Python keeps every closed manager alive until the process exits. Repeatedly opening and closing simulations therefore grows the retained objects and exit callback list, even though native resources are released.
After successful cleanup, call atexit.unregister(self._close_at_exit) and clear _atexit_registered. Keep the callback registered when cleanup fails so it can retry.
| ) | ||
|
|
||
|
|
||
| def _active_coupler_cfg() -> CouplerCfg: |
There was a problem hiding this comment.
Isaac Lab Review Bot
Needs attention: Scope and over-engineering (2), Compatibility and deprecation (4), Implementation (1), Style consistency (2), Test quality (2). Other reviewed categories look good.
- PR description: Retitle to cover all physics backends and add profiler and reset-solver migrations; the body already discloses unexecuted PhysX Kit coverage.
- Design and architecture: Architecture looks good.
- Scope and over-engineering: Minimal implementation: extend PhysicsManager, SimulationContext, FactoryBase, and existing backend, asset, and sensor owners; add no source modules. Delete duplicate AssetBase and SensorBase _sim references, inject the manager into ParticleSurfaceRenderer, and keep direct instance flow through existing managers. Scope is cohesive; no split recommended.
- API: API changes look good.
- Compatibility and deprecation: Breaking changes: class-level manager APIs, backend data constructors, profiler inputs, and InteractiveScene.physics_backend changed without deprecation bridges; preserve old calls with warnings and migration coverage before removal.
- Implementation: OVPhysxManager registers every bound exit callback, retaining sequential managers for the process lifetime; use one process callback or unregister each callback during close.
- Style consistency: Newton manager docstrings contain invalid self-based Sphinx targets and a tautological migration sentence; use class-qualified targets and remove the stale sentence.
- Test quality: The inherited profiler axis and six-manager clear loop repeat identical paths; collapse each to one owner-path case, retaining only MPM-specific cleanup coverage.
Needs rework. Posted 11 inline findings.
The full PR diff was reviewed; some supplemental surrounding file context was omitted.
Automated review; human maintainers own approval decisions.
| backend_name: ClassVar[str] | ||
| """Backend implementation key used by asset and sensor factories.""" | ||
|
|
||
| def __init__(self): |
There was a problem hiding this comment.
🔴 Critical · Compatibility — Class-level manager API removed abruptly
Every class-level call (PhysxManager.get_physics_sim_view(), NewtonManager.get_model(), Manager.register_callback(...), views[(Manager, path)]) now raises TypeError/KeyError. Keep class entry points forwarding to the active instance with a targeted DeprecationWarning for the prescribed window.
| """The name of the backend for the articulation data.""" | ||
|
|
||
| def __init__(self, root_view: ArticulationView, device: str): | ||
| def __init__(self, root_view: ArticulationView, device: str, *, physics_manager: NewtonManager): |
There was a problem hiding this comment.
🔴 Critical · Compatibility — Data constructors require new keyword
ArticulationData(view, device) now fails on the required keyword-only physics_manager; the same break applies to the PhysX and OVPhysX data classes. Accept omission temporarily, resolve the active manager, and warn before requiring it.
| def _register_callbacks(self): | ||
| """Registers physics lifecycle callbacks via the current backend's physics manager.""" | ||
| physics_mgr_cls = SimulationContext.instance().physics_manager | ||
| self._sim = SimulationContext.instance() |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Delete unused _sim field
AssetBase._register_callbacks (and the matching SensorBase change) stores self._sim but only self._physics_manager is used here. Drop the second context reference.
There was a problem hiding this comment.
Kept on purpose: the OVPhysX articulation reads self._sim.stage and self._sim.get_clone_plan() (previously PhysicsManager._sim).
| # Optional: prim deletion (only supported by Kit PhysX backend, not ovphysx) | ||
| self._prim_deletion_handle = None | ||
| physics_backend = physics_mgr_cls.__name__.lower() | ||
| physics_backend = physics_mgr.backend_name |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Backend check inconsistent with sensor_base
backend_name is an exact key, so startswith("physx") is stale; sensor_base._register_callbacks uses == "physx" for the same PhysX-only prim-deletion hook. Use equality here too.
| @contextmanager | ||
| def profile_physics_steps( | ||
| physics_manager: type[PhysicsManager] | ResolvableString, | ||
| physics_manager: PhysicsManager, |
There was a problem hiding this comment.
🟡 Warning · Compatibility — Profiler rejects manager classes
profile_physics_steps no longer accepts a manager class or lazy class reference, breaking its documented input contract. Continue resolving those inputs with a DeprecationWarning while accepting instances.
| assert PHYSICS_PROFILE_SCOPE not in capsys.readouterr().out | ||
| assert manager.step == original_step | ||
| assert ("step" in vars(manager)) is not inherited | ||
| assert "step" not in vars(manager) |
There was a problem hiding this comment.
🟡 Warning · Test Quality — Dead inherited parametrize axis
profile_physics_steps now stores the wrapper on the instance, so vars(manager) never holds step and InheritedManager takes the same path as CoupledManager. Drop the inherited axis and that class.
| :attr:`State.body_f`; ``False`` otherwise. | ||
|
|
||
| Writing through ``NewtonManager._foo`` (rather than ``cls._foo``) | ||
| Writing through ``self._foo`` (rather than ``self._foo``) |
There was a problem hiding this comment.
🟡 Warning · Style Consistency — Docstring self-references break Sphinx
:attr:self._solveris not a resolvable Sphinx target, and "Writing throughself._foo(rather thanself._foo``)" is tautological. Name the class in roles and delete the stale sentence; kamino/mjwarp/mpm managers repeat this.
| assert NewtonManager._supports_rigid_body_force_input is False | ||
| assert NewtonManager._num_envs is None | ||
| for manager in ( | ||
| for manager_cls in ( |
There was a problem hiding this comment.
🟡 Warning · Test Quality — Six-subclass loop now one path
With per-instance state, subclasses can no longer shadow _supports_rigid_body_force_input/_num_envs, so all six manager classes run the same inherited clear(). Keep one manager (plus MPM if its _solver_specific_clear is asserted).
| friction_replacements=sim.cfg.physics.legacy_joint_friction_replacements, | ||
| ) | ||
| cls._stage_usda = stage_usda | ||
| self._stage_usda = stage_usda |
There was a problem hiding this comment.
🟡 Warning · Implementation — atexit retains every manager
Each manager registers a bound _close_at_exit callback, so every sequential simulation context is retained for the process lifetime. Register one process-level callback or unregister the bound callback during close().
| self._state = NewtonManager.get_state_0() | ||
| from isaaclab.sim import SimulationContext | ||
|
|
||
| physics_manager = SimulationContext.instance().physics_manager |
There was a problem hiding this comment.
🟡 Warning · Scope Complexity — Replace singleton lookup with injection
ParticleSurfaceRenderer swaps a manager global for SimulationContext.instance(), though callers already own sim. Pass the manager (or model/state) into the constructor and delete the lookup.
Class-level access to PhysicsManager runtime methods and state forwards to the active simulation's manager with a DeprecationWarning, through a metaclass that leaves instance access untouched. sim.physics_manager is a deprecated alias of sim.backend_manager, and the asset data classes, profile_physics_steps, safe_callback_invoke and ParticleSurfaceRenderer accept their previous inputs with a warning. OVPhysX managers drop their exit hook after a successful close, the multirotor passes its manager to its data class, the coupler reads the active solver config inline, and the PhysX prim-deletion check matches the backend name exactly.
…1-manager-instances
|
run-ci |
# Description Part of the Newton manager redesign (overview with API examples: #8218 (comment)). [1/N] #8711 (merged) made physics managers instances owned by the simulation as `sim.backend_manager`. The former [2/N] #8712 is split into five stacked PRs: | PR | Stage | |---|---| | [2a/N] **#8733 (this PR)** | Move Newton simulation data onto NewtonBackend | | [2b/N] #8734 | Describe Newton solvers with solver specifications | | [2c/N] #8735 | Move Newton manager logic into backend functions | | [2d/N] #8736 | Capture Newton model changes and Torch work in the step | | [2e/N] #8737 | Run each Newton step as one step graph | This PR is the bottom of the stack and targets `main` directly. ## What this PR does Newton's `Model` stays the immutable description (like `mjModel`). **`NewtonBackend`** becomes the mutable data bound to one finalized model (like `mjData`): state, control, solver, collision pipeline, contacts, sensors, Newton actuators and reset masks. The manager reads and writes `backend.*` instead of private fields, and a hard reset closes the backend and finalizes a new one. - The simulation registry still owns the builder and backend: consumers call `sim.get_or_create_backend(NewtonBuilderCfg(...))` / `sim.get_or_create_backend(NewtonBackendCfg(...))` as before. `NewtonBackendCfg.class_type` is `NewtonBackend`, constructed through `instantiate`. - Replication outputs (`NewtonCloneRecord`, site index map, world transforms, source builders) are read through manager accessors instead of private fields; site and extended-attribute requests persist on the builder across hard resets, so sensors no longer re-register them. - `add_contact_sensor` / `add_imu_sensor` return the Newton sensor. - `NewtonBuilderCfg` and `NewtonBackendCfg` move into their own `newton_builder_cfg.py` / `newton_backend_cfg.py`. - The per-solver manager subclasses and their hooks are unchanged apart from operating on the backend. ## Type of change - Breaking change. No deprecation shims: removed APIs are listed below with their replacements. ## Migration | Before | Now | |---|---| | `manager.get_model()`, `get_state_0()`, `get_state_1()`, `get_control()`, `get_contacts()` | `manager.backend.model`, `.state_0`, `.state_1`, `.control`, `.contacts` | | `manager._solver`, `_contacts`, `_collision_pipeline`, `_adapter`, `_world_reset_mask`, `_fk_reset_mask`, `kinematics_dirty` | `backend.solver`, `.contacts`, `.collision_pipeline`, `.actuators`, `.world_mask`, `.fk_mask`, `.kinematics_dirty` | | `get_num_envs()`, `get_dt()`, `get_solver_dt()` | `backend.model.world_count`, `backend.dt`, `backend.solver_dt` | | `cl_register_site(...)` | `register_site(...)` | | `add_frame_transform_sensor(...)` | construct `newton.sensors.SensorFrameTransform` on `backend.model` | | `add_contact_sensor` / `add_imu_sensor` returning a key or index | both return the Newton sensor | | private replication fields (`_cl_site_index_map`, `_world_xforms`, `_cl_protos`, ...) | `get_site_index_map()`, `get_world_xforms()`, `get_clone_source_builders()`, `get_clone_record()` | | `from isaaclab_newton.physics.newton_manager_cfg import NewtonBuilderCfg, NewtonBackendCfg` | `from isaaclab_newton.physics import NewtonBuilderCfg, NewtonBackendCfg` | | sensors re-registering sites / `body_qdd` on `STOP` | not needed; requests persist on the builder | ## Testing Every test file in its own process without Isaac Sim (Kit), compared with `main`: no file has more failures or fewer passes, apart from two tests removed with the deprecated accessors. Remaining failures also fail on `main` or need missing extras (Kit launcher tests, rl_games/sb3, `rerun`). Not run: Kit-only tests and the GB300, Rizon coffee and teapot examples. ## Checklist - [x] I have read and understood the [contribution guidelines](https://isaac-sim.github.io/IsaacLab/main/source/refs/contributing.html) - [x] I have run the [`pre-commit` checks](https://pre-commit.com/) with `./isaaclab.sh --format` - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings - [x] I have added tests that prove my fix is effective or that my feature works - [x] I have added changelog fragments --------- Co-authored-by: Maximilian Krause <[email protected]>
Description
First PR of the Newton manager redesign series, split out of the draft #8218 (reference implementation and
measurements). Overview of the whole redesign, with API examples: #8218 (comment).
This PR changes one contract: physics managers are instances. On develop,
PhysicsManagerand its subclasseskeep all simulation state in class variables and expose classmethods, so a process can hold only one simulation, and
every consumer reaches the backend through a global (
NewtonManager.get_model(),PhysxManager.get_physics_sim_view(), ...). Here:SimulationContextconstructs the manager selected bycfg.physics.class_typeand owns it assim.backend_manager(renamed fromsim.physics_manager, which stays as a deprecated alias). Its runtime methods(
reset,step,forward,register_callback, getters, ...) are instance methods, and its state (_sim,_cfg,_device,_sim_time, callbacks,views) is per instance.self._sim,self._backend_manager); their dataclasses receive the manager at construction. MDP terms use
env.sim.backend_manager.PhysicsManager.backend_name("physx","ovphysx","newton") replaces class-name checks in the factories.viewsis keyed by prim path per manager, instead of(manager class, path)in one process-wide dict.mechanically. Class-level factory hooks used before a manager exists stay classmethods (
_prepare_stage_creation,fix_articulation_root,setup_deformable_body, Newtoncreate_builderand solver construction).Newton solver construction now receives the determinism mode as an argument instead of reading class state.
No behavior changes otherwise; the Newton manager's internals are restructured in [2/N].
Series
env.step)prepare/record_step), world-masked commits, heterogeneous worldsThe split order and scope will change while the design is reviewed.
Type of change
fragments.
Migration
Deprecated (still works, warns with
DeprecationWarning):PhysxManager.get_physics_sim_view(),NewtonManager.get_model(),Manager.register_callback(fn, event), ... (class-level runtime calls and state)sim.backend_manager.get_physics_sim_view(),sim.backend_manager.get_model(), ... (assets and sensors:self._backend_manager). Class-level access forwards to the active simulation's manager.sim.physics_managersim.backend_managerRigidObjectData(view, device)(PhysX, OVPhysX, Newton data classes)RigidObjectData(view, device, backend_manager=manager)profile_physics_steps(ManagerClass)/ lazy class referenceprofile_physics_steps(sim.backend_manager)PhysicsManager.safe_callback_invoke(..., physics_manager=m)PhysicsManager.safe_callback_invoke(..., backend_manager=m)ParticleSurfaceRenderer(visualizers, surface, ...)ParticleSurfaceRenderer(visualizers, surface, ..., backend_manager=sim.backend_manager)Breaking (no shim):
sim.physics_manager is NewtonManager,sim.physics_manager.__name__isinstance(sim.backend_manager, NewtonManager),sim.backend_manager.backend_nameManager.views[(Manager, path)]manager.views[path]InteractiveScene.physics_backend == "newtonmjwarpmanager"(lowercased class name)scene.physics_backend == "newton"(backend key)_build_solver,_solver_specific_clear, ...)_create_solver(model, solver_cfg),_filter_solver_kwargs(solver_cls, solver_cfg)reading the determinism mode from class state_create_solver(model, solver_cfg, deterministic_mode),_filter_solver_kwargs(solver_cls, solver_cfg, deterministic_mode)Testing
Each test file in its own process, without Isaac Sim (Kit):
three backends (articulation 487 passed, rigid object 231 passed); core sim, benchmark and backend-utility tests;
all OVPhysX tests (30 files); contrib coupling and custom-coupling tests; the Newton contrib task tests (Franka pour,
UR10 particle push); visualizer adapter tests.
views), thesim.physics_manageralias,data-class fallback, profiler class input, and the OVPhysX exit hook being dropped on close.
0ab97e9c8(Kit launcher tests,test_api.pywithoutrl_games/sb3,test_rendering_franka_soft_kitless.py,test_xr_camera_feed_presets.py) or need extras not installed here(
rerun).consumer changes are the same mechanical substitution and are lint-checked.
Checklist
pre-commitchecks with./isaaclab.sh --format