Skip to content

Drain stale CUDA errors before simulation start - #6456

Merged
AntoineRichard merged 3 commits into
isaac-sim:developfrom
AntoineRichard:antoiner/fix-warp-stale-cuda-error
Jul 15, 2026
Merged

AntoineRichard merged 3 commits into
isaac-sim:developfrom
AntoineRichard:antoiner/fix-warp-stale-cuda-error

Conversation

@AntoineRichard

@AntoineRichard AntoineRichard commented Jul 10, 2026 •

Copy link
Copy Markdown
Collaborator

Description

A latent Warp defect can abort Newton simulation (re)initialization with a spurious Warp CUDA error 1: invalid argument at the first buffer copy (wp.clone during PHYSICS_READY), in processes that run several simulation lifecycles (test suites, notebooks).

Root cause (fully diagnosed; a ~50-line pure-Warp repro exists and a Warp-side fix is in review):

  • wp.capture_while/wp.capture_if pause the parent capture and resume capturing into the conditional body graph on the same stream. If a Python garbage-collection pass runs inside a body callback and drops the last reference to an array allocated in the parent graph, Warp inserts the memory free node into the body graph with parent-graph dependency nodes — which fails with cudaErrorInvalidValue, leaks the allocation, and leaves the CUDA per-thread error latched.
  • wp_array_copy_device ends with check_cuda(cudaGetLastError()), so the next innocent Warp copy surfaces and mis-attributes the stale error — typically one test/lifecycle later, which made this look like flakiness.

This PR adds two independent layers in NewtonManager until the upstream Warp fix propagates:

  1. Prevention — garbage collection is paused for the duration of graph capture (both the standard ScopedCapture path and the RTX relaxed-capture path), with a collection run immediately after the capture window, where freeing graph-scoped allocations is handled correctly. Reference-count-driven frees are unaffected.
  2. Defense in depth — start_simulation drains (and logs) any latched CUDA error via Warp's own wp_cuda_context_check before dispatching initialization callbacks, so no prior lifecycle can poison the next one through any other latched-error path.

Validation: the deterministic 4-test repro (from the articulation-ordering test additions in #6336) goes red→green with the GC guard alone, with zero failed to add a memory free node warnings (the corrupting frees no longer happen); the full Newton articulation suite is green with ordering tests (257 passed) and on develop (236 passed). A develop-only regression test is not included because develop's current suite never arranges the triggering sequence; #6336's tests cover it organically once merged.

Type of change

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

Checklist

  • I have read and understood the [contribution guidelines]
  • I have run the [pre-commit checks] with ./isaaclab.sh --format
  • My changes generate no new warnings
  • I have added my name to the CONTRIBUTORS.md or my name already exists there

Warp leaves the per-thread CUDA error latched when adding a graph
memory free node fails during an active capture (its capture-ended
sibling branch clears the identical error as benign), and the next
Warp array copy then surfaces that stale error as its own failure,
aborting initialization at an innocent wp.clone during PHYSICS_READY.

The sequence became reachable when the cuBQL BVH constructors became
the default: their GPU scratch allocation pattern can leave a
graph-scoped allocation whose deferred free takes the failing path
when a process runs several simulation lifecycles (test suites,
notebooks). Drain and log any latched error at the top of
start_simulation so a prior lifecycle cannot poison the next one.

Workaround for an upstream Warp defect; remove once Warp clears the
error on the failed free-node branch.
@github-actions github-actions Bot added bug Something isn't working isaac-lab Related to Isaac Lab team labels Jul 10, 2026
@greptile-apps

greptile-apps Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds a targeted workaround to NewtonManager.start_simulation that drains any stale CUDA error latched by a prior simulation lifecycle before dispatching initialization callbacks. The fix addresses a Warp 1.15 defect where wp_free_device_async can leave a per-thread CUDA error latched after failing to add a graph memory-free node, which then mis-attributes as a fresh failure on the next Warp array copy.

  • A new _drain_stale_cuda_error classmethod calls Warp's wp_cuda_context_check via the private warp._src.context.runtime internal module; the call is guarded by an is_cuda check but the import itself has no exception fallback.
  • The changelog fragment is accurate and well-scoped.
  • The workaround is intentionally temporary, with a note to remove it once the upstream Warp fix lands.

Confidence Score: 4/5

The workaround is logically sound and well-scoped, but the unguarded private Warp import in the critical start_simulation path could cause a complete boot failure if Warp's internal module layout changes before this code is removed.

The private warp._src.context import has no try/except fallback. Any Warp update that restructures its internals — independent of the upstream fix this PR is waiting on — would raise an ImportError out of start_simulation, breaking simulation initialization entirely. Adding an exception guard would make this strictly safer.

source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py — specifically the _drain_stale_cuda_error method around lines 1164–1168

Important Files Changed

Filename Overview
source/isaaclab_newton/isaaclab_newton/physics/newton_manager.py Adds _drain_stale_cuda_error classmethod that calls a private Warp internal API (warp._src.context.runtime) without a fallback guard, creating a hard ImportError risk in start_simulation if Warp's internal structure changes
source/isaaclab_newton/changelog.d/fix-warp-stale-cuda-error.rst New changelog fragment accurately describing the stale CUDA error fix in NewtonManager.start_simulation

Sequence Diagram

%%{init: {'theme': 'neutral'}}%%
sequenceDiagram
    participant Caller
    participant NewtonManager
    participant Warp_Private as warp._src.context.runtime
    participant CUDA

    Note over Caller,CUDA: Prior simulation lifecycle (may latch stale CUDA error)
    Caller->>NewtonManager: start_simulation()
    NewtonManager->>NewtonManager: _drain_stale_cuda_error()
    NewtonManager->>NewtonManager: wp.get_device(PhysicsManager._device)
    alt device.is_cuda
        NewtonManager->>Warp_Private: import runtime as _wp_runtime
        NewtonManager->>CUDA: wp_cuda_context_check(device.context)
        CUDA-->>NewtonManager: "stale error code (0 = clean)"
        alt "stale != 0"
            NewtonManager->>NewtonManager: logger.warning(stale error cleared)
        end
    end
    NewtonManager->>NewtonManager: instantiate_builder_from_stage()
    NewtonManager->>NewtonManager: dispatch MODEL_INIT callbacks
    NewtonManager-->>Caller: simulation started
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 Caller
    participant NewtonManager
    participant Warp_Private as warp._src.context.runtime
    participant CUDA

    Note over Caller,CUDA: Prior simulation lifecycle (may latch stale CUDA error)
    Caller->>NewtonManager: start_simulation()
    NewtonManager->>NewtonManager: _drain_stale_cuda_error()
    NewtonManager->>NewtonManager: wp.get_device(PhysicsManager._device)
    alt device.is_cuda
        NewtonManager->>Warp_Private: import runtime as _wp_runtime
        NewtonManager->>CUDA: wp_cuda_context_check(device.context)
        CUDA-->>NewtonManager: "stale error code (0 = clean)"
        alt "stale != 0"
            NewtonManager->>NewtonManager: logger.warning(stale error cleared)
        end
    end
    NewtonManager->>NewtonManager: instantiate_builder_from_stage()
    NewtonManager->>NewtonManager: dispatch MODEL_INIT callbacks
    NewtonManager-->>Caller: simulation started
Loading

Reviews (1): Last reviewed commit: "Drain stale CUDA errors before simulatio..." | Re-trigger Greptile

Comment on lines +1164 to +1168
from warp._src.context import runtime as _wp_runtime

stale = _wp_runtime.core.wp_cuda_context_check(device.context)
if stale != 0:
logger.warning("Cleared stale CUDA error %d latched by a prior Warp graph-memory free failure.", stale)

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 Unguarded private import can hard-fail start_simulation

warp._src.context is a private internal module. If a Warp update renames or restructures that module (independently of the fix the PR is waiting on), this ImportError will propagate out of start_simulation on every simulation start — turning a soft workaround into a complete boot blocker. Wrapping the call in a try/except (ImportError, AttributeError) block that logs a warning and returns would preserve the intent while guaranteeing the fallback path is safe.

A collection pass inside the capture window can drop the last reference
to an array allocated earlier in the capture. While the capture is
paused for a wp.capture_while/capture_if conditional body, Warp inserts
the memory free node into the body graph with parent-graph dependency
nodes, which fails, latches a sticky CUDA error, and leaks the
allocation. Pausing the collector for the capture window prevents the
corrupting frees at the source; the error drain from the previous
commit remains as defense in depth for any other latched-error path.
A collection runs immediately after the capture window, where freeing
graph-scoped allocations is handled correctly.
Comment on lines +1193 to +1195
stale = _wp_runtime.core.wp_cuda_context_check(device.context)
if stale != 0:
logger.warning("Cleared stale CUDA error %d latched by a prior Warp graph-memory free failure.", stale)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

This warning can't fire in the scenario it targets: wp_cuda_context_check drains the latched error via its first cudaGetLastError(), but then (nothing is capturing at this point, so the sync branch always runs) executes cudaDeviceSynchronize() and re-reads the now-clean error state, returning that. So it returns 0 precisely when a non-sticky stale error was successfully drained, and nonzero only for sticky errors that can't be cleared — where "Cleared" would be the opposite of what happened. Meanwhile the drained error still reaches stderr as a raw Warp CUDA error N: ... (in function wp_cuda_context_check, ...) line via Warp's internal check_cuda, with nothing marking it as benign/handled.

Verified on warp 1.15.0.dev20260612 by latching a real error (failed cudaMallocAsync inside Warp's cudart) and calling the drain: it cleared the error and returned 0.

Warp already binds what's needed to report the drain properly: wp_get_error_string (the buffer check_cuda writes into) and wp_set_error_output_enabled. Suppressing the raw print and diffing the buffer reports the drained error once, with framing — and before tends to hold the original failing call's message (in the bug scenario, the wp_free_device_async free-node failure), which gives attribution the return value can't:

Suggested change
stale = _wp_runtime.core.wp_cuda_context_check(device.context)
if stale != 0:
logger.warning("Cleared stale CUDA error %d latched by a prior Warp graph-memory free failure.", stale)
core = _wp_runtime.core
# wp_cuda_context_check drains via cudaGetLastError() but returns the
# post-sync error state (0 once a non-sticky error was drained), and its
# internal check_cuda() prints the drained error verbatim to stderr;
# suppress the print and diff Warp's error buffer to report the drain.
before = core.wp_get_error_string()
was_enabled = bool(core.wp_is_error_output_enabled())
core.wp_set_error_output_enabled(0)
try:
persistent = core.wp_cuda_context_check(device.context)
finally:
core.wp_set_error_output_enabled(1 if was_enabled else 0)
after = core.wp_get_error_string()
if persistent != 0:
logger.error(
"CUDA error %d persists after drain; the device context is likely unrecoverable: %s",
persistent,
after.decode(errors="replace"),
)
elif after != before:
logger.warning(
"Drained stale CUDA error latched by a prior lifecycle: %s "
"(last Warp error recorded before drain: %s)",
after.decode(errors="replace"),
before.decode(errors="replace") or "<none>",
)

Two known limitations, acceptable for a temporary layer: the buffer diff misses byte-identical consecutive drains (the drain itself still works, only the log is skipped), and the buffer/output flag are process-global, so a concurrent Warp error on another thread during this call could interleave.

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.

Applied in 24ad0925c4f — thanks, the inverted-return-value catch is exactly right. The drain now diffs wp_get_error_string() across wp_cuda_context_check with check_cuda's stderr print suppressed via wp_set_error_output_enabled, so:

  • an actual drain (after != before, persistent == 0) is logged once with the pre-drain buffer for attribution (usually the originating free-node failure), and
  • a nonzero return is logged as a likely-unrecoverable persistent error.

I also wrapped the whole warp._src.context interaction in try/except (ImportError, AttributeError) (folding in greptile's P1) — since the suggestion widens the private-symbol surface to four calls, this degrades to a skipped drain instead of raising out of start_simulation if Warp reshuffles internals. Kept your two documented limitations (byte-identical consecutive drains skip only the log; process-global buffer/flag) as acceptable for this temporary layer. Pre-commit clean.

wp_cuda_context_check drains the latched error with its first
cudaGetLastError() but returns the post-cudaDeviceSynchronize() state,
so it returns 0 exactly when a non-sticky error was cleared and nonzero
only for unclearable sticky errors. The prior ``if stale != 0`` warning
therefore fired only when nothing was actually cleared, and the drained
error still reached stderr as a raw, unframed Warp line.

Diff Warp's error-string buffer across the drain instead, suppressing
the internal check_cuda() stderr print, so a successful drain is
reported once with attribution (the pre-drain buffer usually holds the
originating free-node failure) and a truly persistent error is logged
as likely unrecoverable.

Also guard the private warp._src.context interaction with try/except so
a future Warp internals change degrades to a skipped drain rather than
raising ImportError/AttributeError out of start_simulation.
@AntoineRichard
AntoineRichard merged commit 4c4ad5e into isaac-sim:develop Jul 15, 2026
40 of 41 checks passed
matthewtrepte pushed a commit to matthewtrepte/IsaacLab that referenced this pull request Aug 4, 2026
## Description

A latent Warp defect can abort Newton simulation (re)initialization with
a spurious `Warp CUDA error 1: invalid argument` at the first buffer
copy (`wp.clone` during `PHYSICS_READY`), in processes that run several
simulation lifecycles (test suites, notebooks).

Root cause (fully diagnosed; a ~50-line pure-Warp repro exists and a
Warp-side fix is in review):
- `wp.capture_while`/`wp.capture_if` pause the parent capture and resume
capturing into the conditional body graph on the same stream. If a
Python garbage-collection pass runs inside a body callback and drops the
last reference to an array allocated in the parent graph, Warp inserts
the memory free node into the body graph with parent-graph dependency
nodes — which fails with `cudaErrorInvalidValue`, leaks the allocation,
and leaves the CUDA per-thread error latched.
- `wp_array_copy_device` ends with `check_cuda(cudaGetLastError())`, so
the next innocent Warp copy surfaces and mis-attributes the stale error
— typically one test/lifecycle later, which made this look like
flakiness.

This PR adds two independent layers in `NewtonManager` until the
upstream Warp fix propagates:
1. **Prevention** — garbage collection is paused for the duration of
graph capture (both the standard `ScopedCapture` path and the RTX
relaxed-capture path), with a collection run immediately after the
capture window, where freeing graph-scoped allocations is handled
correctly. Reference-count-driven frees are unaffected.
2. **Defense in depth** — `start_simulation` drains (and logs) any
latched CUDA error via Warp's own `wp_cuda_context_check` before
dispatching initialization callbacks, so no prior lifecycle can poison
the next one through any other latched-error path.

Validation: the deterministic 4-test repro (from the
articulation-ordering test additions in isaac-sim#6336) goes red→green with the
GC guard alone, with zero `failed to add a memory free node` warnings
(the corrupting frees no longer happen); the full Newton articulation
suite is green with ordering tests (257 passed) and on develop (236
passed). A develop-only regression test is not included because
develop's current suite never arranges the triggering sequence; isaac-sim#6336's
tests cover it organically once merged.

## Type of change

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

## Checklist

- [x] I have read and understood the [contribution guidelines]
- [x] I have run the [pre-commit checks] with `./isaaclab.sh --format`
- [x] My changes generate no new warnings
- [x] I have added my name to the `CONTRIBUTORS.md` or my name already
exists there
hujc7 added a commit to hujc7/IsaacLab that referenced this pull request Nov 17, 2026
GraphedCallable paused Python's garbage collector while it recorded, to
keep collection-driven frees out of the graph (isaac-sim#6456). Warp 1.17.0, the
locked version, fixes that, so recordings no longer pause it.
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.

3 participants