strided-basic 0.15.0

Shared typed strided CPU primitives and copy/reduction execution.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
//! Prepared (compile-once, execute-many) copy plans over raw strided layouts.
//!
//! [`copy_scale_raw`](crate::copy_scale_raw) and friends rebuild the fused
//! loop nest on every call; for prepared-replay consumers that issue many
//! small copies with a fixed layout, that per-call planning dominates
//! (see issue #139). [`CopyPlan`] splits the work: [`CopyPlan::compile`]
//! validates the layout pair and builds the fused traversal once,
//! [`CopyPlan::execute`]/[`CopyPlan::execute_scale`]/[`CopyPlan::execute_conj`]
//! replay it with no heap allocation for fused ranks at most
//! [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT). The only per-execute
//! planning is the cache-block selection for the element type, which runs the
//! shared block model on layouts of at least two non-unit axes. A layout is
//! walked tile by tile when the tiles change the visit order and can reuse a
//! cache line across the runs they regroup.

use core::{
    marker::PhantomData,
    mem::{size_of, MaybeUninit},
    ops::{Add, Mul},
};

use num_traits::{One, Zero};

use crate::cost::KernelClass;
use crate::raw_ops::{
    apply_fused_range, apply_spilled_range, apply_spilled_tiled_box, apply_tiled_box,
    fuse_pair_traversal, fused_total, pair_tiles, replay_route_serial, FusedAxis, FusedPairLayout,
    PairTiles, PairTraversal, Route, SpilledTiles,
};
use crate::{ElementOpApply, Exec, RawStridedMut, RawStridedRef, Result, StridedError};
use strided_perm::HostClass;

// Same pattern as map_view.rs / outer_product.rs: inline storage in both
// feature configurations. Only `compile` touches these; `execute*` never
// allocates for them. (A spilled fused layout replays from stack arrays bounded
// by its moving-axis count: see `raw_ops::MAX_MOVING_AXES`.)
type AxisVec<T> = crate::inline::InlineVec<T>;

pub(crate) trait OverwriteWriter<T> {
    fn dims(&self) -> &[usize];
    fn strides(&self) -> &[isize];
    fn offset(&self) -> isize;
    /// # Safety
    /// The caller must use the pointer only for the validated allocation and
    /// logical layout represented by this writer.
    unsafe fn data_ptr(&mut self) -> *mut T;
    /// # Safety
    /// The offset must be an in-bounds logical destination proven by layout.
    unsafe fn write_at(&mut self, offset: isize, value: T);
}

pub(crate) trait ReadModifyWrite<T>: OverwriteWriter<T> {
    /// # Safety
    /// The offset must be an in-bounds initialized slot covered by the
    /// traversal's copy and disjointness proof.
    unsafe fn add_at<F>(&mut self, offset: isize, value: T, combine: F)
    where
        F: FnOnce(T, T) -> T;
}

impl<'a, T> OverwriteWriter<T> for RawStridedMut<'a, T> {
    fn dims(&self) -> &[usize] {
        self.dims()
    }
    fn strides(&self) -> &[isize] {
        self.strides()
    }
    fn offset(&self) -> isize {
        self.offset()
    }
    unsafe fn data_ptr(&mut self) -> *mut T {
        self.data_mut().as_mut_ptr()
    }
    unsafe fn write_at(&mut self, offset: isize, value: T) {
        // SAFETY: the prepared layout validates every logical destination.
        unsafe { self.data_mut().as_mut_ptr().offset(offset).write(value) }
    }
}

impl<'a, T> ReadModifyWrite<T> for RawStridedMut<'a, T>
where
    T: Add<Output = T>,
{
    #[inline(always)]
    unsafe fn add_at<F>(&mut self, offset: isize, value: T, combine: F)
    where
        F: FnOnce(T, T) -> T,
    {
        // SAFETY: the copy or initialized caller proves this logical slot.
        unsafe {
            let ptr = self.data_mut().as_mut_ptr().offset(offset);
            ptr.write(combine(ptr.read(), value));
        }
    }
}

impl<'a, T> OverwriteWriter<T> for RawStridedMut<'a, MaybeUninit<T>> {
    fn dims(&self) -> &[usize] {
        self.dims()
    }
    fn strides(&self) -> &[isize] {
        self.strides()
    }
    fn offset(&self) -> isize {
        self.offset()
    }
    unsafe fn data_ptr(&mut self) -> *mut T {
        self.data_mut().as_mut_ptr().cast()
    }
    unsafe fn write_at(&mut self, offset: isize, value: T) {
        // SAFETY: the prepared layout validates every logical destination.
        unsafe {
            self.data_mut()
                .as_mut_ptr()
                .offset(offset)
                .write(MaybeUninit::new(value))
        }
    }
}

pub(crate) struct InitializedRawDest<'a, T> {
    ptr: *mut T,
    extent: usize,
    dims: &'a [usize],
    strides: &'a [isize],
    offset: isize,
    _marker: PhantomData<&'a mut [MaybeUninit<T>]>,
}

impl<'a, T> OverwriteWriter<T> for InitializedRawDest<'a, T> {
    fn dims(&self) -> &[usize] {
        self.dims
    }
    fn strides(&self) -> &[isize] {
        self.strides
    }
    fn offset(&self) -> isize {
        self.offset
    }
    unsafe fn data_ptr(&mut self) -> *mut T {
        self.ptr
    }
    unsafe fn write_at(&mut self, offset: isize, value: T) {
        debug_assert!(offset >= 0 && (offset as usize) < self.extent);
        // SAFETY: the copy proof and extent check cover this logical slot.
        unsafe { self.ptr.offset(offset).write(value) }
    }
}

impl<'a, T> ReadModifyWrite<T> for InitializedRawDest<'a, T>
where
    T: Add<Output = T>,
{
    #[inline(always)]
    unsafe fn add_at<F>(&mut self, offset: isize, value: T, combine: F)
    where
        F: FnOnce(T, T) -> T,
    {
        debug_assert!(offset >= 0 && (offset as usize) < self.extent);
        // SAFETY: the copy proof and extent check cover this logical slot.
        unsafe {
            let ptr = self.ptr.offset(offset);
            ptr.write(combine(ptr.read(), value));
        }
    }
}

/// A compiled copy traversal for one `(dims, dst_strides, src_strides)`
/// layout pair.
///
/// `compile` proves the layout facts once (rank agreement, extent overflow,
/// destination injectivity) and fuses/orders the loop nest; each `execute*`
/// call then only re-checks the per-call facts (that the supplied views carry
/// exactly the compiled layout) and selects the cache blocks for its element
/// type before replaying the prepared loops. The order in which elements are
/// visited is unspecified.
///
/// Overlapping `src`/`dest` memory is not supported, matching the rest of the
/// crate.
///
/// Ranks above [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT) are supported by the same fused
/// traversal, which then stores its axes in one rank-bounded allocation.
///
/// # Example
///
/// ```rust
/// use strided_basic::{CopyPlan, Exec, RawStridedMut, RawStridedRef};
///
/// let dims = [2usize, 3];
/// let src_strides = [3isize, 1];
/// let dst_strides = [1isize, 2]; // transposed destination
/// let plan = CopyPlan::compile(&dims, &dst_strides, &src_strides).unwrap();
///
/// let src = [0.0f64, 1.0, 2.0, 10.0, 11.0, 12.0];
/// let mut dst = [0.0f64; 6];
/// let src_ref = RawStridedRef::new(&src, &dims, &src_strides, 0).unwrap();
/// let mut dst_mut = RawStridedMut::new(&mut dst, &dims, &dst_strides, 0).unwrap();
/// plan.execute(&mut dst_mut, &src_ref, Exec::serial()).unwrap();
/// assert_eq!(dst, [0.0, 10.0, 1.0, 11.0, 2.0, 12.0]);
/// ```
#[derive(Clone, Debug, Default)]
pub struct CopyPlan {
    dims: AxisVec<usize>,
    dst_strides: AxisVec<isize>,
    src_strides: AxisVec<isize>,
    fused: PairTraversal,
    /// Elements each side spans ([`span_elements`]), so that the working set in
    /// bytes is `dst_span * size_of::<D>() + src_span * size_of::<S>()` at replay,
    /// where the element types are known.
    dst_span: usize,
    src_span: usize,
}

impl CopyPlan {
    /// `None` when the fused traversal is stored in the rank-bounded spill.
    #[inline]
    pub(crate) fn fused_layout(&self) -> Option<&FusedPairLayout> {
        self.fused.inline()
    }

    /// The cache tiles [`Self::execute`] replays this plan's inline layout with
    /// for destination element `D` and source element `S`, or `None` when it
    /// keeps the column-major walk or the layout spilled: the one decision a
    /// caller replaying the plan's inline traversal itself must reuse.
    #[inline]
    pub(crate) fn inline_tiles<D, S>(&self) -> Option<PairTiles> {
        self.fused.inline().and_then(pair_tiles::<D, S>)
    }

    /// Whether [`Self::tiles`] can return tiles for any element types; known
    /// at compile time ([`PairTraversal::may_tile`]).
    #[inline]
    pub(crate) fn may_tile(&self) -> bool {
        self.fused.may_tile()
    }

    /// Copy into uninitialized storage, then lend the initialized destination to `f`.
    ///
    /// [`Self::execute_uninit`] initializes every reachable logical destination
    /// element before `f` runs, so the [`InitializedRawDest`] receipt handed to `f`
    /// may read and overwrite exactly those offsets. Slots outside the plan's
    /// reachable set are not written by that copy and it makes no claim about
    /// them: a caller that handed in a `MaybeUninit` array still owns those slots,
    /// so they keep whatever initialization the caller left. With
    /// `CopyPlan::compile(&[2], &[2], &[1])` the offset-1 hole keeps the caller's
    /// value (measured `[7.0, 99.0, 8.0]` for `src = [7, 8]`) rather than
    /// becoming uninitialized. That is why the receipt exposes
    /// `write_at`/`add_at` (copy_plan.rs:138, :150) instead of a typed slice: their
    /// contracts require an offset proven by this plan's layout. The receipt borrows
    /// the destination for `f`'s lifetime, so a read-modify-write consumer (the
    /// gather and scatter update replay in gather_plan.rs) sees the copied operand
    /// once and cannot alias the source.
    ///
    /// # Errors
    ///
    /// Returns the [`Self::execute_uninit`] errors (`PlanLayoutMismatch`, before any
    /// write); `f` runs only on success.
    pub(crate) fn execute_uninit_then<'a, T, R>(
        &self,
        dest: &'a mut RawStridedMut<'a, MaybeUninit<T>>,
        src: &RawStridedRef<'_, T>,
        mut exec: Exec<'_>,
        f: impl for<'b, 'e> FnOnce(InitializedRawDest<'b, T>, Exec<'e>) -> R,
    ) -> Result<R>
    where
        T: Copy + Send + Sync,
    {
        self.execute_uninit(dest, src, exec.reborrow())?;
        let data = dest.data_mut();
        let receipt = InitializedRawDest {
            ptr: data.as_mut_ptr().cast(),
            extent: data.len(),
            dims: dest.dims(),
            strides: dest.strides(),
            offset: dest.offset(),
            _marker: PhantomData,
        };
        Ok(f(receipt, exec))
    }

    /// Compile a copy plan for the given layout pair.
    ///
    /// Performs the layout validation and traversal construction
    /// (fuse + order) once.
    ///
    /// # Errors
    ///
    /// Returns [`StridedError::StrideLengthMismatch`] when `dims`,
    /// `dst_strides`, and `src_strides` do not all have the same length,
    /// [`StridedError::OffsetOverflow`] when the total element count does not
    /// fit `usize`, and [`StridedError::NonInjectiveOutputLayout`] when the
    /// destination layout cannot be proven injective (aliasing elements, or a
    /// span the check cannot represent).
    pub fn compile(dims: &[usize], dst_strides: &[isize], src_strides: &[isize]) -> Result<Self> {
        if dims.len() != dst_strides.len() || dims.len() != src_strides.len() {
            return Err(StridedError::StrideLengthMismatch);
        }
        // A zero-sized layout has zero elements even when its other extents
        // overflow; only a nonempty overflowing count is rejected.
        crate::kernel::total_len(dims)?;
        if !crate::layout_check::is_injective_layout(dims, dst_strides) {
            return Err(StridedError::NonInjectiveOutputLayout);
        }
        let fused = fuse_pair_traversal(dims, dst_strides, src_strides);
        Ok(Self {
            dims: dims.into(),
            dst_strides: dst_strides.into(),
            src_strides: src_strides.into(),
            fused,
            dst_span: span_elements(dims, dst_strides),
            src_span: span_elements(dims, src_strides),
        })
    }

    /// Serial rate this plan prices itself at on host class `host`: the `Copy`
    /// row while the plan is one contiguous run, the row plus one cache line per
    /// run of its walk otherwise, the class's beyond-L2 line past its L2 cache
    /// (strided-rs#364). [`Self::replay`] asks it for [`HostClass::detect`]; the
    /// class is a parameter so that the tests can pin it.
    ///
    /// The element size is the one fact `compile` cannot know, so the footprint
    /// in bytes is formed here from the compiled span; nothing is probed.
    fn ns_per_element_on<D, S>(&self, host: HostClass) -> f64 {
        plan_ns_per_element::<D, S>(host, &self.fused, self.dst_span, self.src_span)
    }

    /// Check the per-call facts: the supplied views must carry exactly the
    /// compiled layout. Buffer bounds against that layout were already proven
    /// by [`RawStridedRef::new`]/[`RawStridedMut::new`] (or asserted by the
    /// caller of the `new_unchecked` constructors), so layout equality is the
    /// complete precondition for the pointer-based fused replay below.
    fn check_call<D, S>(
        &self,
        dest: &RawStridedMut<'_, D>,
        src: &RawStridedRef<'_, S>,
    ) -> Result<()> {
        check_layout_pair(&self.dims, &self.dst_strides, &self.src_strides, dest, src)
    }

    /// Check the per-call facts, then replay the compiled traversal, priced for
    /// this host's class.
    fn replay<D, S, Apply>(
        &self,
        dest: &mut RawStridedMut<'_, D>,
        src: &RawStridedRef<'_, S>,
        apply: Apply,
        exec: Exec<'_>,
    ) -> Result<()>
    where
        D: Copy + Send + Sync,
        S: Copy + Send + Sync,
        Apply: Fn(&mut D, S) + Sync,
    {
        self.replay_on(HostClass::detect(), dest, src, apply, exec)
    }

    /// [`Self::replay`] priced for host class `host`: every scheduling decision
    /// of the replay asks at [`Self::ns_per_element_on`] of that class. Split out
    /// so that a test can pin the class and observe the rate reach the replay on
    /// every host (strided-rs#364).
    fn replay_on<D, S, Apply>(
        &self,
        host: HostClass,
        dest: &mut RawStridedMut<'_, D>,
        src: &RawStridedRef<'_, S>,
        apply: Apply,
        exec: Exec<'_>,
    ) -> Result<()>
    where
        D: Copy + Send + Sync,
        S: Copy + Send + Sync,
        Apply: Fn(&mut D, S) + Sync,
    {
        self.check_call(dest, src)?;
        let ns_per_element = self.ns_per_element_on::<D, S>(host);
        self.fused.with_route::<D, S, _>(|route| {
            // SAFETY: `check_call` proved both views carry exactly the compiled
            // layout, and `fused` is the fusion of that layout (only `compile`
            // and `Default`, the rank-zero layout, build it). `compile` checked
            // the element count and proved the destination injective, so the
            // tiles of `fused` may be replayed.
            unsafe { replay_fused(dest, src, route, apply, ns_per_element, exec) }
        });
        Ok(())
    }

    /// `dest = src` into a potentially uninitialized destination.
    ///
    /// On success every reachable logical destination element is initialized.
    /// Non-reachable holes in the backing allocation are not written.
    ///
    /// # Errors
    ///
    /// Returns [`StridedError::PlanLayoutMismatch`] when the views do not
    /// carry the compiled layout, before any write.
    pub fn execute_uninit<T>(
        &self,
        dest: &mut RawStridedMut<'_, MaybeUninit<T>>,
        src: &RawStridedRef<'_, T>,
        exec: Exec<'_>,
    ) -> Result<()>
    where
        T: Copy + Send + Sync,
    {
        self.replay(
            dest,
            src,
            |dst: &mut MaybeUninit<T>, value: T| {
                dst.write(value);
            },
            exec,
        )
    }

    /// `dest = src`. Allocation-free for fused ranks at most
    /// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT).
    ///
    /// # Errors
    ///
    /// Returns [`StridedError::PlanLayoutMismatch`] when the views do not
    /// carry the compiled layout, before any write.
    pub fn execute<T>(
        &self,
        dest: &mut RawStridedMut<'_, T>,
        src: &RawStridedRef<'_, T>,
        exec: Exec<'_>,
    ) -> Result<()>
    where
        T: Copy + Send + Sync,
    {
        self.replay(dest, src, |dst: &mut T, value: T| *dst = value, exec)
    }

    /// `dest = scale * src`. Allocation-free for fused ranks at most
    /// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT).
    ///
    /// # Errors
    ///
    /// Returns [`StridedError::PlanLayoutMismatch`] when the views do not
    /// carry the compiled layout, before any write.
    pub fn execute_scale<T>(
        &self,
        dest: &mut RawStridedMut<'_, T>,
        src: &RawStridedRef<'_, T>,
        scale: T,
        exec: Exec<'_>,
    ) -> Result<()>
    where
        T: Copy + Mul<T, Output = T> + Send + Sync,
    {
        self.replay(
            dest,
            src,
            |dst: &mut T, value: T| *dst = scale * value,
            exec,
        )
    }

    /// `dest = conj(src)`. Allocation-free for fused ranks at most
    /// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT).
    ///
    /// # Errors
    ///
    /// Returns [`StridedError::PlanLayoutMismatch`] when the views do not
    /// carry the compiled layout, before any write.
    pub fn execute_conj<T>(
        &self,
        dest: &mut RawStridedMut<'_, T>,
        src: &RawStridedRef<'_, T>,
        exec: Exec<'_>,
    ) -> Result<()>
    where
        T: Copy + ElementOpApply + Send + Sync,
    {
        self.replay(dest, src, |dst: &mut T, value: T| *dst = value.conj(), exec)
    }
}

/// Whether the replay walks `fused` as one unit-stride run on each side, the
/// layout the `Copy` row is calibrated on, and the length of the unit-stride run
/// its walk starts with.
///
/// A *run* is a stretch of the walk that advances by one element on both sides;
/// a streamed contiguous copy is one run and keeps the row at every footprint, a
/// reversed one (`-1` on a side) streams the same way, and a transposing walk
/// takes one run of one element per visit. The run length is the
/// `elements / segments` ratio of strided-rs#364's
/// `segments * per_segment + elements * per_element_inside_segment`, read off the
/// frozen fused layout, so it is a compile-time plan property and nothing is
/// probed.
///
/// The question is about the walk the replay takes, not about a walk the layout
/// would allow: both replays walk the fused axes in their stored order with axis 0
/// fastest (`apply_fused_range`, `apply_spilled_range`), and the tiled replay only
/// exists for two or more moving axes. So the strides, read in that order, must be
/// the running products of the extents with one sign per operand. Fusion already
/// merges every such pair, so in practice a one-run walk is a fused rank of one at
/// unit stride; a dense *reversed* buffer of rank two or more is not one run here,
/// because fusion sorts the axes by signed destination stride and walks
/// `[-1, -512]` over `[512, 512]` with `-512` fastest (strided-rs#364 review).
/// That walk's runs are one element long, and it is priced as the strided walk it
/// is.
fn walk_runs(fused: &PairTraversal) -> (usize, bool) {
    /// `(leading run length, that run is the whole walk)`.
    fn runs(axes: impl Iterator<Item = (usize, isize, isize)>) -> (usize, bool) {
        let mut len = 1usize;
        let mut signs = None;
        for (dim, dst, src) in axes {
            if dim == 1 {
                continue;
            }
            // A direction flip ends the run too: the walk reverses there, so the
            // next element is a new cache line even at a unit stride.
            let axis_signs = (dst < 0, src < 0);
            if dst.unsigned_abs() != len
                || src.unsigned_abs() != len
                || *signs.get_or_insert(axis_signs) != axis_signs
            {
                return (len, false);
            }
            len = len.saturating_mul(dim);
        }
        (len, true)
    }
    match fused {
        PairTraversal::Inline(layout) => runs(inline_axes(layout)),
        PairTraversal::Spilled(axes) => runs(spilled_axes(axes)),
    }
}

// shortcut: the run length is the fused axes' untiled walk. The tiled replay of
// strided-rs#422 cuts a box, so its runs can be shorter than the leading axis run
// (an inner extent of 8 tiled to 6 and 2 halves the run length and so doubles the
// per-run line charge). Upgrade when a tiled plan's in-L2 pricing is measured
// against the model: derive the charge from `PairTraversal::with_route` then.

/// The axes of a fused walk in replay order (axis 0 fastest) as
/// `(extent, destination stride, source stride)`.
fn inline_axes(layout: &FusedPairLayout) -> impl Iterator<Item = (usize, isize, isize)> + '_ {
    (0..layout.rank).map(move |axis| {
        (
            layout.dims[axis],
            layout.dst_strides[axis],
            layout.src_strides[axis],
        )
    })
}

/// [`inline_axes`] for the spilled traversal.
fn spilled_axes(axes: &[FusedAxis]) -> impl Iterator<Item = (usize, isize, isize)> + '_ {
    axes.iter().map(|axis| (axis.dim, axis.dst, axis.src))
}

/// Serial rate a copy-shaped plan prices itself at on `host`, from the three
/// facts `compile` froze in its fused layout and spans: whether the whole walk is
/// one contiguous run, the length of its runs, and the working set in bytes.
///
/// [`CopyPlan`] and [`UpdatePlan`] both replay [`replay_fused`], so both ask their
/// rate here (strided-rs#364).
fn plan_ns_per_element<D, S>(
    host: HostClass,
    fused: &PairTraversal,
    dst_span: usize,
    src_span: usize,
) -> f64 {
    let (run_len, one_run) = walk_runs(fused);
    if one_run {
        return KernelClass::Copy.ns_per_element_of(host);
    }
    let bytes = dst_span
        .saturating_mul(size_of::<D>())
        .saturating_add(src_span.saturating_mul(size_of::<S>()));
    crate::cost::copy_ns_per_element_for_plan(host, bytes, run_len)
}

/// Elements one side of a compiled layout spans: `1 + sum((dim - 1) * |stride|)`,
/// the reach of the side from its base offset. Summed over the two sides it is
/// the plan's working set in elements, saturating rather than wrapping because a
/// stride is only bounded by `isize`.
fn span_elements(dims: &[usize], strides: &[isize]) -> usize {
    dims.iter()
        .zip(strides)
        .fold(1usize, |span, (&dim, &stride)| {
            span.saturating_add(dim.saturating_sub(1).saturating_mul(stride.unsigned_abs()))
        })
}

/// Verify that a pair of raw views carries exactly a compiled layout.
///
/// Shared by [`CopyPlan`] and [`UpdatePlan`], whose `compile` methods prove the
/// layout facts once. Buffer bounds against that layout were already proven by
/// [`RawStridedRef::new`]/[`RawStridedMut::new`] (or asserted by the caller of
/// the `new_unchecked` constructors), so layout equality is the complete
/// per-call precondition for the pointer-based fused replay.
fn check_layout_pair<D, S>(
    dims: &[usize],
    dst_strides: &[isize],
    src_strides: &[isize],
    dest: &RawStridedMut<'_, D>,
    src: &RawStridedRef<'_, S>,
) -> Result<()> {
    if dest.dims() != dims
        || src.dims() != dims
        || dest.strides() != dst_strides
        || src.strides() != src_strides
    {
        return Err(StridedError::PlanLayoutMismatch);
    }
    Ok(())
}

/// A compiled read-modify-write traversal for one `(dims, dst_strides,
/// src_strides)` layout pair.
///
/// [`execute`](Self::execute) computes `dest = alpha * f(src) + beta * dest` by
/// replaying the same fused pair traversal as [`CopyPlan`]: `compile` proves
/// the layout facts once (rank agreement, extent overflow, destination
/// injectivity) and each call only re-checks that the supplied views carry the
/// compiled layout before running monomorphized loops. Execute is
/// allocation-free for fused ranks at most
/// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT), and the injective
/// destination makes a large replay parallel-safe exactly as in [`CopyPlan`].
///
/// Overlapping `src`/`dest` memory is not supported, matching the rest of the
/// crate.
///
/// # Example
///
/// ```rust
/// use strided_basic::{Exec, RawStridedMut, RawStridedRef, UpdatePlan};
///
/// let dims = [2usize, 2];
/// let dst_strides = [1isize, 2];
/// let src_strides = [1isize, 2];
/// let plan = UpdatePlan::compile(&dims, &dst_strides, &src_strides).unwrap();
///
/// let src = [1.0f64, 2.0, 3.0, 4.0];
/// let mut dst = [10.0f64, 20.0, 30.0, 40.0];
/// let src_ref = RawStridedRef::new(&src, &dims, &src_strides, 0).unwrap();
/// let mut dst_mut = RawStridedMut::new(&mut dst, &dims, &dst_strides, 0).unwrap();
/// // dst = 2 * src + 3 * dst
/// plan.execute(&mut dst_mut, &src_ref, 2.0, 3.0, |x| x, Exec::serial()).unwrap();
/// assert_eq!(dst, [32.0, 64.0, 96.0, 128.0]);
/// ```
#[derive(Clone, Debug)]
pub struct UpdatePlan {
    dims: AxisVec<usize>,
    dst_strides: AxisVec<isize>,
    src_strides: AxisVec<isize>,
    fused: PairTraversal,
    /// Working-set spans, as on [`CopyPlan`]: the footprint in bytes is formed at
    /// replay, where the element types are known.
    dst_span: usize,
    src_span: usize,
}

impl UpdatePlan {
    /// Compile an update plan for the given layout pair.
    ///
    /// Performs the same layout validation as [`CopyPlan::compile`].
    ///
    /// # Errors
    ///
    /// Returns [`StridedError::StrideLengthMismatch`] when `dims`,
    /// `dst_strides`, and `src_strides` do not all have the same length,
    /// [`StridedError::OffsetOverflow`] when the total element count does not
    /// fit `usize`, and [`StridedError::NonInjectiveOutputLayout`] when the
    /// destination layout cannot be proven injective: two logical indices name
    /// one slot (so a parallel replay would write that slot once per index), or
    /// the offset span cannot be represented, leaving injectivity undecided.
    pub fn compile(dims: &[usize], dst_strides: &[isize], src_strides: &[isize]) -> Result<Self> {
        if dims.len() != dst_strides.len() || dims.len() != src_strides.len() {
            return Err(StridedError::StrideLengthMismatch);
        }
        crate::kernel::total_len(dims)?;
        if !crate::layout_check::is_injective_layout(dims, dst_strides) {
            return Err(StridedError::NonInjectiveOutputLayout);
        }
        let fused = fuse_pair_traversal(dims, dst_strides, src_strides);
        Ok(Self {
            dims: dims.into(),
            dst_strides: dst_strides.into(),
            src_strides: src_strides.into(),
            fused,
            dst_span: span_elements(dims, dst_strides),
            src_span: span_elements(dims, src_strides),
        })
    }

    /// Serial rate this plan prices itself at on host class `host`: the same
    /// [`plan_ns_per_element`] as [`CopyPlan`], because both replay
    /// [`replay_fused`] and a caller that paid the line per run on one would pay
    /// it on the other (strided-rs#364).
    fn ns_per_element_on<D, S>(&self, host: HostClass) -> f64 {
        plan_ns_per_element::<D, S>(host, &self.fused, self.dst_span, self.src_span)
    }

    /// Check the per-call facts, then replay the compiled traversal, priced for
    /// this host's class.
    fn replay<D, S, Apply>(
        &self,
        dest: &mut RawStridedMut<'_, D>,
        src: &RawStridedRef<'_, S>,
        apply: Apply,
        exec: Exec<'_>,
    ) -> Result<()>
    where
        D: Copy + Send + Sync,
        S: Copy + Send + Sync,
        Apply: Fn(&mut D, S) + Sync,
    {
        self.replay_on(HostClass::detect(), dest, src, apply, exec)
    }

    /// [`Self::replay`] priced for host class `host`: split out for the same
    /// reason as [`CopyPlan::replay_on`], so that a test can pin the class and see
    /// the plan's rate reach the replay on every host (strided-rs#364).
    fn replay_on<D, S, Apply>(
        &self,
        host: HostClass,
        dest: &mut RawStridedMut<'_, D>,
        src: &RawStridedRef<'_, S>,
        apply: Apply,
        exec: Exec<'_>,
    ) -> Result<()>
    where
        D: Copy + Send + Sync,
        S: Copy + Send + Sync,
        Apply: Fn(&mut D, S) + Sync,
    {
        check_layout_pair(&self.dims, &self.dst_strides, &self.src_strides, dest, src)?;
        let ns_per_element = self.ns_per_element_on::<D, S>(host);
        self.fused.with_route::<D, S, _>(|route| {
            // SAFETY: as in `CopyPlan::replay`: the views carry the compiled
            // layout, `fused` is its fusion (built only by `compile`), and
            // `compile` checked the count and destination injectivity.
            unsafe { replay_fused(dest, src, route, apply, ns_per_element, exec) }
        });
        Ok(())
    }

    /// `dest = alpha * f(src) + beta * dest`.
    ///
    /// `f` is applied to the source element before scaling. When `beta` is
    /// zero (`-0.0` included; `NaN` is not zero) the replay is write-only: the
    /// old destination element is never read, so a NaN-filled or uninitialized
    /// destination cannot contaminate the result, matching BLAS `beta = 0`
    /// semantics. Otherwise the old destination element is read through the
    /// destination layout. Allocation-free for fused ranks at most
    /// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT).
    ///
    /// `f` runs once per logical element. The order in which elements are
    /// visited is unspecified, and on a parallel replay `f` runs concurrently
    /// on disjoint slots: the result is defined only for an `f` whose effect
    /// depends on the supplied value alone.
    ///
    /// # Errors
    ///
    /// [`StridedError::PlanLayoutMismatch`] when the supplied views do not
    /// carry the compiled layout, before any write.
    pub fn execute<T, F>(
        &self,
        dest: &mut RawStridedMut<'_, T>,
        src: &RawStridedRef<'_, T>,
        alpha: T,
        beta: T,
        f: F,
        exec: Exec<'_>,
    ) -> Result<()>
    where
        T: Copy + Send + Sync + Add<Output = T> + Mul<Output = T> + Zero + One + PartialEq,
        F: Fn(T) -> T + Send + Sync,
    {
        if beta.is_zero() {
            // Write-only: never form a read of the old destination.
            if alpha.is_one() {
                self.replay(dest, src, |dst: &mut T, value: T| *dst = f(value), exec)
            } else {
                self.replay(
                    dest,
                    src,
                    |dst: &mut T, value: T| *dst = alpha * f(value),
                    exec,
                )
            }
        } else {
            self.replay(
                dest,
                src,
                |dst: &mut T, value: T| *dst = alpha * f(value) + beta * *dst,
                exec,
            )
        }
    }

    /// `dest = alpha * f(src)` into a potentially uninitialized destination.
    ///
    /// This is [`execute`](Self::execute) with `beta = 0`: the destination is
    /// never read. On success every reachable logical destination element is
    /// initialized; non-reachable holes in the backing allocation are not
    /// written. Allocation-free for fused ranks at most
    /// [`RAW_FUSED_RANK_LIMIT`](crate::RAW_FUSED_RANK_LIMIT). The visit-order
    /// and callback contract is that of [`execute`](Self::execute).
    ///
    /// # Errors
    ///
    /// [`StridedError::PlanLayoutMismatch`] when the supplied views do not
    /// carry the compiled layout, before any write.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use core::mem::MaybeUninit;
    /// use strided_basic::{Exec, RawStridedMut, RawStridedRef, UpdatePlan};
    ///
    /// let dims = [2usize, 2];
    /// let strides = [1isize, 2];
    /// let plan = UpdatePlan::compile(&dims, &strides, &strides).unwrap();
    /// let src = [1.0f64, 2.0, 3.0, 4.0];
    /// let mut storage = [MaybeUninit::<f64>::uninit(); 4];
    /// let mut dst = RawStridedMut::new(&mut storage, &dims, &strides, 0).unwrap();
    /// let source = RawStridedRef::new(&src, &dims, &strides, 0).unwrap();
    /// // dst = 2 * src
    /// plan.execute_uninit(&mut dst, &source, 2.0, |x| x, Exec::serial()).unwrap();
    /// drop(dst);
    /// // SAFETY: every reachable destination slot was initialized above.
    /// let values: Vec<f64> = storage.iter().map(|v| unsafe { v.assume_init() }).collect();
    /// assert_eq!(values, [2.0, 4.0, 6.0, 8.0]);
    /// ```
    pub fn execute_uninit<T, F>(
        &self,
        dest: &mut RawStridedMut<'_, MaybeUninit<T>>,
        src: &RawStridedRef<'_, T>,
        alpha: T,
        f: F,
        exec: Exec<'_>,
    ) -> Result<()>
    where
        T: Copy + Send + Sync + Mul<Output = T> + One + PartialEq,
        F: Fn(T) -> T + Send + Sync,
    {
        if alpha.is_one() {
            self.replay(
                dest,
                src,
                |dst: &mut MaybeUninit<T>, value: T| {
                    dst.write(f(value));
                },
                exec,
            )
        } else {
            self.replay(
                dest,
                src,
                |dst: &mut MaybeUninit<T>, value: T| {
                    dst.write(alpha * f(value));
                },
                exec,
            )
        }
    }
}

/// Replay `route` over a pair of raw views, splitting it across the budget
/// of `exec` when the repository threshold allows it.
///
/// A tiled route walks its cache tiles and splits the box with the dimension
/// splitter (see [`replay_fused_raw`] and [`replay_spilled_tiled`]). An
/// untiled one splits the logical index space `0..total`
/// (column-major over the traversal axes) is split into contiguous worker
/// ranges, which divides the outer axes and, when there are fewer outer
/// positions than workers, also chunks long inner runs (for example a rank-1
/// contiguous copy). A serial token walks the route through
/// [`replay_route_serial`], the walk [`crate::replay_map_raw_serial`]
/// shares.
///
/// # Safety
///
/// - `route` must replay exactly the logical index space of the two views:
///   either their dims and strides fused by `fuse_pair_traversal`
///   ([`PairTraversal::with_route`]), or given by them
///   ([`crate::raw_ops::with_given_route`]). The views' own bounds proofs
///   ([`RawStridedRef::new`], [`RawStridedMut::new`], or the caller of their
///   `new_unchecked`) then make every replayed offset in-bounds.
/// - The product of the route's extents must not overflow `usize` (a checked
///   count, zero included).
/// - The route's tiles, when present, must be the decision of the route
///   builder for its own axes.
/// - When the route is tiled or `exec` is not serial, the destination strides
///   must be injective over the route.
/// - The destination and source must not overlap.
///
/// `ns_per_element` is the serial rate the replay prices itself at; both plan
/// types pass their own ([`CopyPlan::ns_per_element_on`],
/// `UpdatePlan::ns_per_element_on`), because the pricing follows the traversal and
/// not the entry. The plan-free `replay_*_raw` entries pass the rate of
/// `KernelClass::Copy` ([`crate::cost::KernelClass::ns_per_element`]).
pub(crate) unsafe fn replay_fused<D, S, Apply>(
    dest: &mut RawStridedMut<'_, D>,
    src: &RawStridedRef<'_, S>,
    route: Route<'_>,
    mut apply: Apply,
    ns_per_element: f64,
    exec: Exec<'_>,
) where
    D: Copy + Send + Sync,
    S: Copy + Send + Sync,
    Apply: Fn(&mut D, S) + Sync,
{
    let src_ptr = src.data().as_ptr();
    let src_base = src.offset();
    let dst_base = dest.offset();
    let dst_ptr = dest.data_mut().as_mut_ptr();
    if exec.is_serial() {
        // SAFETY: forwarded caller contract, on a serial token.
        unsafe {
            replay_route_serial(dst_ptr, dst_base, src_ptr, src_base, route, &mut apply);
        }
        return;
    }
    // SAFETY: forwarded caller contract: every logical index of `route` maps
    // to in-bounds slots of both views, injectivity holds whenever the replay
    // is tiled or the token can fan out, and the borrows do not overlap. Inline
    // tiles address exactly the slots of their layout, in the same column-major
    // order.
    unsafe {
        match route {
            Route::Inline { layout, tiles } => replay_fused_raw(
                dst_ptr,
                dst_base,
                src_ptr,
                src_base,
                layout,
                tiles,
                apply,
                ns_per_element,
                exec,
            ),
            Route::Spilled {
                tiles: Some(tiles), ..
            } => replay_spilled_tiled(
                dst_ptr,
                dst_base,
                src_ptr,
                src_base,
                tiles,
                apply,
                exec,
                ns_per_element,
            ),
            Route::Spilled { axes, tiles: None } => replay_spilled_raw(
                dst_ptr,
                dst_base,
                src_ptr,
                src_base,
                axes,
                apply,
                ns_per_element,
                exec,
            ),
        }
    }
}

/// Pointer-level fused replay shared by [`CopyPlan`], [`UpdatePlan`], the
/// plan-free `replay_*_raw` entries and the dynamic slice plans, which replay
/// a fused window layout at a runtime base offset.
///
/// Without `tiles`, splits `0..total` across the budget of `exec` when the
/// repository threshold allows more than one slot, otherwise runs the serial
/// kernel directly. With `tiles`, the box is walked tile by tile; a token on
/// which one fork pays splits it with the dimension splitter, and every leaf
/// walks its sub-box with the same tiles anchored at its origin.
///
/// # Safety
///
/// Every logical index of `layout`, mapped through its destination strides
/// from `dst_base` and its source strides from `src_base`, must be an
/// in-bounds slot of the destination and source allocations, and the product
/// of its extents must not overflow `usize`. `tiles`, when `Some`, must be
/// `pair_tiles::<D, S>(layout)`. When `tiles` is `Some` or `exec` is not
/// serial, the destination strides must be injective over `layout`; an
/// untiled serial replay updates a repeated slot once per logical index, in
/// order. The destination must not overlap the source, and nothing else may
/// access the destination slots during the call.
#[allow(clippy::too_many_arguments)]
pub(crate) unsafe fn replay_fused_raw<D, S, Apply>(
    dst_ptr: *mut D,
    dst_base: isize,
    src_ptr: *const S,
    src_base: isize,
    layout: &FusedPairLayout,
    tiles: Option<&PairTiles>,
    mut apply: Apply,
    ns_per_element: f64,
    exec: Exec<'_>,
) where
    D: Copy + Send + Sync,
    S: Copy + Send + Sync,
    Apply: Fn(&mut D, S) + Sync,
{
    let total = fused_total(layout);
    if total == 0 {
        return;
    }
    if let Some(tiles) = tiles {
        // SAFETY: forwarded caller contract; `tiles` addresses exactly the
        // slots of `layout` and the destination is injective over them.
        unsafe {
            replay_tiled(
                dst_ptr,
                dst_base,
                src_ptr,
                src_base,
                tiles,
                &apply,
                ns_per_element,
                exec,
            )
        };
        return;
    }
    let exec = crate::cost::for_len_at_rate(exec, total, ns_per_element);
    if !exec.is_serial() {
        let dst_ptr = crate::threading::SendPtr(dst_ptr);
        let src_ptr = crate::threading::SendPtr(src_ptr as *mut S);
        crate::threading::parallel_for_each(0..total, exec, &|range| {
            // SAFETY: the caller contract makes every index in bounds; the
            // token is not serial, so the destination strides are injective
            // and the disjoint worker ranges write disjoint slots; the source
            // is only read.
            unsafe {
                apply_fused_range(
                    dst_ptr.as_ptr(),
                    dst_base,
                    src_ptr.as_const(),
                    src_base,
                    layout,
                    range.start,
                    range.len(),
                    &mut &apply,
                );
            }
        });
        return;
    }
    // SAFETY: forwarded caller contract over the full range `0..total`; one
    // sequential walk needs no injectivity.
    unsafe {
        apply_fused_range(
            dst_ptr, dst_base, src_ptr, src_base, layout, 0, total, &mut apply,
        );
    }
}

/// Tiled replay of [`replay_fused_raw`]: serially one [`apply_tiled_box`] over
/// the whole box, or, when one fork pays, the dimension splitter of the view
/// path with one [`apply_tiled_box`] per leaf box.
///
/// The leaves walk the model's own blocks clipped to the leaf, as Strided.jl's
/// leaves rerun `_mapreduce_kernel!` with the same `blocks`; the halved blocks
/// the splitter normalizes internally only steer where it may cut.
///
/// # Safety
///
/// The [`replay_fused_raw`] contract for `tiles.layout`, with an injective
/// destination.
#[inline(never)]
#[allow(clippy::too_many_arguments)]
unsafe fn replay_tiled<D, S, Apply>(
    dst_ptr: *mut D,
    dst_base: isize,
    src_ptr: *const S,
    src_base: isize,
    tiles: &PairTiles,
    apply: &Apply,
    ns_per_element: f64,
    exec: Exec<'_>,
) where
    D: Copy + Send + Sync,
    S: Copy + Send + Sync,
    Apply: Fn(&mut D, S) + Sync,
{
    let layout = &tiles.layout;
    let rank = layout.rank;
    let total = fused_total(layout);
    // The plan's rate, not the row: a footprint past the class's L2 pays here too
    // (strided-rs#364).
    if !crate::cost::is_parallel_at_rate(total, ns_per_element, &exec) {
        // SAFETY: forwarded caller contract over the whole box.
        unsafe {
            apply_tiled_box(
                dst_ptr,
                dst_base,
                src_ptr,
                src_base,
                layout,
                &tiles.blocks,
                &mut &*apply,
            )
        };
        return;
    }
    let strides = [&layout.dst_strides[..rank], &layout.src_strides[..rank]];
    let costs = crate::fuse::compute_costs(&strides);
    let dst_ptr = crate::threading::SendPtr(dst_ptr);
    let src_ptr = crate::threading::SendPtr(src_ptr as *mut S);
    #[cfg(test)]
    let leaves = std::sync::Mutex::new(Vec::new());
    let result = crate::threading::mapreduce_threaded_at_rate(
        &layout.dims[..rank],
        &tiles.blocks[..rank],
        &strides,
        &[dst_base, src_base],
        &costs,
        ns_per_element,
        exec,
        &|box_dims, _, _, offsets| {
            #[cfg(test)]
            if let Ok(mut leaves) = leaves.lock() {
                leaves.push((offsets[0], offsets[1], box_dims.to_vec()));
            }
            let mut leaf = *layout;
            leaf.dims[..rank].copy_from_slice(box_dims);
            // SAFETY: the splitter hands disjoint sub-boxes of `layout` with
            // the offsets of their origins, so every logical index of a leaf
            // is one of `layout`; the injective destination makes the leaves
            // write disjoint slots, and the source is only read.
            unsafe {
                apply_tiled_box(
                    dst_ptr.as_ptr(),
                    offsets[0],
                    src_ptr.as_const(),
                    offsets[1],
                    &leaf,
                    &tiles.blocks,
                    &mut &*apply,
                )
            };
            Ok(())
        },
    );
    // INVARIANT: the splitter fails only on an extent product beyond `usize`,
    // which the caller contract excludes, and the leaves never fail.
    debug_assert!(result.is_ok());
    #[cfg(test)]
    crate::threading::record_tiled_leaves(leaves.into_inner().unwrap_or_default());
}

/// Tiled replay of a spilled axis list: serially one
/// [`apply_spilled_tiled_box`] over the whole box, or, when one fork pays, the
/// dimension splitter of the view path with one box walk per leaf box.
///
/// The spilled counterpart of [`replay_tiled`], on the slice-backed
/// [`SpilledTiles`]: same splitter, same per-leaf clipping of the model's own
/// blocks.
///
/// # Safety
///
/// The [`replay_spilled_raw`] contract for `tiles.dims`, with an injective
/// destination.
#[allow(clippy::too_many_arguments)]
#[inline(never)]
unsafe fn replay_spilled_tiled<D, S, Apply>(
    dst_ptr: *mut D,
    dst_base: isize,
    src_ptr: *const S,
    src_base: isize,
    tiles: &SpilledTiles,
    mut apply: Apply,
    exec: Exec<'_>,
    ns_per_element: f64,
) where
    D: Copy + Send + Sync,
    S: Copy + Send + Sync,
    Apply: Fn(&mut D, S) + Sync,
{
    let total = tiles.dims().iter().product::<usize>();
    if !crate::cost::is_parallel_at_rate(total, ns_per_element, &exec) {
        // SAFETY: forwarded caller contract over the whole box.
        unsafe {
            apply_spilled_tiled_box(
                dst_ptr,
                dst_base,
                src_ptr,
                src_base,
                tiles,
                tiles.dims(),
                &mut apply,
            )
        };
        return;
    }
    let strides = [tiles.dst(), tiles.src()];
    let costs = crate::fuse::compute_costs(&strides);
    let dst_ptr = crate::threading::SendPtr(dst_ptr);
    let src_ptr = crate::threading::SendPtr(src_ptr as *mut S);
    #[cfg(test)]
    let leaves = std::sync::Mutex::new(Vec::new());
    let result = crate::threading::mapreduce_threaded_at_rate(
        tiles.dims(),
        tiles.blocks(),
        &strides,
        &[dst_base, src_base],
        &costs,
        ns_per_element,
        exec,
        &|box_dims, _, _, offsets| {
            #[cfg(test)]
            if let Ok(mut leaves) = leaves.lock() {
                leaves.push((offsets[0], offsets[1], box_dims.to_vec()));
            }
            // SAFETY: the splitter hands disjoint sub-boxes of `tiles.dims`
            // with the offsets of their origins, so every logical index of a
            // leaf is one of the tiles' slots; the injective destination makes
            // the leaves write disjoint slots, and the source is only read.
            unsafe {
                apply_spilled_tiled_box(
                    dst_ptr.as_ptr(),
                    offsets[0],
                    src_ptr.as_const(),
                    offsets[1],
                    tiles,
                    box_dims,
                    &mut &apply,
                )
            };
            Ok(())
        },
    );
    // INVARIANT: the splitter fails only on an extent product beyond `usize`,
    // which the caller contract excludes, and the leaves never fail.
    debug_assert!(result.is_ok());
    #[cfg(test)]
    crate::threading::record_tiled_leaves(leaves.into_inner().unwrap_or_default());
}

/// Pointer-level replay of a spilled axis list.
///
/// Mirrors [`replay_fused_raw`] including its worker split; kept separate so
/// that the inline replay keeps its fixed-rank shape.
///
/// # Safety
///
/// The [`replay_fused_raw`] contract, for `axes`.
#[allow(clippy::too_many_arguments)]
pub(crate) unsafe fn replay_spilled_raw<D, S, Apply>(
    dst_ptr: *mut D,
    dst_base: isize,
    src_ptr: *const S,
    src_base: isize,
    axes: &[FusedAxis],
    mut apply: Apply,
    ns_per_element: f64,
    exec: Exec<'_>,
) where
    D: Copy + Send + Sync,
    S: Copy + Send + Sync,
    Apply: Fn(&mut D, S) + Sync,
{
    let total = axes.iter().map(|axis| axis.dim).product::<usize>();
    if total == 0 {
        return;
    }
    let exec = crate::cost::for_len_at_rate(exec, total, ns_per_element);
    if !exec.is_serial() {
        let dst_ptr = crate::threading::SendPtr(dst_ptr);
        let src_ptr = crate::threading::SendPtr(src_ptr as *mut S);
        crate::threading::parallel_for_each(0..total, exec, &|range| {
            // SAFETY: as in `replay_fused_raw`: in-bounds indices, injective
            // destination for a non-serial token, disjoint worker ranges.
            unsafe {
                apply_spilled_range(
                    dst_ptr.as_ptr(),
                    dst_base,
                    src_ptr.as_const(),
                    src_base,
                    axes,
                    range.start,
                    range.len(),
                    &mut &apply,
                );
            }
        });
        return;
    }
    // SAFETY: forwarded caller contract over the full range `0..total`; one
    // sequential walk needs no injectivity.
    unsafe {
        apply_spilled_range(
            dst_ptr, dst_base, src_ptr, src_base, axes, 0, total, &mut apply,
        );
    }
}

#[cfg(test)]
#[path = "copy_plan/tests/tests.rs"]
mod tests;

#[cfg(test)]
#[path = "copy_plan/tests/parallel_tests.rs"]
mod parallel_tests;