Skip to content

Complete Newton state write boundaries - #6351

Closed
ooctipus wants to merge 2 commits into
isaac-sim:developfrom
ooctipus:zhengyuz/newton-state-boundaries
Closed

ooctipus wants to merge 2 commits into
isaac-sim:developfrom
ooctipus:zhengyuz/newton-state-boundaries

Conversation

@ooctipus

@ooctipus ooctipus commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator

Description

This completes the authored rigid-state boundary contract on top of #6350.

State writers now separate two responsibilities:

  • skip_forward=True preserves the caller-managed asset-cache behavior.
  • The physics write is always published to the shared transaction, so FK and mandatory backend synchronization still happen before the next step or coherent read.

Partial RigidObjectCollection writes preserve their selected body columns when marking articulations, including a no-op fast path for empty selections. Direct consumers of live Newton body state—site frames, PVA, ray-caster site transforms, and joint-wrench conversion—flush pending synchronization before reading.

This PR does not add optional solver reset, particle-state publication, or coupled deformable synchronization.

Depends on #6350. The commit is intentionally isolated so the displayed diff will reduce to this boundary layer once the dependency merges.

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Refactor (non-breaking change)

Testing

  • Foundation + boundary unit suites — 40 passed.
  • Newton site-frame contract suite — 46 passed.
  • PVA and joint-wrench stale-state integrations — 2 passed.
  • Targeted pre-commit hooks, compileall, and git diff --check pass.

Checklist

  • I have read and understood the contribution guidelines
  • I have run the pre-commit checks
  • My changes generate no new warnings
  • I have added tests for the changed behavior
  • I have added a changelog fragment for the touched package
  • My name already exists in CONTRIBUTORS.md

ooctipus added 2 commits July 3, 2026 22:12
Coalesce rigid state writes into a device-backed transaction consumed at step and coherent read boundaries. Keep solver-specific synchronization in backend hooks and preserve CUDA graph replay semantics.
Publish every rigid state write independently of asset cache invalidation, preserve partial collection selection, and flush pending synchronization before direct body-state reads.
@github-actions github-actions Bot added the isaac-lab Related to Isaac Lab team label Jul 4, 2026
@greptile-apps

greptile-apps Bot commented Jul 4, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR completes the Newton authored-state boundary contract: skip_forward=True now preserves the asset-cache invalidation while still publishing the write to a new AuthoredStateTransaction, which is flushed at every coherent read boundary (step, forward, pre_render, and direct sensor/site reads). A companion _cuda_graph.py module extracts the RTX-safe relaxed-graph capture helper, and _authored_state_transaction.py adds the device-backed coalescing transaction with CUDA conditional-graph support.

  • Asset data layer (articulation_data, rigid_object_data, rigid_object_collection_data): _reset_pose/_reset_velocity gain an invalidate_cache parameter; SimulationManager.invalidate_fk is called unconditionally, separating cache staleness from physics notification. RigidObjectCollection additionally forwards partial body_ids as articulation_selection to scope dirtying to modified bodies only.
  • Newton manager: Replaces raw world/FK reset masks and the _eval_fk delegate with AuthoredStateTransaction; introduces _resolve_active_manager, _apply_state_writes, _flush_pending_changes, and _owned_solvers hooks. Kamino removes lazy buffer allocation during graph capture via _register_builder_attributes. MJWarp adds _synchronize_solver_state for sparse-update intervals.
  • Sensors and site views: JointWrenchSensor, Pva, _NewtonRayCasterMixin, and NewtonSiteFrameView all call NewtonManager.forward() before touching live body state, establishing the same coherent read contract as asset property getters.

Confidence Score: 4/5

The change is well-structured and the test coverage is thorough; the two friction points are a private-API call into SolverMuJoCo that could silently break on an upstream release, and Warp-internal field writes that are carried forward from the previous implementation.

The authored-state transaction logic is cleanly isolated, correctly orders flush-before-step, and handles CUDA graph capture and replay properly. The _synchronize_solver_state method in mjwarp_manager.py calls solver._update_mjc_data() — a private method with no public alternative — which could produce a hard-to-diagnose runtime failure on any MuJoCo solver update that renames this helper. The Warp-internal graph.graph / graph.graph_exec patch in _cuda_graph.py is an acknowledged carry-over rather than a new risk.

mjwarp_manager.py (private _update_mjc_data coupling) and _cuda_graph.py (Warp-internal graph field writes) are the two files most worth a second look before merging.

Important Files Changed

Filename Overview
source/isaaclab_newton/isaaclab_newton/physics/_authored_state_transaction.py New file implementing a device-backed coalescing transaction for authored state writes; uses Warp kernels and CUDA conditional graphs. Minor style issue with redundant null-guard conditions after an early return in mark_rigid.
source/isaaclab_newton/isaaclab_newton/physics/_cuda_graph.py Extracts the RTX-compatible relaxed CUDA graph capture helper from newton_manager.py; logic is unchanged but now directly exposes the Warp-internal graph.graph / graph.graph_exec field writes in an isolated, more visible location.
source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py Major refactor replacing per-world reset masks and the _eval_fk_unbound sentinel with AuthoredStateTransaction; introduces _resolve_active_manager, _apply_state_writes, and _flush_pending_changes hooks. Removes the defensive guard that raised on forward() before initialize_solver, but the practical risk is low because state writes cannot occur in that window under normal use.
source/isaaclab_newton/isaaclab_newton/physics/mjwarp_manager.py Adds _state_write_graph_safe, _supports_cuda_graph_capture, and _synchronize_solver_state overrides; validates CPU MuJoCo world count. _synchronize_solver_state calls the private solver._update_mjc_data() method as no public equivalent exists.
source/isaaclab_newton/isaaclab_newton/physics/kamino_manager.py Removes _needs_fk_before_step = True (superseded by the transaction flush in step()); adds _register_builder_attributes so Kamino state buffers are model-owned before finalization rather than lazily allocated during graph capture.
source/isaaclab_newton/isaaclab_newton/assets/articulation/articulation_data.py Adds invalidate_cache parameter to _reset_pose and _reset_velocity; SimulationManager.invalidate_fk is now always called regardless of skip_forward, which is the core behavior change this PR introduces.
source/isaaclab_newton/isaaclab_newton/assets/rigid_object_collection/rigid_object_collection_data.py Adds body_ids and invalidate_cache to _reset_pose/_reset_velocity; partial writes now forward body_ids as articulation_selection to invalidate_fk, enabling selective articulation dirtying.
source/isaaclab_newton/isaaclab_newton/sensors/joint_wrench/joint_wrench_sensor.py Adds NewtonManager.forward() before the kernel launch in _update_buffers_impl so joint-wrench computation sees coherent body state.
source/isaaclab_newton/isaaclab_newton/sim/views/newton_site_frame_view.py Adds NewtonManager.forward() before both get_world_poses and set_world_poses read paths to flush pending authored state before site-frame queries.
source/isaaclab_newton/test/physics/test_newton_state_pipeline.py New comprehensive test suite covering the full authored-state pipeline: transaction flushing, CUDA graph replay, model-change delivery, manager resolution, and ordering guarantees at step/pre_render boundaries.
source/isaaclab_newton/test/physics/test_newton_state_boundaries.py New boundary-contract tests verifying that skip_forward=True preserves asset caches while still publishing FK invalidation, and that sensor reads flush pending state before kernel launch.

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant Asset as Asset (write_*_to_sim)
    participant Data as *Data (_reset_pose/vel)
    participant SimMgr as SimulationManager
    participant AST as AuthoredStateTransaction
    participant NM as NewtonManager
    participant Solver as Solver (Kamino/MJWarp)

    Asset->>Data: "_reset_pose(invalidate_cache=not skip_forward)"
    alt "invalidate_cache=True"
        Data->>Data: "reset_timestamps() + _fk_timestamp=-1"
    end
    Data->>SimMgr: invalidate_fk(env_ids, articulation_ids, articulation_selection)
    SimMgr->>NM: _mark_transforms_dirty()
    SimMgr->>AST: mark_rigid(env_mask/env_ids, articulation_ids, selection)
    AST->>AST: launch _mark_from_mask/_mark_from_ids kernel

    Note over NM,Solver: Coherent read boundary

    alt step()
        NM->>NM: _notify_solver_model_changes()
        NM->>NM: _flush_pending_changes()
    else forward() or sensor read
        NM->>NM: _flush_pending_changes()
    end

    NM->>AST: flush()
    AST->>AST: wp.capture_if(pending, _consume)
    AST->>NM: _apply_state_writes(world_mask, fk_mask)
    NM->>NM: _eval_fk_impl(world_mask, fk_mask)
    NM->>Solver: _synchronize_solver_state(solver, world_mask, fk_mask)
    AST->>AST: zero world_mask, fk_mask, pending
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
sequenceDiagram
    participant Asset as Asset (write_*_to_sim)
    participant Data as *Data (_reset_pose/vel)
    participant SimMgr as SimulationManager
    participant AST as AuthoredStateTransaction
    participant NM as NewtonManager
    participant Solver as Solver (Kamino/MJWarp)

    Asset->>Data: "_reset_pose(invalidate_cache=not skip_forward)"
    alt "invalidate_cache=True"
        Data->>Data: "reset_timestamps() + _fk_timestamp=-1"
    end
    Data->>SimMgr: invalidate_fk(env_ids, articulation_ids, articulation_selection)
    SimMgr->>NM: _mark_transforms_dirty()
    SimMgr->>AST: mark_rigid(env_mask/env_ids, articulation_ids, selection)
    AST->>AST: launch _mark_from_mask/_mark_from_ids kernel

    Note over NM,Solver: Coherent read boundary

    alt step()
        NM->>NM: _notify_solver_model_changes()
        NM->>NM: _flush_pending_changes()
    else forward() or sensor read
        NM->>NM: _flush_pending_changes()
    end

    NM->>AST: flush()
    AST->>AST: wp.capture_if(pending, _consume)
    AST->>NM: _apply_state_writes(world_mask, fk_mask)
    NM->>NM: _eval_fk_impl(world_mask, fk_mask)
    NM->>Solver: _synchronize_solver_state(solver, world_mask, fk_mask)
    AST->>AST: zero world_mask, fk_mask, pending
Loading

Comments Outside Diff (2)

  1. source/isaaclab_newton/isaaclab_newton/physics/mjwarp_manager.py, line 258-261 (link)

    P2 Private API coupling in _synchronize_solver_state

    solver._update_mjc_data(...) is a name-mangled private method. The comment acknowledges this gap in the public API, but if SolverMuJoCo renames or removes this helper (even in a minor release), the call will fail silently at runtime with an AttributeError — and only when update_data_interval != 1, making it hard to catch in normal test runs. It would be worth tracking an upstream request to expose this as a stable, public synchronization hook.

  2. source/isaaclab_newton/isaaclab_newton/physics/_cuda_graph.py, line 372-373 (link)

    P2 Warp internal fields patched directly

    graph.graph = raw_graph and graph.graph_exec = None write to Warp's private Graph representation. This is inherited from the previous newton_manager.py implementation (the TODO comment acknowledges it), but extracting the logic into a dedicated helper file makes the risk more visible: any Warp release that renames or restructures Graph.graph / Graph.graph_exec will silently corrupt the graph handle and produce a hard-to-diagnose crash on the first capture_launch. Worth adding a Warp-version guard or an assertion on the attribute existence so the failure mode is an AttributeError rather than a CUDA error.

Reviews (1): Last reviewed commit: "Complete Newton state write boundaries" | Re-trigger Greptile

Comment on lines +159 to +181
outputs=[self._world_mask, self._fk_mask, self._pending],
device=self._device,
)
elif articulation_ids is not None and env_ids is not None:
selection = self._empty_selection if articulation_selection is None else articulation_selection
wp.launch(
_mark_from_ids,
dim=env_ids.shape[0],
inputs=[env_ids, articulation_ids, selection, int(articulation_selection is not None)],
outputs=[self._world_mask, self._fk_mask, self._pending],
device=self._device,
)
else:
# No selection means every world and articulation.
self._world_mask.fill_(True)
self._fk_mask.fill_(True)
self._pending.fill_(1)

def configure_capture(self, graph_safe: bool, defer: bool = False, enabled: bool = True) -> None:
"""Configure the reusable conditional graph for the active backend."""
self._graph = None
self._graph_safe = graph_safe
self._capture_state = _CaptureState.DISABLED

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Redundant articulation_ids is not None guards after early return

The early return at line 153–157 already handles the articulation_ids is None case. The subsequent if articulation_ids is not None and env_mask is not None / elif articulation_ids is not None and env_ids is not None checks always have articulation_ids is not None as true at that point, making the repeated test a no-op. This can be simplified to if env_mask is not None / elif env_ids is not None to make the branching intent clearer without changing behavior.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@ooctipus

ooctipus commented Jul 4, 2026

Copy link
Copy Markdown
Collaborator Author

Closing this implementation because it depends on the discarded authored-state transaction foundation. The proven NewtonSiteFrameView freshness issue will be handled separately as a minimal boundary fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

isaac-lab Related to Isaac Lab team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant