Repository navigation
feat(disjoint): bounds-checked write/read for algorithm-guaranteed uniqueness - #572
honeyspoon wants to merge 4 commits into
Conversation
…thods Signed-off-by: abder <[email protected]>
Signed-off-by: abder <[email protected]>
…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`.
|
Pushed one change while writing the soundness argument for the description:
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. |
|
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: That covers three gates my local pre-push script does not: 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, |
|
Closing — on reflection this is an escape hatch rather than a fix. The argument in the description still holds as far as it goes: The real gap is a witness for uniqueness established by means other than a One thing from this PR worth keeping regardless of the design: |
DisjointSlicehas two access paths with a gap between them:get_mut(ThreadIndex)ThreadIndexget_unchecked_mut(usize)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 noThreadIndexto offer and must drop all the way toget_unchecked_mut, losing the bounds check along with the proof.API decisions, and the alternatives rejected
1.
unsafe fn, despite the bounds checkChosen:
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
DisjointSlicewrite 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. Theunsafemarks exactly the residual obligation, and the docs say explicitly that the returnedboolis not a safety signal.2.
boolfromwrite,Option<T>fromreadChosen:
-> booland-> Option<T>, both#[must_use].Alternatives:
Result<(), OutOfBounds>; or-> ()with a debug assert.Resultimplies a recoverable error with a reason, and there is only one reason. Device code also has no error-reporting path, so aResultwould mostly be.ok()-ed at the call site.-> ()with a debug assert was tempting for symmetry withget_unchecked_mut, but then a release build silently drops the write — the failure this method exists to prevent.#[must_use]is what stops theboolbeing ignored, which would reintroduce exactly that.The asymmetry is deliberate: a failed
writehas nothing to return, a failedreadhas no value to give, soboolandOption<T>are each the smallest honest type.3.
T: Copyon bothChosen: bound both methods on
T: Copy.Alternative: allow any
Tand useptr::write, which does not drop the old value.Without
Copy,writeoverwrites a slot whose previous occupant is never dropped — a leak for anyTwith a destructor, and silent.Copymakes 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.readcarries it for the same reason a bitwise copy out is only sound forCopy.4.
write/readrather thanset/getorstore/loadChosen:
write/read.get/setwould sit confusingly beside the existingget_mut, which has entirely different (proof-carrying) semantics.store/loadimplies atomics or explicit ordering, which these are not.write/readmatchesptr::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
UniqueWritewitness 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 competitorget_mutis strictly better wherever aThreadIndexexists, and nothing here relaxes, wraps or duplicates it. These serve the cases where no such index exists, and the honest alternative today isget_unchecked_mut, which is worse on every axis than a bounds-checkedunsafe fn. If you would rather the crate not grow a middle tier at all, the reasonable response is to reject this and keep users onget_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 fnadded 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'sThis is the core claim, and it is checkable against the existing docs.
get_unchecked_mutdocuments three obligations:idx < self.len()writerequires only (2) and (3). Obligation (1) is discharged by the bounds check, which returnsfalseinstead of reaching for the pointer. So: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_mutwith obligation (1) still live.Memory safety, per operation
Bounds.
idx < self.lenguardsself.ptr.add(idx).lenis the element count the view was constructed with, soidx < lenputs the offset inside the allocation — the same condition<[T]>::getrelies on. The byte offsetidx * size_of::<T>()cannot overflowisize, because an allocation oflen * size_of::<T>()bytes exists, which already implies that product is representable.Alignment.
ptroriginates fromDeviceBuffer<T>orfrom_mut_slice, so it is aligned forT;addadvances 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 < lenon 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 thatget_block_mutneedschecked_addfor, since it validatesstart + N.Type safety
T: Copyis load-bearing twice. Forwrite,ptr::writedoes not drop the overwritten value; with aDroptype that is a silent leak, so the bound makes the leak unrepresentable rather than merely undocumented. Forread, a by-value bitwise copy out of the slice is only a valid way to produce aTwhenThas no ownership semantics.No transmutation, no lifetime laundering. Neither method casts
T, and neither returns a reference —writeconsumes aTby value,readproduces one by value. So there is no borrow whose lifetime could outlive the view, and none of the&mut [T; N]-style aliasing questions thatget_block_muthas to answer.Initialization.
readcopying by value means a never-written slot yields an indeterminate bit pattern, which is UB for anyTwhose values are not all bit patterns (bool,char, enums, references). That obligation was missing from the# Safetysection and this PR now documents it; it is reachable today viaDeviceBuffer::uninitialized_async.writehas no such requirement — it is what makes a slot initialized.What is deliberately not proven, and why the
unsafeis honestThe data-race freedom is not established by these methods and cannot be.
&mut selfonwritedoes not help: the entire design ofDisjointSliceis that every thread holds its own view over the same buffer, so a per-thread&mutsays nothing about the other threads. That is the pre-existing model of the type, inherited unchanged.So the residual obligation is exactly:
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
boolis not a safety signal.ZSTs
Unguarded, and safely so. For
size_of::<T>() == 0,addis a no-op andptr::writetouches zero bytes, so even two threads "writing the same slot" writes nothing. This differs fromget_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 onnightly-2026-04-03. +97/−0 againstmain.