Skip to content

Refresh PhysX and OVPhysX contact sensor buffers on every physics step - #7614

Merged
kellyguo11 merged 3 commits into
developfrom
antoiner/fix-physx-lazy-contact-loss
Sep 11, 2026
Merged

kellyguo11 merged 3 commits into
developfrom
antoiner/fix-physx-lazy-contact-loss

Conversation

@AntoineRichard

@AntoineRichard AntoineRichard commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

Description

On the PhysX and OVPhysX backends on GPU, a ContactSensor with the default history_length=0 and the default lazy_sensor_update=True kept reporting the last in-contact force after the body had left contact, for as long as the body stayed in the air, whenever its data was read less often than every physics step (for example once per policy step with decimation=4).

Root cause. PhysX zeroes a body's entry in get_net_contact_forces() only on the exact physics step where that body's contact is lost. With history_length=0 the sensor only called the getter when .data was accessed, so a policy-rate reader skipped most contact-lost steps and never saw the zero. The Isaac Lab kernels and the CUDA-graph replay are not involved: the raw getter output, the cached Warp view, and the sensor output agree at every read, and disabling the graph changes nothing. CPU is unaffected. history_length > 0 is unaffected because the base class already refreshes every physics step. The experiment table and a standalone reproduction are in #7613; OVPhysX reproduces identically through its contact binding.

Fix. Both sensors override update() to fetch the physics-owned buffers on every physics step, skipping the fetch when the base class already refreshed on that step (history-bearing sensors, or force_recompute). The Warp kernels that turn the fetched buffers into sensor data still run lazily on data access, so the per-step cost is one getter call, which is exactly what history-bearing sensors already pay. The buffers are refreshed in place, so the cached views and the captured CUDA graph stay valid. On PhysX the outer-graph-capture guard moves into a helper shared by the eager fetch and the buffer update, so a capture is rejected on either path and the existing capture test keeps its "raise before touching PhysX" contract.

Tests. test_lazy_sensor_reports_contact_loss in both the PhysX and OVPhysX contact sensor suites: settle a cube for six policy steps of four physics steps each, reading the sensor once per policy step, then hold it in the air for six more, and require every air read after the first to be below 0.1 N. On the unfixed code it fails on cuda:0 with the force stuck at the resting value for all six reads, and passes on cpu; with the fix it passes on both. The PhysX test_contact_history_updates_at_sensor_period row for history_length=0 asserted the old zero-fetch cadence and was updated to the new one; its history-bearing rows are unchanged.

Exposure. Every shipped velocity task sets history_length=3 and is unaffected. The Kuka Allegro and Franka lift tasks configure fingertip contact sensors with the default history length and feed the force matrix into observations, so on PhysX GPU those observations could hold a stale contact force after a finger released the object.

Found while working on #7283 / #7574.

Fixes #7613

Type of change

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

Release backport

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

Checklist

  • I have read and understood the contribution guidelines
  • I have run the pre-commit checks with ./isaaclab.sh --format
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • I have added a changelog fragment under source/<pkg>/changelog.d/ for every touched package (do not edit CHANGELOG.rst or bump extension.toml — CI handles that)
  • I have added my name to the CONTRIBUTORS.md or my name already exists there

PhysX zeroes the net contact force of a body only on the exact physics
step where its contact is lost. The PhysX and OVPhysX contact sensors
only called their contact getters when their data was accessed unless
the sensor carried a history buffer, so a reader that polls the sensor
once per policy step (the default lazy_sensor_update=True with a
decimation greater than one) skipped the contact-loss step and kept
reporting the last in-contact force until the next touchdown. This only
affects GPU simulation; the CPU pipeline zeroes the entry regardless of
when the getter runs.

Both sensors now refresh the physics-owned buffers on every physics step
from update(), while the warp kernels that turn those buffers into
sensor data still run lazily on data access. The PhysX CUDA graph
capture guard moves into a helper shared by the eager fetch and the
buffer update, so an outer capture is rejected on either path.

