Skip to content

feat(disjoint): bounds-checked write/read for algorithm-guaranteed uniqueness - #572

Closed
honeyspoon wants to merge 4 commits into
NVIDIA:mainfrom
honeyspoon:up2/disjoint-slice-write
Closed

honeyspoon wants to merge 4 commits into
NVIDIA:mainfrom
honeyspoon:up2/disjoint-slice-write

Conversation

@honeyspoon

@honeyspoon honeyspoon commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

DisjointSlice has two access paths with a gap between them:

today proof required bounds checked
get_mut(ThreadIndex) a ThreadIndex yes
get_unchecked_mut(usize) none no

An algorithm whose write uniqueness comes from somewhere other than a ThreadIndex — a warp reduction where only lane 0 writes, a scatter with known-unique destinations, a manually clipped tile — has no ThreadIndex to offer and must drop all the way to get_unchecked_mut, losing the bounds check along with the proof.

pub unsafe fn write(&mut self, idx: usize, value: T) -> bool where T: Copy;
pub unsafe fn read(&self, idx: usize) -> Option<T> where T: Copy;
// only lane 0 writes, so uniqueness holds without a ThreadIndex
if warp::lane_id() == 0 {
    unsafe { slice.write(out_idx, total) };
}

API decisions, and the alternatives rejected

1. unsafe fn, despite the bounds check

Chosen: unsafe, with the bounds check inside.

Alternative: safe, since it is checked.

The bounds check does not discharge the obligation that matters. What makes a DisjointSlice write sound is that no two threads target the same index, and that no read races a write without an intervening barrier — neither of which an index comparison can see. Making these safe would be claiming a guarantee the check does not provide. The unsafe marks exactly the residual obligation, and the docs say explicitly that the returned bool is not a safety signal.

2. bool from write, Option<T> from read

Chosen: -> bool and -> Option<T>, both #[must_use].

Alternatives: Result<(), OutOfBounds>; or -> () with a debug assert.

Result implies a recoverable error with a reason, and there is only one reason. Device code also has no error-reporting path, so a Result would mostly be .ok()-ed at the call site. -> () with a debug assert was tempting for symmetry with get_unchecked_mut, but then a release build silently drops the write — the failure this method exists to prevent. #[must_use] is what stops the bool being ignored, which would reintroduce exactly that.

The asymmetry is deliberate: a failed write has nothing to return, a failed read has no value to give, so bool and Option<T> are each the smallest honest type.

3. T: Copy on both

Chosen: bound both methods on T: Copy.

Alternative: allow any T and use ptr::write, which does not drop the old value.

Without Copy, write overwrites a slot whose previous occupant is never dropped — a leak for any T with a destructor, and silent. Copy makes that impossible to express. Device buffers hold plain data, so in practice this costs nothing; the bound is documented as a leak-prevention measure rather than an arbitrary restriction. read carries it for the same reason a bitwise copy out is only sound for Copy.

4. write/read rather than set/get or store/load

Chosen: write/read.

get/set would sit confusingly beside the existing get_mut, which has entirely different (proof-carrying) semantics. store/load implies atomics or explicit ordering, which these are not. write/read matches ptr::write/ptr::read, whose obligations are the closest analogue.

5. What I did not build: a second proof type

The principled fix is a proof type for "uniqueness established by other means" — something like a UniqueWrite witness that lane-0 patterns could construct — so these could be safe. I did not, for two reasons: it is a design question about what evidence such a witness would carry (and #515's rejection upstream shows a per-call witness cannot carry a slice-lifetime property), and it would still need this bounds-checked primitive underneath. This PR is the primitive; the witness is a separate conversation.

6. Relationship to get_mut — not a competitor

get_mut is strictly better wherever a ThreadIndex exists, and nothing here relaxes, wraps or duplicates it. These serve the cases where no such index exists, and the honest alternative today is get_unchecked_mut, which is worse on every axis than a bounds-checked unsafe fn. If you would rather the crate not grow a middle tier at all, the reasonable response is to reject this and keep users on get_unchecked_mut — I would want that stated in the docs, since right now nothing points them there.


Soundness: what these methods do and do not put at risk

Since both are unsafe fn added to a type whose whole purpose is disciplined aliasing, here is the argument in full rather than by assertion.

The obligations are a strict subset of get_unchecked_mut's

This is the core claim, and it is checkable against the existing docs. get_unchecked_mut documents three obligations:

  1. idx < self.len()
  2. no two threads write the same index simultaneously
  3. the uniqueness guarantee comes from the algorithm

write requires only (2) and (3). Obligation (1) is discharged by the bounds check, which returns false instead of reaching for the pointer. So:

every program that is sound using get_unchecked_mut remains sound if it uses write, and write additionally rejects the out-of-bounds case that would have been UB.

That makes this a monotonic change to the crate's safety surface: it adds no new kind of obligation, and strictly weakens the preconditions of the path callers use today. Rejecting this PR does not make anything safer — it leaves those callers on get_unchecked_mut with obligation (1) still live.

Memory safety, per operation

Bounds. idx < self.len guards self.ptr.add(idx). len is the element count the view was constructed with, so idx < len puts the offset inside the allocation — the same condition <[T]>::get relies on. The byte offset idx * size_of::<T>() cannot overflow isize, because an allocation of len * size_of::<T>() bytes exists, which already implies that product is representable.

Alignment. ptr originates from DeviceBuffer<T> or from_mut_slice, so it is aligned for T; add advances by whole elements, which preserves alignment. Neither method can produce a misaligned access from an aligned view.

Provenance. Both derive from the view's own pointer via add, staying within the provenance the view was created with. No integer-to-pointer casts, no pointer synthesised from an index.

No wrap-to-alias. Because the comparison is idx < len on the element index rather than arithmetic on a byte address, there is no route by which an offset wraps and lands back inside the allocation — the failure mode that get_block_mut needs checked_add for, since it validates start + N.

Type safety

T: Copy is load-bearing twice. For write, ptr::write does not drop the overwritten value; with a Drop type that is a silent leak, so the bound makes the leak unrepresentable rather than merely undocumented. For read, a by-value bitwise copy out of the slice is only a valid way to produce a T when T has no ownership semantics.

No transmutation, no lifetime laundering. Neither method casts T, and neither returns a reference — write consumes a T by value, read produces one by value. So there is no borrow whose lifetime could outlive the view, and none of the &mut [T; N]-style aliasing questions that get_block_mut has to answer.

Initialization. read copying by value means a never-written slot yields an indeterminate bit pattern, which is UB for any T whose values are not all bit patterns (bool, char, enums, references). That obligation was missing from the # Safety section and this PR now documents it; it is reachable today via DeviceBuffer::uninitialized_async. write has no such requirement — it is what makes a slot initialized.

What is deliberately not proven, and why the unsafe is honest

The data-race freedom is not established by these methods and cannot be. &mut self on write does not help: the entire design of DisjointSlice is that every thread holds its own view over the same buffer, so a per-thread &mut says nothing about the other threads. That is the pre-existing model of the type, inherited unchanged.

So the residual obligation is exactly:

  • no two threads target the same index, and
  • no read races a write without an intervening barrier.

Neither is visible to an index comparison, which is why the bounds check does not earn a safe signature and why the docs state plainly that the returned bool is not a safety signal.

ZSTs

Unguarded, and safely so. For size_of::<T>() == 0, add is a no-op and ptr::write touches zero bytes, so even two threads "writing the same slot" writes nothing. This differs from get_block_mut, which guards ZSTs explicitly because it hands out &mut [T; N] and the aliasing question becomes real there. Worth stating so the asymmetry does not read as an oversight.

Gates

fmt, clippy --workspace --all-targets -D warnings, rustdoc -D warnings, tests and doctests clean on nightly-2026-04-03. +97/−0 against main.

…leak

`write` used `core::ptr::write`, which overwrites the slot without running a
destructor on the value already there. The slot is initialized (it is an
element of a live slice), so for a `T` with a `Drop` impl the previous value
would leak.

`read` already required `T: Copy`, so bounding `write` the same way makes the
pair consistent and lets the type system rule the leak out rather than a doc
comment asking callers not to hit it. Device buffers hold plain data, so no
real caller loses anything.

Signed-off-by: abder <[email protected]>
`read` copies by value via `ptr::read`, so a slot that was never written holds
an indeterminate bit pattern and producing a `T` from it is UB for any `T` whose
values are not all bit patterns. The `# Safety` section listed the data-race
obligations but not this one, which is reachable today through
`DeviceBuffer::uninitialized_async`.
@honeyspoon

Copy link
Copy Markdown
Contributor Author

Pushed one change while writing the soundness argument for the description: read's # Safety section was missing the initialization obligation.

read copies by value via ptr::read, so a slot that was never written holds an indeterminate bit pattern, and producing a T from it is UB for any T whose values are not all bit patterns (bool, char, enums, references). The section listed the data-race obligations but not that one, and it is reachable today through DeviceBuffer::uninitialized_async — buffers from zeroed or from_host are fine.

Found by writing out the per-operation argument rather than asserting soundness, which is the case for doing it that way. +97/−0 now; gates re-run green.

@honeyspoon

honeyspoon commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor Author

All CI jobs pass on this branch. Workflows here need maintainer approval before they start, so I ran the repository's own workflow job set against this tree myself. All 16 succeed:

fmt                                       clippy
fork-guard                                generated intrinsics are current and ABI-compatible
cargo test -p cuda-device                 cargo test -p dialect-nvvm
cargo test -p mir-importer                cargo test -p mir-lower
cargo test -p dialect-mir                 cargo test -p llvm-export
cargo test -p mir-transforms              cargo test -p nvvm-transforms
cargo test -p cuda-intrinsics             cargo test -p cuda-intrinsics-gen
cargo test -p oxide-artifacts             cargo test -p reserved-oxide-symbols

That covers three gates my local pre-push script does not: fmt across the rustc-codegen-cuda workspace and every example crate, clippy on those too, and generated intrinsics are current and ABI-compatible.

Also re-ran my pre-push review checklist over the diff: no em-dashes, no unescaped intra-doc brackets, SPDX headers present on new files, cargo fmt --check clean in both workspaces.

@honeyspoon

Copy link
Copy Markdown
Contributor Author

Closing — on reflection this is an escape hatch rather than a fix.

The argument in the description still holds as far as it goes: write's obligations are a strict subset of get_unchecked_mut's, so it is monotonically safer than the path callers use today. But that makes the unsound path slightly less unsound instead of making the sound path expressible, and it adds a third access method whose contract users must read carefully to tell apart from the other two. The returned bool invites precisely the wrong reading — it looks like the safety signal and is not.

The real gap is a witness for uniqueness established by means other than a ThreadIndex (warp reductions where only lane 0 writes, scatters with known-unique destinations). Filed with worked examples as #584, including why such a witness cannot be a per-call parameter — #515's rejection shows safe code can vary it between calls on one slice and reintroduce the aliasing, so it likely belongs in the slice type instead.

One thing from this PR worth keeping regardless of the design: read copying by value means an uninitialized slot is UB for any T whose values are not all bit patterns, and that obligation is currently undocumented on get_unchecked too. Noted in #584.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant