tenferro-runtime 0.9.0

Concrete tensor helpers, traced tensors, graph execution, and extension runtime support for tenferro.
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
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
use tenferro_cpu::CpuEngine;
use tenferro_ops::dim_expr::DimExpr;
use tenferro_runtime::{
    CompiledGraph, DType, DotGeneralConfig, Error, ErrorPhase, ExecutionEngine, GatherConfig,
    GraphCompiler, PadConfig, Prepared, Runtime, ScatterConfig, SliceConfig, Tensor,
    TensorSessionOpsExt, TracedTensor,
};
use tenferro_tensor::{Error as TensorError, ShapeMismatch, TensorRead, ValidationError};

fn cpu_runtime(engine: &CpuEngine) -> Runtime {
    let mut builder = Runtime::builder();
    builder
        .register_engine(tenferro_cpu::runtime_engine_registration(engine).unwrap())
        .unwrap();
    builder.build().unwrap()
}

/// A serial CPU engine with a runtime that registers it.
fn cpu_engine_and_runtime() -> (CpuEngine, Runtime) {
    let engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    (engine, runtime)
}

fn inputs_of<'a>(inputs: &[&'a Tensor]) -> Vec<TensorRead<'a>> {
    inputs
        .iter()
        .map(|input| TensorRead::from_tensor(input))
        .collect()
}

fn run_compiled(
    engine: &mut CpuEngine,
    runtime: &Runtime,
    program: &CompiledGraph,
    inputs: &[&Tensor],
) -> tenferro_runtime::Result<Vec<Tensor>> {
    let reads = inputs_of(inputs);
    let prepared = runtime.prepare(program, &reads, &[engine.target()])?;
    let outputs = runtime.run(&mut [engine], &prepared, &reads)?;
    let mut owned = Vec::with_capacity(outputs.len());
    for output in outputs {
        owned.push(output.into_tensor(engine).unwrap());
    }
    Ok(owned)
}

fn prepare(
    engine: &CpuEngine,
    runtime: &Runtime,
    program: &CompiledGraph,
    inputs: &[&Tensor],
) -> tenferro_runtime::Result<Prepared> {
    let reads = inputs_of(inputs);
    runtime.prepare(program, &reads, &[engine.target()])
}

fn run_prepared(
    engine: &mut CpuEngine,
    runtime: &Runtime,
    prepared: &Prepared,
    inputs: &[&Tensor],
) -> tenferro_runtime::Result<Vec<Tensor>> {
    let reads = inputs_of(inputs);
    let outputs = {
        let mut engines: [&mut dyn ExecutionEngine; 1] = [engine];
        runtime.run(&mut engines, prepared, &reads)?
    };
    let mut owned = Vec::with_capacity(outputs.len());
    for output in outputs {
        owned.push(output.into_tensor(engine).unwrap());
    }
    Ok(owned)
}

fn run_compiled_one(program: &CompiledGraph, inputs: &[&Tensor]) -> Tensor {
    let (mut engine, runtime) = cpu_engine_and_runtime();
    let mut outputs = run_compiled(&mut engine, &runtime, program, inputs).unwrap();
    assert_eq!(outputs.len(), 1);
    outputs.pop().unwrap()
}

#[test]
fn runtime_prepared_compiled_graph_runs_repeated_inputs() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let x = TracedTensor::input_concrete_shape(DType::F64, &[2]).unwrap();
    let y = (&x + &x).unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(&y, &[(&x, DType::F64, &[2])])
        .unwrap();
    let first = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
    let second = Tensor::from_vec_col_major(vec![2], vec![3.0_f64, 4.0]).unwrap();

    let prepared = prepare(&engine, &runtime, &program, &[&first]).unwrap();

    let mut outputs = run_prepared(&mut engine, &runtime, &prepared, &[&first]).unwrap();
    assert_eq!(
        outputs.pop().unwrap().as_slice::<f64>().unwrap(),
        &[2.0, 4.0]
    );
    let mut outputs = run_prepared(&mut engine, &runtime, &prepared, &[&second]).unwrap();
    assert_eq!(
        outputs.pop().unwrap().as_slice::<f64>().unwrap(),
        &[6.0, 8.0]
    );

    // Another runtime cannot run a handle prepared by this one.
    let other_runtime = cpu_runtime(&engine);
    assert!(run_prepared(&mut engine, &other_runtime, &prepared, &[&first]).is_err());
}

#[test]
fn one_prepared_program_runs_concurrently_on_two_engines() {
    let (engine, runtime) = cpu_engine_and_runtime();
    let x = TracedTensor::input_concrete_shape(DType::F64, &[4]).unwrap();
    let y = (&x + &x).unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(&y, &[(&x, DType::F64, &[4])])
        .unwrap();
    let input = Tensor::from_vec_col_major(vec![4], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();

    std::thread::scope(|scope| {
        let handles: Vec<_> = (0..2)
            .map(|_| {
                let runtime = &runtime;
                let prepared = &prepared;
                let input = &input;
                scope.spawn(move || {
                    let mut engine = CpuEngine::serial();
                    run_prepared(&mut engine, runtime, prepared, &[input])
                        .unwrap()
                        .into_iter()
                        .map(|output| output.as_slice::<f64>().unwrap().to_vec())
                        .collect::<Vec<_>>()
                })
            })
            .collect();
        for handle in handles {
            let outputs = handle.join().expect("concurrent prepared run");
            assert_eq!(outputs, vec![vec![2.0, 4.0, 6.0, 8.0]]);
        }
    });
}

#[test]
fn prepared_execution_checks_retained_defaults_preparation_did_not_validate() {
    use tenferro_runtime::program::{ProgramInputSpec, SemanticProgramBuilder};

    // Both inputs declare `[n]` with `n` = input 1's axis 0, so the pair must
    // agree: the retained defaults below are 2 and 3, which do not.
    let shared_extent = || DimExpr::InputDim {
        input_idx: 1,
        axis: 0,
    };
    let mut builder = SemanticProgramBuilder::new();
    let first = builder
        .input(ProgramInputSpec::new(DType::F64, [shared_extent()]))
        .unwrap();
    let second = builder
        .input(ProgramInputSpec::new(DType::F64, [shared_extent()]))
        .unwrap();
    // Binding checks constant extents only, so an inconsistent default pair is
    // accepted here; the mismatch surfaces when a run resolves the defaults.
    builder
        .bind_input(
            first,
            Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap(),
        )
        .unwrap();
    builder
        .bind_input(
            second,
            Tensor::from_vec_col_major(vec![3], vec![3.0_f64, 4.0, 5.0]).unwrap(),
        )
        .unwrap();
    let frozen = builder.finish(&[first, second]).unwrap();
    let program = GraphCompiler::new()
        .compile_frozen_program(&frozen)
        .unwrap();

    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    // Preparation replaces every input, so it validates the replacements and
    // never the retained defaults.
    let replacement_first = Tensor::from_vec_col_major(vec![3], vec![7.0_f64; 3]).unwrap();
    let replacement_second = Tensor::from_vec_col_major(vec![3], vec![8.0_f64; 3]).unwrap();
    let prepared = prepare(
        &engine,
        &runtime,
        &program,
        &[&replacement_first, &replacement_second],
    )
    .unwrap();

    let outputs = run_prepared(
        &mut engine,
        &runtime,
        &prepared,
        &[&replacement_first, &replacement_second],
    )
    .expect("the validated replacements satisfy the declared shape relation");
    assert_eq!(outputs.len(), 2);

    // Resolving the retained defaults must still apply the metadata check that
    // preparation never ran on them.
    let error = run_prepared(&mut engine, &runtime, &prepared, &[])
        .expect_err("the retained defaults violate the declared shape relation");
    assert!(
        matches!(error, Error::PlaceholderShapeMismatch { .. }),
        "got {error:?}"
    );
}

#[test]
fn runtime_prepared_execution_hot_path_keeps_input_metadata_inline() {
    let source = include_str!("../../src/runtime/execution.rs");

    assert!(
        source.contains("type RuntimeInputReads<'a> = SmallVec"),
        "Runtime::run_prepared should keep short input reference lists inline"
    );
    // `TensorRead` has no `Default`, so `tinyvec::Array` cannot hold the input
    // read list; the shape list has no such constraint and moved to `TinyVec`.
    assert!(
        source.contains("type RuntimeInputShapes<'a> = TinyVec"),
        "Runtime::run_prepared should keep short input shape lists inline"
    );
    assert!(
        !source.contains("inputs.to_vec()"),
        "Runtime::run_prepared should not allocate a heap Vec just to copy input refs"
    );
}

#[test]
fn runtime_crate_exposes_traced_graph_execution_api() {
    let x = TracedTensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
    let y = (&x + &x).unwrap();

    let mut compiler = GraphCompiler::new();
    let program = compiler.compile(&y).unwrap();
    let out = run_compiled_one(&program, &[]);

    assert_eq!(out.as_slice::<f64>().unwrap(), &[2.0, 4.0]);
}

#[test]
fn runtime_program_api_is_public_read_only_and_bounded_debug() {
    use tenferro_runtime::program::{
        CoreSemanticOp, ProgramInputSpec, SemanticProgramBuilder, SemanticTransform,
    };

    fn accepts_transform_object(_: &dyn SemanticTransform) {}

    let mut builder = SemanticProgramBuilder::new();
    let input = builder
        .input(ProgramInputSpec::new(DType::F64, [DimExpr::Const(2)]))
        .unwrap();
    let output = builder.add_op(CoreSemanticOp::Neg, &[input]).unwrap()[0];
    let frozen = builder.finish(&[output]).unwrap();
    let operation = frozen.program.operations().next().unwrap();

    assert_eq!(frozen.program.inputs(), &[input]);
    assert_eq!(frozen.program.outputs(), &[output]);
    assert!(format!("{operation:?}").len() < 256);
    assert!(format!("{:?}", frozen.program).len() < 256);
    let _ = accepts_transform_object;
}

#[test]
fn tensor_extension_trait_covers_eager_runtime_paths() {
    let mut engine = CpuEngine::serial();
    let input = Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
    let f32_input = Tensor::from_vec_col_major(vec![2], vec![1.0_f32, 2.0]).unwrap();

    let converted = f32_input.convert(DType::F64, &mut engine).unwrap();
    let casted = input.cast(DType::F32, &mut engine).unwrap();
    let reshaped = input.reshape(&[4], &mut engine).unwrap();
    let transposed = input.transpose(&[1, 0], &mut engine).unwrap();
    let summed = input.reduce_sum(Some(&[0]), &mut engine).unwrap();
    assert_eq!(converted.dtype(), DType::F64);
    assert_eq!(converted.as_slice::<f64>().unwrap(), &[1.0, 2.0]);
    assert_eq!(casted.dtype(), DType::F32);
    assert_eq!(casted.as_slice::<f32>().unwrap(), &[1.0, 2.0, 3.0, 4.0]);
    assert_eq!(reshaped.shape(), &[4]);
    assert_eq!(reshaped.as_slice::<f64>().unwrap(), &[1.0, 2.0, 3.0, 4.0]);
    assert_eq!(transposed.shape(), &[2, 2]);
    assert_eq!(transposed.as_slice::<f64>().unwrap(), &[1.0, 3.0, 2.0, 4.0]);
    assert_eq!(summed.shape(), &[2]);
    assert_eq!(summed.as_slice::<f64>().unwrap(), &[3.0, 7.0]);
}

#[test]
fn concrete_tensor_matmul_rejects_non_matrix_inputs_without_rank_underflow() {
    let mut engine = CpuEngine::serial();
    let scalar = Tensor::from_vec_col_major(vec![], vec![1.0_f64]).unwrap();
    let vector = Tensor::from_vec_col_major(vec![1], vec![1.0_f64]).unwrap();

    let err = scalar.matmul(&vector, &mut engine).unwrap_err();

    assert!(matches!(
        err,
        TensorError::Validation {
            op: "matmul",
            source: ValidationError::RankMismatch {
                expected: 2,
                actual: 0,
            },
        }
    ));
}

#[test]
fn traced_tensor_methods_cover_conversion_and_rank_errors() {
    let scalar = TracedTensor::from_vec_col_major(vec![], vec![1.0_f64]).unwrap();
    let vector = TracedTensor::from_vec_col_major(vec![2], vec![1.25_f64, -2.75]).unwrap();

    let converted = vector.convert(DType::C64).unwrap();
    assert_eq!(converted.dtype, DType::C64);

    let casted = vector.cast(DType::I32).unwrap();
    assert_eq!(casted.dtype, DType::I32);

    let err = scalar.matmul(&vector).unwrap_err();
    assert!(matches!(
        &err,
        Error::Validation {
            op: "TracedTensor::matmul",
            phase: ErrorPhase::GraphBuild,
            source: ValidationError::RankMismatch {
                expected: 2,
                actual: 0,
            },
        }
    ));
}

#[test]
fn traced_tensor_methods_cover_structural_surface() {
    fn run(output: &TracedTensor) -> Tensor {
        let mut compiler = GraphCompiler::new();
        let program = compiler.compile(output).unwrap();
        run_compiled_one(&program, &[])
    }

    let vector = TracedTensor::from_vec_col_major(vec![4], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
    let sliced = vector
        .slice(SliceConfig {
            starts: vec![1],
            limits: vec![3],
            strides: vec![1],
        })
        .unwrap();
    assert_eq!(run(&sliced).as_slice::<f64>().unwrap(), &[2.0, 3.0]);

    let matrix_3x4 = TracedTensor::from_vec_col_major(
        vec![3, 4],
        vec![
            1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0,
        ],
    )
    .unwrap();
    let row_slice = matrix_3x4.slice_axis(0, 1..3).unwrap();
    assert_eq!(row_slice.try_concrete_shape(), Some(vec![2, 4]));
    assert_eq!(
        run(&row_slice).as_slice::<f64>().unwrap(),
        &[2.0, 3.0, 5.0, 6.0, 8.0, 9.0, 11.0, 12.0]
    );

    let builder_slice = matrix_3x4
        .slice_builder()
        .axis(0, 1..3)
        .axis_step(1, 0..4, 2)
        .apply()
        .unwrap();
    assert_eq!(builder_slice.try_concrete_shape(), Some(vec![2, 2]));
    assert_eq!(
        run(&builder_slice).as_slice::<f64>().unwrap(),
        &[2.0, 3.0, 8.0, 9.0]
    );

    let selected = matrix_3x4.take_axis(1, &[3, 1, 3]).unwrap();
    assert_eq!(selected.try_concrete_shape(), Some(vec![3, 3]));
    assert_eq!(
        run(&selected).as_slice::<f64>().unwrap(),
        &[10.0, 11.0, 12.0, 4.0, 5.0, 6.0, 10.0, 11.0, 12.0]
    );

    let mixed = matrix_3x4
        .slice_builder()
        .axis(0, 0..2)
        .take_axis(1, &[3, 1, 3])
        .apply()
        .unwrap();
    assert_eq!(mixed.try_concrete_shape(), Some(vec![2, 3]));
    assert_eq!(
        run(&mixed).as_slice::<f64>().unwrap(),
        &[10.0, 11.0, 4.0, 5.0, 10.0, 11.0]
    );

    let padded = sliced
        .pad(PadConfig {
            edge_padding_low: vec![1],
            edge_padding_high: vec![1],
            interior_padding: vec![0],
        })
        .unwrap();
    let reversed = padded.reverse(&[0]).unwrap();
    assert_eq!(
        run(&reversed).as_slice::<f64>().unwrap(),
        &[0.0, 3.0, 2.0, 0.0]
    );

    let starts = TracedTensor::from_vec_col_major(vec![1], vec![1_i64]).unwrap();
    let dynamic = vector.dynamic_slice(&starts, &[2]).unwrap();
    assert_eq!(run(&dynamic).as_slice::<f64>().unwrap(), &[2.0, 3.0]);

    let indices = TracedTensor::from_vec_col_major(vec![3], vec![3_i64, 1, 0]).unwrap();
    let gathered = vector
        .gather(
            &indices,
            GatherConfig {
                offset_dims: vec![],
                collapsed_slice_dims: vec![0],
                start_index_map: vec![0],
                index_vector_dim: 1,
                slice_sizes: vec![1],
            },
        )
        .unwrap();
    assert_eq!(run(&gathered).as_slice::<f64>().unwrap(), &[4.0, 2.0, 1.0]);

    let operand = TracedTensor::from_vec_col_major(vec![4], vec![0.0_f64, 0.0, 0.0, 0.0]).unwrap();
    let scatter_indices = TracedTensor::from_vec_col_major(vec![2, 1], vec![1_i64, 3]).unwrap();
    let updates = TracedTensor::from_vec_col_major(vec![2], vec![5.0_f64, 7.0]).unwrap();
    let scattered = operand
        .scatter(
            &scatter_indices,
            &updates,
            ScatterConfig {
                update_window_dims: vec![],
                inserted_window_dims: vec![0],
                scatter_dims_to_operand_dims: vec![0],
                index_vector_dim: 1,
            },
        )
        .unwrap();
    assert_eq!(
        run(&scattered).as_slice::<f64>().unwrap(),
        &[0.0, 5.0, 0.0, 7.0]
    );

    let concatenated = TracedTensor::concatenate(&[&vector, &vector], 0).unwrap();
    assert_eq!(run(&concatenated).shape(), &[8]);

    let matrix =
        TracedTensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
    assert_eq!(
        run(&matrix.tril(0).unwrap()).as_slice::<f64>().unwrap(),
        &[1.0, 2.0, 0.0, 4.0]
    );
    assert_eq!(
        run(&matrix.triu(0).unwrap()).as_slice::<f64>().unwrap(),
        &[1.0, 0.0, 3.0, 4.0]
    );
    let rectangular =
        TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0])
            .unwrap();
    let diag = rectangular.extract_diag(1, 0).unwrap();
    assert_eq!(diag.try_concrete_shape(), Some(vec![2]));
    assert_eq!(run(&diag).shape(), &[2]);

    let lhs = TracedTensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
    let rhs = TracedTensor::from_vec_col_major(vec![3, 2], vec![1.0_f64; 6]).unwrap();
    assert_eq!(run(&lhs.matmul(&rhs).unwrap()).shape(), &[2, 2]);
}

#[test]
fn traced_shape_packing_rejects_symbolic_shapes_as_graph_build_errors() {
    let x = TracedTensor::input_symbolic_shape(DType::F64, 1).unwrap();

    let err = x.index_select(0, &[0]).unwrap_err();
    assert!(matches!(
        &err,
        Error::Validation {
            phase: ErrorPhase::GraphBuild,
            source: ValidationError::InvalidArgument { .. },
            ..
        }
    ));

    let err = TracedTensor::stack(&[&x], 0).unwrap_err();
    assert!(matches!(
        &err,
        Error::Validation {
            phase: ErrorPhase::GraphBuild,
            source: ValidationError::InvalidArgument { .. },
            ..
        }
    ));
}

#[test]
fn runtime_runs_elementwise_and_reduction_with_ordered_inputs() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let x = TracedTensor::input_symbolic_shape(DType::F64, 1).unwrap();
    let y = (&x + &x).unwrap().reduce_sum(Some(&[0])).unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(&y, &[(&x, DType::F64, &[2])])
        .unwrap();
    let input = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();

    let out = run_compiled(&mut engine, &runtime, &program, &[&input]).unwrap();

    assert_eq!(out.len(), 1);
    assert_eq!(out[0].as_slice::<f64>().unwrap(), &[6.0]);
    assert_eq!(input.as_slice::<f64>().unwrap(), &[1.0, 2.0]);
}

#[test]
fn traced_broadcast_binary_accepts_symbolic_same_rank_input() {
    let x = TracedTensor::input_symbolic_shape(DType::F64, 1).unwrap();
    let y_data = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
    let y = TracedTensor::from_tensor_concrete_shape(y_data.duplicate().unwrap()).unwrap();

    let z = (&x + &y).unwrap();

    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(&z, &[(&x, DType::F64, &[2])])
        .unwrap();
    let input = Tensor::from_vec_col_major(vec![2], vec![3.0_f64, 4.0]).unwrap();
    let out = run_compiled_one(&program, &[&input, &y_data]);

    assert_eq!(out.as_slice::<f64>().unwrap(), &[4.0, 6.0]);
}

#[test]
fn traced_reduction_with_too_many_axes_returns_error_without_rank_underflow() {
    let x = TracedTensor::from_vec_col_major(vec![2, 2], vec![1.0_f64; 4]).unwrap();

    let err = x.reduce_max(Some(&[0, 1, 2])).unwrap_err().to_string();

    assert!(err.contains("axis 2 out of bounds for rank 2"), "{err}");
}

#[test]
fn runtime_runs_dot_general_with_ordered_inputs() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let lhs = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
    let rhs = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
    let product = lhs
        .dot_general(
            &rhs,
            DotGeneralConfig {
                lhs_contracting_dims: [1].as_slice().into(),
                rhs_contracting_dims: [0].as_slice().into(),
                lhs_batch_dims: [].as_slice().into(),
                rhs_batch_dims: [].as_slice().into(),
            },
        )
        .unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(
            &product,
            &[(&lhs, DType::F64, &[2, 3]), (&rhs, DType::F64, &[3, 2])],
        )
        .unwrap();
    let lhs_data =
        Tensor::from_vec_col_major(vec![2, 3], vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap();
    let rhs_data =
        Tensor::from_vec_col_major(vec![3, 2], vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap();

    let out = run_compiled(&mut engine, &runtime, &program, &[&lhs_data, &rhs_data]).unwrap();

    assert_eq!(out.len(), 1);
    assert_eq!(out[0].shape(), &[2, 2]);
    assert_eq!(out[0].as_slice::<f64>().unwrap(), &[22.0, 28.0, 49.0, 64.0]);
}

#[test]
fn runtime_ordered_input_errors_are_covered() {
    let x = TracedTensor::input_symbolic_shape(DType::F64, 1).unwrap();
    let y = (&x + &x).unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(&y, &[(&x, DType::F64, &[2])])
        .unwrap();
    let input = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0]).unwrap();
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);

    let out = run_compiled_one(&program, &[&input]);
    assert_eq!(out.as_slice::<f64>().unwrap(), &[2.0, 4.0]);

    let unbound = run_compiled(&mut engine, &runtime, &program, &[]).unwrap_err();
    assert!(matches!(unbound, Error::UnboundPlaceholder { .. }));

    let extra = run_compiled(&mut engine, &runtime, &program, &[&input, &input]).unwrap_err();
    assert!(matches!(extra, Error::GraphInputCountMismatch { .. }));

    let f32_input = Tensor::from_vec_col_major(vec![2], vec![1.0_f32, 2.0]).unwrap();
    let dtype = run_compiled(&mut engine, &runtime, &program, &[&f32_input]).unwrap_err();
    assert!(matches!(dtype, Error::PlaceholderDtypeMismatch { .. }));

    let rank_input = Tensor::from_vec_col_major(vec![1, 2], vec![1.0_f64, 2.0]).unwrap();
    let rank = run_compiled(&mut engine, &runtime, &program, &[&rank_input]).unwrap_err();
    assert!(matches!(rank, Error::PlaceholderRankMismatch { .. }));

    let shape_input = Tensor::from_vec_col_major(vec![3], vec![1.0_f64, 2.0, 3.0]).unwrap();
    let shape = run_compiled(&mut engine, &runtime, &program, &[&shape_input]).unwrap_err();
    assert!(matches!(shape, Error::PlaceholderShapeMismatch { .. }));
}

/// Negative companion to
/// `traced::tests::concatenate_of_distinct_inputs_compiles_without_input_specs`:
/// distinct rank-2 symbolic inputs still compile without concrete input specs,
/// and a concrete non-axis mismatch is rejected on the public compiled path.
#[test]
fn runtime_concatenate_rejects_incompatible_concrete_shapes_without_input_specs() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    // Data-attached but shape-symbolic inputs: the compiled program keeps their
    // extents free, so `run_compiled` reaches the concatenate kernel.
    let a = TracedTensor::from_tensor_symbolic_shape(
        Tensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap(),
    )
    .unwrap();
    let b = TracedTensor::from_tensor_symbolic_shape(
        Tensor::from_vec_col_major(vec![2, 4], vec![2.0_f64; 8]).unwrap(),
    )
    .unwrap();

    let joined = TracedTensor::concatenate(&[&a, &b], 1).unwrap();
    let program = GraphCompiler::new().compile(&joined).unwrap();
    assert_eq!(program.input_count(), 2);

    // Incompatible concrete non-axis extents ([2, 3] axis 0 versus [4, 4] axis 0),
    // supplied in compiled input-key order.
    let a_value = Tensor::from_vec_col_major(vec![2, 3], vec![1.0_f64; 6]).unwrap();
    let b_value = Tensor::from_vec_col_major(vec![4, 4], vec![2.0_f64; 16]).unwrap();
    let mut ordered: [Option<&Tensor>; 2] = [None, None];
    ordered[program.input_key_index(&a.input_key().unwrap()).unwrap()] = Some(&a_value);
    ordered[program.input_key_index(&b.input_key().unwrap()).unwrap()] = Some(&b_value);

    let err = run_compiled(
        &mut engine,
        &runtime,
        &program,
        &ordered.map(Option::unwrap),
    )
    .unwrap_err();

    assert!(
        matches!(
            &err,
            Error::TensorRuntime(TensorError::Validation {
                op: "concatenate",
                source: ValidationError::ShapeMismatch(source),
                ..
            }) if matches!(
                source.as_ref(),
                ShapeMismatch::IncompatibleShapes { lhs, rhs }
                    if lhs.as_slice() == [2, 3] && rhs.as_slice() == [4, 4]
            )
        ),
        "expected a concrete concatenate shape mismatch, got: {err}"
    );
}

/// Execution-path parity (Stage 0): the prepared and unprepared paths must agree
/// numerically on an elementwise chain, even though they submit a different
/// number of commands today.
#[test]
fn runtime_prepared_matches_compiled_for_elementwise_chain() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let x = TracedTensor::input_concrete_shape(DType::F64, &[4]).unwrap();
    let doubled = (&x + &x).unwrap();
    let y = doubled
        .mul(&doubled)
        .unwrap()
        .exp()
        .unwrap()
        .tanh()
        .unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(&y, &[(&x, DType::F64, &[4])])
        .unwrap();
    let input = Tensor::from_vec_col_major(vec![4], vec![0.5_f64, 1.0, 1.5, 2.0]).unwrap();

    let mut compiled = run_compiled(&mut engine, &runtime, &program, &[&input]).unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();
    let mut prepared_out = run_prepared(&mut engine, &runtime, &prepared, &[&input]).unwrap();

    let compiled = compiled.pop().unwrap();
    let prepared_out = prepared_out.pop().unwrap();
    assert_eq!(compiled.shape(), prepared_out.shape());
    let compiled = compiled.as_slice::<f64>().unwrap();
    let prepared_out = prepared_out.as_slice::<f64>().unwrap();
    for (left, right) in compiled.iter().zip(prepared_out) {
        assert!(
            (left - right).abs() <= 1e-12,
            "prepared and unprepared paths diverged: {left} != {right}"
        );
    }
}

/// Plan census: a pure elementwise chain is one command, and a run containing a
/// reduction stays one command per instruction.
///
/// The scheduled executor is the only production executor, so this census is the
/// production command count for the prepared path; the legacy segmented executor
/// is test-only.
#[test]
fn prepared_execution_command_count_fuses_elementwise_chains() {
    let engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let n = 4usize;

    let x = TracedTensor::input_concrete_shape(DType::F64, &[n]).unwrap();
    let doubled = (&x + &x).unwrap();
    let chain = doubled
        .mul(&doubled)
        .unwrap()
        .exp()
        .unwrap()
        .tanh()
        .unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(&chain, &[(&x, DType::F64, &[n])])
        .unwrap();
    let input = Tensor::from_vec_col_major(vec![n], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();
    assert_eq!(
        prepared.execution_command_count(),
        1,
        "the chain should be one fused command"
    );

    let x2 = TracedTensor::input_concrete_shape(DType::F64, &[n]).unwrap();
    let with_reduce = (&x2 + &x2)
        .unwrap()
        .exp()
        .unwrap()
        .reduce_sum(None)
        .unwrap();
    let mut compiler2 = GraphCompiler::new();
    let program2 = compiler2
        .compile_with_input_specs(&with_reduce, &[(&x2, DType::F64, &[n])])
        .unwrap();
    let input2 = Tensor::from_vec_col_major(vec![n], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
    let prepared2 = prepare(&engine, &runtime, &program2, &[&input2]).unwrap();
    assert_eq!(
        prepared2.execution_command_count(),
        3,
        "a run containing a reduction is fusion-ineligible and keeps one command per instruction"
    );
}

/// Runtime evidence: the compiled and prepared entry points each submit a pure
/// elementwise chain once through the scheduled production executor.
#[test]
fn compiled_and_prepared_submission_counts_match() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let n = 4usize;

    let x = TracedTensor::input_concrete_shape(DType::F64, &[n]).unwrap();
    let chain = (&x + &x)
        .unwrap()
        .mul(&x)
        .unwrap()
        .exp()
        .unwrap()
        .tanh()
        .unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(&chain, &[(&x, DType::F64, &[n])])
        .unwrap();
    let input = Tensor::from_vec_col_major(vec![n], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();
    assert_eq!(prepared.execution_submission_count(), 0);

    let _ = run_compiled(&mut engine, &runtime, &program, &[&input]).unwrap();
    assert_eq!(
        prepared.execution_submission_count(),
        1,
        "compiled execution should submit the region once"
    );

    let _ = run_prepared(&mut engine, &runtime, &prepared, &[&input]).unwrap();
    assert_eq!(
        prepared.execution_submission_count(),
        2,
        "prepared execution should submit the same region once"
    );
}

/// Runtime parity matrix: shapes in the normal fused range submit once through
/// each production entry point.
#[test]
fn compiled_and_prepared_submission_counts_match_shape_matrix() {
    for n in [4usize, 64, 1024] {
        let mut engine = CpuEngine::serial();
        let runtime = cpu_runtime(&engine);
        let x = TracedTensor::input_concrete_shape(DType::F64, &[n]).unwrap();
        let chain = (&x + &x)
            .unwrap()
            .mul(&x)
            .unwrap()
            .exp()
            .unwrap()
            .tanh()
            .unwrap();
        let mut compiler = GraphCompiler::new();
        let program = compiler
            .compile_with_input_specs(&chain, &[(&x, DType::F64, &[n])])
            .unwrap();
        let input = Tensor::from_vec_col_major(vec![n], vec![1.0_f64; n]).unwrap();
        let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();
        let baseline = prepared.execution_submission_count();

        run_compiled(&mut engine, &runtime, &program, &[&input]).unwrap();
        let after_compiled = prepared.execution_submission_count();
        run_prepared(&mut engine, &runtime, &prepared, &[&input]).unwrap();
        let after_prepared = prepared.execution_submission_count();

        assert_eq!(
            after_compiled - baseline,
            1,
            "compiled path submission count for shape {n}"
        );
        assert_eq!(
            after_prepared - after_compiled,
            1,
            "prepared path submission count for shape {n}"
        );
    }
}

/// Stage 1 planning: the elementwise chain becomes one planned region covering
/// all four instructions, while a run containing a reduction plans none.
#[test]
fn prepared_elementwise_regions_are_planned_at_prepare_time() {
    let engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let n = 4usize;

    let x = TracedTensor::input_concrete_shape(DType::F64, &[n]).unwrap();
    let doubled = (&x + &x).unwrap();
    let chain = doubled
        .mul(&doubled)
        .unwrap()
        .exp()
        .unwrap()
        .tanh()
        .unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(&chain, &[(&x, DType::F64, &[n])])
        .unwrap();
    let input = Tensor::from_vec_col_major(vec![n], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();
    assert_eq!(
        prepared.elementwise_region_summary(),
        (1, 4),
        "the pure elementwise chain should plan one region over four instructions"
    );

    let x2 = TracedTensor::input_concrete_shape(DType::F64, &[n]).unwrap();
    let with_reduce = (&x2 + &x2)
        .unwrap()
        .exp()
        .unwrap()
        .reduce_sum(None)
        .unwrap();
    let mut compiler2 = GraphCompiler::new();
    let program2 = compiler2
        .compile_with_input_specs(&with_reduce, &[(&x2, DType::F64, &[n])])
        .unwrap();
    let input2 = Tensor::from_vec_col_major(vec![n], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
    let prepared2 = prepare(&engine, &runtime, &program2, &[&input2]).unwrap();
    assert_eq!(
        prepared2.elementwise_region_summary(),
        (0, 0),
        "a run containing a reduction is not an elementwise region"
    );
}

/// Stage 1 evidence: the planned region executes as one fused command (the
/// runtime counter records it), the results match a host reference, and a run
/// containing a reduction plans and executes no region at all.
#[test]
fn prepared_elementwise_region_executes_as_one_fused_command() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let n = 16 * 1024usize;

    let x = TracedTensor::input_concrete_shape(DType::F64, &[n]).unwrap();
    let doubled = (&x + &x).unwrap();
    let chain = doubled
        .mul(&doubled)
        .unwrap()
        .exp()
        .unwrap()
        .tanh()
        .unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(&chain, &[(&x, DType::F64, &[n])])
        .unwrap();
    let data: Vec<f64> = (0..n).map(|i| 0.25 + (i % 17) as f64 * 0.125).collect();
    let input = Tensor::from_vec_col_major(vec![n], data.clone()).unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();

    let mut fused = run_prepared(&mut engine, &runtime, &prepared, &[&input]).unwrap();
    assert_eq!(
        prepared.elementwise_region_execution_counts(),
        (1, 0),
        "the CPU engine should execute the chain region fused"
    );

    let fused = fused.pop().unwrap();
    let fused = fused.as_slice::<f64>().unwrap();
    for (index, value) in fused.iter().enumerate() {
        let doubled = data[index] + data[index];
        let expected = (doubled * doubled).exp().tanh();
        assert!(
            (value - expected).abs() <= 1e-12,
            "fused region diverged from the host reference at {index}: {value} != {expected}"
        );
    }

    let x2 = TracedTensor::input_concrete_shape(DType::F64, &[n]).unwrap();
    let with_reduce = (&x2 + &x2)
        .unwrap()
        .exp()
        .unwrap()
        .reduce_sum(None)
        .unwrap();
    let mut compiler2 = GraphCompiler::new();
    let program2 = compiler2
        .compile_with_input_specs(&with_reduce, &[(&x2, DType::F64, &[n])])
        .unwrap();
    let data2: Vec<f64> = (0..n).map(|i| 0.5 + (i % 11) as f64 * 0.25).collect();
    let input2 = Tensor::from_vec_col_major(vec![n], data2).unwrap();
    let prepared2 = prepare(&engine, &runtime, &program2, &[&input2]).unwrap();
    let _ = run_prepared(&mut engine, &runtime, &prepared2, &[&input2]).unwrap();
    assert_eq!(
        prepared2.elementwise_region_execution_counts(),
        (0, 0),
        "a run containing a reduction plans no region"
    );
}

/// An ordered op (`maximum`/`minimum`/`clamp`) above the floor fuses and keeps
/// tenferro's NaN propagation.
///
/// `strided-fused 0.6.0` propagates NaN through its ordered kernels with the same
/// `strided_basic` select the unfused kernels use (TF5, strided-rs#315), so the
/// region executes through the fused route and must still return NaN for a NaN
/// operand (`R-numerics-01`).
#[test]
fn prepared_ordered_region_fuses_and_propagates_nan() {
    for dtype in [DType::F32, DType::F64] {
        let mut engine = CpuEngine::serial();
        let runtime = cpu_runtime(&engine);
        let n = 16 * 1024usize;

        let x = TracedTensor::input_concrete_shape(dtype, &[n]).unwrap();
        let y = TracedTensor::input_concrete_shape(dtype, &[n]).unwrap();
        let z = TracedTensor::input_concrete_shape(dtype, &[n]).unwrap();
        let out = (&x.maximum(&y).unwrap() + &z).unwrap();
        let program = GraphCompiler::new()
            .compile_with_input_specs(
                &out,
                &[(&x, dtype, &[n]), (&y, dtype, &[n]), (&z, dtype, &[n])],
            )
            .unwrap();

        let nan_input = match dtype {
            DType::F32 => Tensor::from_vec_col_major(vec![n], vec![f32::NAN; n]).unwrap(),
            DType::F64 => Tensor::from_vec_col_major(vec![n], vec![f64::NAN; n]).unwrap(),
            _ => unreachable!(),
        };
        let finite_input = match dtype {
            DType::F32 => Tensor::from_vec_col_major(vec![n], vec![1.0_f32; n]).unwrap(),
            DType::F64 => Tensor::from_vec_col_major(vec![n], vec![1.0_f64; n]).unwrap(),
            _ => unreachable!(),
        };
        let one = match dtype {
            DType::F32 => Tensor::from_vec_col_major(vec![n], vec![1.0_f32; n]).unwrap(),
            DType::F64 => Tensor::from_vec_col_major(vec![n], vec![1.0_f64; n]).unwrap(),
            _ => unreachable!(),
        };

        let prepared = prepare(
            &engine,
            &runtime,
            &program,
            &[&nan_input, &finite_input, &one],
        )
        .unwrap();
        assert!(
            prepared.elementwise_region_summary().0 >= 1,
            "{dtype:?}: the ordered chain should still plan a region"
        );

        let mut out = run_prepared(
            &mut engine,
            &runtime,
            &prepared,
            &[&nan_input, &finite_input, &one],
        )
        .unwrap();
        assert_eq!(
            prepared.elementwise_region_execution_counts(),
            (1, 0),
            "{dtype:?}: the NaN-propagating ordered region must run through the fused route"
        );
        let out = out.pop().unwrap();
        match dtype {
            DType::F32 => assert!(
                out.as_slice::<f32>()
                    .unwrap()
                    .iter()
                    .all(|value| value.is_nan()),
                "f32 NaN must propagate through the fused route"
            ),
            DType::F64 => assert!(
                out.as_slice::<f64>()
                    .unwrap()
                    .iter()
                    .all(|value| value.is_nan()),
                "f64 NaN must propagate through the fused route"
            ),
            _ => unreachable!(),
        }
    }
}

/// A region whose dtype is not F32/F64 stays unfused above the floor.
///
/// `strided-fused 0.6.0`'s vectorized chunk replay covers only F32/F64; every
/// other dtype would run the unmeasured per-element interpreter, so the region
/// is declined and the per-instruction path is compared against a host
/// reference.
#[test]
fn prepared_non_f32_f64_region_is_declined() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let n = 16 * 1024usize;

    let x = TracedTensor::input_concrete_shape(DType::I64, &[n]).unwrap();
    let doubled = (&x + &x).unwrap();
    let chain = (&doubled * &doubled).unwrap();
    let program = GraphCompiler::new()
        .compile_with_input_specs(&chain, &[(&x, DType::I64, &[n])])
        .unwrap();
    let data: Vec<i64> = (0..n).map(|i| (i % 100) as i64 + 1).collect();
    let input = Tensor::from_vec_col_major(vec![n], data.clone()).unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();
    assert!(
        prepared.elementwise_region_summary().0 >= 1,
        "the I64 chain should still plan a region"
    );

    let mut out = run_prepared(&mut engine, &runtime, &prepared, &[&input]).unwrap();
    assert_eq!(
        prepared.elementwise_region_execution_counts(),
        (0, 1),
        "I64 has no measured vectorized replay and must run per instruction"
    );
    let out = out.pop().unwrap();
    let out = out.as_slice::<i64>().unwrap();
    for (index, &value) in out.iter().enumerate() {
        let doubled = data[index] + data[index];
        assert_eq!(
            value,
            doubled * doubled,
            "I64 fallback diverged from the host reference at {index}"
        );
    }
}

/// Stage 1 evidence: when the backend declines the fusion the region falls back
/// to its instructions and still matches the unprepared path. A tiny element
/// count is below the CPU fused kernel's floor, so this exercises the fallback.
#[test]
fn prepared_elementwise_region_falls_back_when_fusion_is_declined() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let n = 4usize;

    let x = TracedTensor::input_concrete_shape(DType::F64, &[n]).unwrap();
    let doubled = (&x + &x).unwrap();
    let chain = doubled
        .mul(&doubled)
        .unwrap()
        .exp()
        .unwrap()
        .tanh()
        .unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(&chain, &[(&x, DType::F64, &[n])])
        .unwrap();
    let input = Tensor::from_vec_col_major(vec![n], vec![0.5_f64, 1.0, 1.5, 2.0]).unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();

    let mut compiled = run_compiled(&mut engine, &runtime, &program, &[&input]).unwrap();
    let mut prepared_out = run_prepared(&mut engine, &runtime, &prepared, &[&input]).unwrap();
    // The two entry points share the prepared-plan cache, so the counters on the
    // prepared handle count both runs: one fallback each.
    let (fused, fallbacks) = prepared.elementwise_region_execution_counts();
    assert_eq!(fused, 0, "the CPU backend declines fusion below its floor");
    assert_eq!(
        fallbacks, 2,
        "each run's region should fall back exactly once"
    );

    let compiled = compiled.pop().unwrap();
    let prepared_out = prepared_out.pop().unwrap();
    let compiled = compiled.as_slice::<f64>().unwrap();
    let prepared_out = prepared_out.as_slice::<f64>().unwrap();
    for (left, right) in compiled.iter().zip(prepared_out) {
        assert!(
            (left - right).abs() <= 1e-12,
            "fallback diverged from the unprepared path: {left} != {right}"
        );
    }
}

/// Regression for #1968: the CPU engine reports the fused kernel's input
/// limit, so a region reading more inputs is not planned at all. It runs
/// instruction by instruction, without a fusion attempt the backend would
/// decline on every execution, and still matches the unprepared path.
#[test]
fn prepared_elementwise_region_above_cpu_input_limit_is_not_planned() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let n = 16 * 1024usize;
    let inputs = (0..5)
        .map(|_| TracedTensor::input_concrete_shape(DType::F64, &[n]).unwrap())
        .collect::<Vec<_>>();
    let mut sum = (&inputs[0] + &inputs[1]).unwrap();
    for input in &inputs[2..] {
        sum = (&sum + input).unwrap();
    }
    let shape = [n];
    let specs = inputs
        .iter()
        .map(|input| (input, DType::F64, &shape[..]))
        .collect::<Vec<_>>();
    let program = GraphCompiler::new()
        .compile_with_input_specs(&sum, &specs)
        .unwrap();
    let data = (0..5)
        .map(|k| {
            Tensor::from_vec_col_major(
                vec![n],
                (0..n).map(|i| (k + 1) as f64 + (i % 7) as f64).collect(),
            )
            .unwrap()
        })
        .collect::<Vec<_>>();
    let refs = data.iter().collect::<Vec<_>>();
    let prepared = prepare(&engine, &runtime, &program, &refs).unwrap();
    assert_eq!(
        prepared.elementwise_region_summary(),
        (0, 0),
        "a five-input region exceeds the CPU fused kernel's input limit"
    );

    let mut prepared_out = run_prepared(&mut engine, &runtime, &prepared, &refs).unwrap();
    assert_eq!(prepared.elementwise_region_execution_counts(), (0, 0));
    let actual = prepared_out.pop().unwrap();
    let actual = actual.as_slice::<f64>().unwrap();
    for (i, value) in actual.iter().enumerate() {
        let expected = 15.0 + 5.0 * (i % 7) as f64;
        assert_eq!(*value, expected);
    }
}

/// Stage 1: a region with several live-outs publishes every one of them.
///
/// Both `y` and `z` are program outputs of one elementwise region.
#[test]
fn prepared_elementwise_region_publishes_multiple_live_outs() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let n = 16 * 1024usize;

    let data: Vec<f64> = (0..n).map(|i| 0.25 + (i % 13) as f64 * 0.125).collect();
    let x = TracedTensor::from_tensor_concrete_shape(
        Tensor::from_vec_col_major(vec![n], data.clone()).unwrap(),
    )
    .unwrap();
    let shared = (&x + &x).unwrap();
    let y = shared.exp().unwrap().tanh().unwrap();
    let z = (&shared * &shared).unwrap();
    let program = GraphCompiler::new()
        .compile_many(&[&y, &z])
        .expect("two-output constant graph should compile");

    let prepared = prepare(&engine, &runtime, &program, &[]).unwrap();
    let (regions, covered) = prepared.elementwise_region_summary();
    assert_eq!((regions, covered), (1, 4), "one region covers the chain");

    let mut prepared_out = run_prepared(&mut engine, &runtime, &prepared, &[]).unwrap();
    let (fused, fallbacks) = prepared.elementwise_region_execution_counts();
    assert_eq!(
        (fused, fallbacks),
        (1, 0),
        "the two-live-output region should fuse once"
    );

    assert_eq!(prepared_out.len(), 2);
    let z_out = prepared_out.pop().unwrap();
    let y_out = prepared_out.pop().unwrap();
    let y_out = y_out.as_slice::<f64>().unwrap();
    let z_out = z_out.as_slice::<f64>().unwrap();
    for (index, &value) in data.iter().enumerate() {
        let doubled = value + value;
        let expected_y = doubled.exp().tanh();
        let expected_z = doubled * doubled;
        assert!(
            (y_out[index] - expected_y).abs() <= 1e-12,
            "live-out y diverged from the host reference at {index}: {} != {expected_y}",
            y_out[index]
        );
        assert!(
            (z_out[index] - expected_z).abs() <= 1e-12,
            "live-out z diverged from the host reference at {index}: {} != {expected_z}",
            z_out[index]
        );
    }
}

/// Stage 1: an elementwise region next to an FFI operation.
///
/// The region covers only the elementwise chain; the matrix multiply stays its
/// own command, and both outputs match a host reference.
#[test]
fn prepared_elementwise_region_stays_separate_from_ffi_op() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    // The CPU fused kernel only engages above its element floor, so the chain
    // runs over a vector large enough to fuse while the multiply stays small.
    let n = 8usize;
    let chain_len = 16 * 1024usize;

    let matrix = |data: &[f64]| Tensor::from_vec_col_major(vec![n, n], data.to_vec()).unwrap();
    let a_data: Vec<f64> = (0..n * n).map(|i| 0.5 + (i % 7) as f64 * 0.125).collect();
    let b_data: Vec<f64> = (0..n * n).map(|i| 0.25 + (i % 7) as f64 * 0.125).collect();
    let a = TracedTensor::from_tensor_concrete_shape(matrix(&a_data)).unwrap();
    let b = TracedTensor::from_tensor_concrete_shape(matrix(&b_data)).unwrap();
    let chain_data: Vec<f64> = (0..chain_len)
        .map(|i| 0.5 + (i % 5) as f64 * 0.25)
        .collect();
    let x = TracedTensor::from_tensor_concrete_shape(
        Tensor::from_vec_col_major(vec![chain_len], chain_data.clone()).unwrap(),
    )
    .unwrap();

    let m = a.matmul(&b).unwrap();
    let chain = (&x * &x).unwrap().exp().unwrap().tanh().unwrap();
    let program = GraphCompiler::new()
        .compile_many(&[&m, &chain])
        .expect("mixed graph should compile");

    let prepared = prepare(&engine, &runtime, &program, &[]).unwrap();
    let (regions, covered) = prepared.elementwise_region_summary();
    assert_eq!(
        (regions, covered),
        (1, 3),
        "only the elementwise chain should form a region"
    );

    let mut prepared_out = run_prepared(&mut engine, &runtime, &prepared, &[]).unwrap();
    let (fused, fallbacks) = prepared.elementwise_region_execution_counts();
    assert_eq!(
        (fused, fallbacks),
        (1, 0),
        "the CPU engine should fuse the chain region"
    );

    assert_eq!(prepared_out.len(), 2);
    let chain_out = prepared_out.pop().unwrap();
    let m_out = prepared_out.pop().unwrap();
    let chain_out = chain_out.as_slice::<f64>().unwrap();
    let m_out = m_out.as_slice::<f64>().unwrap();
    for (index, &value) in chain_data.iter().enumerate() {
        let expected = (value * value).exp().tanh();
        assert!(
            (chain_out[index] - expected).abs() <= 1e-12,
            "chain output diverged from the host reference at {index}: {} != {expected}",
            chain_out[index]
        );
    }
    for j in 0..n {
        for i in 0..n {
            let expected: f64 = (0..n).map(|k| a_data[i + k * n] * b_data[k + j * n]).sum();
            assert!(
                (m_out[i + j * n] - expected).abs() <= 1e-12,
                "matmul output diverged from the host reference at ({i}, {j}): {} != {expected}",
                m_out[i + j * n]
            );
        }
    }
}

/// Stage 1: repeated prepared runs neither fall back nor accumulate state.
#[test]
fn prepared_elementwise_region_is_stable_across_repeated_runs() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let n = 16 * 1024usize;

    let x = TracedTensor::input_concrete_shape(DType::F64, &[n]).unwrap();
    let doubled = (&x + &x).unwrap();
    let chain = doubled
        .mul(&doubled)
        .unwrap()
        .exp()
        .unwrap()
        .tanh()
        .unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(&chain, &[(&x, DType::F64, &[n])])
        .unwrap();
    let data: Vec<f64> = (0..n).map(|i| 0.25 + (i % 17) as f64 * 0.125).collect();
    let input = Tensor::from_vec_col_major(vec![n], data).unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();

    let mut first: Option<Vec<f64>> = None;
    for run in 1..=16 {
        let mut out = run_prepared(&mut engine, &runtime, &prepared, &[&input]).unwrap();
        let out = out.pop().unwrap();
        let values = out.as_slice::<f64>().unwrap().to_vec();
        match &first {
            None => first = Some(values),
            Some(expected) => {
                for (left, right) in values.iter().zip(expected) {
                    assert!(
                        (left - right).abs() <= 1e-15,
                        "run {run} diverged from the first run: {left} != {right}"
                    );
                }
            }
        }
        let (fused, fallbacks) = prepared.elementwise_region_execution_counts();
        assert_eq!((fused, fallbacks), (run, 0), "run {run} should fuse once");
    }
}

/// Stage 1: a chain, an FFI operation, and another chain in one program.
///
/// The large chain fuses, the small chain after the matrix multiply falls back
/// below the CPU fused kernel's element floor, and both outputs match a host
/// reference, so interleaving regions with FFI work keeps its contract.
#[test]
fn prepared_regions_interleave_with_ffi_work() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let chain_len = 16 * 1024usize;
    let n = 8usize;

    let x_data: Vec<f64> = (0..chain_len)
        .map(|i| 0.5 + (i % 11) as f64 * 0.125)
        .collect();
    let a_data: Vec<f64> = (0..n * n).map(|i| 0.5 + (i % 7) as f64 * 0.125).collect();
    let b_data: Vec<f64> = (0..n * n).map(|i| 0.25 + (i % 7) as f64 * 0.125).collect();

    let x = TracedTensor::from_tensor_concrete_shape(
        Tensor::from_vec_col_major(vec![chain_len], x_data.clone()).unwrap(),
    )
    .unwrap();
    let a = TracedTensor::from_tensor_concrete_shape(
        Tensor::from_vec_col_major(vec![n, n], a_data.clone()).unwrap(),
    )
    .unwrap();
    let b = TracedTensor::from_tensor_concrete_shape(
        Tensor::from_vec_col_major(vec![n, n], b_data.clone()).unwrap(),
    )
    .unwrap();

    let before = (&x * &x).unwrap().exp().unwrap().tanh().unwrap();
    let product = a.matmul(&b).unwrap();
    let after = (&product * &product)
        .unwrap()
        .exp()
        .unwrap()
        .tanh()
        .unwrap();
    let program = GraphCompiler::new()
        .compile_many(&[&before, &after])
        .expect("interleaved graph should compile");

    let prepared = prepare(&engine, &runtime, &program, &[]).unwrap();
    let (regions, _) = prepared.elementwise_region_summary();
    assert!(regions >= 1, "the chains should plan at least one region");

    let mut prepared_out = run_prepared(&mut engine, &runtime, &prepared, &[]).unwrap();
    let (fused, fallbacks) = prepared.elementwise_region_execution_counts();
    assert!(fused >= 1, "the large chain should fuse: {fused} fused");
    assert!(
        fallbacks >= 1,
        "the chain below the element floor should fall back: {fallbacks} fallbacks"
    );

    assert_eq!(prepared_out.len(), 2);
    let after_out = prepared_out.pop().unwrap();
    let before_out = prepared_out.pop().unwrap();
    let after_out = after_out.as_slice::<f64>().unwrap();
    let before_out = before_out.as_slice::<f64>().unwrap();
    for (index, &value) in x_data.iter().enumerate() {
        let expected = (value * value).exp().tanh();
        assert!(
            (before_out[index] - expected).abs() <= 1e-12,
            "fused chain output diverged from the host reference at {index}: {} != {expected}",
            before_out[index]
        );
    }
    let mut product_data = vec![0.0_f64; n * n];
    for j in 0..n {
        for i in 0..n {
            product_data[i + j * n] = (0..n).map(|k| a_data[i + k * n] * b_data[k + j * n]).sum();
        }
    }
    for (index, &value) in product_data.iter().enumerate() {
        let expected = (value * value).exp().tanh();
        assert!(
            (after_out[index] - expected).abs() <= 1e-12,
            "fallback chain output diverged from the host reference at {index}: {} != {expected}",
            after_out[index]
        );
    }
}

/// Stage 1: the fallback path stays stable across repeated runs.
#[test]
fn prepared_elementwise_fallback_is_stable_across_repeated_runs() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let n = 4usize;

    let x = TracedTensor::input_concrete_shape(DType::F64, &[n]).unwrap();
    let doubled = (&x + &x).unwrap();
    let chain = doubled
        .mul(&doubled)
        .unwrap()
        .exp()
        .unwrap()
        .tanh()
        .unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(&chain, &[(&x, DType::F64, &[n])])
        .unwrap();
    let input = Tensor::from_vec_col_major(vec![n], vec![0.5_f64, 1.0, 1.5, 2.0]).unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();

    let mut first: Option<Vec<f64>> = None;
    for run in 1..=8 {
        let mut out = run_prepared(&mut engine, &runtime, &prepared, &[&input]).unwrap();
        let out = out.pop().unwrap();
        let values = out.as_slice::<f64>().unwrap().to_vec();
        match &first {
            None => first = Some(values),
            Some(expected) => {
                for (left, right) in values.iter().zip(expected) {
                    assert!(
                        (left - right).abs() <= 1e-15,
                        "fallback run {run} diverged: {left} != {right}"
                    );
                }
            }
        }
        let (fused, fallbacks) = prepared.elementwise_region_execution_counts();
        assert_eq!(
            (fused, fallbacks),
            (0, run),
            "run {run} should fall back once"
        );
    }
}

#[test]
fn traced_slice_rejects_out_of_range_limit_at_graph_build() {
    // The sibling `slice_axis` builder, the CPU backend, and the CUDA backend
    // all reject a limit that exceeds a concrete input extent; raw
    // `TracedTensor::slice` used to build successfully and register a phantom
    // output shape. See issue #2042.
    let x = TracedTensor::from_vec_col_major(vec![4], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
    let err = x
        .slice(SliceConfig {
            starts: vec![0],
            limits: vec![100],
            strides: vec![1],
        })
        .unwrap_err();
    assert!(matches!(
        err,
        Error::Validation {
            op: "TracedTensor::slice",
            phase: ErrorPhase::GraphBuild,
            source: ValidationError::InvalidSliceBounds {
                start: 0,
                end: 100,
                axis_len: 4,
            },
        }
    ));
}

#[test]
fn prepared_identity_output_is_borrowed_and_a_computed_output_is_compact() {
    let (engine, runtime) = cpu_engine_and_runtime();
    let x = TracedTensor::input_concrete_shape(DType::F64, &[2, 2]).unwrap();
    let identity = GraphCompiler::new()
        .compile_with_input_specs(&x, &[(&x, DType::F64, &[2, 2])])
        .unwrap();
    let input = Tensor::from_vec_col_major(vec![2, 2], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
    let prepared = prepare(&engine, &runtime, &identity, &[&input]).unwrap();
    let reads = inputs_of(&[&input]);
    let mut engine = engine;
    let outputs = runtime.run(&mut [&mut engine], &prepared, &reads).unwrap();
    assert!(matches!(outputs[0], tenferro_runtime::Output::Borrowed(_)));

    // A computed value with a non-compact program layout is materialized.
    let y = x.transpose(&[1, 0]).unwrap().neg().unwrap();
    let program = GraphCompiler::new()
        .compile_with_input_specs(&y, &[(&x, DType::F64, &[2, 2])])
        .unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();
    let outputs = runtime.run(&mut [&mut engine], &prepared, &reads).unwrap();
    match &outputs[0] {
        tenferro_runtime::Output::Owned(tensor) => {
            assert!(tensor.is_col_major_contiguous().unwrap());
            assert_eq!(tensor.shape(), &[2, 2]);
        }
        tenferro_runtime::Output::Borrowed(_) => panic!("a computed output must be owned"),
    }
}

#[test]
fn run_rejects_a_replacement_input_that_changes_the_prepared_specialization() {
    let mut engine = CpuEngine::serial();
    let runtime = cpu_runtime(&engine);
    let lhs = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
    let rhs = TracedTensor::input_symbolic_shape(DType::F64, 2).unwrap();
    let product = lhs
        .dot_general(
            &rhs,
            DotGeneralConfig {
                lhs_contracting_dims: [1].as_slice().into(),
                rhs_contracting_dims: [0].as_slice().into(),
                lhs_batch_dims: [].as_slice().into(),
                rhs_batch_dims: [].as_slice().into(),
            },
        )
        .unwrap();
    let mut compiler = GraphCompiler::new();
    let program = compiler
        .compile_with_input_specs(
            &product,
            &[(&lhs, DType::F64, &[2, 3]), (&rhs, DType::F64, &[3, 2])],
        )
        .unwrap();
    let lhs_data =
        Tensor::from_vec_col_major(vec![2, 3], vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap();
    let rhs_data =
        Tensor::from_vec_col_major(vec![3, 2], vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&lhs_data, &rhs_data]).unwrap();
    run_prepared(&mut engine, &runtime, &prepared, &[&lhs_data, &rhs_data])
        .expect("the prepared layout runs");

    // Same shape and rank, but a non-compact layout: the graph metadata accepts
    // it, so run must re-project the actual signature against the prepared
    // layout-class specialization.
    let lhs_base =
        Tensor::from_vec_col_major(vec![3, 2], vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap();
    let transposed_lhs = lhs_base
        .as_typed::<f64>()
        .unwrap()
        .as_view()
        .transpose_view([1, 0])
        .unwrap()
        .into_tensor_read()
        .unwrap();
    let rhs_read = TensorRead::from_tensor(&rhs_data);
    let error = runtime
        .run(&mut [&mut engine], &prepared, &[transposed_lhs, rhs_read])
        .expect_err(
            "a replacement input that does not match the prepared specialization is rejected",
        );
    assert!(
        error.to_string().contains("specialization"),
        "the rejection names the prepared contract: {error}"
    );
}

#[test]
fn prepared_transpose_and_slice_outputs_alias_their_input_without_a_copy() {
    let (mut engine, runtime) = cpu_engine_and_runtime();
    let x = TracedTensor::input_concrete_shape(DType::F64, &[1, 4]).unwrap();
    let transposed = x.transpose(&[1, 0]).unwrap();
    let program = GraphCompiler::new()
        .compile_with_input_specs(&transposed, &[(&x, DType::F64, &[1, 4])])
        .unwrap();
    let input = Tensor::from_vec_col_major(vec![1, 4], vec![1.0_f64, 2.0, 3.0, 4.0]).unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();
    let reads = inputs_of(&[&input]);
    let outputs = runtime.run(&mut [&mut engine], &prepared, &reads).unwrap();
    let tenferro_runtime::Output::Borrowed(read) = &outputs[0] else {
        panic!("a transpose of an input must stay borrowed");
    };
    assert_eq!(read.shape(), &[4, 1]);
    let tenferro_tensor::TensorView::F64(view) = read.clone().tensor_view() else {
        panic!("test input is F64");
    };
    let input_values = input.as_slice::<f64>().unwrap();
    for (index, expected) in input_values.iter().enumerate() {
        let element = view.get(&[index, 0]).expect("transposed view element");
        assert_eq!(element, expected);
        assert_eq!(
            std::ptr::from_ref(element),
            std::ptr::from_ref(&input_values[index]),
            "the transpose output shares the input allocation"
        );
    }

    let x = TracedTensor::input_concrete_shape(DType::F64, &[2, 3]).unwrap();
    let sliced = x
        .slice(SliceConfig {
            starts: vec![0, 0],
            limits: vec![2, 1],
            strides: vec![1, 1],
        })
        .unwrap();
    let program = GraphCompiler::new()
        .compile_with_input_specs(&sliced, &[(&x, DType::F64, &[2, 3])])
        .unwrap();
    let input =
        Tensor::from_vec_col_major(vec![2, 3], vec![1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap();
    let prepared = prepare(&engine, &runtime, &program, &[&input]).unwrap();
    let reads = inputs_of(&[&input]);
    let outputs = runtime.run(&mut [&mut engine], &prepared, &reads).unwrap();
    let tenferro_runtime::Output::Borrowed(read) = &outputs[0] else {
        panic!("a slice of an input must stay borrowed");
    };
    assert_eq!(read.shape(), &[2, 1]);
    let aliased = read
        .as_slice::<f64>()
        .expect("the compact slice aliases the input");
    assert_eq!(aliased, &[1.0, 2.0]);
    assert_eq!(
        aliased.as_ptr(),
        input.as_slice::<f64>().unwrap().as_ptr(),
        "the slice output shares the input allocation"
    );
}