Fixes #7613
@AntoineRichard
AntoineRichard requested a review from a team September 7, 2026 08:26
@github-actions github-actions Bot added bug Something isn't working isaac-lab Related to Isaac Lab team labels Sep 7, 2026
@greptile-apps

greptile-apps Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes stale contact forces in lazy, history-less PhysX and OVPhysX contact sensors by refreshing physics-owned contact buffers after every physics step while retaining lazy Warp-kernel computation.

  • Adds backend-specific eager buffer refresh paths.
  • Extends the PhysX outer-CUDA-capture guard to the eager path.
  • Adds GPU/CPU regressions for policy-rate reads after contact loss and updates fetch-cadence expectations.
  • Adds changelog fragments for both affected packages.

Confidence Score: 4/5

The PR appears safe to merge, with a non-blocking opportunity to avoid eager pose reads for lazy sensors.

The contact-loss behavior is covered through the full lazy read path, and no correctness or security failure remains; the only accepted issue is avoidable simulation-rate pose fetching introduced by reusing the full buffer helper.

Files Needing Attention: source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py, source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py

Important Files Changed

Filename Overview
source/isaaclab_physx/isaaclab_physx/sensors/contact_sensor/contact_sensor.py Adds per-step PhysX buffer fetching and applies the CUDA-capture guard to both eager and recompute paths; the full helper also eagerly fetches pose.
source/isaaclab_ov/isaaclab_ov/sensors/contact_sensor/contact_sensor.py Extracts OVPhysX buffer fetching and invokes it every physics step; the full helper unnecessarily includes pose reads.
source/isaaclab_physx/test/sensors/test_contact_sensor.py Updates fetch-cadence assertions and adds a realistic contact-loss regression across CPU and CUDA.
source/isaaclab_ov/test/sensors/test_contact_sensor.py Adds the corresponding OVPhysX contact-loss regression across CPU and CUDA.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  P[Physics step] --> U[ContactSensor.update]
  U --> F[Refresh backend buffers]
  F --> C[Stable cached buffer views]
  D[Later data access] --> B[_update_buffers_impl]
  B --> F
  B --> K[Run lazy Warp kernels]
  C --> K
  K --> O[Sensor data]
Loading

Reviews (1): Last reviewed commit: "Refresh contact sensor buffers on every ..." | Re-trigger Greptile

super().update(dt, force_recompute=force_recompute)
# Skip the read if the base class already refreshed the buffers on this step, which it
# does when the sensor carries a history buffer.
if self._is_initialized and self._data_generation != self._data_generation_last_update:

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 Eager pose reads add overhead

The eager refresh uses the full buffer-fetch helper, so a lazy, history-less sensor with track_pose=True now reads rigid-body transforms on every physics step. Pose data does not have the contact-loss transient addressed here, and _update_buffers_impl reads it again when the sensor data is consumed. This defeats lazy pose sampling and adds avoidable backend and GPU work at simulation rate. The PhysX path has the same behavior. Please limit the per-step refresh to contact-derived buffers and fetch pose only during data recomputation.

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!

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.

Done in 21280d6: the per-step refresh in update() now calls the fetch helper with include_pose=False on both the PhysX and OVPhysX sensors, so poses are only read on data access as before. Measured on an RTX 5090 at 4096 envs x 17 bodies: the pose read is 32 us per physics step, and sensor.update() with track_pose=True went from 73 us to 48 us, matching the no-pose case.

@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 per-step backend-buffer refresh addresses stale contact loss while keeping Warp computation lazy, but the PhysX implementation introduces an undocumented exception path during outer CUDA graph capture.

  • Design and architecture: Refreshing physics-owned buffers in each backend subclass is appropriately scoped, avoids duplicate history-bearing refreshes, and preserves the stable buffers consumed by cached Warp views and the captured compute graph.
  • API: Public signatures and return types remain unchanged. However, ContactSensor.update() for a lazy, history-less PhysX sensor can now raise RuntimeError during outer CUDA graph capture, whereas that call path previously did not access PhysX. This behavior change needs documentation in the public method and PhysX changelog, including guidance to update the sensor outside capture.
  • Implementation: The generation-based condition implements the intended cadence: history-less sensors fetch every physics step while remaining computationally lazy, and history-bearing sensors avoid duplicate fetches. The shared PhysX capture guard correctly runs before tensor reads, and the OVPhysX force, force-matrix, and pose paths retain their existing guards.

Minor fixes needed. Posted 1 actionable finding inline.

Automated review; human maintainers own approval decisions.

# Skip the fetch if the base class already refreshed the buffers on this step, which it
# does when the sensor carries a history buffer.
if self._is_initialized and self._data_generation != self._data_generation_last_update:
self._fetch_physx_buffers()

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.

🔵 Suggestion · Api — New capture rejection for lazy history-less sensors

Previously a history_length=0 lazy sensor never touched PhysX inside update(), so callers could run it under an outer CUDA graph capture and read data afterwards. The added fetch reaches _raise_if_graph_capturing() and now raises RuntimeError on that path. The restriction is inherent to the fix, but it is a user-visible behavior change: document it in the update() docstring and the PhysX changelog fragment with guidance to step the sensor outside capture.

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.

Done in 21280d6: update() now documents the RuntimeError raised under an outer CUDA graph capture, and the PhysX changelog fragment notes that lazy history-less sensors now reject a capture like history-bearing sensors already did, with the guidance to update the sensor outside the capture.

@ClemensSchwarke ClemensSchwarke 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.

Is the overhead of reading the pose every step significant? If so, maybe address the bot comment. Otherwise looks good.

@kellyguo11

Copy link
Copy Markdown
Contributor

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 9, 2026
Only the contact-derived PhysX buffers carry the contact-loss transient
that motivates refreshing them on every physics step. Body poses are
read again on data access anyway, so the per-step refresh in update()
now skips them on both the PhysX and OVPhysX sensors. Document that a
lazy history-less PhysX sensor now raises inside an outer CUDA graph
capture like history-bearing sensors already did.
@AntoineRichard

Copy link
Copy Markdown
Collaborator Author

@ClemensSchwarke Measured it on the RTX 5090 workstation rather than guessing. Short answer: not significant, and the pose read is now out of the per-step path anyway (21280d6).

Micro-timing inside the live env (Isaac-Velocity-Flat-AnymalD, PhysX GPU, 4096 envs x 17 bodies, history_length=0, decimation 4, device-synced, median of 200 calls):

per physics step no pose track_pose=True (061d759) track_pose=True (21280d6)
get_net_contact_forces 26 us 31 us 26 us
get_transforms (pose) n/a 32 us 32 us
full fetch helper (data access) 28 us 51 us 51 us
sensor.update() (added per-step work) 49 us 73 us 48 us
sim.step 3.85 ms 3.89 ms 3.99 ms
env.step (4 physics steps) 16.5 ms 16.7 ms 16.4 ms

So the PR adds four extra fetches per env step: about 0.1 ms, or 0.7% of a 16.5 ms env step, for a history_length=0 sensor. With track_pose=True that was 0.2 ms (1.2%) at 061d759; after 21280d6 the per-step refresh passes include_pose=False on both backends and it is back to 0.1 ms. Poses are still read on data access, as before. track_pose defaults to False and no shipped task enables it.

End-to-end runtime benchmark, same machine, isaaclab benchmark runtime, 1000 steps + 50 warmup, seed 42, physics=isaacsim_physx, base (57cc1cd) vs PR head (061d759), one fresh uv env per worktree, strictly sequential runs with alternating order:

task n per side base FPS PR FPS delta (1 SE)
Flat-AnymalD, shipped (history_length=3) 8 238.0k 239.0k +0.4% +/- 2.3%
Flat-AnymalD, history_length=0 8 241.4k 240.3k -0.5% +/- 1.6%
Flat-AnymalD, history_length=0, track_pose=True 8 242.8k 237.4k -2.2% +/- 1.5%
Rough-AnymalD, shipped (history_length=3) 3 50.1k 48.8k -2.5% +/- 9.9%
Rough-AnymalD, history_length=0 3 47.1k 47.7k +1.3% +/- 3.3%

Every delta is within one standard error of zero. Run-to-run scatter is 3-4% on flat and ~10% on rough, so end-to-end can only bound the effect; the micro-timing above is the actual number. The shipped velocity tasks use history_length=3 and already fetched every step before this PR, so the first row is the expected null result.

The history_length=0 rows are variants of the shipped AnymalD configs registered by a small launcher around isaaclab.benchmark.entrypoints.runtime.run that only overrides scene.contact_forces.history_length / track_pose.

Both bot comments are addressed in 21280d6: pose skipped in the per-step refresh (PhysX and OVPhysX), and the new capture-time RuntimeError for lazy history-less PhysX sensors is documented in the update() docstring and the changelog fragment.

@AntoineRichard

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 10, 2026
@AntoineRichard

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 10, 2026
@marcodiiga

Copy link
Copy Markdown
Collaborator

run-ci

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

@marcodiiga marcodiiga 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.

Reviewed at 2bd5e60. The per-step contact refresh fixes the stale-force regression while preserving sensor output cadence and avoiding duplicate fetches after eager updates. I found no new correctness blocker.

Validation: 14 focused PhysX tests passed, including CPU/GPU contact loss, history cadence, reset, and CUDA-graph behavior. The ovphysx contact-loss regression passed on CPU and GPU. A GPU two-cube release check also cleared both net and filtered forces; restoring the old update cadence reproduced stale forces in both the ground and two-cube cases. The previous Docker CI reports for this same head also show all four new contact-loss cases passing.

Approving with three non-blocking follow-ups inline (one redundant-fetch optimization and two regression-test additions); please address them despite the approval. The fresh Docker CI run is still in progress. The existing Multi-GPU failure occurred during runner setup, before checkout or test execution.

# Skip the fetch if the base class already refreshed the buffers on this step, which it
# does when the sensor carries a history buffer.
if self._is_initialized and self._data_generation != self._data_generation_last_update:
self._fetch_physx_buffers(include_pose=False)

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.

Non-blocking test follow-up: please extend test_contact_sensor_refuses_update_inside_outer_graph_capture to exercise public update(dt) with history_length=0 and force_recompute=False. The existing test calls _update_buffers_impl() and replaces _fetch_physx_buffers(), so it does not protect the new eager path shown here. Keep the real fetch helper and assert that the capture raises before any backend contact getter is called.

for _ in range(decimation):
shape.write_root_pose_to_sim_index(root_pose=root_pose)
_perform_sim_step(sim, scene, sim_dt)
return torch.linalg.norm(sensor.data.net_normal_forces_w.torch, dim=-1).max().item()

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.

Non-blocking test follow-up for both backend suites: this regression has no partner filter and only checks net_normal_forces_w, so it does not verify filtered contact loss. Please extend the contact-loss coverage with a filtered body pair and assert that normal_force_matrix_w also returns to zero when read once per four physics steps, with a nonzero-contact assertion first.

An ovphysx GPU check with two 0.5 m cubes, no terrain, zero gravity, and 0.05 m overlap followed by 10 m separation cleared both outputs with this fix. Restoring the old update cadence left both outputs stuck around 4687 N. This is worth retaining as a regression alongside the ground-contact case.

expected_fetches_after_read = 1 if history_length == 0 else expected_fetches
# A history-less sensor did not recompute during the steps, so the read triggers one
# more fetch; a history-bearing one is already up to date.
expected_fetches_after_read = expected_fetches + 1 if history_length == 0 else expected_fetches

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.

Non-blocking performance follow-up for both backends: the extra fetch asserted here means that a lazy, history-less sensor fetches contacts in update() and fetches them again when .data is read in the same generation. With decimation 1, this doubles contact-buffer retrievals per physics step. Please consider tracking which sensor generation already fetched contacts so data recomputation can reuse them, while still fetching poses lazily and invalidating that state on reset. The existing cadence test can then protect the single-fetch behavior.

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

Labels

bug Something isn't working isaac-lab Related to Isaac Lab team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants