Skip to content

Fix index_2d soundness: stride-consistency gap #34

Closed

Description

@nihalpasham

Background

In the initial public release, index_2d(row_stride: usize) took the row stride at runtime and returned a ThreadIndex. Uniqueness was conditional on every thread in the block passing the same row_stride — but nothing in the type system enforced that. Two threads picking different strides could compute the same scalar index, hand it to DisjointSlice::get_mut, and race.

This was a known unsound API; a caveat was supposed to ship in the docs and didn't. @Nekrolm flagged it on x.com with the minimal counterexample:

let a = index_2d(100);
let b = index_2d(200);
let c = if some_crafted_condition { a } else { b };
// two threads in the block can pick c such that they collide

This issue records the bug and the fix that just landed on main.

The bug

index_2d's uniqueness guarantee was conditional on a runtime parameter that the compiler had no way to constrain. Mix strides across threads → two threads compute the same linear index → DisjointSlice::get_mut hands out aliasing &mut T → data race. The unsoundness is at the type level, not the implementation level — no amount of internal bounds checking would have caught it.

The fix, in two halves

Fixing one half without the other leaves the same hole open through a different path, so both are needed.

Half 1 — encode the stride in the type

ThreadIndex<'kernel, IndexSpace = Index1D>

// IndexSpace markers:
Index1D                          // 1D, fully type-safe
Index2D<const STRIDE: usize>     // 2D, stride known at compile time
Runtime2DIndex                   // 2D, stride only known at runtime

The 2D constructors:

thread::index_2d::<256>()              // -> ThreadIndex<'_, Index2D<256>>
unsafe { thread::index_2d_runtime(s) } // -> Option<ThreadIndex<'_, Runtime2DIndex>>

DisjointSlice<T, IndexSpace> is parameterised on the index space, so passing a ThreadIndex<Index2D<256>> to a DisjointSlice<f32, Index2D<128>> is a compile error. Stride mixing is now unrepresentable in safe code.

The runtime-stride variant stays unsafe because the same-stride invariant has to move to the caller.

Half 2 — seal the witness

A typed witness alone isn't enough. Without further restrictions, a thread can park its ThreadIndex in static mut SMEM: [ThreadIndex; N], another thread can read it back, and we've recreated the same aliasing hole through shared memory instead of through stride math. So ThreadIndex is also sealed:

  • private raw: usize field; only constructor is a private unsafe fn new(raw, &KernelScope<'kernel>)
  • !Send + !Sync (via PhantomData<*mut ()>) — can't cross threads
  • !Copy + !Clone — can't be duplicated and reused
  • 'kernel lifetime, tied to a stack-local KernelScope<'kernel> that the #[kernel] macro injects — can't escape the kernel body
  • deliberately no #[repr(transparent)] — keeping the layout unspecified makes mem::transmute::<usize, ThreadIndex> UB by the language rules, which blocks forgery from unsafe code

Also added: get_mut_indexed

In the same thread, @Nekrolm also proposed a more ergonomic API, which we landed:

slice.get_mut_indexed() // -> (Option<&mut T>, ThreadIndex)

One call, one index computation, witness handed back so the caller never constructs one by hand. Gated on the IndexFormula trait, so it's available where the stride is known to the type (Index1D, Index2D<S>) but not for Runtime2DIndex. The macro splices in the kernel scope the same way it does for index_1d / index_2d.

Verification

  • Compile-fail tests for: mixing strides, returning ThreadIndex from #[device], smuggling via smem, Copy/Clone attempts, Send across threads.
  • All examples updated to the new APIs and re-run.
  • cargo clippy --all-targets -- -D warnings clean on the workspace + rustc-codegen-cuda + all examples.
  • Workspace unit tests pass.

Not in scope (separate follow-up)

A #[kernel] fn(data: &mut [T]) parameter is still source-level UB — every thread receives the same &mut. Our backend doesn't currently exploit it because we don't emit LLVM noalias, but the source is UB by the Rust language model. Tracking that as its own issue.

Acknowledgments

Thanks to @Nekrolm for flagging this in public and for the get_mut_indexed suggestion.

Activity

  1. self-assigned this
    on May 11, 2026
  2. added
    bug
    safety
    on May 11, 2026
  3. added a commit that references this issue on May 11, 2026
    54f45e6
  4. added a commit that references this issue on Sep 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

bugsafety

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions