Skip to main content

strided_basic/
gather_plan.rs

1//! Prepared indexed plans over raw strided value and index layouts.
2//!
3//! This module owns the generic gather, dynamic-slice/update, and scatter
4//! traversals used by the erased replay layer. It models the XLA/tenferro
5//! indexed shape vocabulary, but keeps tensor allocation, dtype promotion, and
6//! frontend error policy outside `strided-kernel`.
7
8use core::mem::MaybeUninit;
9
10use num_complex::{Complex32, Complex64};
11
12use crate::copy_plan::{replay_fused_raw, CopyPlan, OverwriteWriter, ReadModifyWrite};
13use crate::cost::KernelClass;
14use crate::inline::InlineVec;
15use crate::raw_ops::pair_tiles;
16use crate::raw_ops::{fuse_pair_layout, FusedPairLayout};
17use crate::{Exec, RawStridedMut, RawStridedRef, Result, StridedError, RAW_FUSED_RANK_LIMIT};
18
19type AxisVec<T> = InlineVec<T>;
20
21/// Gather configuration shared by generic and erased replay.
22///
23/// The fields follow the usual gather vocabulary:
24///
25/// - `start_index_map[component]` names the operand axis controlled by a
26///   component in the index vector;
27/// - `collapsed_slice_dims` names operand axes whose slice size is one and
28///   which do not appear as output window axes;
29/// - `offset_dims` names output axes that represent window offsets;
30/// - output axes not in `offset_dims` are batch axes from `start_indices`;
31/// - `index_vector_dim == start_indices_rank` represents scalar index vectors.
32#[derive(Clone, Debug, Eq, PartialEq)]
33pub struct GatherSpec {
34    pub offset_dims: Vec<usize>,
35    pub collapsed_slice_dims: Vec<usize>,
36    pub start_index_map: Vec<usize>,
37    pub index_vector_dim: usize,
38    pub slice_sizes: Vec<usize>,
39}
40
41/// Index scalar types accepted by [`GatherPlan`].
42pub trait GatherIndex: Copy + Send + Sync {
43    fn to_i64(self) -> i64;
44}
45
46impl GatherIndex for i32 {
47    #[inline]
48    fn to_i64(self) -> i64 {
49        i64::from(self)
50    }
51}
52
53impl GatherIndex for i64 {
54    #[inline]
55    fn to_i64(self) -> i64 {
56        self
57    }
58}
59
60mod sealed {
61    pub trait Sealed {}
62}
63
64/// Element types accepted by [`ScatterPlan::execute`].
65///
66/// The trait is sealed: it is implemented for `f32`, `f64`, `i32`, `i64`,
67/// [`Complex32`] and [`Complex64`] (the dtypes the erased scatter entry
68/// dispatches) and cannot be implemented outside this crate. Its one method
69/// is the accumulating combine of additive scatter, so the typed and
70/// dtype-erased entries share the same element arithmetic.
71pub trait ScatterScalar: sealed::Sealed + Copy + Send + Sync {
72    /// The additive-scatter combine, `self + rhs`.
73    ///
74    /// Integer types wrap on overflow in every build profile
75    /// (`i32::wrapping_add`, `i64::wrapping_add`); floating-point and complex
76    /// types use IEEE addition, which has no overflow panic.
77    ///
78    /// # Examples
79    ///
80    /// ```
81    /// use strided_basic::ScatterScalar;
82    /// assert_eq!(ScatterScalar::wrapping_add(i32::MAX, 1), i32::MIN);
83    /// assert_eq!(ScatterScalar::wrapping_add(1.5_f64, 2.0), 3.5);
84    /// ```
85    fn wrapping_add(self, rhs: Self) -> Self;
86}
87
88macro_rules! impl_scatter_scalar {
89    (wrapping: $($int:ty),*; ieee: $($float:ty),*) => {
90        $(
91            impl sealed::Sealed for $int {}
92            impl ScatterScalar for $int {
93                #[inline(always)]
94                fn wrapping_add(self, rhs: Self) -> Self {
95                    <$int>::wrapping_add(self, rhs)
96                }
97            }
98        )*
99        $(
100            impl sealed::Sealed for $float {}
101            impl ScatterScalar for $float {
102                #[inline(always)]
103                fn wrapping_add(self, rhs: Self) -> Self {
104                    self + rhs
105                }
106            }
107        )*
108    };
109}
110
111impl_scatter_scalar!(wrapping: i32, i64; ieee: f32, f64, Complex32, Complex64);
112
113/// A compiled gather traversal for one value layout, index layout, and output layout.
114#[derive(Clone, Debug)]
115pub struct GatherPlan {
116    operand_dims: AxisVec<usize>,
117    operand_strides: AxisVec<isize>,
118    index_dims: AxisVec<usize>,
119    index_strides: AxisVec<isize>,
120    dest_dims: AxisVec<usize>,
121    dest_strides: AxisVec<isize>,
122    spec: GatherSpec,
123    replay: GatherReplay,
124    total: usize,
125}
126
127#[derive(Clone, Copy, Debug, Default)]
128struct GatherReplayAxis {
129    dest_step: isize,
130    dest_reset: isize,
131    window_step: isize,
132    window_reset: isize,
133    index_batch_step: isize,
134    index_batch_reset: isize,
135}
136
137#[derive(Clone, Debug)]
138struct GatherReplay {
139    axes: AxisVec<GatherReplayAxis>,
140    index_component_offsets: AxisVec<isize>,
141    index_operand_strides: AxisVec<isize>,
142}
143
144struct GatherReplayState {
145    coords: AxisVec<usize>,
146    dest_offset: isize,
147    window_offset: isize,
148    index_batch_offset: isize,
149}
150
151#[derive(Clone, Copy, Debug, Default)]
152struct WindowReplayAxis {
153    source_step: isize,
154    source_reset: isize,
155    dest_step: isize,
156    dest_reset: isize,
157}
158
159/// The offsets a strided window reaches, relative to its base offset.
160#[derive(Clone, Copy, Debug, Default)]
161struct OffsetSpan {
162    min: isize,
163    max: isize,
164}
165
166impl OffsetSpan {
167    /// Every offset the window reaches from `base` fits `isize`.
168    fn covers(&self, base: isize) -> Result<()> {
169        base.checked_add(self.min)
170            .ok_or(StridedError::OffsetOverflow)?;
171        base.checked_add(self.max)
172            .ok_or(StridedError::OffsetOverflow)?;
173        Ok(())
174    }
175}
176
177#[derive(Clone, Debug)]
178struct WindowReplay {
179    shape: AxisVec<usize>,
180    axes: AxisVec<WindowReplayAxis>,
181    /// Offsets the window reaches in the update and destination layouts,
182    /// relative to the runtime base. Fusing keeps the reachable offset set, so
183    /// these spans also bound every fused replay step.
184    source_span: OffsetSpan,
185    dest_span: OffsetSpan,
186}
187
188struct WindowReplayState {
189    coords: CoordScratch,
190    source_offset: isize,
191    dest_offset: isize,
192}
193
194#[derive(Clone, Debug)]
195struct ScatterReplay {
196    batch: WindowReplay,
197    window: WindowReplay,
198    index_component_offsets: AxisVec<isize>,
199}
200
201impl ScatterReplay {
202    // Scatter compile: batch and window shapes, the index layout with its vector
203    // stride and component count, and the collapsed-slice set.
204    #[allow(clippy::too_many_arguments)]
205    fn compile(
206        batch_shape: &[usize],
207        index_dims: &[usize],
208        index_strides: &[isize],
209        index_vector_dim: usize,
210        index_component_count: usize,
211        update_dims: &[usize],
212        update_strides: &[isize],
213        update_window_dims: &[usize],
214        is_update_window_dim: &[bool],
215        window_shape_updates: &[usize],
216        window_dims: &[usize],
217        dest_strides: &[isize],
218    ) -> Result<Self> {
219        let (
220            batch_source_strides,
221            batch_dest_strides,
222            window_source_strides,
223            window_dest_strides,
224            vector_stride,
225        ) = scatter_replay_strides(
226            index_dims,
227            index_strides,
228            index_vector_dim,
229            update_dims,
230            update_strides,
231            update_window_dims,
232            is_update_window_dim,
233            window_dims,
234            dest_strides,
235        );
236        let batch = WindowReplay::compile(batch_shape, &batch_source_strides, &batch_dest_strides)?;
237        let window = WindowReplay::compile(
238            window_shape_updates,
239            &window_source_strides,
240            &window_dest_strides,
241        )?;
242        let mut index_component_offsets = AxisVec::with_capacity(index_component_count);
243        for component in 0..index_component_count {
244            index_component_offsets.push(checked_offset_add(0, vector_stride, component)?);
245        }
246        Ok(Self {
247            batch,
248            window,
249            index_component_offsets,
250        })
251    }
252}
253
254// Replay strides: both shapes, the index strides and vector axis, the update
255// window set and the operand shape.
256#[allow(clippy::too_many_arguments)]
257fn scatter_replay_strides(
258    index_dims: &[usize],
259    index_strides: &[isize],
260    index_vector_dim: usize,
261    update_dims: &[usize],
262    update_strides: &[isize],
263    update_window_dims: &[usize],
264    is_update_window_dim: &[bool],
265    window_dims: &[usize],
266    dest_strides: &[isize],
267) -> (
268    AxisVec<isize>,
269    AxisVec<isize>,
270    AxisVec<isize>,
271    AxisVec<isize>,
272    isize,
273) {
274    let batch_source_strides = index_dims
275        .iter()
276        .zip(index_strides.iter())
277        .enumerate()
278        .filter_map(|(axis, (_, &stride))| (axis != index_vector_dim).then_some(stride))
279        .collect();
280    let batch_dest_strides = update_dims
281        .iter()
282        .zip(update_strides.iter())
283        .enumerate()
284        .filter_map(|(axis, (_, &stride))| (!is_update_window_dim[axis]).then_some(stride))
285        .collect();
286    let window_source_strides = update_window_dims
287        .iter()
288        .map(|&axis| update_strides[axis])
289        .collect();
290    let window_dest_strides = window_dims.iter().map(|&axis| dest_strides[axis]).collect();
291    let vector_stride = if index_vector_dim < index_dims.len() {
292        index_strides[index_vector_dim]
293    } else {
294        0
295    };
296    (
297        batch_source_strides,
298        batch_dest_strides,
299        window_source_strides,
300        window_dest_strides,
301        vector_stride,
302    )
303}
304
305impl WindowReplay {
306    fn compile(shape: &[usize], source_strides: &[isize], dest_strides: &[isize]) -> Result<Self> {
307        let source_span = validate_layout_span(shape, source_strides)?;
308        let dest_span = validate_layout_span(shape, dest_strides)?;
309        let mut fused_shape: AxisVec<usize> = AxisVec::with_capacity(shape.len());
310        let mut axes: AxisVec<WindowReplayAxis> = AxisVec::with_capacity(shape.len());
311        for (axis, &dim) in shape.iter().enumerate() {
312            let source_step = source_strides[axis];
313            let dest_step = dest_strides[axis];
314            if let Some(previous_axis) = fused_shape.len().checked_sub(1) {
315                let previous_extent = fused_shape[previous_axis];
316                let previous_extent =
317                    isize::try_from(previous_extent).map_err(|_| StridedError::OffsetOverflow)?;
318                let expected_source = axes[previous_axis]
319                    .source_step
320                    .checked_mul(previous_extent)
321                    .ok_or(StridedError::OffsetOverflow)?;
322                let expected_dest = axes[previous_axis]
323                    .dest_step
324                    .checked_mul(previous_extent)
325                    .ok_or(StridedError::OffsetOverflow)?;
326                if source_step == expected_source && dest_step == expected_dest {
327                    let fused_extent = fused_shape[previous_axis]
328                        .checked_mul(dim)
329                        .ok_or(StridedError::OffsetOverflow)?;
330                    fused_shape[previous_axis] = fused_extent;
331                    axes[previous_axis].source_reset =
332                        checked_replay_reset(fused_extent, axes[previous_axis].source_step)?;
333                    axes[previous_axis].dest_reset =
334                        checked_replay_reset(fused_extent, axes[previous_axis].dest_step)?;
335                    continue;
336                }
337            }
338            fused_shape.push(dim);
339            axes.push(WindowReplayAxis {
340                source_step,
341                source_reset: checked_replay_reset(dim, source_step)?,
342                dest_step,
343                dest_reset: checked_replay_reset(dim, dest_step)?,
344            });
345        }
346        Ok(Self {
347            shape: fused_shape,
348            axes,
349            source_span,
350            dest_span,
351        })
352    }
353
354    /// The replay state at linear index zero. Every coordinate is zero, so
355    /// this needs no offset arithmetic and cannot fail after the destination
356    /// copy.
357    fn start(&self, source_base: isize, dest_base: isize) -> WindowReplayState {
358        WindowReplayState {
359            coords: CoordScratch::new(self.shape.len()),
360            source_offset: source_base,
361            dest_offset: dest_base,
362        }
363    }
364
365    fn decode(
366        &self,
367        mut linear: usize,
368        source_base: isize,
369        dest_base: isize,
370    ) -> Result<WindowReplayState> {
371        let mut coords = CoordScratch::new(self.shape.len());
372        let mut source_offset = source_base;
373        let mut dest_offset = dest_base;
374        for (axis, (&dim, coord)) in self
375            .shape
376            .iter()
377            .zip(coords.as_mut_slice().iter_mut())
378            .enumerate()
379        {
380            *coord = linear % dim;
381            linear /= dim;
382            let replay_axis = self.axes[axis];
383            source_offset = checked_offset_add(source_offset, replay_axis.source_step, *coord)?;
384            dest_offset = checked_offset_add(dest_offset, replay_axis.dest_step, *coord)?;
385        }
386        Ok(WindowReplayState {
387            coords,
388            source_offset,
389            dest_offset,
390        })
391    }
392
393    #[inline]
394    fn advance(&self, state: &mut WindowReplayState) {
395        for ((coord, &dim), replay_axis) in state
396            .coords
397            .as_mut_slice()
398            .iter_mut()
399            .zip(self.shape.iter())
400            .zip(self.axes.iter())
401        {
402            let next = *coord + 1;
403            if next < dim {
404                *coord = next;
405                state.source_offset += replay_axis.source_step;
406                state.dest_offset += replay_axis.dest_step;
407                return;
408            }
409            *coord = 0;
410            state.source_offset += replay_axis.source_reset;
411            state.dest_offset += replay_axis.dest_reset;
412        }
413    }
414}
415
416/// Scatter configuration shared by generic and erased replay.
417///
418/// `ScatterPlan` implements tenferro's current additive scatter semantics:
419/// every update value is added to the selected output slot, so overlapping
420/// windows accumulate in deterministic column-major replay order.
421#[derive(Clone, Debug, Eq, PartialEq)]
422pub struct ScatterSpec {
423    pub update_window_dims: Vec<usize>,
424    pub inserted_window_dims: Vec<usize>,
425    pub scatter_dims_to_operand_dims: Vec<usize>,
426    pub index_vector_dim: usize,
427}
428
429/// A compiled fixed-window dynamic-slice traversal.
430#[derive(Clone, Debug)]
431pub struct DynamicSlicePlan {
432    operand_dims: AxisVec<usize>,
433    operand_strides: AxisVec<isize>,
434    start_dims: AxisVec<usize>,
435    start_strides: AxisVec<isize>,
436    dest_dims: AxisVec<usize>,
437    dest_strides: AxisVec<isize>,
438    slice_sizes: AxisVec<usize>,
439    total: usize,
440    /// Fused window traversal (dest strides, operand strides) replayed at the
441    /// runtime source base; `None` when its fused rank exceeds
442    /// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT), in which case
443    /// `replay`/`execute_parallel` walk the window instead.
444    window: Option<FusedPairLayout>,
445    replay: WindowReplay,
446}
447
448/// A compiled dynamic-update-slice traversal.
449///
450/// Execution first copies `operand` into `dest`, then overwrites the clamped
451/// update window. The plan performs no allocation for ranks at most
452/// [`RAW_FUSED_RANK_LIMIT`].
453#[derive(Clone, Debug)]
454pub struct DynamicUpdateSlicePlan {
455    operand_dims: AxisVec<usize>,
456    operand_strides: AxisVec<isize>,
457    start_dims: AxisVec<usize>,
458    start_strides: AxisVec<isize>,
459    update_dims: AxisVec<usize>,
460    update_strides: AxisVec<isize>,
461    dest_dims: AxisVec<usize>,
462    dest_strides: AxisVec<isize>,
463    total: usize,
464    copy_plan: CopyPlan,
465    /// Fused update window traversal (dest strides, update strides) replayed
466    /// at the runtime destination base; `None` when its fused rank exceeds
467    /// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT), in which case
468    /// `replay`/`execute_update_parallel` walk the window instead.
469    window: Option<FusedPairLayout>,
470    replay: WindowReplay,
471}
472
473/// Update-window metadata resolved before the operand copy.
474///
475/// Reading the clamped start vector, mapping it onto the destination layout,
476/// bounding the window against both runtime bases, and (on the rank-one
477/// contiguous path) converting the run bounds are the only fallible steps of
478/// the update phase. Preparing them up front keeps a rejected call from
479/// leaving `dest` copied but un-updated.
480enum UpdateWindow<'a, T> {
481    /// The window is empty: the copy alone is the result.
482    Empty,
483    /// Rank-one contiguous run, as the checked update run and destination
484    /// index.
485    RankOne { update: &'a [T], dest_start: usize },
486    /// Replay base in the destination layout, shared by the fused and generic
487    /// paths.
488    Replay { dest_base: isize },
489}
490
491/// A compiled additive scatter traversal.
492///
493/// Execution first copies `operand` into `dest`, then applies additive updates
494/// in deterministic column-major order. Boolean values are intentionally not
495/// supported because additive scatter has no bool semantics.
496#[derive(Clone, Debug)]
497pub struct ScatterPlan {
498    operand_dims: AxisVec<usize>,
499    operand_strides: AxisVec<isize>,
500    index_dims: AxisVec<usize>,
501    index_strides: AxisVec<isize>,
502    update_dims: AxisVec<usize>,
503    update_strides: AxisVec<isize>,
504    dest_dims: AxisVec<usize>,
505    dest_strides: AxisVec<isize>,
506    spec: ScatterSpec,
507    window_shape: AxisVec<usize>,
508    batch_elems: usize,
509    window_elems: usize,
510    copy_plan: CopyPlan,
511    replay: ScatterReplay,
512}
513
514impl GatherPlan {
515    /// Compile a gather plan for fixed operand, index, and destination layouts.
516    ///
517    /// # Errors
518    ///
519    /// Returns [`StridedError::StrideLengthMismatch`] when a stride list does
520    /// not match its dimension list, [`StridedError::OffsetOverflow`] when an
521    /// element count or a layout span does not fit `usize`/`isize`,
522    /// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
523    /// maps two logical indices onto one offset.
524    /// [`StridedError::RankMismatch`] reports `spec.slice_sizes` or
525    /// `spec.offset_dims` of the wrong length, or an index vector that does not
526    /// match `spec.start_index_map`;
527    /// [`StridedError::InvalidAxis`] reports `collapsed_slice_dims`,
528    /// `start_index_map`, or `offset_dims` that repeat or exceed their rank,
529    /// `index_vector_dim` beyond the index rank, a slice size beyond its
530    /// operand extent, or a collapsed axis whose slice size is not one; and
531    /// [`StridedError::ShapeMismatch`] reports a `dest_dims` that is not the
532    /// gathered window/batch shape.
533    pub fn compile(
534        operand_dims: &[usize],
535        operand_strides: &[isize],
536        index_dims: &[usize],
537        index_strides: &[isize],
538        dest_dims: &[usize],
539        dest_strides: &[isize],
540        spec: GatherSpec,
541    ) -> Result<Self> {
542        if operand_dims.len() != operand_strides.len()
543            || index_dims.len() != index_strides.len()
544            || dest_dims.len() != dest_strides.len()
545        {
546            return Err(StridedError::StrideLengthMismatch);
547        }
548        checked_total_len(operand_dims)?;
549        checked_total_len(index_dims)?;
550        let total = checked_total_len(dest_dims)?;
551        validate_layout_span(operand_dims, operand_strides)?;
552        validate_layout_span(index_dims, index_strides)?;
553        validate_layout_span(dest_dims, dest_strides)?;
554        if !crate::layout_check::is_injective_layout(dest_dims, dest_strides) {
555            return Err(StridedError::NonInjectiveOutputLayout);
556        }
557
558        let operand_rank = operand_dims.len();
559        if spec.slice_sizes.len() != operand_rank {
560            return Err(StridedError::RankMismatch(
561                spec.slice_sizes.len(),
562                operand_rank,
563            ));
564        }
565        validate_unique_axes(&spec.collapsed_slice_dims, operand_rank)?;
566        validate_unique_axes(&spec.start_index_map, operand_rank)?;
567        if spec.index_vector_dim > index_dims.len() {
568            return Err(StridedError::InvalidAxis {
569                axis: spec.index_vector_dim,
570                rank: index_dims.len() + 1,
571            });
572        }
573
574        for (axis, (&window, &dim)) in spec.slice_sizes.iter().zip(operand_dims.iter()).enumerate()
575        {
576            if window > dim {
577                return Err(StridedError::InvalidAxis {
578                    axis,
579                    rank: operand_rank,
580                });
581            }
582        }
583        for &axis in &spec.collapsed_slice_dims {
584            if spec.slice_sizes[axis] != 1 {
585                return Err(StridedError::InvalidAxis {
586                    axis,
587                    rank: operand_rank,
588                });
589            }
590        }
591
592        let index_vector_size = if spec.index_vector_dim == index_dims.len() {
593            1
594        } else {
595            index_dims[spec.index_vector_dim]
596        };
597        if index_vector_size != spec.start_index_map.len() {
598            return Err(StridedError::RankMismatch(
599                index_vector_size,
600                spec.start_index_map.len(),
601            ));
602        }
603
604        let window_dims = operand_window_dims(operand_rank, &spec.collapsed_slice_dims);
605        if spec.offset_dims.len() != window_dims.len() {
606            return Err(StridedError::RankMismatch(
607                spec.offset_dims.len(),
608                window_dims.len(),
609            ));
610        }
611
612        let batch_shape = index_batch_shape(index_dims, spec.index_vector_dim);
613        let out_rank = batch_shape.len() + spec.offset_dims.len();
614        validate_unique_axes(&spec.offset_dims, out_rank)?;
615
616        let mut out_axis_to_operand_dim: AxisVec<Option<usize>> =
617            (0..out_rank).map(|_| None).collect();
618        for (offset_axis, &out_axis) in spec.offset_dims.iter().enumerate() {
619            out_axis_to_operand_dim[out_axis] = Some(window_dims[offset_axis]);
620        }
621
622        let mut expected_dest_dims: AxisVec<usize> = AxisVec::with_capacity(out_rank);
623        let mut batch_axis = 0usize;
624        for &operand_dim in &out_axis_to_operand_dim {
625            match operand_dim {
626                Some(axis) => expected_dest_dims.push(spec.slice_sizes[axis]),
627                None => {
628                    expected_dest_dims.push(batch_shape[batch_axis]);
629                    batch_axis += 1;
630                }
631            }
632        }
633        if dest_dims != &expected_dest_dims[..] {
634            return Err(StridedError::ShapeMismatch(
635                dest_dims.to_vec(),
636                expected_dest_dims.to_vec(),
637            ));
638        }
639
640        let batch_index_strides: AxisVec<isize> = index_dims
641            .iter()
642            .zip(index_strides.iter())
643            .enumerate()
644            .filter_map(|(axis, (_, &stride))| (axis != spec.index_vector_dim).then_some(stride))
645            .collect();
646        let mut batch_axis = 0usize;
647        let mut replay_axes = AxisVec::with_capacity(out_rank);
648        for (out_axis, &operand_dim) in out_axis_to_operand_dim.iter().enumerate() {
649            let (window_step, index_batch_step) = match operand_dim {
650                Some(axis) => (operand_strides[axis], 0),
651                None => {
652                    let step = batch_index_strides[batch_axis];
653                    batch_axis += 1;
654                    (0, step)
655                }
656            };
657            replay_axes.push(GatherReplayAxis {
658                dest_step: dest_strides[out_axis],
659                dest_reset: checked_replay_reset(dest_dims[out_axis], dest_strides[out_axis])?,
660                window_step,
661                window_reset: checked_replay_reset(dest_dims[out_axis], window_step)?,
662                index_batch_step,
663                index_batch_reset: checked_replay_reset(dest_dims[out_axis], index_batch_step)?,
664            });
665        }
666
667        let vector_stride = if spec.index_vector_dim < index_dims.len() {
668            index_strides[spec.index_vector_dim]
669        } else {
670            0
671        };
672        let mut index_component_offsets = AxisVec::with_capacity(spec.start_index_map.len());
673        for component in 0..spec.start_index_map.len() {
674            index_component_offsets.push(checked_offset_add(0, vector_stride, component)?);
675        }
676
677        let index_operand_strides: AxisVec<isize> = spec
678            .start_index_map
679            .iter()
680            .map(|&axis| operand_strides[axis])
681            .collect();
682
683        Ok(Self {
684            operand_dims: operand_dims.into(),
685            operand_strides: operand_strides.into(),
686            index_dims: index_dims.into(),
687            index_strides: index_strides.into(),
688            dest_dims: dest_dims.into(),
689            dest_strides: dest_strides.into(),
690            spec,
691            replay: GatherReplay {
692                axes: replay_axes,
693                index_component_offsets,
694                index_operand_strides,
695            },
696            total,
697        })
698    }
699
700    #[inline]
701    pub fn spec(&self) -> &GatherSpec {
702        &self.spec
703    }
704
705    #[inline]
706    pub fn dest_dims(&self) -> &[usize] {
707        &self.dest_dims
708    }
709
710    /// Execute the prepared gather traversal.
711    ///
712    /// # Errors
713    ///
714    /// Returns [`StridedError::PlanLayoutMismatch`] when the operand, index,
715    /// or destination view does not carry its compiled extents and strides,
716    /// before any destination write, and
717    /// [`StridedError::OffsetOverflow`] when a replayed chunk's offset
718    /// arithmetic cannot be represented. Start indices are clamped into the
719    /// operand window, so an out-of-range index is not an error. The offset
720    /// arithmetic runs per worker above the threading threshold, so a
721    /// destination split across workers may be partially written when that
722    /// error surfaces.
723    pub fn execute<T, I>(
724        &self,
725        dest: &mut RawStridedMut<'_, T>,
726        operand: &RawStridedRef<'_, T>,
727        start_indices: &RawStridedRef<'_, I>,
728        exec: Exec<'_>,
729    ) -> Result<()>
730    where
731        T: Copy + Send + Sync,
732        I: GatherIndex,
733    {
734        self.execute_with_writer(dest, operand, start_indices, exec)
735    }
736
737    /// Execute the prepared gather into a destination whose reachable slots
738    /// may be uninitialized. Every logical destination slot is written.
739    pub(crate) fn execute_uninit<T, I>(
740        &self,
741        dest: &mut RawStridedMut<'_, MaybeUninit<T>>,
742        operand: &RawStridedRef<'_, T>,
743        start_indices: &RawStridedRef<'_, I>,
744        exec: Exec<'_>,
745    ) -> Result<()>
746    where
747        T: Copy + Send + Sync,
748        I: GatherIndex,
749    {
750        self.execute_with_writer(dest, operand, start_indices, exec)
751    }
752
753    fn execute_with_writer<T, I, W>(
754        &self,
755        dest: &mut W,
756        operand: &RawStridedRef<'_, T>,
757        start_indices: &RawStridedRef<'_, I>,
758        exec: Exec<'_>,
759    ) -> Result<()>
760    where
761        T: Copy + Send + Sync,
762        I: GatherIndex,
763        W: OverwriteWriter<T>,
764    {
765        self.check_call(dest, operand, start_indices)?;
766        if self.total == 0 {
767            return Ok(());
768        }
769        if self.uses_rank_one_scalar_take_path() {
770            let exec = crate::cost::for_len_tree(exec, KernelClass::Copy, self.total);
771            if !exec.is_serial() {
772                return self.execute_rank_one_scalar_take_parallel(
773                    dest,
774                    operand,
775                    start_indices,
776                    exec,
777                );
778            }
779            return self.execute_rank_one_scalar_take(dest, operand, start_indices);
780        }
781        let exec = crate::cost::for_len_tree(exec, KernelClass::Copy, self.total);
782        if !exec.is_serial() {
783            return self.execute_parallel(dest, operand, start_indices, exec);
784        }
785
786        let mut state =
787            self.decode_replay_state(0, dest.offset(), operand.offset(), start_indices.offset())?;
788        let operand_data = operand.data();
789        let index_data = start_indices.data();
790
791        // INVARIANT: the checked decode starts at a valid logical output. Each
792        // replay axis has checked step/reset deltas, so this state remains the
793        // corresponding destination, window, and batch-index offsets.
794        for _ in 0..self.total {
795            // INVARIANT: window_offset plus every clamped mapped contribution
796            // is an operand offset for coordinates inside operand_dims; the
797            // validated operand span and RawStridedRef reachability therefore
798            // keep the fresh source offset inside the allocation.
799            let mut source_offset = state.window_offset;
800            for ((&index_component_offset, &operand_stride), &operand_dim) in self
801                .replay
802                .index_component_offsets
803                .iter()
804                .zip(self.replay.index_operand_strides.iter())
805                .zip(self.spec.start_index_map.iter())
806            {
807                let index_offset = state.index_batch_offset + index_component_offset;
808                // SAFETY: checked index layout replay and RawStridedRef
809                // reachability prove this component read is in bounds.
810                let start = unsafe { *index_data.as_ptr().offset(index_offset) }.to_i64();
811                let clamped = self.clamp_window_start(start, operand_dim);
812                source_offset += operand_stride * clamped as isize;
813            }
814
815            // SAFETY: checked replay metadata and the validated writer prove
816            // both the source and the distinct destination offset are valid.
817            let value = unsafe { *operand_data.as_ptr().offset(source_offset) };
818            unsafe { dest.write_at(state.dest_offset, value) };
819            self.advance_replay_state(&mut state);
820        }
821        Ok(())
822    }
823
824    fn uses_rank_one_scalar_take_path(&self) -> bool {
825        self.operand_dims.len() == 1
826            && self.index_dims.len() == 1
827            && self.dest_dims.len() == 1
828            && self.operand_strides[0] == 1
829            && self.index_strides[0] == 1
830            && self.dest_strides[0] == 1
831            && self.spec.offset_dims.is_empty()
832            && self.spec.collapsed_slice_dims.as_slice() == [0]
833            && self.spec.start_index_map.as_slice() == [0]
834            && self.spec.index_vector_dim == 1
835            && self.spec.slice_sizes.as_slice() == [1]
836    }
837
838    fn execute_rank_one_scalar_take<T, I, W>(
839        &self,
840        dest: &mut W,
841        operand: &RawStridedRef<'_, T>,
842        start_indices: &RawStridedRef<'_, I>,
843    ) -> Result<()>
844    where
845        T: Copy,
846        I: GatherIndex,
847        W: OverwriteWriter<T>,
848    {
849        let mut dest_offset = dest.offset();
850        let mut index_offset = start_indices.offset();
851        let operand_offset = operand.offset();
852        let operand_data = operand.data();
853        let index_data = start_indices.data();
854
855        // INVARIANT: compile and check_call validated compact rank-one layouts,
856        // so incrementing these offsets once per logical element stays within
857        // the validated allocations and cannot overflow isize.
858        // `index_offset` is the pointer walk of this gather line, not a counter.
859        #[allow(clippy::explicit_counter_loop)]
860        for _ in 0..self.total {
861            // SAFETY: the invariant above proves all three offsets are in bounds.
862            unsafe {
863                let start = (*index_data.as_ptr().offset(index_offset)).to_i64();
864                let source_offset = operand_offset + self.clamp_window_start(start, 0) as isize;
865                dest.write_at(dest_offset, *operand_data.as_ptr().offset(source_offset));
866            }
867            dest_offset += 1;
868            index_offset += 1;
869        }
870        Ok(())
871    }
872
873    fn execute_rank_one_scalar_take_parallel<T, I, W>(
874        &self,
875        dest: &mut W,
876        operand: &RawStridedRef<'_, T>,
877        start_indices: &RawStridedRef<'_, I>,
878        exec: Exec<'_>,
879    ) -> Result<()>
880    where
881        T: Copy + Send + Sync,
882        I: GatherIndex,
883        W: OverwriteWriter<T>,
884    {
885        let dest_offset = dest.offset();
886        let operand_offset = operand.offset();
887        let index_offset = start_indices.offset();
888        // SAFETY: check_call validated the writer's complete destination layout.
889        let dest_ptr = crate::threading::SendPtr(unsafe { dest.data_ptr() });
890        let operand_ptr = crate::threading::SendPtr(operand.data().as_ptr() as *mut T);
891        let index_ptr = crate::threading::SendPtr(start_indices.data().as_ptr() as *mut I);
892
893        crate::threading::parallel_map_reduce(
894            0..self.total,
895            exec,
896            &|range| {
897                let dest_ptr = dest_ptr.as_ptr();
898                let operand_ptr = operand_ptr.as_const();
899                let index_ptr = index_ptr.as_const();
900                // INVARIANT: the validated compact rank-one layouts map each
901                // output position to one distinct destination offset.
902                for position in range {
903                    let position = position as isize;
904                    // SAFETY: the invariant above proves the source and distinct
905                    // destination offsets are in their validated allocations.
906                    unsafe {
907                        let start = (*index_ptr.offset(index_offset + position)).to_i64();
908                        let source_offset =
909                            operand_offset + self.clamp_window_start(start, 0) as isize;
910                        dest_ptr
911                            .offset(dest_offset + position)
912                            .write(operand_ptr.offset(source_offset).read());
913                    }
914                }
915                Ok(())
916            },
917            &|left, right| left.and(right),
918        )
919    }
920
921    fn execute_parallel<T, I, W>(
922        &self,
923        dest: &mut W,
924        operand: &RawStridedRef<'_, T>,
925        start_indices: &RawStridedRef<'_, I>,
926        exec: Exec<'_>,
927    ) -> Result<()>
928    where
929        T: Copy + Send + Sync,
930        I: GatherIndex,
931        W: OverwriteWriter<T>,
932    {
933        let dest_offset_base = dest.offset();
934        let operand_offset_base = operand.offset();
935        let index_offset_base = start_indices.offset();
936        // SAFETY: the validated writer owns the destination allocation.
937        let dest_ptr = crate::threading::SendPtr(unsafe { dest.data_ptr() });
938        let operand_ptr = crate::threading::SendPtr(operand.data().as_ptr() as *mut T);
939        let index_ptr = crate::threading::SendPtr(start_indices.data().as_ptr() as *mut I);
940
941        crate::threading::parallel_map_reduce(
942            0..self.total,
943            exec,
944            &|range| {
945                let mut state = self.decode_replay_state(
946                    range.start,
947                    dest_offset_base,
948                    operand_offset_base,
949                    index_offset_base,
950                )?;
951                let dest_ptr = dest_ptr.as_ptr();
952                let operand_ptr = operand_ptr.as_const();
953                let index_ptr = index_ptr.as_const();
954
955                // INVARIANT: this worker owns a disjoint logical range. Checked
956                // range-start decode plus checked replay deltas keeps every
957                // state at its corresponding output, and injectivity makes all
958                // writes across workers distinct.
959                for _ in range {
960                    // INVARIANT: source_offset is freshly based on the current
961                    // window offset; clamped mapped coordinates remain inside
962                    // the validated operand span and are never accumulated.
963                    let mut source_offset = state.window_offset;
964                    for ((&index_component_offset, &operand_stride), &operand_dim) in self
965                        .replay
966                        .index_component_offsets
967                        .iter()
968                        .zip(self.replay.index_operand_strides.iter())
969                        .zip(self.spec.start_index_map.iter())
970                    {
971                        let index_offset = state.index_batch_offset + index_component_offset;
972                        // SAFETY: the checked index span and this worker's
973                        // validated range-start state prove this read is valid.
974                        let start = unsafe { (*index_ptr.offset(index_offset)).to_i64() };
975                        let clamped = self.clamp_window_start(start, operand_dim);
976                        source_offset += operand_stride * clamped as isize;
977                    }
978
979                    // SAFETY: the source proof above and distinct destination
980                    // invariant justify these raw accesses.
981                    unsafe {
982                        dest_ptr
983                            .offset(state.dest_offset)
984                            .write(operand_ptr.offset(source_offset).read());
985                    }
986                    self.advance_replay_state(&mut state);
987                }
988                Ok(())
989            },
990            &|left, right| left.and(right),
991        )
992    }
993
994    fn check_call<T, I, W>(
995        &self,
996        dest: &W,
997        operand: &RawStridedRef<'_, T>,
998        start_indices: &RawStridedRef<'_, I>,
999    ) -> Result<()>
1000    where
1001        W: OverwriteWriter<T>,
1002    {
1003        if dest.dims() != &self.dest_dims[..]
1004            || dest.strides() != &self.dest_strides[..]
1005            || operand.dims() != &self.operand_dims[..]
1006            || operand.strides() != &self.operand_strides[..]
1007            || start_indices.dims() != &self.index_dims[..]
1008            || start_indices.strides() != &self.index_strides[..]
1009        {
1010            return Err(StridedError::PlanLayoutMismatch);
1011        }
1012        Ok(())
1013    }
1014
1015    fn decode_replay_state(
1016        &self,
1017        mut linear: usize,
1018        dest_offset_base: isize,
1019        operand_offset_base: isize,
1020        index_offset_base: isize,
1021    ) -> Result<GatherReplayState> {
1022        let mut coords = AxisVec::with_capacity(self.dest_dims.len());
1023        let mut dest_offset = dest_offset_base;
1024        let mut window_offset = operand_offset_base;
1025        let mut index_batch_offset = index_offset_base;
1026        for (axis, &dim) in self.dest_dims.iter().enumerate() {
1027            let coord = linear % dim;
1028            linear /= dim;
1029            let replay_axis = self.replay.axes[axis];
1030            coords.push(coord);
1031            dest_offset = checked_offset_add(dest_offset, replay_axis.dest_step, coord)?;
1032            window_offset = checked_offset_add(window_offset, replay_axis.window_step, coord)?;
1033            index_batch_offset =
1034                checked_offset_add(index_batch_offset, replay_axis.index_batch_step, coord)?;
1035        }
1036        Ok(GatherReplayState {
1037            coords,
1038            dest_offset,
1039            window_offset,
1040            index_batch_offset,
1041        })
1042    }
1043
1044    #[inline]
1045    fn advance_replay_state(&self, state: &mut GatherReplayState) {
1046        for (axis, replay_axis) in self.replay.axes.iter().enumerate() {
1047            let coord = state.coords[axis];
1048            if coord + 1 < self.dest_dims[axis] {
1049                state.coords[axis] = coord + 1;
1050                state.dest_offset += replay_axis.dest_step;
1051                state.window_offset += replay_axis.window_step;
1052                state.index_batch_offset += replay_axis.index_batch_step;
1053                return;
1054            }
1055            state.coords[axis] = 0;
1056            state.dest_offset += replay_axis.dest_reset;
1057            state.window_offset += replay_axis.window_reset;
1058            state.index_batch_offset += replay_axis.index_batch_reset;
1059        }
1060    }
1061
1062    #[inline]
1063    fn clamp_window_start(&self, start: i64, operand_dim: usize) -> usize {
1064        let dim_size = self.operand_dims[operand_dim];
1065        let window_size = self.spec.slice_sizes[operand_dim];
1066        let max_start = dim_size.saturating_sub(window_size) as i64;
1067        start.clamp(0, max_start) as usize
1068    }
1069}
1070
1071impl DynamicSlicePlan {
1072    /// Compile a fixed-window dynamic-slice traversal.
1073    ///
1074    /// `start_*` describes a rank-1 index vector whose length equals the
1075    /// operand rank. `dest_dims` must equal `slice_sizes`.
1076    ///
1077    /// # Errors
1078    ///
1079    /// Returns [`StridedError::StrideLengthMismatch`] when a stride list does
1080    /// not match its dimension list, [`StridedError::RankMismatch`] when
1081    /// `slice_sizes` differs from the operand rank or the start layout is not a
1082    /// rank-1 vector of that same length,
1083    /// [`StridedError::OffsetOverflow`] when an element count or layout span
1084    /// does not fit `usize`/`isize`, [`StridedError::ShapeMismatch`] when
1085    /// `dest_dims` differs from `slice_sizes` in extent or rank,
1086    /// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
1087    /// maps two logical indices onto one offset, and
1088    /// [`StridedError::InvalidAxis`] when a slice size exceeds its operand
1089    /// extent.
1090    pub fn compile(
1091        operand_dims: &[usize],
1092        operand_strides: &[isize],
1093        start_dims: &[usize],
1094        start_strides: &[isize],
1095        dest_dims: &[usize],
1096        dest_strides: &[isize],
1097        slice_sizes: &[usize],
1098    ) -> Result<Self> {
1099        if operand_dims.len() != operand_strides.len()
1100            || start_dims.len() != start_strides.len()
1101            || dest_dims.len() != dest_strides.len()
1102        {
1103            return Err(StridedError::StrideLengthMismatch);
1104        }
1105        if slice_sizes.len() != operand_dims.len() {
1106            return Err(StridedError::RankMismatch(
1107                slice_sizes.len(),
1108                operand_dims.len(),
1109            ));
1110        }
1111        validate_start_vector(start_dims, operand_dims.len())?;
1112        checked_total_len(operand_dims)?;
1113        checked_total_len(start_dims)?;
1114        let total = checked_total_len(dest_dims)?;
1115        validate_layout_span(operand_dims, operand_strides)?;
1116        validate_layout_span(start_dims, start_strides)?;
1117        validate_layout_span(dest_dims, dest_strides)?;
1118        if dest_dims != slice_sizes {
1119            return Err(StridedError::ShapeMismatch(
1120                dest_dims.to_vec(),
1121                slice_sizes.to_vec(),
1122            ));
1123        }
1124        if !crate::layout_check::is_injective_layout(dest_dims, dest_strides) {
1125            return Err(StridedError::NonInjectiveOutputLayout);
1126        }
1127        validate_window_sizes(operand_dims, slice_sizes)?;
1128        let replay = WindowReplay::compile(slice_sizes, operand_strides, dest_strides)?;
1129
1130        Ok(Self {
1131            operand_dims: operand_dims.into(),
1132            operand_strides: operand_strides.into(),
1133            start_dims: start_dims.into(),
1134            start_strides: start_strides.into(),
1135            dest_dims: dest_dims.into(),
1136            dest_strides: dest_strides.into(),
1137            slice_sizes: slice_sizes.into(),
1138            total,
1139            window: fuse_pair_layout(slice_sizes, dest_strides, operand_strides),
1140            replay,
1141        })
1142    }
1143
1144    /// Execute the prepared dynamic-slice traversal.
1145    ///
1146    /// # Errors
1147    ///
1148    /// Returns [`StridedError::PlanLayoutMismatch`] when the operand, start,
1149    /// or destination view does not carry its compiled extents and strides,
1150    /// before any destination write. Start values are clamped to
1151    /// `operand_dims - slice_sizes`, so an out-of-range start is not an
1152    /// error.
1153    pub fn execute<T, I>(
1154        &self,
1155        dest: &mut RawStridedMut<'_, T>,
1156        operand: &RawStridedRef<'_, T>,
1157        starts: &RawStridedRef<'_, I>,
1158        exec: Exec<'_>,
1159    ) -> Result<()>
1160    where
1161        T: Copy + Send + Sync,
1162        I: GatherIndex,
1163    {
1164        self.execute_with_writer(dest, operand, starts, exec)
1165    }
1166
1167    pub(crate) fn execute_uninit<T, I>(
1168        &self,
1169        dest: &mut RawStridedMut<'_, MaybeUninit<T>>,
1170        operand: &RawStridedRef<'_, T>,
1171        starts: &RawStridedRef<'_, I>,
1172        exec: Exec<'_>,
1173    ) -> Result<()>
1174    where
1175        T: Copy + Send + Sync,
1176        I: GatherIndex,
1177    {
1178        self.execute_with_writer(dest, operand, starts, exec)
1179    }
1180
1181    fn execute_with_writer<T, I, W>(
1182        &self,
1183        dest: &mut W,
1184        operand: &RawStridedRef<'_, T>,
1185        starts: &RawStridedRef<'_, I>,
1186        exec: Exec<'_>,
1187    ) -> Result<()>
1188    where
1189        T: Copy + Send + Sync,
1190        I: GatherIndex,
1191        W: OverwriteWriter<T>,
1192    {
1193        self.check_call(dest, operand, starts)?;
1194        if self.total == 0 {
1195            return Ok(());
1196        }
1197        if self.uses_rank_one_contiguous_path() {
1198            return self.execute_rank_one_contiguous(dest, operand, starts, exec);
1199        }
1200        if let Some(window) = &self.window {
1201            return self.execute_fused_window(dest, operand, starts, window, exec);
1202        }
1203        let replay = &self.replay;
1204        let exec = crate::cost::for_len_tree(exec, KernelClass::Copy, self.total);
1205        if !exec.is_serial() {
1206            return self.execute_parallel(dest, operand, starts, exec, replay);
1207        }
1208
1209        let mut starts_storage = CoordScratch::new(self.operand_dims.len());
1210        let clamped_starts = starts_storage.as_mut_slice();
1211        read_clamped_starts(
1212            starts,
1213            &self.operand_dims,
1214            &self.slice_sizes,
1215            clamped_starts,
1216        )?;
1217        let source_base =
1218            checked_strided_offset(operand.offset(), &self.operand_strides, clamped_starts)?;
1219        let mut state = replay.decode(0, source_base, dest.offset())?;
1220        let operand_data = operand.data();
1221
1222        // INVARIANT: compile validated the full operand/destination spans and the
1223        // replay window spans; checked bases plus checked reset deltas therefore
1224        // keep every current offset reachable without per-element offset scans.
1225        for _ in 0..self.total {
1226            // SAFETY: the invariant above proves both current offsets are valid.
1227            let value = unsafe { *operand_data.as_ptr().offset(state.source_offset) };
1228            // SAFETY: the invariant above proves this logical destination offset
1229            // is in-bounds, and the output layout is injective.
1230            unsafe { dest.write_at(state.dest_offset, value) };
1231            replay.advance(&mut state);
1232        }
1233        Ok(())
1234    }
1235
1236    /// Replay the compiled fused window from the clamped runtime source base.
1237    ///
1238    /// The window is a CopyPlan-style fused layout, so full inner runs are
1239    /// replayed with a pointer loop (slice copies for unit strides) and the
1240    /// work is split across workers above the repository threshold.
1241    fn execute_fused_window<T, I, W>(
1242        &self,
1243        dest: &mut W,
1244        operand: &RawStridedRef<'_, T>,
1245        starts: &RawStridedRef<'_, I>,
1246        window: &FusedPairLayout,
1247        exec: Exec<'_>,
1248    ) -> Result<()>
1249    where
1250        T: Copy + Send + Sync,
1251        I: GatherIndex,
1252        W: OverwriteWriter<T>,
1253    {
1254        let mut starts_storage = CoordScratch::new(self.operand_dims.len());
1255        let clamped_starts = starts_storage.as_mut_slice();
1256        read_clamped_starts(
1257            starts,
1258            &self.operand_dims,
1259            &self.slice_sizes,
1260            clamped_starts,
1261        )?;
1262        let source_base =
1263            checked_strided_offset(operand.offset(), &self.operand_strides, clamped_starts)?;
1264        let dest_base = dest.offset();
1265        // SAFETY: the validated writer owns the destination allocation.
1266        let dest_ptr = unsafe { dest.data_ptr() }.cast::<MaybeUninit<T>>();
1267        let tiles = pair_tiles::<MaybeUninit<T>, T>(window);
1268        // SAFETY: `window` fuses `slice_sizes` with the checked destination
1269        // and operand strides. The clamped window `start + slice_sizes` lies
1270        // inside `operand_dims`, so every source offset from `source_base` is
1271        // an offset the validated operand view can reach; the destination has
1272        // exactly `slice_sizes` dims and its validated layout reaches every
1273        // destination offset. Compile proved the destination injective, and
1274        // the exclusive writer borrow does not overlap the shared operand.
1275        // Writing `MaybeUninit::new` is valid for both initialized and
1276        // uninitialized destination slots. The injective destination lets the
1277        // window replay its tiles.
1278        unsafe {
1279            replay_fused_raw(
1280                dest_ptr,
1281                dest_base,
1282                operand.data().as_ptr(),
1283                source_base,
1284                window,
1285                tiles.as_ref(),
1286                |slot: &mut MaybeUninit<T>, value: T| *slot = MaybeUninit::new(value),
1287                KernelClass::Copy.ns_per_element(),
1288                exec,
1289            );
1290        }
1291        Ok(())
1292    }
1293
1294    #[inline]
1295    fn uses_rank_one_contiguous_path(&self) -> bool {
1296        self.operand_dims.len() == 1 && self.operand_strides[0] == 1 && self.dest_strides[0] == 1
1297    }
1298
1299    fn execute_rank_one_contiguous<T, I, W>(
1300        &self,
1301        dest: &mut W,
1302        operand: &RawStridedRef<'_, T>,
1303        starts: &RawStridedRef<'_, I>,
1304        exec: Exec<'_>,
1305    ) -> Result<()>
1306    where
1307        T: Copy + Send + Sync,
1308        I: GatherIndex,
1309        W: OverwriteWriter<T>,
1310    {
1311        let mut clamped_starts = [0usize; 1];
1312        read_clamped_starts(
1313            starts,
1314            &self.operand_dims,
1315            &self.slice_sizes,
1316            &mut clamped_starts,
1317        )?;
1318        let source_start = checked_offset_add(operand.offset(), 1, clamped_starts[0])?;
1319        let source_start =
1320            usize::try_from(source_start).map_err(|_| StridedError::OffsetOverflow)?;
1321        let dest_start =
1322            usize::try_from(dest.offset()).map_err(|_| StridedError::OffsetOverflow)?;
1323        let source_end = source_start
1324            .checked_add(self.total)
1325            .ok_or(StridedError::OffsetOverflow)?;
1326        let source = operand
1327            .data()
1328            .get(source_start..source_end)
1329            .ok_or(StridedError::OffsetOverflow)?;
1330        // SAFETY: the validated writer owns the destination allocation.
1331        let dest_ptr = unsafe { dest.data_ptr() };
1332        // SAFETY: the source run was resolved above (`operand.data().get`,
1333        // :1260) and the destination run is the plan's own layout: compile set
1334        // `total = checked_total_len(dest_dims)` with `dest_dims == slice_sizes`
1335        // (:1050-:1054), required `dest_strides[0] == 1` on this rank-one path
1336        // (:1228), and `check_call` (:1341) proved the writer carries exactly the
1337        // compiled destination layout, whose reachable offsets `RawStridedMut::new`
1338        // validated (strided-view/src/raw.rs:1036, `validate_bounds` at :1042;
1339        // strided-view/src/view.rs:187). `data_ptr()` (copy_plan.rs:41) is the
1340        // allocation base, so `dest.offset() .. dest.offset() + total` is inside the
1341        // writer's allocation and the chunked workers write disjoint slices of it.
1342        unsafe {
1343            // Chunked across workers above the repository threshold; each
1344            // worker writes a disjoint chunk of the checked destination run.
1345            crate::threading::copy_contiguous(
1346                source.as_ptr(),
1347                dest_ptr.add(dest_start),
1348                self.total,
1349                exec,
1350            );
1351        }
1352        Ok(())
1353    }
1354
1355    fn execute_parallel<T, I, W>(
1356        &self,
1357        dest: &mut W,
1358        operand: &RawStridedRef<'_, T>,
1359        starts: &RawStridedRef<'_, I>,
1360        exec: Exec<'_>,
1361        replay: &WindowReplay,
1362    ) -> Result<()>
1363    where
1364        T: Copy + Send + Sync,
1365        I: GatherIndex,
1366        W: OverwriteWriter<T>,
1367    {
1368        let mut clamped_starts: AxisVec<usize> = (0..self.operand_dims.len()).map(|_| 0).collect();
1369        read_clamped_starts(
1370            starts,
1371            &self.operand_dims,
1372            &self.slice_sizes,
1373            &mut clamped_starts,
1374        )?;
1375        let source_base =
1376            checked_strided_offset(operand.offset(), &self.operand_strides, &clamped_starts)?;
1377        let dest_base = dest.offset();
1378        let operand_ptr = crate::threading::SendPtr(operand.data().as_ptr() as *mut T);
1379        // SAFETY: the validated writer owns the destination allocation.
1380        let dest_ptr = crate::threading::SendPtr(unsafe { dest.data_ptr() });
1381
1382        crate::threading::parallel_map_reduce(
1383            0..self.total,
1384            exec,
1385            &|range| {
1386                let mut state = replay.decode(range.start, source_base, dest_base)?;
1387                let operand_ptr = operand_ptr.as_const();
1388                let dest_ptr = dest_ptr.as_ptr();
1389
1390                // INVARIANT: each worker decodes one checked range start. Its
1391                // replay range is disjoint, and the injective output layout makes
1392                // all writes distinct across workers.
1393                for _ in range {
1394                    // SAFETY: checked replay bases/resets keep both offsets in
1395                    // their validated allocations.
1396                    unsafe {
1397                        dest_ptr
1398                            .offset(state.dest_offset)
1399                            .write(operand_ptr.offset(state.source_offset).read());
1400                    }
1401                    replay.advance(&mut state);
1402                }
1403                Ok(())
1404            },
1405            &|left, right| left.and(right),
1406        )
1407    }
1408
1409    fn check_call<T, I, W>(
1410        &self,
1411        dest: &W,
1412        operand: &RawStridedRef<'_, T>,
1413        starts: &RawStridedRef<'_, I>,
1414    ) -> Result<()>
1415    where
1416        W: OverwriteWriter<T>,
1417    {
1418        if dest.dims() != &self.dest_dims[..]
1419            || dest.strides() != &self.dest_strides[..]
1420            || operand.dims() != &self.operand_dims[..]
1421            || operand.strides() != &self.operand_strides[..]
1422            || starts.dims() != &self.start_dims[..]
1423            || starts.strides() != &self.start_strides[..]
1424        {
1425            return Err(StridedError::PlanLayoutMismatch);
1426        }
1427        Ok(())
1428    }
1429}
1430
1431impl DynamicUpdateSlicePlan {
1432    /// Compile a dynamic-update-slice traversal.
1433    ///
1434    /// `dest_dims` must match `operand_dims`; execution materializes
1435    /// `dest = operand` and then overwrites the clamped update window.
1436    ///
1437    /// # Errors
1438    ///
1439    /// Returns [`StridedError::StrideLengthMismatch`] when a stride list does
1440    /// not match its dimension list, [`StridedError::RankMismatch`] when
1441    /// `update_dims` differs from the operand rank or the start layout is not a
1442    /// rank-1 vector of that same length,
1443    /// [`StridedError::OffsetOverflow`] when an element count or layout span
1444    /// does not fit `usize`/`isize`, [`StridedError::ShapeMismatch`] when
1445    /// `dest_dims` differs from `operand_dims` in extent or rank,
1446    /// [`StridedError::NonInjectiveOutputLayout`] when the destination layout
1447    /// maps two logical indices onto one offset, and
1448    /// [`StridedError::InvalidAxis`] when an update extent exceeds its
1449    /// operand extent.
1450    // Compile key: the operand, start, update and destination layouts, as four
1451    // dim/stride pairs; a wrapper type would only move the same slices.
1452    #[allow(clippy::too_many_arguments)]
1453    pub fn compile(
1454        operand_dims: &[usize],
1455        operand_strides: &[isize],
1456        start_dims: &[usize],
1457        start_strides: &[isize],
1458        update_dims: &[usize],
1459        update_strides: &[isize],
1460        dest_dims: &[usize],
1461        dest_strides: &[isize],
1462    ) -> Result<Self> {
1463        if operand_dims.len() != operand_strides.len()
1464            || start_dims.len() != start_strides.len()
1465            || update_dims.len() != update_strides.len()
1466            || dest_dims.len() != dest_strides.len()
1467        {
1468            return Err(StridedError::StrideLengthMismatch);
1469        }
1470        if update_dims.len() != operand_dims.len() {
1471            return Err(StridedError::RankMismatch(
1472                update_dims.len(),
1473                operand_dims.len(),
1474            ));
1475        }
1476        validate_start_vector(start_dims, operand_dims.len())?;
1477        checked_total_len(operand_dims)?;
1478        checked_total_len(start_dims)?;
1479        let total = checked_total_len(update_dims)?;
1480        validate_layout_span(operand_dims, operand_strides)?;
1481        validate_layout_span(start_dims, start_strides)?;
1482        validate_layout_span(update_dims, update_strides)?;
1483        validate_layout_span(dest_dims, dest_strides)?;
1484        if dest_dims != operand_dims {
1485            return Err(StridedError::ShapeMismatch(
1486                dest_dims.to_vec(),
1487                operand_dims.to_vec(),
1488            ));
1489        }
1490        if !crate::layout_check::is_injective_layout(dest_dims, dest_strides) {
1491            return Err(StridedError::NonInjectiveOutputLayout);
1492        }
1493        validate_window_sizes(operand_dims, update_dims)?;
1494        let copy_plan = CopyPlan::compile(operand_dims, dest_strides, operand_strides)?;
1495        let replay = WindowReplay::compile(update_dims, update_strides, dest_strides)?;
1496
1497        Ok(Self {
1498            operand_dims: operand_dims.into(),
1499            operand_strides: operand_strides.into(),
1500            start_dims: start_dims.into(),
1501            start_strides: start_strides.into(),
1502            update_dims: update_dims.into(),
1503            update_strides: update_strides.into(),
1504            dest_dims: dest_dims.into(),
1505            dest_strides: dest_strides.into(),
1506            total,
1507            copy_plan,
1508            window: fuse_pair_layout(update_dims, dest_strides, update_strides),
1509            replay,
1510        })
1511    }
1512
1513    /// Execute the prepared dynamic-update-slice traversal.
1514    ///
1515    /// # Errors
1516    ///
1517    /// Returns [`StridedError::PlanLayoutMismatch`] when the operand, update,
1518    /// start, or destination view does not carry its compiled extents and
1519    /// strides, and [`StridedError::OffsetOverflow`] when the checked update
1520    /// window does not fit `isize`. Both are decided before the operand copy
1521    /// runs, so a failed call leaves `dest` unmodified. Start values are
1522    /// clamped to `operand_dims - update_dims`, so an out-of-range start is
1523    /// not an error.
1524    pub fn execute<T, I>(
1525        &self,
1526        dest: &mut RawStridedMut<'_, T>,
1527        operand: &RawStridedRef<'_, T>,
1528        update: &RawStridedRef<'_, T>,
1529        starts: &RawStridedRef<'_, I>,
1530        exec: Exec<'_>,
1531    ) -> Result<()>
1532    where
1533        T: Copy + Send + Sync,
1534        I: GatherIndex,
1535    {
1536        let mut exec = exec;
1537        self.check_call(dest, operand, update, starts)?;
1538        let window = self.preflight_update_window(dest, update, starts)?;
1539        self.copy_plan.execute(dest, operand, exec.reborrow())?;
1540        self.execute_update_with_writer(dest, update, &window, exec)
1541    }
1542
1543    /// Execute dynamic update into a destination whose reachable slots may be
1544    /// uninitialized. The copy completes before any read-modify-write access,
1545    /// and a rejected update window is reported before the copy.
1546    pub(crate) fn execute_uninit<'a, T, I>(
1547        &self,
1548        dest: &'a mut RawStridedMut<'a, MaybeUninit<T>>,
1549        operand: &RawStridedRef<'_, T>,
1550        update: &RawStridedRef<'_, T>,
1551        starts: &RawStridedRef<'_, I>,
1552        exec: Exec<'_>,
1553    ) -> Result<()>
1554    where
1555        T: Copy + Send + Sync,
1556        I: GatherIndex,
1557    {
1558        self.check_call(dest, operand, update, starts)?;
1559        let window = self.preflight_update_window(dest, update, starts)?;
1560        self.copy_plan
1561            .execute_uninit_then(dest, operand, exec, |mut receipt, exec| {
1562                self.execute_update_with_writer(&mut receipt, update, &window, exec)
1563            })?
1564    }
1565
1566    /// Resolve every fallible step of the update phase before the operand copy.
1567    fn preflight_update_window<'a, T, I, W>(
1568        &self,
1569        dest: &W,
1570        update: &'a RawStridedRef<'_, T>,
1571        starts: &RawStridedRef<'_, I>,
1572    ) -> Result<UpdateWindow<'a, T>>
1573    where
1574        T: Copy,
1575        I: GatherIndex,
1576        W: OverwriteWriter<T>,
1577    {
1578        if self.total == 0 {
1579            return Ok(UpdateWindow::Empty);
1580        }
1581        let mut starts_storage = CoordScratch::new(self.operand_dims.len());
1582        let clamped_starts = starts_storage.as_mut_slice();
1583        read_clamped_starts(
1584            starts,
1585            &self.operand_dims,
1586            &self.update_dims,
1587            clamped_starts,
1588        )?;
1589        let dest_base = checked_strided_offset(dest.offset(), &self.dest_strides, clamped_starts)?;
1590        // The replay adds per-axis steps to these bases, on every worker, so
1591        // the whole window and not only its base has to fit `isize` first.
1592        self.replay.source_span.covers(update.offset())?;
1593        self.replay.dest_span.covers(dest_base)?;
1594        if self.uses_rank_one_contiguous_path() {
1595            let update_start =
1596                usize::try_from(update.offset()).map_err(|_| StridedError::OffsetOverflow)?;
1597            let dest_start =
1598                usize::try_from(dest_base).map_err(|_| StridedError::OffsetOverflow)?;
1599            let update_end = update_start
1600                .checked_add(self.total)
1601                .ok_or(StridedError::OffsetOverflow)?;
1602            let run = update
1603                .data()
1604                .get(update_start..update_end)
1605                .ok_or(StridedError::OffsetOverflow)?;
1606            return Ok(UpdateWindow::RankOne {
1607                update: run,
1608                dest_start,
1609            });
1610        }
1611        Ok(UpdateWindow::Replay { dest_base })
1612    }
1613
1614    fn execute_update_with_writer<T, W>(
1615        &self,
1616        dest: &mut W,
1617        update: &RawStridedRef<'_, T>,
1618        window: &UpdateWindow<'_, T>,
1619        exec: Exec<'_>,
1620    ) -> Result<()>
1621    where
1622        T: Copy + Send + Sync,
1623        W: OverwriteWriter<T>,
1624    {
1625        let dest_base = match *window {
1626            UpdateWindow::Empty => return Ok(()),
1627            UpdateWindow::RankOne { update, dest_start } => {
1628                return self.execute_rank_one_contiguous(dest, update, dest_start, exec)
1629            }
1630            UpdateWindow::Replay { dest_base } => dest_base,
1631        };
1632        if let Some(fused) = &self.window {
1633            return self.execute_fused_window(dest, update, dest_base, fused, exec);
1634        }
1635        let replay = &self.replay;
1636        let exec = crate::cost::for_len_tree(exec, KernelClass::Copy, self.total);
1637        if !exec.is_serial() {
1638            return self.execute_update_parallel(dest, update, dest_base, exec);
1639        }
1640
1641        let mut state = replay.start(update.offset(), dest_base);
1642        let update_data = update.data();
1643
1644        // INVARIANT: the initial CopyPlan has completed before this replay;
1645        // compile validated both window spans and the preflight proved every
1646        // replay offset fits from the checked bases.
1647        for _ in 0..self.total {
1648            // SAFETY: checked replay metadata proves the current update read.
1649            let value = unsafe { *update_data.as_ptr().offset(state.source_offset) };
1650            // SAFETY: the copied, injective destination layout proves this write
1651            // is initialized and in-bounds.
1652            unsafe { dest.write_at(state.dest_offset, value) };
1653            replay.advance(&mut state);
1654        }
1655        Ok(())
1656    }
1657
1658    /// Replay the compiled fused update window at the preflighted runtime
1659    /// destination base (see [`DynamicSlicePlan`]'s fused window replay).
1660    fn execute_fused_window<T, W>(
1661        &self,
1662        dest: &mut W,
1663        update: &RawStridedRef<'_, T>,
1664        dest_base: isize,
1665        window: &FusedPairLayout,
1666        exec: Exec<'_>,
1667    ) -> Result<()>
1668    where
1669        T: Copy + Send + Sync,
1670        W: OverwriteWriter<T>,
1671    {
1672        // SAFETY: the validated writer owns the destination allocation.
1673        let dest_ptr = unsafe { dest.data_ptr() }.cast::<MaybeUninit<T>>();
1674        let tiles = pair_tiles::<MaybeUninit<T>, T>(window);
1675        // SAFETY: `window` fuses `update_dims` with the checked destination
1676        // and update strides. The update view has exactly `update_dims` and
1677        // its validated layout reaches every source offset; the clamped window
1678        // lies inside `dest_dims`, so every destination offset from
1679        // `dest_base` is reachable through the validated destination layout.
1680        // Compile proved the destination injective, and the exclusive writer
1681        // borrow does not overlap the shared update. The injective destination
1682        // lets the window replay its tiles.
1683        unsafe {
1684            replay_fused_raw(
1685                dest_ptr,
1686                dest_base,
1687                update.data().as_ptr(),
1688                update.offset(),
1689                window,
1690                tiles.as_ref(),
1691                |slot: &mut MaybeUninit<T>, value: T| *slot = MaybeUninit::new(value),
1692                KernelClass::Copy.ns_per_element(),
1693                exec,
1694            );
1695        }
1696        Ok(())
1697    }
1698
1699    #[inline]
1700    fn uses_rank_one_contiguous_path(&self) -> bool {
1701        self.operand_dims.len() == 1
1702            && self.operand_strides[0] == 1
1703            && self.update_strides[0] == 1
1704            && self.dest_strides[0] == 1
1705    }
1706
1707    fn execute_rank_one_contiguous<T, W>(
1708        &self,
1709        dest: &mut W,
1710        update: &[T],
1711        dest_start: usize,
1712        exec: Exec<'_>,
1713    ) -> Result<()>
1714    where
1715        T: Copy + Send + Sync,
1716        W: OverwriteWriter<T>,
1717    {
1718        // SAFETY: the validated writer owns the destination allocation.
1719        let dest_ptr = unsafe { dest.data_ptr() };
1720        // SAFETY: the preflight resolved the update run (`update.data().get`,
1721        // :1534) and proved the window span fits `isize` (`dest_span.covers`,
1722        // :1523); the destination run is the plan's own layout: compile set
1723        // `total = checked_total_len(update_dims)` (:1409) with
1724        // `dest_dims == operand_dims` (:1414) and `validate_window_sizes`
1725        // (:1423), this rank-one path requires `dest_strides[0] == 1` (:1630),
1726        // and `check_call` (:1718) proved the writer carries exactly that
1727        // layout. The last offset this run writes is `dest_start + total - 1`
1728        // (`total >= 1` here: an empty window returns as `UpdateWindow::Empty`
1729        // at :1508 and leaves at :1556), and that offset cannot pass the
1730        // highest one `RawStridedMut::new` validated
1731        // (strided-view/src/raw.rs:1036, `validate_bounds` at :1042). The
1732        // exclusive end `dest_start + total` is one past the run's last
1733        // element and may equal `max + 1`.
1734        unsafe {
1735            // Chunked across workers above the repository threshold; each
1736            // worker writes a disjoint chunk of the checked destination run.
1737            crate::threading::copy_contiguous(
1738                update.as_ptr(),
1739                dest_ptr.add(dest_start),
1740                self.total,
1741                exec,
1742            );
1743        }
1744        Ok(())
1745    }
1746
1747    fn execute_update_parallel<T, W>(
1748        &self,
1749        dest: &mut W,
1750        update: &RawStridedRef<'_, T>,
1751        dest_base: isize,
1752        exec: Exec<'_>,
1753    ) -> Result<()>
1754    where
1755        T: Copy + Send + Sync,
1756        W: OverwriteWriter<T>,
1757    {
1758        let replay = &self.replay;
1759        let source_base = update.offset();
1760        let update_ptr = crate::threading::SendPtr(update.data().as_ptr() as *mut T);
1761        // SAFETY: the validated writer owns the destination allocation.
1762        let dest_ptr = crate::threading::SendPtr(unsafe { dest.data_ptr() });
1763
1764        crate::threading::parallel_map_reduce(
1765            0..self.total,
1766            exec,
1767            &|range| {
1768                let mut state = replay.decode(range.start, source_base, dest_base)?;
1769                let update_ptr = update_ptr.as_const();
1770                let dest_ptr = dest_ptr.as_ptr();
1771
1772                // INVARIANT: the initial operand copy completed before this
1773                // replay; workers own disjoint ranges and injective output
1774                // layouts make their writes distinct. Preflight bounded both
1775                // window spans, so a worker decode cannot overflow.
1776                for _ in range {
1777                    // SAFETY: checked replay bases/resets prove both offsets are
1778                    // within the initialized update and destination allocations.
1779                    unsafe {
1780                        dest_ptr
1781                            .offset(state.dest_offset)
1782                            .write(update_ptr.offset(state.source_offset).read());
1783                    }
1784                    replay.advance(&mut state);
1785                }
1786                Ok(())
1787            },
1788            &|left, right| left.and(right),
1789        )
1790    }
1791
1792    fn check_call<T, I, W>(
1793        &self,
1794        dest: &W,
1795        operand: &RawStridedRef<'_, T>,
1796        update: &RawStridedRef<'_, T>,
1797        starts: &RawStridedRef<'_, I>,
1798    ) -> Result<()>
1799    where
1800        W: OverwriteWriter<T>,
1801    {
1802        if dest.dims() != &self.dest_dims[..]
1803            || dest.strides() != &self.dest_strides[..]
1804            || operand.dims() != &self.operand_dims[..]
1805            || operand.strides() != &self.operand_strides[..]
1806            || update.dims() != &self.update_dims[..]
1807            || update.strides() != &self.update_strides[..]
1808            || starts.dims() != &self.start_dims[..]
1809            || starts.strides() != &self.start_strides[..]
1810        {
1811            return Err(StridedError::PlanLayoutMismatch);
1812        }
1813        Ok(())
1814    }
1815}
1816
1817impl ScatterPlan {
1818    /// Compile an additive scatter traversal.
1819    ///
1820    /// # Errors
1821    ///
1822    /// Returns [`StridedError::StrideLengthMismatch`] when a stride list does
1823    /// not match its dimension list, [`StridedError::OffsetOverflow`] when an
1824    /// element count or layout span does not fit `usize`/`isize`,
1825    /// [`StridedError::ShapeMismatch`] when `dest_dims` differs from
1826    /// `operand_dims` or an update batch extent differs from the index batch
1827    /// shape, and [`StridedError::NonInjectiveOutputLayout`] when the
1828    /// destination layout cannot be proven injective (aliasing elements, or a
1829    /// span the check cannot represent).
1830    /// [`StridedError::InvalidAxis`] reports `inserted_window_dims`,
1831    /// `scatter_dims_to_operand_dims`, or `update_window_dims` that repeat or
1832    /// exceed their rank, `index_vector_dim` beyond the index rank, or an
1833    /// update window extent beyond its operand extent; and
1834    /// [`StridedError::RankMismatch`] reports an index vector that does not
1835    /// match `scatter_dims_to_operand_dims`, a wrong-length
1836    /// `update_window_dims`, or an update batch rank that disagrees with the
1837    /// index batch shape.
1838    // Compile key: the operand, index, update and destination layouts, as four
1839    // dim/stride pairs, plus the scatter spec.
1840    #[allow(clippy::too_many_arguments)]
1841    pub fn compile(
1842        operand_dims: &[usize],
1843        operand_strides: &[isize],
1844        index_dims: &[usize],
1845        index_strides: &[isize],
1846        update_dims: &[usize],
1847        update_strides: &[isize],
1848        dest_dims: &[usize],
1849        dest_strides: &[isize],
1850        spec: ScatterSpec,
1851    ) -> Result<Self> {
1852        if operand_dims.len() != operand_strides.len()
1853            || index_dims.len() != index_strides.len()
1854            || update_dims.len() != update_strides.len()
1855            || dest_dims.len() != dest_strides.len()
1856        {
1857            return Err(StridedError::StrideLengthMismatch);
1858        }
1859        checked_total_len(operand_dims)?;
1860        checked_total_len(index_dims)?;
1861        checked_total_len(update_dims)?;
1862        if dest_dims != operand_dims {
1863            return Err(StridedError::ShapeMismatch(
1864                dest_dims.to_vec(),
1865                operand_dims.to_vec(),
1866            ));
1867        }
1868        if !crate::layout_check::is_injective_layout(dest_dims, dest_strides) {
1869            return Err(StridedError::NonInjectiveOutputLayout);
1870        }
1871
1872        let operand_rank = operand_dims.len();
1873        validate_unique_axes(&spec.inserted_window_dims, operand_rank)?;
1874        validate_unique_axes(&spec.scatter_dims_to_operand_dims, operand_rank)?;
1875        if spec.index_vector_dim > index_dims.len() {
1876            return Err(StridedError::InvalidAxis {
1877                axis: spec.index_vector_dim,
1878                rank: index_dims.len() + 1,
1879            });
1880        }
1881        let index_vector_size = if spec.index_vector_dim == index_dims.len() {
1882            1
1883        } else {
1884            index_dims[spec.index_vector_dim]
1885        };
1886        if index_vector_size != spec.scatter_dims_to_operand_dims.len() {
1887            return Err(StridedError::RankMismatch(
1888                index_vector_size,
1889                spec.scatter_dims_to_operand_dims.len(),
1890            ));
1891        }
1892
1893        let batch_shape = index_batch_shape(index_dims, spec.index_vector_dim);
1894        let window_dims = operand_window_dims(operand_rank, &spec.inserted_window_dims);
1895        if spec.update_window_dims.len() != window_dims.len() {
1896            return Err(StridedError::RankMismatch(
1897                spec.update_window_dims.len(),
1898                window_dims.len(),
1899            ));
1900        }
1901
1902        let update_rank = update_dims.len();
1903        let expected_batch_rank = update_rank
1904            .checked_sub(spec.update_window_dims.len())
1905            .ok_or(StridedError::RankMismatch(
1906                spec.update_window_dims.len(),
1907                update_rank,
1908            ))?;
1909        if expected_batch_rank != batch_shape.len() {
1910            return Err(StridedError::RankMismatch(
1911                expected_batch_rank,
1912                batch_shape.len(),
1913            ));
1914        }
1915        validate_unique_axes(&spec.update_window_dims, update_rank)?;
1916
1917        let mut is_update_window_dim: AxisVec<bool> = (0..update_rank).map(|_| false).collect();
1918        for &axis in &spec.update_window_dims {
1919            is_update_window_dim[axis] = true;
1920        }
1921
1922        let mut batch_axis = 0usize;
1923        for axis in 0..update_rank {
1924            if !is_update_window_dim[axis] {
1925                if update_dims[axis] != batch_shape[batch_axis] {
1926                    return Err(StridedError::ShapeMismatch(
1927                        update_dims.to_vec(),
1928                        expected_scatter_update_shape(&batch_shape, &spec, update_dims).to_vec(),
1929                    ));
1930                }
1931                batch_axis += 1;
1932            }
1933        }
1934
1935        let mut window_shape: AxisVec<usize> = (0..operand_rank).map(|_| 1).collect();
1936        let mut window_shape_updates: AxisVec<usize> =
1937            AxisVec::with_capacity(spec.update_window_dims.len());
1938        for (pos, &update_axis) in spec.update_window_dims.iter().enumerate() {
1939            let dim = update_dims[update_axis];
1940            window_shape_updates.push(dim);
1941            window_shape[window_dims[pos]] = dim;
1942        }
1943        validate_window_sizes(operand_dims, &window_shape)?;
1944
1945        let batch_elems = checked_total_len(&batch_shape)?;
1946        let window_elems = checked_total_len(&window_shape_updates)?;
1947        let copy_plan = CopyPlan::compile(operand_dims, dest_strides, operand_strides)?;
1948        let replay = ScatterReplay::compile(
1949            &batch_shape,
1950            index_dims,
1951            index_strides,
1952            spec.index_vector_dim,
1953            spec.scatter_dims_to_operand_dims.len(),
1954            update_dims,
1955            update_strides,
1956            &spec.update_window_dims,
1957            &is_update_window_dim,
1958            &window_shape_updates,
1959            &window_dims,
1960            dest_strides,
1961        )?;
1962
1963        Ok(Self {
1964            operand_dims: operand_dims.into(),
1965            operand_strides: operand_strides.into(),
1966            index_dims: index_dims.into(),
1967            index_strides: index_strides.into(),
1968            update_dims: update_dims.into(),
1969            update_strides: update_strides.into(),
1970            dest_dims: dest_dims.into(),
1971            dest_strides: dest_strides.into(),
1972            spec,
1973            window_shape,
1974            batch_elems,
1975            window_elems,
1976            copy_plan,
1977            replay,
1978        })
1979    }
1980
1981    /// Execute the prepared additive scatter traversal.
1982    ///
1983    /// The accumulating combine is [`ScatterScalar::wrapping_add`]: integer
1984    /// element types wrap on overflow in every build profile, and floating-point
1985    /// and complex types use IEEE addition. This is the combine the dtype-erased
1986    /// entries (`ErasedScatterPlan::execute` and `execute_uninit`) use, so the
1987    /// typed and erased, initialized and uninitialized entries agree on the same
1988    /// input. Use [`Self::execute_with_combine`] for any other combine or for an
1989    /// element type outside the sealed [`ScatterScalar`] set.
1990    ///
1991    /// # Examples
1992    ///
1993    /// ```
1994    /// use strided_basic::{Exec, RawStridedMut, RawStridedRef, ScatterPlan, ScatterSpec};
1995    /// let spec = ScatterSpec {
1996    ///     update_window_dims: vec![],
1997    ///     inserted_window_dims: vec![0],
1998    ///     scatter_dims_to_operand_dims: vec![0],
1999    ///     index_vector_dim: 1,
2000    /// };
2001    /// let plan =
2002    ///     ScatterPlan::compile(&[2], &[1], &[1, 1], &[1, 1], &[1], &[1], &[2], &[1], spec).unwrap();
2003    /// let operand = RawStridedRef::new(&[i32::MAX, 7], &[2], &[1], 0).unwrap();
2004    /// let indices = RawStridedRef::new(&[0_i64], &[1, 1], &[1, 1], 0).unwrap();
2005    /// let updates = RawStridedRef::new(&[1_i32], &[1], &[1], 0).unwrap();
2006    /// let mut out = [0_i32; 2];
2007    /// let mut dest = RawStridedMut::new(&mut out, &[2], &[1], 0).unwrap();
2008    /// plan.execute(&mut dest, &operand, &indices, &updates, Exec::serial()).unwrap();
2009    /// assert_eq!(out, [i32::MIN, 7]);
2010    /// ```
2011    ///
2012    /// # Errors
2013    ///
2014    /// Returns [`StridedError::PlanLayoutMismatch`] when the operand, index,
2015    /// update, or destination view does not carry its compiled extents and
2016    /// strides, before the operand copy runs. Start values are clamped into
2017    /// the operand window, so an out-of-range scatter index is not an error.
2018    #[inline(always)]
2019    pub fn execute<T, I>(
2020        &self,
2021        dest: &mut RawStridedMut<'_, T>,
2022        operand: &RawStridedRef<'_, T>,
2023        scatter_indices: &RawStridedRef<'_, I>,
2024        updates: &RawStridedRef<'_, T>,
2025        exec: Exec<'_>,
2026    ) -> Result<()>
2027    where
2028        T: ScatterScalar,
2029        I: GatherIndex,
2030    {
2031        self.execute_with_combine(
2032            dest,
2033            operand,
2034            scatter_indices,
2035            updates,
2036            <T as ScatterScalar>::wrapping_add,
2037            exec,
2038        )
2039    }
2040
2041    /// Execute the prepared scatter traversal with an explicit combine.
2042    ///
2043    /// `combine(current, update)` is the read-modify-write applied to each
2044    /// destination slot an update reaches, after the operand copy. Pass
2045    /// [`ScatterScalar::wrapping_add`] for the [`Self::execute`] contract;
2046    /// any other combine is the caller's contract, including its overflow
2047    /// behavior.
2048    ///
2049    /// # Errors
2050    ///
2051    /// The same as [`Self::execute`].
2052    pub fn execute_with_combine<T, I>(
2053        &self,
2054        dest: &mut RawStridedMut<'_, T>,
2055        operand: &RawStridedRef<'_, T>,
2056        scatter_indices: &RawStridedRef<'_, I>,
2057        updates: &RawStridedRef<'_, T>,
2058        combine: fn(T, T) -> T,
2059        exec: Exec<'_>,
2060    ) -> Result<()>
2061    where
2062        T: Copy + Send + Sync,
2063        I: GatherIndex,
2064    {
2065        self.check_call(dest, operand, scatter_indices, updates)?;
2066        self.copy_plan.execute(dest, operand, exec)?;
2067        self.execute_updates(dest, scatter_indices, updates, combine)
2068    }
2069
2070    /// Execute additive scatter into a destination whose reachable slots may
2071    /// be uninitialized. The operand copy completes before any RMW access.
2072    pub(crate) fn execute_uninit<'a, T, I>(
2073        &self,
2074        dest: &'a mut RawStridedMut<'a, MaybeUninit<T>>,
2075        operand: &RawStridedRef<'_, T>,
2076        scatter_indices: &RawStridedRef<'_, I>,
2077        updates: &RawStridedRef<'_, T>,
2078        combine: fn(T, T) -> T,
2079        exec: Exec<'_>,
2080    ) -> Result<()>
2081    where
2082        T: Copy + Send + Sync,
2083        I: GatherIndex,
2084    {
2085        self.check_call(dest, operand, scatter_indices, updates)?;
2086        self.copy_plan
2087            .execute_uninit_then(dest, operand, exec, |mut receipt, _| {
2088                self.execute_updates(&mut receipt, scatter_indices, updates, combine)
2089            })?
2090    }
2091
2092    #[inline(always)]
2093    fn execute_updates<T, I, W, F>(
2094        &self,
2095        dest: &mut W,
2096        scatter_indices: &RawStridedRef<'_, I>,
2097        updates: &RawStridedRef<'_, T>,
2098        combine: F,
2099    ) -> Result<()>
2100    where
2101        T: Copy + Send + Sync,
2102        I: GatherIndex,
2103        W: ReadModifyWrite<T>,
2104        F: Fn(T, T) -> T + Copy,
2105    {
2106        if self.batch_elems == 0 || self.window_elems == 0 {
2107            return Ok(());
2108        }
2109        if self.uses_rank_one_scalar_update_path() {
2110            return self.execute_rank_one_scalar_updates(dest, scatter_indices, updates, combine);
2111        }
2112        self.execute_generic_updates(dest, scatter_indices, updates, combine)
2113    }
2114
2115    #[inline(never)]
2116    fn execute_generic_updates<T, I, W, F>(
2117        &self,
2118        dest: &mut W,
2119        scatter_indices: &RawStridedRef<'_, I>,
2120        updates: &RawStridedRef<'_, T>,
2121        combine: F,
2122    ) -> Result<()>
2123    where
2124        T: Copy + Send + Sync,
2125        I: GatherIndex,
2126        W: ReadModifyWrite<T>,
2127        F: Fn(T, T) -> T + Copy,
2128    {
2129        // Overlapping additive updates are order-sensitive, so this remains a
2130        // deterministic serial replay until a combine-aware parallel plan exists.
2131        let replay = &self.replay;
2132
2133        let mut operand_base_storage = CoordScratch::new(self.operand_dims.len());
2134        let operand_base = operand_base_storage.as_mut_slice();
2135        let mut batch_state = replay
2136            .batch
2137            .decode(0, scatter_indices.offset(), updates.offset())?;
2138        let index_data = scatter_indices.data();
2139        let update_data = updates.data();
2140
2141        // INVARIANT: batch and window replay metadata was checked at compile;
2142        // the indirect component loop below is the only data-dependent lookup.
2143        for _ in 0..self.batch_elems {
2144            operand_base.fill(0);
2145            for (&component_offset, &operand_axis) in replay
2146                .index_component_offsets
2147                .iter()
2148                .zip(self.spec.scatter_dims_to_operand_dims.iter())
2149            {
2150                let index_offset = batch_state
2151                    .source_offset
2152                    .checked_add(component_offset)
2153                    .ok_or(StridedError::OffsetOverflow)?;
2154                // SAFETY: checked batch replay and component offsets keep this
2155                // indirect index read inside the validated index allocation.
2156                let start = unsafe { *index_data.as_ptr().offset(index_offset) }.to_i64();
2157                operand_base[operand_axis] = clamp_window_start(
2158                    start,
2159                    self.operand_dims[operand_axis],
2160                    self.window_shape[operand_axis],
2161                );
2162            }
2163
2164            let dest_base = checked_strided_offset(dest.offset(), dest.strides(), operand_base)?;
2165            let mut window_state = replay
2166                .window
2167                .decode(0, batch_state.dest_offset, dest_base)?;
2168            for _ in 0..self.window_elems {
2169                // SAFETY: copy completion and checked replay state prove both
2170                // the update read and initialized destination RMW are valid.
2171                let value = unsafe { *update_data.as_ptr().offset(window_state.source_offset) };
2172                unsafe { dest.add_at(window_state.dest_offset, value, combine) };
2173                replay.window.advance(&mut window_state);
2174            }
2175            replay.batch.advance(&mut batch_state);
2176        }
2177        Ok(())
2178    }
2179
2180    fn uses_rank_one_scalar_update_path(&self) -> bool {
2181        self.operand_dims.len() == 1
2182            && self.index_dims.len() == 2
2183            && self.update_dims.len() == 1
2184            && self.dest_dims.len() == 1
2185            && self.operand_strides[0] == 1
2186            && self.index_strides[0] == 1
2187            && self.update_strides[0] == 1
2188            && self.dest_strides[0] == 1
2189            && self.index_dims[1] == 1
2190            && self.spec.update_window_dims.is_empty()
2191            && self.spec.inserted_window_dims.as_slice() == [0]
2192            && self.spec.scatter_dims_to_operand_dims.as_slice() == [0]
2193            && self.spec.index_vector_dim == 1
2194            && self.window_elems == 1
2195    }
2196
2197    #[inline(always)]
2198    fn execute_rank_one_scalar_updates<T, I, W, F>(
2199        &self,
2200        dest: &mut W,
2201        scatter_indices: &RawStridedRef<'_, I>,
2202        updates: &RawStridedRef<'_, T>,
2203        combine: F,
2204    ) -> Result<()>
2205    where
2206        T: Copy,
2207        I: GatherIndex,
2208        W: ReadModifyWrite<T>,
2209        F: Fn(T, T) -> T + Copy,
2210    {
2211        let mut index_offset = scatter_indices.offset();
2212        let mut update_offset = updates.offset();
2213        let dest_offset = dest.offset();
2214        let index_data = scatter_indices.data();
2215        let update_data = updates.data();
2216        // SAFETY: the validated writer owns the destination allocation.
2217        let dest_ptr = unsafe { dest.data_ptr() };
2218
2219        // INVARIANT: compile and check_call validated compact rank-one index
2220        // and update layouts. Ordered replay preserves repeated-index semantics.
2221        // `index_offset`/`update_offset` are the pointer walk, not counters.
2222        #[allow(clippy::explicit_counter_loop)]
2223        for _ in 0..self.batch_elems {
2224            // SAFETY: the invariant above proves index/update reads and the
2225            // clamped destination offset are in their validated allocations.
2226            unsafe {
2227                let start = (*index_data.as_ptr().offset(index_offset)).to_i64();
2228                let output_offset =
2229                    dest_offset + clamp_window_start(start, self.operand_dims[0], 1) as isize;
2230                let output = dest_ptr.offset(output_offset);
2231                output.write(combine(
2232                    output.read(),
2233                    *update_data.as_ptr().offset(update_offset),
2234                ));
2235            }
2236            index_offset += 1;
2237            update_offset += 1;
2238        }
2239        Ok(())
2240    }
2241
2242    fn check_call<T, I, W>(
2243        &self,
2244        dest: &W,
2245        operand: &RawStridedRef<'_, T>,
2246        scatter_indices: &RawStridedRef<'_, I>,
2247        updates: &RawStridedRef<'_, T>,
2248    ) -> Result<()>
2249    where
2250        W: OverwriteWriter<T>,
2251    {
2252        if dest.dims() != &self.dest_dims[..]
2253            || dest.strides() != &self.dest_strides[..]
2254            || operand.dims() != &self.operand_dims[..]
2255            || operand.strides() != &self.operand_strides[..]
2256            || scatter_indices.dims() != &self.index_dims[..]
2257            || scatter_indices.strides() != &self.index_strides[..]
2258            || updates.dims() != &self.update_dims[..]
2259            || updates.strides() != &self.update_strides[..]
2260        {
2261            return Err(StridedError::PlanLayoutMismatch);
2262        }
2263        Ok(())
2264    }
2265}
2266
2267fn validate_unique_axes(axes: &[usize], rank: usize) -> Result<()> {
2268    // Inline boolean metadata: rank <= INLINE_RANK validation allocates
2269    // nothing, and it spills above the inline bound.
2270    let mut seen: InlineVec<bool> = InlineVec::new();
2271    seen.resize(rank, false);
2272    for &axis in axes {
2273        if axis >= rank {
2274            return Err(StridedError::InvalidAxis { axis, rank });
2275        }
2276        if seen[axis] {
2277            return Err(StridedError::InvalidAxis { axis, rank });
2278        }
2279        seen[axis] = true;
2280    }
2281    Ok(())
2282}
2283
2284fn validate_start_vector(start_dims: &[usize], operand_rank: usize) -> Result<()> {
2285    if start_dims.len() != 1 {
2286        return Err(StridedError::RankMismatch(start_dims.len(), 1));
2287    }
2288    if start_dims[0] != operand_rank {
2289        return Err(StridedError::RankMismatch(start_dims[0], operand_rank));
2290    }
2291    Ok(())
2292}
2293
2294fn validate_window_sizes(operand_dims: &[usize], window_sizes: &[usize]) -> Result<()> {
2295    if operand_dims.len() != window_sizes.len() {
2296        return Err(StridedError::RankMismatch(
2297            window_sizes.len(),
2298            operand_dims.len(),
2299        ));
2300    }
2301    for (axis, (&window, &dim)) in window_sizes.iter().zip(operand_dims.iter()).enumerate() {
2302        if window > dim {
2303            return Err(StridedError::InvalidAxis {
2304                axis,
2305                rank: operand_dims.len(),
2306            });
2307        }
2308    }
2309    Ok(())
2310}
2311
2312fn read_clamped_starts<I>(
2313    starts: &RawStridedRef<'_, I>,
2314    operand_dims: &[usize],
2315    window_sizes: &[usize],
2316    out: &mut [usize],
2317) -> Result<()>
2318where
2319    I: GatherIndex,
2320{
2321    debug_assert_eq!(operand_dims.len(), window_sizes.len());
2322    debug_assert_eq!(operand_dims.len(), out.len());
2323    for axis in 0..operand_dims.len() {
2324        let offset = checked_offset_add(starts.offset(), starts.strides()[0], axis)?;
2325        let start = unsafe { *starts.data().as_ptr().offset(offset) }.to_i64();
2326        out[axis] = clamp_window_start(start, operand_dims[axis], window_sizes[axis]);
2327    }
2328    Ok(())
2329}
2330
2331#[inline]
2332fn clamp_window_start(start: i64, dim_size: usize, window_size: usize) -> usize {
2333    let max_start = dim_size.saturating_sub(window_size) as i64;
2334    start.clamp(0, max_start) as usize
2335}
2336
2337fn expected_scatter_update_shape(
2338    batch_shape: &[usize],
2339    spec: &ScatterSpec,
2340    update_dims: &[usize],
2341) -> AxisVec<usize> {
2342    let mut expected: AxisVec<usize> = AxisVec::with_capacity(update_dims.len());
2343    let mut batch_axis = 0usize;
2344    for (axis, &dim) in update_dims.iter().enumerate() {
2345        if spec.update_window_dims.contains(&axis) {
2346            expected.push(dim);
2347        } else {
2348            expected.push(batch_shape[batch_axis]);
2349            batch_axis += 1;
2350        }
2351    }
2352    expected
2353}
2354
2355fn operand_window_dims(rank: usize, collapsed_slice_dims: &[usize]) -> AxisVec<usize> {
2356    (0..rank)
2357        .filter(|axis| !collapsed_slice_dims.contains(axis))
2358        .collect()
2359}
2360
2361fn index_batch_shape(index_dims: &[usize], index_vector_dim: usize) -> AxisVec<usize> {
2362    if index_vector_dim == index_dims.len() {
2363        return index_dims.into();
2364    }
2365    index_dims
2366        .iter()
2367        .enumerate()
2368        .filter_map(|(axis, &dim)| (axis != index_vector_dim).then_some(dim))
2369        .collect()
2370}
2371
2372/// Validate a layout's reachable offsets and return them relative to its base.
2373fn validate_layout_span(dims: &[usize], strides: &[isize]) -> Result<OffsetSpan> {
2374    if dims.len() != strides.len() {
2375        return Err(StridedError::StrideLengthMismatch);
2376    }
2377    let mut span = OffsetSpan::default();
2378    for (&dim, &stride) in dims.iter().zip(strides.iter()) {
2379        let last =
2380            isize::try_from(dim.saturating_sub(1)).map_err(|_| StridedError::OffsetOverflow)?;
2381        let extent = stride
2382            .checked_mul(last)
2383            .ok_or(StridedError::OffsetOverflow)?;
2384        if extent < 0 {
2385            span.min = span
2386                .min
2387                .checked_add(extent)
2388                .ok_or(StridedError::OffsetOverflow)?;
2389        } else {
2390            span.max = span
2391                .max
2392                .checked_add(extent)
2393                .ok_or(StridedError::OffsetOverflow)?;
2394        }
2395    }
2396    Ok(span)
2397}
2398
2399fn checked_replay_reset(dim: usize, step: isize) -> Result<isize> {
2400    if dim == 0 {
2401        return Ok(0);
2402    }
2403    let last = isize::try_from(dim - 1).map_err(|_| StridedError::OffsetOverflow)?;
2404    step.checked_mul(last)
2405        .and_then(isize::checked_neg)
2406        .ok_or(StridedError::OffsetOverflow)
2407}
2408
2409fn checked_total_len(dims: &[usize]) -> Result<usize> {
2410    if dims.is_empty() {
2411        return Ok(1);
2412    }
2413    dims.iter()
2414        .try_fold(1usize, |acc, &dim| acc.checked_mul(dim))
2415        .ok_or(StridedError::OffsetOverflow)
2416}
2417
2418fn checked_strided_offset(base: isize, strides: &[isize], index: &[usize]) -> Result<isize> {
2419    let mut offset = base;
2420    for (&stride, &coord) in strides.iter().zip(index.iter()) {
2421        offset = checked_offset_add(offset, stride, coord)?;
2422    }
2423    Ok(offset)
2424}
2425
2426fn checked_offset_add(base: isize, stride: isize, coord: usize) -> Result<isize> {
2427    let coord = isize::try_from(coord).map_err(|_| StridedError::OffsetOverflow)?;
2428    let scaled = stride
2429        .checked_mul(coord)
2430        .ok_or(StridedError::OffsetOverflow)?;
2431    base.checked_add(scaled).ok_or(StridedError::OffsetOverflow)
2432}
2433
2434struct CoordScratch {
2435    inline: [usize; RAW_FUSED_RANK_LIMIT],
2436    heap: Option<Vec<usize>>,
2437    len: usize,
2438}
2439
2440impl CoordScratch {
2441    fn new(len: usize) -> Self {
2442        if len <= RAW_FUSED_RANK_LIMIT {
2443            Self {
2444                inline: [0; RAW_FUSED_RANK_LIMIT],
2445                heap: None,
2446                len,
2447            }
2448        } else {
2449            Self {
2450                inline: [0; RAW_FUSED_RANK_LIMIT],
2451                heap: Some(vec![0; len]),
2452                len,
2453            }
2454        }
2455    }
2456
2457    fn as_mut_slice(&mut self) -> &mut [usize] {
2458        match &mut self.heap {
2459            Some(heap) => heap,
2460            None => &mut self.inline[..self.len],
2461        }
2462    }
2463}
2464
2465#[cfg(test)]
2466#[path = "gather_plan/tests/tests.rs"]
2467mod tests;
2468
2469#[cfg(test)]
2470#[path = "gather_plan/tests/parallel_tests.rs"]
2471mod parallel_tests;