Skip to content

[Newton] Share one Newton sensor among contact sensors with identical expressions - #8649

Closed
NeoZng wants to merge 3 commits into
isaac-sim:mainfrom
NeoZng:fix/newton-contact-sensor-shared-key
Closed

NeoZng wants to merge 3 commits into
isaac-sim:mainfrom
NeoZng:fix/newton-contact-sensor-shared-key

Conversation

@NeoZng

@NeoZng NeoZng commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Description

On the Newton backend, ContactSensors with identical body and filter expressions all reported zero forces except
the last one created. NewtonManager.add_contact_sensor keyed the Newton SensorContact by these expressions, but
built a new one on every call and replaced the registered entry. Sensors that differ only in settings Isaac Lab
applies itself (update period, history, air time) kept the arrays of the replaced Newton sensor, which was no longer
updated.

  • add_contact_sensor now reuses the registered sensor for an identical request instead of building a new one. Each
    Isaac Lab sensor copies the shared Newton arrays into its own buffers and applies its update period, history and
    air time there, so sharing changes nothing else.
  • A Newton sensor belongs to one model, so a hard reset (a further sim.reset(), which finalizes a new model) now
    drops the registry. The sensors register again on PHYSICS_READY and get a Newton sensor built for the new model.
    Without this, a reused sensor would belong to the old model. The new model would then never request the contact
    force attribute, and the first step after the reset would raise SensorContact requires contact-force solver observables.

Open draft #8218 (Newton manager rewrite) also lets identical requests share one sensor. This is the minimal fix for
the current manager.

Fixes #8648

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

On release/3.0.0 the hard-reset hunk conflicts, because that branch's reset block has no view or callback cleanup.
The two added lines go right after the STOP dispatch.

Screenshots

Repro script from the issue, Newton:

Sensor Before After
contact_a (history_length=3) 0.000 N 9.810 N
contact_b (update_period=0.02) 9.810 N 9.810 N

Checklist

Docker and GPU tests run on demand. Push the commits you want tested, then
comment run-ci on the pull request.

  • I have read and understood the contribution guidelines
  • I have run the pre-commit checks with uv run isaaclab --format
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have validated the changed behavior with focused coverage and applied the test-audit criteria to any test changes
  • I have added a changelog fragment under source/<pkg>/changelog.d/ for every touched package (do not edit CHANGELOG.rst or bump package versions — CI handles that)
  • I have added my name to the CONTRIBUTORS.md or my name already exists there

Tests

  • isaaclab_newton/test/sensors/test_contact_sensor.py::test_resting_object_contact_force: a second sensor on BoxA,
    differing only in update period and history length, must also report its weight, and the settle runs twice (the
    second sim.reset() is a hard reset). Without the reuse, the first BoxA sensor reads 0 N. Without the registry
    clear, the second pass raises the force error above. Both fail on both contact pipelines.
  • test_contact_sensor.py on develop 5088b326c7 (Newton 71eeba16, MuJoCo Warp 3.15.0): 24 passed, 4 skipped by
    existing skip marks.

NewtonManager.add_contact_sensor keyed the Newton SensorContact by the
sensing and filter expressions, but built a new one on every call and
replaced the registered entry. Contact sensors that differ only in
settings Isaac Lab applies itself (update period, history, air time)
kept the arrays of the replaced Newton sensor, which was no longer
updated, so all but the last one created reported zero forces.

add_contact_sensor now reuses the registered sensor for an identical
request instead of building a new one. A Newton sensor belongs to one
model, so a hard reset now drops the registry: the sensors register
again on PHYSICS_READY and get a Newton sensor built for the new model,
which also requests the contact force attribute from it.
@NeoZng
NeoZng requested a review from a team October 16, 2026 05:55
@github-actions github-actions Bot added bug Something isn't working isaac-lab Related to Isaac Lab team labels Oct 16, 2026
@greptile-apps

greptile-apps Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The PR appears safe to merge; no actionable issues were found.

Summary

Newton contact sensors with identical expressions now share one Newton sensor instead of replacing each other.

  • Matching Newton contact sensors now share one live sensor.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Register contact sensor] --> B{Expressions already registered?}
  B -->|Yes| C[Reuse Newton sensor]
  B -->|No| D[Build and register Newton sensor]
  C --> E[Copy outputs into each caller's own buffers]
  D --> E
  F[Hard reset] --> G[Mark sensors uninitialized and clear registry]
  G --> H[Build new model]
  H --> A
Loading

Reviews (1) · Last reviewed commit: "Share one Newton sensor among contact se..." · Reviewed by Greptile

@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

Needs attention: Test quality (1). Other reviewed categories look good.

  • PR description: The title and scope match the diff; correct the conflicting 113/114 manager-test counts and remove the repeated baseline/fixed validation narrative.
  • Design and architecture: Architecture looks good.
  • Scope and over-engineering: No over-engineering issues.
  • API: API changes look good.
  • Compatibility and deprecation: No breaking changes identified.
  • Implementation: Implementation looks good.
  • Style consistency: Style consistency looks good.
  • Test quality: The regression distinctly covers shared expressions and hard resets, but its single undamped force sample uses a 2% band despite documented solver oscillation; average settled samples before asserting.

Minor fixes needed. Posted 1 inline finding.

Automated review; human maintainers own approval decisions.

perform_sim_step(sim, scene, SIM_DT)
# One row per sensor: the 1 kg box rests on the ground.
force_z = torch.stack([sensor.data.net_normal_forces_w.torch[..., 2] for sensor in sensors])
torch.testing.assert_close(force_z, torch.full_like(force_z, gravity_magnitude), rtol=0.02, atol=0.0)

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 · Test Quality — Force assertion sampled from a single step

test_resting_object_contact_force in this file settles 90 steps and averages 20 samples because per-step solver oscillation exceeds a 2% band. This asserts the same band from one sample after 40 steps on an undamped box. Average…

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

Thanks for the PR @NeoZng! The fix looks great. Please look at the comment for the test.


# Sensor registration is host-side bookkeeping, identical on every device.
@pytest.mark.parametrize("device", test_devices(DeviceScope.CUDA))
def test_sensors_with_identical_expressions(device: str):

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.

The test fails for the right reason, and it doesn't pin the sharing itself, which is good. But it builds a second simulation for the fixture test_resting_object_contact_force already has, and it's weaker than that test:

  • It checks one reading after 40 steps on an undamped box, with a 2% band. The sibling averages the last 20 of 90 steps because the resting force oscillates from step to step.
  • The expected force is gravity_magnitude only because create_shape_cfg uses 1 kg.
  • With a constant resting force, the update_period and history_length sensor reads the same as the plain one, so those settings aren't exercised. Fine to keep as a copy of the issue's repro, but the docstring suggests otherwise.

Could you fold it into test_resting_object_contact_force instead? Add a third sensor on BoxA and run the settle twice:

        # Same expression as sensor A; differs only in settings Isaac Lab applies itself.
        scene_cfg.contact_sensor_c = ContactSensorCfg(
            prim_path="{ENV_REGEX_NS}/BoxA", update_period=4 * SIM_DT, history_length=3
        )

        scene = InteractiveScene(scene_cfg)
        sensor_a: ContactSensor = scene["contact_sensor_a"]
        sensor_b: ContactSensor = scene["contact_sensor_b"]
        sensor_c: ContactSensor = scene["contact_sensor_c"]

        # The second sim.reset() is a hard reset: it finalizes a new model, for which the sensors register again.
        for reset_pass in range(2):
            sim.reset()
            scene.reset()
            # ... existing settle and 20-sample average, also collecting sensor_c ...
            errs: list[str] = []
            for env_idx in range(num_envs):
                # ... existing BoxA / BoxB checks, with the pass in the message ...
                fc = force_mags_c[env_idx].max().item()
                if abs(fc - expected_force_a) >= 0.02 * expected_force_a:
                    errs.append(
                        f"Pass {reset_pass}, env {env_idx}: second BoxA sensor should read"
                        f" ~{expected_force_a:.2f} N. Got {fc:.2f} N"
                    )
            assert not errs, "\n".join(errs)

Without the early return, the existing BoxA check reads 0 N. Without the clear(), the second pass raises the force error. This also covers both contact pipelines and 4 envs, and saves a simulation build. Could you check that both of those mutations turn it red?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@AntoineRichard Done in d88ff8e: folded into test_resting_object_contact_force as you suggested, and the separate test is gone. Both mutations turn it red on both pipelines: without the early return, BoxA reads 0.00 N in the first pass; without the clear(), the first step of the second pass raises the force error (SensorContact requires contact-force solver observables).

…-sensor-shared-key

# Conflicts:
#	source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py
@NeoZng

NeoZng commented Oct 27, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #8733, which keeps Newton contact sensors on the backend and returns the existing sensor for identical expressions; this PR's test passes on main without its source change, so I'm closing this.

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.

[Bug Report] Newton ContactSensors with identical body and filter expressions report zero forces except the last one

4 participants