Skip to content

[4B/10] Build rendering representations through the clone lifecycle - #7929

Merged
StafaH merged 4 commits into
isaac-sim:developfrom
ooctipus:refactor/pr4b-consumer-lifecycle
Sep 22, 2026
Merged

StafaH merged 4 commits into
isaac-sim:developfrom
ooctipus:refactor/pr4b-consumer-lifecycle

Conversation

@ooctipus

@ooctipus ooctipus commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Follow-up to #7899 (4A). This is the clone-lifecycle step, not the SDP transport cutover.

The intended order is:

Construct consumers from cfg → build one clone plan → clone representations
                            → allocate native models → initialize consumer bindings

Before and after

The snippets below are shortened excerpts. Unrelated bookkeeping and arguments are omitted; they illustrate the lifecycle, not complete standalone programs.

1. Construct consumers before cloning; initialize them afterward

Before: visualizers were constructed when they were initialized, too late for their constructors to participate in clone planning.

# Construction and binding happened together during visualizer initialization.
visualizer = cfg.class_type(cfg)
visualizer.initialize(self._scene_data_provider)

After: construct the configured consumers early, then bind the same objects to the completed scene later.

# Before cloning: record what each viewer needs and construct it from cfg.
for cfg in self._resolve_visualizer_cfgs():
    self._render_context.clone_contexts.update(cfg.cloning_contexts)
    self._pending_visualizers.append(cfg.class_type(cfg))

# Once cloned native resources are available: bind the objects we already constructed.
for visualizer in tuple(self._pending_visualizers):
    visualizer.initialize(self._scene_data_provider)
    self._pending_visualizers.remove(visualizer)
    self._visualizers.append(visualizer)

Camera renderers also register during cfg processing, before the plan is built:

# A camera's renderer must declare its requirements before we clone its scene.
for cfg in asset_cfgs:
    if isinstance(cfg, CameraCfg):
        sim.get_or_create_backend(cfg.renderer_cfg)

Renderer acquisition now uses the same cfg-based registry as native resources:

# Before: a renderer-specific factory and cache, separate from native ownership.
renderer = sim.render_context.get_renderer(renderer_cfg)

# After: one simulation-owned registry constructs cfg.class_type(cfg) on a miss.
renderer = sim.get_or_create_backend(renderer_cfg)

RenderContext reads renderer entries from that registry and coordinates initialization,
stage preparation, and updates. It neither caches nor closes renderer instances. Shutdown
releases camera data, material writers, renderer bindings, visualizers, then native resources;
it does not rely on registration order to determine dependencies.

2. Declare required representations in cfg and route them through the same plan

Before: InteractiveScene inferred stage/model requirements from renderer and viewer type names after the sensors existed.

# These flags describe what is needed, but do not route asset rows to clone contexts.
for type_name in requested_viz_types.union(cam_types):
    requires_stage, requires_model = REQUIRES_STAGE_AND_MODEL[type_name]
    self.sim.requires_usd_stage |= requires_stage
    self.sim.requires_newton_model |= requires_model

After: renderer and visualizer cfgs explicitly declare the contexts that build their representations.

class NewtonWarpRendererCfg(RendererCfg):
    # This camera renderer needs a Newton representation of the declared scene.
    cloning_contexts = ("isaaclab_newton.cloner:NewtonReplicateContext",)


class NewtonVisualizerCfg(VisualizerCfg):
    # The viewer requests the same context, not a separate cloning pass.
    cloning_contexts = ("isaaclab_newton.cloner:NewtonReplicateContext",)
# Renderer registration collects the declared requirements before planning.
self.clone_contexts.update(cfg.cloning_contexts)

# The planner routes asset rows to those contexts alongside per-asset overrides.
# Dispatch then gives every participating context the same plan (simplified).
for context_type in plan.context_rows:
    sim.clone_contexts[context_type].replicate(plan)

When Newton is already the physics context, its renderer/viewer requirement uses that same context. There is no separate rendering clone lifecycle. Existing stage/model flags are not all removed by this PR.

3. Build the Newton representation during cloning, not from a getter

Before: asking for the Newton model could build it by discovering and importing the completed USD stage, when another backend supplied physics.

@classmethod
def get_model(cls):
    # A read could trigger scene discovery and native-model construction.
    cls._ensure_visualization_model()
    return None if cls.backend is None else cls.backend.model

After: physics and render-only Newton representations use the same import-and-replicate function. The plan supplies the routed prototypes and shared roots. Newton physics keeps its solver-specific defaults, sites, and hooks; foreign-physics rendering imports geometry without a Newton solver. There is no separate visualization-builder module.

# Both physics and rendering enter this same construction path.
return _replicate_newton(
    self._sim.stage, plan, plan.context_rows[type(self)], self._sim, up_axis=self.up_axis
)
# Inside the shared path: choose physics defaults or a plain geometry builder.
create_builder = partial(manager_cls.create_builder if simulation else ModelBuilder, up_axis=up_axis)

# Import each prototype once, then expand the same clone mapping in either mode.
source_builders = build_source_builders(stage, sources, create_builder, schema_resolvers, ...)
replicate_builder_mapping(...)  # Uses the plan's routed mask, positions, env IDs, and destinations.

# For foreign physics, allocate the resulting model only after physics is ready.
backend_cfg = NewtonBackendCfg(
    builder=builder, device=sim.device, num_envs=len(plan.env_ids), simulation=False
)
sim.physics_manager.register_callback(
    partial(NewtonManager._initialize_visualization_model, backend_cfg, geometry),
    PhysicsEvent.PHYSICS_READY,
    name="newton_visualization_model",
    wrap_weak_ref=False,
)
# Inside that readiness callback: use the native-resource registry introduced in 4A.
NewtonManager.backend = sim.get_or_create_backend(cfg)


@classmethod
def get_model(cls):
    # Reading the model no longer constructs anything or scans the stage.
    return None if cls.backend is None else cls.backend.model

This removes late full-stage reconstruction from this rendering path. It does not eliminate every geometry scan: deformable metadata is still inspected within the declared source/shared roots.

4. Make standalone demos declare what belongs to their scene

Before: standalone demos could author geometry without a plan, relying on a Newton-backed viewer to discover it later.

scene_entities, scene_origins = design_scene()
sim.reset()  # A viewer could reconstruct its representation from the finished stage.

After: the quadruped demo declares its roots before authoring and asks the clone lifecycle to build the required representations before reset.

# This demo authors independent roots, so it uses a global-only plan.
global_paths = (
    "/World/defaultGroundPlane", "/World/Light",
    *(f"/World/Origin{i}" for i in range(1, 8)),
)
plan = cloner.make_clone_plan((), 1, 0.0, global_paths=global_paths)
sim.set_clone_plan(plan)

# Author the declared scene, then build its rendering representations.
scene_entities, scene_origins = design_scene()
cloner.replicate(plan, replicate_physics=False)  # Keep the existing native physics setup.
sim.reset()

The same minimal migration covers the affected standalone demos and URDF/MJCF previews. InteractiveScene handles the ordering automatically; its callers do not need this explicit ceremony.

Scope and size

No new production classes or files. Production −274 LOC, tests −99 LOC against develop eaab09fd0 after the conflict-resolution merge. The builder-consolidation follow-up alone removed 122 production lines, including visualization_builder.py and two redundant helper layers. The renderer-registry follow-up removed another 21 production lines and 93 test lines while adding teardown-order and registration regressions. Config-keyed sharing now also owns renderer instances; supported native-model sharing cases are unchanged. Independently configured Newton models, singleton query routing, and SDP conversion/copy changes remain outside this PR. Performance samples below retain their explicitly pinned historical baselines; they were not rerun for this merge.

Initial develop comparison

Baseline: merged develop c90c3a1097a0a669a823b880b1c8d0654d7fd267. GPU 0, RTX 5090, Isaac-Lift-KukaAllegro-Camera, 4096 environments, seed 0, no interactive visualizer. One warm sample each, same installed dependencies/cache and resolved workload configuration. Startup includes imports, construction, reset, and first step. Runtime discards 25 steps, then measures 200 synchronized full environment steps, including actions, camera observations, and episode resets.

Physics → renderer Startup 4B / develop Runtime ms/step 4B / develop Environment FPS 4B / develop
Newton MJWarp → Newton 28.34 / 28.33 s 46.31 / 45.94 88,457 / 89,159
OVPhysX → Newton 62.94 / 62.95 s 163.02 / 160.83 25,126 / 25,468

These samples preceded the builder-consolidation follow-up. Startup was effectively unchanged; runtime was 0.8% and 1.4% slower respectively, which a single pair cannot establish as significant. This measures incremental 4B, not the later full-refactor optimization stack. All 4096 camera outputs were finite and nonconstant. The separate follow-up check below compares consolidation against its immediate parent; do not combine timings across the two sessions.

Builder-consolidation follow-up check

GPU 0, same 4096-environment workload, seed, dependencies, _isaac_sim launcher, 25 discarded steps and 200 measured steps. One warm sample per revision/path. Before is this PR's previous head 2f75d462a8; after is the consolidated pipeline committed as b39adbd4d. Resolved configurations were byte-identical. Earlier temporary-worktree measurements without the matching Isaac Sim launcher were discarded.

Physics → renderer Startup after / before Runtime ms/step after / before Environment FPS after / before
Newton MJWarp → Newton 28.73 / 29.02 s 50.32 / 48.14 81,395 / 85,090
OVPhysX → Newton 68.33 / 65.56 s 174.20 / 163.59 23,513 / 25,038

These are not a demonstrated no-regression result: startup changed −1.0% / +4.2% and runtime +4.5% / +6.5%. There was no competing GPU 0 compute job, but host CPU activity was not isolated. One pair cannot establish whether those differences are repeatable. This follow-up changes construction only, not the stepping/render transport loop. All 4096 camera outputs passed the finite/nonconstant checks.

Validation

  • Conflict resolution against develop eaab09fd0: preserved upstream MPM particle-range tracking in the shared clone path. 114 focused tests plus four subtests passed, including GPU 0 MPM initialization/reset and OVRTX cleanup checks. Formatting/changelog validation passed against the updated base.
  • Renderer-registry follow-up: 163 focused CPU tests and 11 profiler-target checks passed. Five regression cases failed when the prior registry methods were substituted: pre-construction global-setting validation and renderer-before-native teardown in both creation orders, with and without cleanup failures.
  • Builder-consolidation follow-up: 172 focused CPU tests (plus four subtests) and four solver-specific import cases passed, covering cloning, source geometry, renderer registration, visualizer lifecycle, native ownership, and SDP copy/remap behavior.
  • Regression checks failed on the pre-consolidation commit and passed here: omitted clone positions and excluded deformable rows beneath an overlapping shared root. Public direct replication kept its signature.
  • Standalone script contract checks passed (launch matrix not run in full).
  • GPU 0: Newton/OVPhysX → Newton camera smokes; OVPhysX → OVRTX camera smoke; OVPhysX camera + headless Newton GL shared one native model across an ordinary reset; migrated Isaac PhysX marker and OVPhysX deformable demos reached readiness and stepped.
  • After registry consolidation, repeated 16-environment GPU 0 Kuka camera checks for Newton → Newton, OVPhysX → OVRTX, and OVPhysX → Newton camera + headless Newton GL. All passed, including valid images, model sharing/reset, and teardown. These are correctness smokes, not new matched performance samples.
  • uv run --no-sync isaaclab -f passed, with changelog validation pinned to the actual upstream baseline. After registry consolidation, the full isolated documentation build (uv run --no-sync isaaclab -d, using the branch's docs-enabled dev extra) passed with warnings treated as errors.

The pre-existing forced native-rewarm issue, where some consumers retain old model bindings after STOP/recreation, is not claimed fixed here. Ordinary reset and first initialization are covered.

Type of change

  • Refactor and lifecycle correction.
  • Breaking behavior for external standalone foreign-physics rendering workflows that never declared a plan: declare source/shared roots before cloning. Maintained affected demos are migrated; the cloning guide includes the standalone pattern.
  • Removed RenderContext.get_renderer: use sim.get_or_create_backend(renderer_cfg). Use sim.render_context for orchestration; its constructor now takes the shared registry.

Release backport

  • Backport this pull request to the active release branch after it merges into develop

Checklist

  • Contribution guidelines read.
  • Pre-commit checks passed.
  • Documentation and per-package changelog fragments updated.
  • Focused tests and GPU smoke checks completed.
  • Contributor already listed.

@ooctipus
ooctipus requested a review from a team September 21, 2026 05:05
@github-actions github-actions Bot added documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team labels Sep 21, 2026
@ooctipus

Copy link
Copy Markdown
Collaborator Author

run-ci

@isaaclab-bot isaaclab-bot Bot added ci:run-docker Trigger the on-demand Docker and GPU CI workflow and removed ci:run-docker Trigger the on-demand Docker and GPU CI workflow labels Sep 21, 2026
@greptile-apps

greptile-apps Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 3/5

The PR is not yet safe to merge because failed visualizer construction can poison the global simulation context and Newton deformables can bypass per-context row routing.

Findings

  1. P1 Singleton remains partially initialized ▶
  2. P1 Deformables bypass row routing ▶

Summary

This PR moves renderer and visualizer representation construction into the clone lifecycle, routes those consumers through the shared clone plan, and allocates foreign-physics Newton models at physics readiness.

  • Adds declarative clone-context requirements to renderer and visualizer configurations.
  • Builds Newton visualization geometry from routed prototypes and declared shared roots.
  • Migrates maintained standalone demos and converter previews to explicit global-only plans.
  • Two lifecycle/routing defects remain: failed consumer construction can poison the simulation singleton, and deformable expansion can bypass routed-row filtering.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  C[Renderer and visualizer configs] --> R[Register clone contexts]
  A[Asset configs and shared roots] --> P[Build ClonePlan]
  R --> P
  P --> D[Dispatch routed clone contexts]
  D --> N[Build Newton representation]
  D --> U[Build USD representation]
  N --> Q[PHYSICS_READY]
  Q --> M[Allocate native render model]
  M --> I[Initialize renderers, sensors, and visualizers]
Loading

Reviews (1) · Last reviewed commit: "Build rendering representations in the s..."

Comment on lines +249 to +250
type(self)._instance = self
self._create_visualizers()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Singleton remains partially initialized

If visualizer resolution or construction raises, _instance has already been published. Later SimulationContext(...) calls return that partial object and skip initialization, so the process cannot retry without explicitly clearing the singleton. Publish the instance only after successful construction, or roll it back and clean up when construction fails.

env_ids=plan.env_ids,
)
return builder, (shadow_entities, registry_groups)
return builder, add_shadow_deformables_to_builder(builder, stage, entries, plan, device=device)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Deformables bypass row routing

Ordinary source geometry is restricted to rows, but this call passes the complete plan to deformable expansion. When a shared root contains a deformable under a source excluded from the Newton context, discovery still includes it and expansion clones it using that excluded row. The Newton model therefore renders geometry that the per-asset context routing explicitly omitted. Pass the routed rows or an equivalent routed sub-plan into deformable expansion.

@isaaclab-review-bot isaaclab-review-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isaac Lab Review Bot

The clone-plan routing and PHYSICS_READY allocation paths are internally consistent, but the visualizer lifecycle changes an established failure-handling contract and the isaaclab changelog does not disclose that change or the expanded behavior of replicate_physics=False.

  • Design and architecture: Constructing visualizers before cloning enables their representation requirements to participate in the shared clone plan. However, the new lifecycle removes the prior graceful-degradation boundary: construction or initialization failures from implicitly resolved, configured, or XR-injected visualizers now abort SimulationContext construction or reset.
  • API: replicate(plan, replicate_physics=False) now dispatches all non-active-physics contexts rather than only USD replication, and non-explicit visualizer failures now propagate instead of being logged and skipped. These user-visible contract changes require an isaaclab changelog Changed section with appropriate migration guidance.
  • Implementation: The plan-derived renderer routing, Newton representation construction, and pending-visualizer teardown paths are coherent. The concrete issue is that _create_visualizers and _initialize_visualizers invoke construction and initialization without preserving the previous explicit-versus-implicit exception policy, causing optional visualizer failures to terminate startup.

Minor fixes needed. Posted 2 actionable findings inline.

Automated review; human maintainers own approval decisions.

Added
^^^^^

* Added declarative ``cloning_contexts`` to renderer and visualizer configurations and routed their representations

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Api — Changelog omits changed isaaclab behaviors

The fragment lists only additions, but this diff changes user-visible isaaclab behavior: replicate(plan, replicate_physics=False) now dispatches every non-physics clone context instead of only UsdReplicateContext, and visualizer failures are no longer logged and skipped. Repository rules require past-tense entries with migration guidance for changed behavior and clear marking of breaks. Add a Changed section covering both.

self.requires_usd_stage |= requires_stage
self.requires_newton_model |= requires_model
self._render_context.clone_contexts.update(cfg.cloning_contexts)
self._pending_visualizers.append(cfg.class_type(cfg))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Warning · Api — Optional visualizer failures now abort startup

Construction and initialization failures now propagate for every resolved visualizer. The replaced code raised only when the type was explicitly requested on the CLI and otherwise logged and skipped, so cfg-supplied and XR auto-injected visualizers degraded gracefully. An unavailable optional backend now aborts SimulationContext.__init__ or reset() for callers that previously ran. Preserve the explicit-versus-implicit error boundary, or document the break with migration guidance.

renderer_type: str = "ovrtx"
"""Type identifier for OVRTX renderer."""

cloning_contexts: tuple[type | str, ...] = ("isaaclab_newton.cloner:NewtonReplicateContext",)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ovrtx uses newton replicate context?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is be gone in 4c

cfg = self._sim.cfg.physics
load_visual_shapes = cfg.load_visual_shapes if isinstance(cfg, NewtonCfg) else None
if not isinstance(cfg, NewtonCfg):
builder, geometry = build_visualization_builder_from_plan(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought we are not doing visualization builder anymore (and just keeping one builder for newton)?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consolidated in b39adbd. Physics and render-only Newton construction now share one plan-driven import/replication path; visualization_builder.py and the forwarding helper are removed. Physics retains solver-specific defaults, sites, and hooks; render-only models retain compact collision-filter storage and PHYSICS_READY allocation. This follow-up removes 122 production lines. Focused tests and GPU camera/viewer sharing checks passed; the description includes the measured startup/runtime results and their limitations.


cfgs = tuple(cfgs)
global_paths = _minimal_roots(global_paths)
sim = sim_utils.SimulationContext.instance()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder if we should pass sim as a argument (so that we can begin to think of sim as not a singleton global). This will help in future when the singleton is removed?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I want to do a single pr that remove the singelton, but not today!

@StafaH StafaH left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some AI review comments as well

type(self)._instance = self # Mark as valid singleton only after successful init
# Publish the context before configured consumers register their clone requirements.
type(self)._instance = self
self._create_visualizers()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major: Roll back the singleton when pre-clone consumer construction fails

_instance is published immediately before _create_visualizers(), and that method can now import and construct optional backends. If any constructor raises, SimulationContext(...) fails but SimulationContext.instance() retains the partial object; subsequent construction cannot retry (and current develop now explicitly raises whenever an instance already exists). Construct into temporary state and publish only after success, or wrap this phase in rollback that closes created consumers/resources and clears _instance. Add a regression test that fails one visualizer constructor, verifies instance() is None, and then successfully constructs a replacement context.

self.requires_usd_stage |= requires_stage
self.requires_newton_model |= requires_model
self._render_context.clone_contexts.update(cfg.cloning_contexts)
self._pending_visualizers.append(cfg.class_type(cfg))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major: Preserve an explicit required-versus-optional visualizer failure policy

Construction and later initialization now propagate for every resolved visualizer. Previously only an explicitly CLI-requested visualizer was fatal; configured defaults and XR auto-injection logged and degraded gracefully. An unavailable optional backend can therefore abort SimulationContext.__init__() or reset(), and the new changelog does not disclose this compatibility change. Define required/optional semantics explicitly (at minimum keep XR auto-injection best-effort), preserve the old boundary or document the break with migration guidance, and wrap failures with the visualizer type plus install hint.

env_ids=plan.env_ids,
)
return builder, (shadow_entities, registry_groups)
return builder, add_shadow_deformables_to_builder(builder, stage, entries, plan, device=device)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major: Restrict deformable expansion to the rows routed to this context

Rigid geometry uses rows, but deformable expansion receives the complete plan. This is observable when a declared global root contains clone sources (an overlap this PR's own builder test supports): discovery sees a deformable under a source excluded from the Newton context, then _expand_clone_plan_deformable_entries() walks every plan row and clones it anyway. The resulting render model violates context_rows. Pass a routed sub-plan/row set through deformable grouping and expansion, and add an overlap test with one included and one excluded source row.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b39adbd: routed rows now reach deformable expansion. The overlapping-global-root regression excludes the unselected source and passes here; it fails against the previous head.

mapping=mapping,
positions=positions,
mapping=plan.clone_mask[list(rows)],
positions=plan.positions,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major: Honor the optional ClonePlan.positions contract

ClonePlan.positions is public and optional, and the other clone contexts accept None; however this new path forwards None to replicate_builder_mapping(), which immediately calls positions.astype(...). Deformable expansion also indexes clone_plan.positions. A valid hand-built plan therefore crashes only when a foreign-physics Newton renderer/visualizer is selected. Normalize missing positions to a zero array (as Newton physics replication already does), or make positions required for all executable plans and validate that consistently at dispatch with a clear error.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in b39adbd without changing the public optional-positions contract. The shared construction path normalizes missing positions, and shadow deformables use zero offsets. Existing clone and deformable tests now cover None; the previous head fails the full-context regression.

}
for context_type in render_contexts:
if context_type not in sim.clone_contexts:
sim.clone_contexts[context_type] = context_type(sim)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major: Define one clone-context factory contract before exposing it in configs

The new public RendererCfg.cloning_contexts / VisualizerCfg.cloning_contexts accepts arbitrary context classes, but missing contexts are instantiated as context_type(sim). Existing built-ins do not share that contract: Newton and OvPhysX take a SimulationContext, while USD and PhysX take a stage. For example, a renderer that declares PhysxReplicateContext under another physics backend fails inside its constructor with the wrong object. Route creation through an explicit simulation-owned registry/factory (or standardize every context constructor) and document/type the protocol; do not infer construction from a raw class reference.

raise RuntimeError("Renderers must be registered before rendering consumers are finalized.")
new_renderer = cfg.class_type(cfg)
self._renderer_entries.append((cfg, new_renderer))
self.clone_contexts.update(cfg.cloning_contexts)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor: Reject representation requirements registered after the plan is frozen

get_renderer() continues to accept a new renderer and mutate clone_contexts after SimulationContext already owns a ClonePlan. That renderer's context is absent from plan.context_rows, so it is never replicated; with lazy Newton model construction removed, users get a missing/stale model failure much later during camera initialization or rendering. Freeze representation registration when the plan is built and raise an actionable error here when a newly requested context is not present (for example: register this camera/renderer before cloning).

@ooctipus

Copy link
Copy Markdown
Collaborator Author

run-ci

@isaaclab-bot isaaclab-bot Bot added ci:run-docker Trigger the on-demand Docker and GPU CI workflow and removed ci:run-docker Trigger the on-demand Docker and GPU CI workflow labels Sep 21, 2026
@ooctipus
ooctipus requested a review from r-schmitt as a code owner September 21, 2026 23:54
@ooctipus

Copy link
Copy Markdown
Collaborator Author

run-ci

@isaaclab-bot isaaclab-bot Bot added the ci:run-docker Trigger the on-demand Docker and GPU CI workflow label Sep 21, 2026
@isaaclab-bot isaaclab-bot Bot removed the ci:run-docker Trigger the on-demand Docker and GPU CI workflow label Sep 21, 2026
@ooctipus

Copy link
Copy Markdown
Collaborator Author

run-ci

@isaaclab-bot isaaclab-bot Bot added ci:run-docker Trigger the on-demand Docker and GPU CI workflow and removed ci:run-docker Trigger the on-demand Docker and GPU CI workflow labels Sep 22, 2026
@StafaH
StafaH merged commit 335a87b into isaac-sim:develop Sep 22, 2026
52 of 53 checks passed
@isaaclab-bot

isaaclab-bot Bot commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Backported to release/3.0.0 as b3eb75c.

isaaclab-bot Bot pushed a commit that referenced this pull request Sep 22, 2026
…7929)

# Description

Follow-up to #7899 (4A). This is the clone-lifecycle step, not the SDP
transport cutover.

The intended order is:

```text
Construct consumers from cfg → build one clone plan → clone representations
                            → allocate native models → initialize consumer bindings
```

## Before and after

The snippets below are shortened excerpts. Unrelated bookkeeping and
arguments are omitted; they illustrate the lifecycle, not complete
standalone programs.

### 1. Construct consumers before cloning; initialize them afterward

**Before:** visualizers were constructed when they were initialized, too
late for their constructors to participate in clone planning.

```python
# Construction and binding happened together during visualizer initialization.
visualizer = cfg.class_type(cfg)
visualizer.initialize(self._scene_data_provider)
```

**After:** construct the configured consumers early, then bind the same
objects to the completed scene later.

```python
# Before cloning: record what each viewer needs and construct it from cfg.
for cfg in self._resolve_visualizer_cfgs():
    self._render_context.clone_contexts.update(cfg.cloning_contexts)
    self._pending_visualizers.append(cfg.class_type(cfg))

# Once cloned native resources are available: bind the objects we already constructed.
for visualizer in tuple(self._pending_visualizers):
    visualizer.initialize(self._scene_data_provider)
    self._pending_visualizers.remove(visualizer)
    self._visualizers.append(visualizer)
```

Camera renderers also register during cfg processing, before the plan is
built:

```python
# A camera's renderer must declare its requirements before we clone its scene.
for cfg in asset_cfgs:
    if isinstance(cfg, CameraCfg):
        sim.get_or_create_backend(cfg.renderer_cfg)
```

Renderer acquisition now uses the same cfg-based registry as native
resources:

```python
# Before: a renderer-specific factory and cache, separate from native ownership.
renderer = sim.render_context.get_renderer(renderer_cfg)

# After: one simulation-owned registry constructs cfg.class_type(cfg) on a miss.
renderer = sim.get_or_create_backend(renderer_cfg)
```

`RenderContext` reads renderer entries from that registry and
coordinates initialization,
stage preparation, and updates. It neither caches nor closes renderer
instances. Shutdown
releases camera data, material writers, renderer bindings, visualizers,
then native resources;
it does not rely on registration order to determine dependencies.

### 2. Declare required representations in cfg and route them through
the same plan

**Before:** `InteractiveScene` inferred stage/model requirements from
renderer and viewer type names after the sensors existed.

```python
# These flags describe what is needed, but do not route asset rows to clone contexts.
for type_name in requested_viz_types.union(cam_types):
    requires_stage, requires_model = REQUIRES_STAGE_AND_MODEL[type_name]
    self.sim.requires_usd_stage |= requires_stage
    self.sim.requires_newton_model |= requires_model
```

**After:** renderer and visualizer cfgs explicitly declare the contexts
that build their representations.

```python
class NewtonWarpRendererCfg(RendererCfg):
    # This camera renderer needs a Newton representation of the declared scene.
    cloning_contexts = ("isaaclab_newton.cloner:NewtonReplicateContext",)


class NewtonVisualizerCfg(VisualizerCfg):
    # The viewer requests the same context, not a separate cloning pass.
    cloning_contexts = ("isaaclab_newton.cloner:NewtonReplicateContext",)
```

```python
# Renderer registration collects the declared requirements before planning.
self.clone_contexts.update(cfg.cloning_contexts)

# The planner routes asset rows to those contexts alongside per-asset overrides.
# Dispatch then gives every participating context the same plan (simplified).
for context_type in plan.context_rows:
    sim.clone_contexts[context_type].replicate(plan)
```

When Newton is already the physics context, its renderer/viewer
requirement uses that same context. There is no separate rendering clone
lifecycle. Existing stage/model flags are not all removed by this PR.

### 3. Build the Newton representation during cloning, not from a getter

**Before:** asking for the Newton model could build it by discovering
and importing the completed USD stage, when another backend supplied
physics.

```python
@classmethod
def get_model(cls):
    # A read could trigger scene discovery and native-model construction.
    cls._ensure_visualization_model()
    return None if cls.backend is None else cls.backend.model
```

**After:** physics and render-only Newton representations use the same
import-and-replicate function. The plan supplies the routed prototypes
and shared roots. Newton physics keeps its solver-specific defaults,
sites, and hooks; foreign-physics rendering imports geometry without a
Newton solver. There is no separate visualization-builder module.

```python
# Both physics and rendering enter this same construction path.
return _replicate_newton(
    self._sim.stage, plan, plan.context_rows[type(self)], self._sim, up_axis=self.up_axis
)
```

```python
# Inside the shared path: choose physics defaults or a plain geometry builder.
create_builder = partial(manager_cls.create_builder if simulation else ModelBuilder, up_axis=up_axis)

# Import each prototype once, then expand the same clone mapping in either mode.
source_builders = build_source_builders(stage, sources, create_builder, schema_resolvers, ...)
replicate_builder_mapping(...)  # Uses the plan's routed mask, positions, env IDs, and destinations.

# For foreign physics, allocate the resulting model only after physics is ready.
backend_cfg = NewtonBackendCfg(
    builder=builder, device=sim.device, num_envs=len(plan.env_ids), simulation=False
)
sim.physics_manager.register_callback(
    partial(NewtonManager._initialize_visualization_model, backend_cfg, geometry),
    PhysicsEvent.PHYSICS_READY,
    name="newton_visualization_model",
    wrap_weak_ref=False,
)
```

```python
# Inside that readiness callback: use the native-resource registry introduced in 4A.
NewtonManager.backend = sim.get_or_create_backend(cfg)


@classmethod
def get_model(cls):
    # Reading the model no longer constructs anything or scans the stage.
    return None if cls.backend is None else cls.backend.model
```

This removes late full-stage reconstruction from this rendering path. It
does **not** eliminate every geometry scan: deformable metadata is still
inspected within the declared source/shared roots.

### 4. Make standalone demos declare what belongs to their scene

**Before:** standalone demos could author geometry without a plan,
relying on a Newton-backed viewer to discover it later.

```python
scene_entities, scene_origins = design_scene()
sim.reset()  # A viewer could reconstruct its representation from the finished stage.
```

**After:** the quadruped demo declares its roots before authoring and
asks the clone lifecycle to build the required representations before
reset.

```python
# This demo authors independent roots, so it uses a global-only plan.
global_paths = (
    "/World/defaultGroundPlane", "/World/Light",
    *(f"/World/Origin{i}" for i in range(1, 8)),
)
plan = cloner.make_clone_plan((), 1, 0.0, global_paths=global_paths)
sim.set_clone_plan(plan)

# Author the declared scene, then build its rendering representations.
scene_entities, scene_origins = design_scene()
cloner.replicate(plan, replicate_physics=False)  # Keep the existing native physics setup.
sim.reset()
```

The same minimal migration covers the affected standalone demos and
URDF/MJCF previews. `InteractiveScene` handles the ordering
automatically; its callers do not need this explicit ceremony.

## Scope and size

No new production classes or files. Production **−274 LOC**, tests **−99
LOC** against develop `eaab09fd0` after the conflict-resolution merge.
The builder-consolidation follow-up alone removed **122 production
lines**, including `visualization_builder.py` and two redundant helper
layers. The renderer-registry follow-up removed another **21 production
lines** and **93 test lines** while adding teardown-order and
registration regressions. Config-keyed sharing now also owns renderer
instances; supported native-model sharing cases are unchanged.
Independently configured Newton models, singleton query routing, and SDP
conversion/copy changes remain outside this PR. Performance samples
below retain their explicitly pinned historical baselines; they were not
rerun for this merge.

## Initial develop comparison

Baseline: merged develop `c90c3a1097a0a669a823b880b1c8d0654d7fd267`. GPU
0, RTX 5090, `Isaac-Lift-KukaAllegro-Camera`, 4096 environments, seed 0,
no interactive visualizer. One warm sample each, same installed
dependencies/cache and resolved workload configuration. Startup includes
imports, construction, reset, and first step. Runtime discards 25 steps,
then measures 200 synchronized full environment steps, including
actions, camera observations, and episode resets.

| Physics → renderer | Startup 4B / develop | Runtime ms/step 4B /
develop | Environment FPS 4B / develop |
| --- | ---: | ---: | ---: |
| Newton MJWarp → Newton | 28.34 / 28.33 s | 46.31 / 45.94 | 88,457 /
89,159 |
| OVPhysX → Newton | 62.94 / 62.95 s | 163.02 / 160.83 | 25,126 / 25,468
|

These samples preceded the builder-consolidation follow-up. Startup was
effectively unchanged; runtime was 0.8% and 1.4% slower respectively,
which a single pair cannot establish as significant. This measures
incremental 4B, not the later full-refactor optimization stack. All 4096
camera outputs were finite and nonconstant. The separate follow-up check
below compares consolidation against its immediate parent; do not
combine timings across the two sessions.

### Builder-consolidation follow-up check

GPU 0, same 4096-environment workload, seed, dependencies, `_isaac_sim`
launcher, 25 discarded steps and 200 measured steps. One warm sample per
revision/path. Before is this PR's previous head `2f75d462a8`; after is
the consolidated pipeline committed as `b39adbd4d`. Resolved
configurations were byte-identical. Earlier temporary-worktree
measurements without the matching Isaac Sim launcher were discarded.

| Physics → renderer | Startup after / before | Runtime ms/step after /
before | Environment FPS after / before |
| --- | ---: | ---: | ---: |
| Newton MJWarp → Newton | 28.73 / 29.02 s | 50.32 / 48.14 | 81,395 /
85,090 |
| OVPhysX → Newton | 68.33 / 65.56 s | 174.20 / 163.59 | 23,513 / 25,038
|

These are **not a demonstrated no-regression result**: startup changed
−1.0% / +4.2% and runtime +4.5% / +6.5%. There was no competing GPU 0
compute job, but host CPU activity was not isolated. One pair cannot
establish whether those differences are repeatable. This follow-up
changes construction only, not the stepping/render transport loop. All
4096 camera outputs passed the finite/nonconstant checks.

## Validation

- Conflict resolution against develop `eaab09fd0`: preserved upstream
MPM particle-range tracking in the shared clone path. 114 focused tests
plus four subtests passed, including GPU 0 MPM initialization/reset and
OVRTX cleanup checks. Formatting/changelog validation passed against the
updated base.
- Renderer-registry follow-up: 163 focused CPU tests and 11
profiler-target checks passed. Five regression cases failed when the
prior registry methods were substituted: pre-construction global-setting
validation and renderer-before-native teardown in both creation orders,
with and without cleanup failures.
- Builder-consolidation follow-up: 172 focused CPU tests (plus four
subtests) and four solver-specific import cases passed, covering
cloning, source geometry, renderer registration, visualizer lifecycle,
native ownership, and SDP copy/remap behavior.
- Regression checks failed on the pre-consolidation commit and passed
here: omitted clone positions and excluded deformable rows beneath an
overlapping shared root. Public direct replication kept its signature.
- Standalone script contract checks passed (launch matrix not run in
full).
- GPU 0: Newton/OVPhysX → Newton camera smokes; OVPhysX → OVRTX camera
smoke; OVPhysX camera + headless Newton GL shared one native model
across an ordinary reset; migrated Isaac PhysX marker and OVPhysX
deformable demos reached readiness and stepped.
- After registry consolidation, repeated 16-environment GPU 0 Kuka
camera checks for Newton → Newton, OVPhysX → OVRTX, and OVPhysX → Newton
camera + headless Newton GL. All passed, including valid images, model
sharing/reset, and teardown. These are correctness smokes, not new
matched performance samples.
- `uv run --no-sync isaaclab -f` passed, with changelog validation
pinned to the actual upstream baseline. After registry consolidation,
the full isolated documentation build (`uv run --no-sync isaaclab -d`,
using the branch's docs-enabled `dev` extra) passed with warnings
treated as errors.

The pre-existing forced native-rewarm issue, where some consumers retain
old model bindings after STOP/recreation, is not claimed fixed here.
Ordinary reset and first initialization are covered.

## Type of change

- Refactor and lifecycle correction.
- Breaking behavior for external standalone foreign-physics rendering
workflows that never declared a plan: declare source/shared roots before
cloning. Maintained affected demos are migrated; the cloning guide
includes the standalone pattern.
- Removed `RenderContext.get_renderer`: use
`sim.get_or_create_backend(renderer_cfg)`. Use `sim.render_context` for
orchestration; its constructor now takes the shared registry.

## Release backport

- [x] <!-- backport-active-release --> Backport this pull request to the
active release branch after it merges into `develop`

## Checklist

- [x] Contribution guidelines read.
- [x] Pre-commit checks passed.
- [x] Documentation and per-package changelog fragments updated.
- [x] Focused tests and GPU smoke checks completed.
- [x] Contributor already listed.

(cherry picked from commit 335a87b)
ooctipus added a commit that referenced this pull request Sep 24, 2026
…ng docs (#7957)

Backports the three changes from the September 20–23 `develop` audit
that are missing from `release/3.0.0`, alongside the existing
cloning-guide backport:

- #7722 (`4cf439dfeb`): reject a second `SimulationContext` construction
instead of silently discarding its configuration. Includes the original
fixture cleanup and regression coverage.
- #7893 (`22fcd71bc4`): validate DelayBuffer lag values before mutating
its live configuration.
- #7947 (`6e9ef17f59`): make `v3.0.0-EA` the default documentation
version in deployment and local multi-version builds.
- #7129 (`354168560f`): clarify that `replicate_physics=False` skips the
active physics context while other declared replication contexts still
run.

**Compatibility:** repeated `SimulationContext(...)` calls now raise.
Retrieve the live context with `SimulationContext.instance()`, or call
`clear_instance()` before constructing a replacement. The original major
changelog fragment includes this migration.

The runtime and test files match current `develop`. The docs-default
backport adapts the release branch's existing redirect template,
validates the target page, and preserves explicit overrides. The
cloning-guide backport preserves the current release APIs; its obsolete
sections were already removed.

## Release audit

Checked all **35 PRs** merged into `develop` from **2026-09-20 16:43:18
UTC** through `cff81e8473` (September 23), against release head
`5d3e0b695e`. **32 are already covered; the remaining three are included
here.** Git history, patch equivalence, GitHub's merged PR list, and
remaining file differences were checked. Branch-specific
version/changelog compilation and existing release-only changes are
preserved.

<details>
<summary>Already covered PRs</summary>

26 have an equivalent patch in release: #7919, #7922, #7923, #7924,
#7925, #6758, #7928, #7902, #7927, #7891, #7931, #7691, #7861, #7929,
#7916, #7939, #4609, #7942, #7940, #7948, #7937, #7955, #7960, #7961,
#7970, #7958.

Six were squash-merged or adapted: #7530 and #7899 in #7926; #7637 in
#7933; #7860 in #7936; #7954 and #7950 in #7964. Their implementation
differences were checked against the current release tree.

</details>

## Validation

- **276 tests passed**: SimulationContext (51, including CPU/CUDA),
headless context construction (15), nine schema/fragment suites (165),
four manager suites (38), and DelayBuffer (7).
- Both backported regressions reproduce with the original release
implementations.
- Docs redirect recipe: local/deployment EA defaults, explicit override,
and missing-target rejection passed with a stubbed Sphinx builder.
- All 22 changed files match the intended backport scope; `uv run
isaaclab -f` and `git diff --check` passed.
- Fresh Sphinx validation (`-b dummy -W --keep-going`): passed without
warnings, excluding static assets as the HTML builder does. Full HTML
documentation CI is running.

Local runtime validation used PyTorch 2.12.0, CUDA 13.0, Isaac Sim
6.0.1.0, and an RTX 5090. Existing runtime/deprecation warnings
occurred; the CI jobs validate the pinned environments.

The previous [docs CI
failure](https://github.com/isaac-sim/IsaacLab/actions/runs/35795116307/job/106972539281)
was an external connection reset fetching the Omniverse intersphinx
inventory, producing one warning under `-W`. That URL returned HTTP 200
when rechecked. This update starts a fresh docs build.

---------

Co-authored-by: hujc <[email protected]>
Co-authored-by: Zihan Xu <[email protected]>
@ooctipus ooctipus self-assigned this Sep 25, 2026
@ooctipus ooctipus added this to the Isaac Lab 3.0 GA milestone Sep 25, 2026
@ooctipus
ooctipus deleted the refactor/pr4b-consumer-lifecycle branch October 14, 2026 14:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

documentation Improvements or additions to documentation isaac-lab Related to Isaac Lab team

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

2 participants