Skip to content

Key arena per-stream state by CUDA stream ID - #2471

Open
nethum529 wants to merge 8 commits into
rapidsai:mainfrom
nethum529:fix/issue-2394-arena-stream-id
Open

Key arena per-stream state by CUDA stream ID#2471
nethum529 wants to merge 8 commits into
rapidsai:mainfrom
nethum529:fix/issue-2394-arena-stream-id

Conversation

@nethum529

Copy link
Copy Markdown
Contributor

Description

arena_memory_resource_impl stored per-stream arena state in a std::map keyed by the raw cudaStream_t handle, looked up with stream.value().
CUDA can reassign a destroyed stream's raw handle value to a newly created stream (ABA reuse), so a new logical stream could inherit stale arena state left behind by an earlier, unrelated stream that happened to share the same handle value.

This mirrors the fix already applied to stream_ordered_memory_resource in #2252, which keys stream state by cudaStreamGetId for exactly this reason.

Changes:

  • Add a rmm::mr::detail::get_stream_id helper that normalizes the default stream to cudaStreamLegacy and returns the ID from cudaStreamGetId.
  • Key stream_arenas_ by stream_id_type (the stream ID) instead of the raw cudaStream_t handle.
  • get_stream_arena now looks up and inserts by the stream ID.

closes #2394

Before / After

Key for stream_arenas_ ABA reuse hazard
Before raw cudaStream_t handle (stream.value()) a reused handle inherits the dead stream's arena
After cudaStreamGetId(stream) a reused handle gets a distinct ID, so a fresh arena

Tests

Added three tests to cpp/tests/mr/arena_mr_tests.cpp:

  • distinct live streams get distinct, stable IDs;
  • the default stream normalizes to the legacy stream ID (non-PTDS) and never collides with a real stream's key;
  • a bounded, non-flaky regression that cycles stream create/destroy until a raw handle is observably reused, then asserts the IDs still differ (skips if reuse is never observed, since CUDA gives no handle-reuse-timing guarantee).

ARENA_MR_TEST and ARENA_MR_PTDS_TEST both pass 44/44.

Checklist

  • I am familiar with the Contributing Guidelines.
  • New or existing tests cover these changes.
  • The documentation is up to date with these changes.

@nethum529
nethum529 requested a review from a team as a code owner July 6, 2026 21:19
@nethum529
nethum529 requested review from bdice and lamarrr July 6, 2026 21:19
@copy-pr-bot

copy-pr-bot Bot commented Jul 6, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@coderabbitai

coderabbitai Bot commented Jul 6, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 76b00c91-fc3c-473d-a592-7892fe65efc5

📥 Commits

Reviewing files that changed from the base of the PR and between afbf0a3 and f8c2ed6.

📒 Files selected for processing (1)
  • cpp/tests/mr/arena_mr_tests.cpp
🚧 Files skipped from review as they are similar to previous changes (1)
  • cpp/tests/mr/arena_mr_tests.cpp

📝 Walkthrough

Summary by CodeRabbit

  • Bug Fixes
    • Improved CUDA stream handling for per-stream memory arenas by using stable, normalized stream identifiers instead of raw stream handles, reducing incorrect arena reuse.
    • Added safer fallback behavior when stream ID retrieval fails, preventing incorrect deallocation targeting.
  • Tests
    • Added coverage for stream ID stability, default-stream normalization, try_get_stream_id behavior, and an ABA-style regression check for potential CUDA handle reuse.
  • Documentation
    • Updated memory resource documentation and refreshed copyright notices.

Walkthrough

This PR keys per-stream arena state by normalized CUDA stream IDs from cudaStreamGetId, adds throwing and non-throwing lookup helpers, handles lookup failures during deallocation, protects concurrent map access, and adds stream-ID regression tests.

Changes

Arena stream ID keying

Layer / File(s) Summary
Stream ID contract and arena storage
cpp/include/rmm/mr/detail/arena_memory_resource_impl.hpp, cpp/include/rmm/mr/arena_memory_resource.hpp
Adds stream ID helpers, changes stream arena storage interfaces to use stream_id_type keys, and documents stream-ID-based arena lifetime and bookkeeping.
Stream ID lookup and deallocation handling
cpp/src/mr/detail/arena_memory_resource_impl.cpp
Normalizes default streams, retrieves CUDA stream IDs, handles lookup failures during deallocation, switches arena lookup to ID keys, and adds shared locking around map searches.
Stream ID behavior tests
cpp/tests/mr/arena_mr_tests.cpp
Tests ID uniqueness, stability, non-throwing lookup, default-stream normalization, and raw-handle reuse.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related issues

  • Issue 2478: The PR adds the throwing and non-throwing cudaStreamGetId helpers and failure handling described by this issue.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: keying per-stream arena state by CUDA stream ID.
Description check ✅ Passed The description matches the PR and explains the stream-ID keying fix, tests, and ABA reuse motivation.
Linked Issues check ✅ Passed The implementation matches #2394: stream arenas are keyed by stream ID, default streams are normalized, and get_stream_arena uses the ID.
Out of Scope Changes check ✅ Passed The changes appear scoped to the stream-ID fix and its supporting tests/docs, with no clearly unrelated additions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cpp/src/mr/detail/arena_memory_resource_impl.cpp`:
- Around line 18-29: The get_stream_id helper currently uses
RMM_ASSERT_CUDA_SUCCESS around cudaStreamGetId, which can be compiled out in
release builds and silently leave stream_id at 0. Update get_stream_id in
arena_memory_resource_impl.cpp to use RMM_CUDA_TRY for the cudaStreamGetId call
so failures throw immediately, while keeping the existing stream_to_store
selection and stream_id_type handling unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 7abeee32-a042-4e92-9329-6234930bfe09

📥 Commits

Reviewing files that changed from the base of the PR and between 547286a and fd6a2ed.

📒 Files selected for processing (3)
  • cpp/include/rmm/mr/detail/arena_memory_resource_impl.hpp
  • cpp/src/mr/detail/arena_memory_resource_impl.cpp
  • cpp/tests/mr/arena_mr_tests.cpp

Comment thread cpp/src/mr/detail/arena_memory_resource_impl.cpp Outdated
@nethum529
nethum529 force-pushed the fix/issue-2394-arena-stream-id branch from fd6a2ed to a215f77 Compare July 6, 2026 21:48
@bdice bdice added bug Something isn't working non-breaking Non-breaking change labels Jul 8, 2026

@bdice bdice 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 this and the other PRs you filed! Seems mostly good, I have a couple questions.

Comment thread cpp/tests/mr/arena_mr_tests.cpp
* `noexcept`-safe requirements of the `deallocate`/`deallocate_sync` path.
* @return The CUDA stream ID.
*/
stream_id_type get_stream_id(cuda_stream_view stream, bool may_throw);

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.

Hmm. Do we need something like may_throw in the corresponding code for stream_ordered_memory_resource?

Is it possible to catch and swallow the exception in the deallocation path and still count that as noexcept?

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.

Design proposal: #2471 (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.

nit: Let's make this a method on cuda_stream_view, I think.

@bdice bdice Jul 9, 2026

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.

@wence- We'll be migrating from rmm::cuda_stream_view to cuda::stream_ref in the relatively near future. I'd like to keep this a free function for now, though we can file an upstream feature request with CCCL for that if you like.

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.

ah ok, I withdraw my suggestion

@bdice

bdice commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator

I thought about this some more. A cleaner design would be to split this into get_stream_id(...) for throwing paths and try_get_stream_id(...) noexcept for deallocate() / deallocate_sync(). The try variant can return std::optional<stream_id_type>, forcing the noexcept caller to handle failure explicitly rather than silently using key 0.

For stream_ordered_memory_resource, RMM_CUDA_TRY cannot simply be used in get_event() because get_event() is called by deallocate() and deallocate_sync(), which are noexcept. I do not see get_event() used in the destructor path; release() only uses stored events.

I think any stream_ordered_memory_resource change should be handled in a separate PR, since it affects pool/fixed-size MRs rather than this arena-specific fix. Proposal in #2478.

* `noexcept`-safe requirements of the `deallocate`/`deallocate_sync` path.
* @return The CUDA stream ID.
*/
stream_id_type get_stream_id(cuda_stream_view stream, bool may_throw);

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.

nit: Let's make this a method on cuda_stream_view, I think.

Comment on lines +28 to +33
// Safe to throw: only called from the non-noexcept allocate() path.
RMM_CUDA_TRY(cudaStreamGetId(stream_to_store, &stream_id));
} else {
// Called from the noexcept deallocate()/deallocate_sync() path: must not throw. A failure
// here is only surfaced via assertion in debug builds.
RMM_ASSERT_CUDA_SUCCESS(cudaStreamGetId(stream_to_store, &stream_id));

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.

If this were a method on cuda_stream_view we could plausibly query the ID on creation (if it is fast) and stash it on the stream view. That's a ctor that may throw, so we're all good. And then get_stream_id could itself be noexcept

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 like the idea of querying/caching on construction, we'll need to gather some benchmarks to understand the cost.

@nethum529

Copy link
Copy Markdown
Contributor Author

Thanks @bdice, the split makes sense to me. A throwing get_stream_id(...) for the normal paths, plus a try_get_stream_id(...) noexcept returning std::optional for the deallocate paths that can't throw. Agreed on keeping stream_ordered_memory_resource out of scope for this PR.

The arena memory resource keyed per-stream arenas by the raw
cudaStream_t handle. CUDA can hand a destroyed stream's handle value
to a new stream (ABA reuse), so a new logical stream could inherit
stale arena state. Key stream_arenas_ by cudaStreamGetId instead,
mirroring the pattern already used by stream_ordered_memory_resource.

Closes rapidsai#2394

Signed-off-by: nethum529 <nethumweerasinghe.nw@gmail.com>
Signed-off-by: nethum529 <nethumweerasinghe.nw@gmail.com>
Signed-off-by: nethum529 <nethumweerasinghe.nw@gmail.com>
Signed-off-by: nethum529 <nethumweerasinghe.nw@gmail.com>
@nethum529
nethum529 force-pushed the fix/issue-2394-arena-stream-id branch from a215f77 to 293338d Compare July 18, 2026 02:23

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@cpp/include/rmm/mr/detail/arena_memory_resource_impl.hpp`:
- Around line 126-130: Update the stream_arenas_ lifecycle in the arena memory
resource implementation to retire and erase arenas associated with destroyed or
otherwise inactive CUDA streams, while preserving safety for arenas still in use
and avoiding stream-ID reuse hazards. Ensure eviction releases arena-owned
resources and does not leave permanently retained entries for every stream ever
seen.

In `@cpp/tests/mr/arena_mr_tests.cpp`:
- Line 657: Replace the direct cudaStreamGetId assertion in the affected test
with RMM_CUDA_TRY, preserving the existing stream.view().value() argument and
expected_id output parameter.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 3c5143cc-9f5a-4b62-a206-65bcf0fd1b61

📥 Commits

Reviewing files that changed from the base of the PR and between a215f77 and 293338d.

📒 Files selected for processing (3)
  • cpp/include/rmm/mr/detail/arena_memory_resource_impl.hpp
  • cpp/src/mr/detail/arena_memory_resource_impl.cpp
  • cpp/tests/mr/arena_mr_tests.cpp

Comment thread cpp/include/rmm/mr/detail/arena_memory_resource_impl.hpp
Comment thread cpp/tests/mr/arena_mr_tests.cpp Outdated
@nethum529
nethum529 force-pushed the fix/issue-2394-arena-stream-id branch from 293338d to afbf0a3 Compare July 18, 2026 02:54

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
cpp/tests/mr/arena_mr_tests.cpp (2)

658-660: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Exercise the try_get_stream_id failure path.

This test only covers successful lookup. Add a controlled invalid or destroyed-stream case and assert that try_get_stream_id returns std::nullopt without throwing, since deallocation relies on that contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cpp/tests/mr/arena_mr_tests.cpp` around lines 658 - 660, Add a failure-path
case alongside the existing successful `try_get_stream_id` test, using a
controlled invalid or destroyed stream. Assert that the call returns
std::nullopt and does not throw, while preserving the current expected-ID
assertion for valid streams.

664-680: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert default-stream normalization in PTDS builds too.

The #ifndef CUDA_API_PER_THREAD_DEFAULT_STREAM excludes the default-versus-legacy assertion in PTDS builds, although the helper contract says normalization applies in both modes. Keep this assertion unconditional.

Proposed adjustment
-#ifndef CUDA_API_PER_THREAD_DEFAULT_STREAM
-  // Non-PTDS: the default stream normalizes to cudaStreamLegacy, so it keys to the legacy id.
+  // The default stream normalizes to cudaStreamLegacy in both default-stream modes.
   EXPECT_EQ(rmm::mr::detail::get_stream_id(rmm::cuda_stream_view{}),
             rmm::mr::detail::get_stream_id(rmm::cuda_stream_legacy));
-#endif
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@cpp/tests/mr/arena_mr_tests.cpp` around lines 664 - 680, Make the
default-versus-legacy stream ID assertion in ArenaStreamIdTest unconditional by
removing the CUDA_API_PER_THREAD_DEFAULT_STREAM guard, while preserving the
existing real-stream collision check and other test assertions.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@cpp/tests/mr/arena_mr_tests.cpp`:
- Around line 658-660: Add a failure-path case alongside the existing successful
`try_get_stream_id` test, using a controlled invalid or destroyed stream. Assert
that the call returns std::nullopt and does not throw, while preserving the
current expected-ID assertion for valid streams.
- Around line 664-680: Make the default-versus-legacy stream ID assertion in
ArenaStreamIdTest unconditional by removing the
CUDA_API_PER_THREAD_DEFAULT_STREAM guard, while preserving the existing
real-stream collision check and other test assertions.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 329e0086-c249-41a0-8848-9fabb7ccabe8

📥 Commits

Reviewing files that changed from the base of the PR and between 293338d and afbf0a3.

📒 Files selected for processing (4)
  • cpp/include/rmm/mr/arena_memory_resource.hpp
  • cpp/include/rmm/mr/detail/arena_memory_resource_impl.hpp
  • cpp/src/mr/detail/arena_memory_resource_impl.cpp
  • cpp/tests/mr/arena_mr_tests.cpp
🚧 Files skipped from review as they are similar to previous changes (2)
  • cpp/include/rmm/mr/detail/arena_memory_resource_impl.hpp
  • cpp/src/mr/detail/arena_memory_resource_impl.cpp

Switch the raw ASSERT_EQ(..., cudaSuccess) check to RMM_CUDA_TRY, the repo's
CUDA error-checking macro, and include <rmm/detail/error.hpp> directly where
the macro is defined rather than relying on a transitive include.

Signed-off-by: nethum529 <nethumweerasinghe.nw@gmail.com>
@nethum529

Copy link
Copy Markdown
Contributor Author

Two notes on the latest CodeRabbit nitpicks that were in the review body rather than inline threads:

try_get_stream_id failure-path test (nullopt): not adding one. There is no portable, non-UB way to force cudaStreamGetId to return an error. Passing a destroyed or bogus stream handle is undefined behavior and would make the test crash or flake rather than reliably return an error. The noexcept / std::nullopt-on-failure contract is what the deallocate path depends on; the success path is covered by TryGetStreamIdReturnsCudaStreamId.

Default-stream normalization assertion under PTDS (removing the #ifndef CUDA_API_PER_THREAD_DEFAULT_STREAM guard): keeping the guard, because the equality does not hold in PTDS. cuda_stream_view::is_default() returns true in PTDS only when the handle equals cuda_stream_legacy; a default-constructed cuda_stream_view{} (handle 0, the per-thread default) is therefore not normalized to legacy, so get_stream_id(cuda_stream_view{}) returns the per-thread default stream ID, which differs from get_stream_id(cuda_stream_legacy). Making the assertion unconditional would fail ARENA_MR_PTDS_TEST. The real-stream collision check below stays unconditional in both modes.

@bdice

bdice commented Jul 25, 2026

Copy link
Copy Markdown
Collaborator

@nethum529 I am working through a few items for our 26.08 release and I'll keep working through reviewing and merging the PRs you filed in the next few days. I really appreciate the PRs you've filed, they are helpful contributions!

@nethum529

Copy link
Copy Markdown
Contributor Author

@nethum529 I am working through a few items for our 26.08 release and I'll keep working through reviewing and merging the PRs you filed in the next few days. I really appreciate the PRs you've filed, they are helpful contributions!

Of course not a problem Bradley! This is cool stuff so I don't mind 😁

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

Labels

bug Something isn't working non-breaking Non-breaking change

Projects

Status: Review

Development

Successfully merging this pull request may close these issues.

Key arena per-stream state by CUDA stream ID

4 participants