polydat-core 0.6.1

Polydat runtime: value model, graph compiler, execution engines, kernels
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
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Kernel compilation: assembled DAG โ†’ fast executable kernel.
//!
//! Everything in this module is on the path between
//! [`assembly::PolydatAssembler`] and an executable kernel. The
//! pipeline:
//!
//! ```text
//! PolydatAssembler โ”€โ”€resolveโ”€โ”€โ–ถ ResolvedDag โ”€โ”€compile_with(Engine)โ”€โ”€โ”
//!   (fusion, adapters,                                              โ”‚
//!    round-trip lint,          โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
//!    topo sort)                โ–ผ                  โ–ผ                 โ–ผ
//!                  Interpreter(JitMode)  Closures(Provenance)  Native(Provenance)
//!                  cone::extract_jit_cones  closures::           hybrid::
//!                  โ†’ PolydatKernel          CompiledKernel*      HybridKernel*
//! ```
//!
//! The host names the engine ([`select::Engine`]); under
//! `Provenance::Auto` the selector picks the provenance mode from the
//! graph's shape. `Engine::PureNative` builds the pure native kernels
//! (`jit::JitKernel*`): Cranelift code for the whole program, with no
//! closure fallback (engines.md ยง1).
//!
//! - [`assembly`]: the public construction surface
//!   ([`assembly::PolydatAssembler`] + [`assembly::WireRef`]) and
//!   the per-engine compile paths.
//! - [`fusion`]: graph-level subgraph fusion pass; runs during
//!   assembly after wiring resolution.
//! - [`roundtrip_lint`]: the structural type-round-trip lint run at
//!   resolution.
//! - [`cone`]: cone-level JIT inside the interpreter kernel
//!   (engines.md ยง2), under a [`cone::JitMode`].
//! - [`lattice`]: the engine-mix report of a compiled program.
//! - [`select`]: the engine and provenance enums, and the heuristic
//!   that picks a provenance mode under `Provenance::Auto`.
//! - [`closures`]: the closure tier, one generated op per node over
//!   a flat u64 slot buffer, by-reference outputs as `Ref2` pairs.
//! - [`hybrid`]: the native engine (native segments + closure steps
//!   sharing a flat u64 buffer).
//! - [`marshal`]: the boundary marshalling between slots and `Value`s.
//! - `externs`: extern inputs and `shared` cells on the compiled
//!   engines.
//! - [`simd_plan`], `simd_tier1`: scalar-flow SIMD promotion.
//! - `jit`: Cranelift lowering and the pure native kernels
//!   (feature-gated on `jit`).

pub mod assembly;
pub mod closures;
pub mod cone;
#[cfg(all(test, feature = "jit"))]
mod cone_tests;
pub(crate) mod externs;
pub mod fusion;
#[cfg(feature = "jit")]
pub(crate) mod fusion_units;
pub mod hybrid;
#[cfg(feature = "jit")]
pub mod jit;
pub mod lattice;
/// The boundary marshalling a compiled node kit reads its arguments
/// and writes its outputs through (compiled_handles.md ยง4): a node
/// crate's kits use it as the core's own do.
pub mod marshal;
pub mod roundtrip_lint;
pub mod select;
pub mod simd_plan;
#[cfg(feature = "jit")]
pub mod simd_tier1;

/// Axiom S2 typed accessors, shared by the P2 and hybrid kernel
/// types (both expose `self.core.ref_entry(slot)`). Each returns
/// a borrow whose lifetime ties to `&self`, so the borrow checker
/// statically prevents holding a slice across the next
/// `eval(&mut self)` โ€” stale Ref reads are compile errors.
macro_rules! ref_readers {
    () => {
        /// Borrow a `vec_f32` output's current contents.
        pub fn read_vec_f32(&self, slot: usize) -> &[f32] {
            match self.core.ref_entry(slot) {
                crate::ast::ScratchBuf::F32(v) => v,
                other => panic!("slot {slot} is not f32-lane scratch: {other:?}"),
            }
        }
        /// Borrow a `vec_f64` output's current contents.
        pub fn read_vec_f64(&self, slot: usize) -> &[f64] {
            match self.core.ref_entry(slot) {
                crate::ast::ScratchBuf::F64(v) => v,
                other => panic!("slot {slot} is not f64-lane scratch: {other:?}"),
            }
        }
        /// Borrow a `vec_f16` output's current contents.
        pub fn read_vec_f16(&self, slot: usize) -> &[half::f16] {
            match self.core.ref_entry(slot) {
                crate::ast::ScratchBuf::F16(v) => v,
                other => panic!("slot {slot} is not f16-lane scratch: {other:?}"),
            }
        }
        /// Borrow a `vec_i8` output's current contents.
        pub fn read_vec_i8(&self, slot: usize) -> &[i8] {
            match self.core.ref_entry(slot) {
                crate::ast::ScratchBuf::I8(v) => v,
                other => panic!("slot {slot} is not i8-lane scratch: {other:?}"),
            }
        }
        /// Borrow a `vec_i16` output's current contents.
        pub fn read_vec_i16(&self, slot: usize) -> &[i16] {
            match self.core.ref_entry(slot) {
                crate::ast::ScratchBuf::I16(v) => v,
                other => panic!("slot {slot} is not i16-lane scratch: {other:?}"),
            }
        }
        /// Borrow a `vec_i32` output's current contents.
        pub fn read_vec_i32(&self, slot: usize) -> &[i32] {
            match self.core.ref_entry(slot) {
                crate::ast::ScratchBuf::I32(v) => v,
                other => panic!("slot {slot} is not i32-lane scratch: {other:?}"),
            }
        }
        /// Borrow a `vec_i64` output's current contents.
        pub fn read_vec_i64(&self, slot: usize) -> &[i64] {
            match self.core.ref_entry(slot) {
                crate::ast::ScratchBuf::I64(v) => v,
                other => panic!("slot {slot} is not i64-lane scratch: {other:?}"),
            }
        }
    };
}
pub(crate) use ref_readers;

/// The accessors every compiled kernel type carries, whichever tier it
/// belongs to: reading an output by name or by slot, the externs and
/// the cursors it declares, and applying the coordinates a `Kernel`
/// caller left pending before a pull or an eval. Every one of them
/// delegates to `self.core`, so none decides anything about evaluation
/// โ€” which is why seven types can share one copy.
///
/// `$set_coords` is the coordinate writer the type uses: the provenance
/// modes that track a changed-input mask apply coordinates through
/// `set_inputs`, the rest through `set_coords`. It is the only thing
/// that varies, and the closure tier and the hybrid had a macro each to
/// vary it.
macro_rules! kernel_accessors {
    ($set_coords:ident) => {
        /// How many inputs are coordinates. (The core's `coord_count`
        /// field counts the buffer slots all inputs occupy.)
        pub fn coord_count(&self) -> usize {
            self.core.externs.coordinate_count()
        }

        /// The slot of a named output.
        pub fn resolve_output(&self, name: &str) -> Option<usize> {
            self.core.output_map.get(name).copied()
        }

        /// Read an output by pre-resolved slot index. Panics on
        /// Ref2-colored slots (axiom S2) โ€” use `read_vec_*`.
        #[inline]
        pub fn get_slot(&self, slot: usize) -> u64 {
            self.core.guard_ref_slot(slot);
            self.core.buffer[slot]
        }

        /// Read a named output variate after `eval()`. Panics on
        /// Ref2-colored outputs (axiom S2) โ€” use `read_vec_*`.
        #[inline]
        pub fn get(&self, name: &str) -> u64 {
            let slot = self.core.output_map[name];
            self.core.guard_ref_slot(slot);
            self.core.buffer[slot]
        }

        /// The named output as a typed `Value`, decoded by its port
        /// type: a `Ref2` output is copied out through its pair
        /// (compiled_handles.md ยง4), so the caller never holds a
        /// pointer; a slot that holds `None` reads as `None`.
        pub fn get_value(&self, name: &str) -> crate::ast::Value {
            self.core.value_of(name)
        }

        /// A named output, its cone run if a write is pending.
        pub fn pull_output(&mut self, name: &str) -> crate::ast::Value {
            self.core.pull_named(name)
        }

        /// The named output through the `Kernel` trait: the pending
        /// coordinates are applied, a round begins if a write is pending, and
        /// only the output's cone runs.
        fn pull_value(&mut self, name: &str) -> crate::ast::Value {
            self.apply_pending_coords();
            self.pull_output(name)
        }

        /// [`Self::pull_value`] by output index.
        fn pull_value_at(&mut self, index: usize) -> crate::ast::Value {
            self.apply_pending_coords();
            self.core.pull_at(index)
        }

        /// The coordinates of a pending write, applied once: a pull
        /// after the first in a round finds nothing written and skips
        /// the comparison. The round itself begins in the core, which
        /// clears the pending flag.
        #[inline]
        fn apply_pending_coords(&mut self) {
            if self.core.drive.stale {
                let coords = std::mem::take(&mut self.core.drive.coords);
                self.$set_coords(&coords);
                self.core.drive.coords = coords;
            }
        }

        /// `eval` through the `Kernel` trait: the pending coordinates,
        /// then every step.
        fn eval_pending(&mut self) {
            let coords = std::mem::take(&mut self.core.drive.coords);
            self.eval(&coords);
            self.core.drive.coords = coords;
        }

        /// The kernel's externs by name and declared type.
        pub fn externs(&self) -> Vec<(&str, crate::ast::PortType)> {
            self.core.externs.names()
        }

        /// The cursors the program declares, with the partitions the
        /// compiler resolved where its `over` clause and extent were
        /// constant, as `PolydatProgram::cursor_schemas` reports them.
        pub fn cursor_schemas(&self) -> &[crate::iteration::source::SourceSchema] {
            self.core.externs.cursor_schemas()
        }

        /// Narrow a cursor to one partition, as `narrow_cursor` does on
        /// the interpreter: its `Ext` slot and six scalar projections
        /// are set as externs.
        pub fn set_cursor(
            &mut self,
            name: &str,
            partition: &crate::iteration::cursor_partition::Partition,
        ) -> Result<(), crate::kernel::WriteError> {
            for (slot, value) in self.core.externs.cursor_writes(name, partition)? {
                self.set_input(&slot, value)?;
            }
            Ok(())
        }

        crate::compile::ref_readers!();
    };
}
pub(crate) use kernel_accessors;

/// The None rule for fusion (engines.md ยง3.3): whether a node may join
/// the run of fused code being formed, as far as `None` is concerned.
/// The one predicate
/// both fusers apply โ€” the interpreter's cone planner and the hybrid's
/// segment batcher โ€” so that what one admits the other admits.
///
/// Fused code answers a `None` on a boundary input by making every one
/// of its outputs `None`, because native code cannot carry one. That is
/// none_semantics.md Rule 1 and it is the right answer for a node that propagates
/// a `None`. It is the wrong answer for a node that *consumes* one and
/// keeps going โ€” `to_json` writes `null`, a `printf` with an `Option`
/// argument writes its own text โ€” so such a node may join only when
/// every one of its inputs comes from inside, where a `None` cannot
/// arrive: either no boundary input is `None` and the run proceeds
/// normally, or one is and the whole run answers `None` without any
/// member running at all.
///
/// `eligible` is indexed by node and filled in topological order, so a
/// node's producers are decided before it is.
#[cfg(feature = "jit")]
pub(crate) fn none_rule_admits(
    accepts_none: bool,
    wiring: &[crate::kernel::WireSource],
    eligible: &[bool],
) -> bool {
    !accepts_none
        || wiring
            .iter()
            .all(|src| matches!(src, crate::kernel::WireSource::NodeOutput(j, _) if eligible[*j]))
}

/// The highest tier a node can reach, given the types of the wires
/// feeding it: the one answer to a question four places were asking
/// separately.
///
/// The order is the one every builder walks. Native first, since a node
/// with a lowering joins a segment; then the compiled forms, in the
/// order `assembly::node_step_op` tries them โ€” a copy step, the scalar
/// `compiled_u64`, the node's own slot kit; then the interpreter.
///
/// The wire types are not optional. `compiled_slot` is offered per call
/// site with the types the kernel fixed, so a caller without them can
/// only ask the first two questions, and the three callers that
/// reported a tier rather than selecting one did exactly that โ€” they
/// asked `compiled_u64().is_some()` and called a node with a slot kit
/// `Phase1`, which is what the binary printed for `printf`.
pub fn node_tier(
    node: &dyn crate::ast::PolydatNode,
    wire_types: &[crate::ast::PortType],
) -> crate::ast::CompileLevel {
    #[cfg(feature = "jit")]
    if !matches!(
        crate::compile::jit::classify_node_typed(node, wire_types),
        crate::compile::jit::JitOp::Fallback
    ) {
        return crate::ast::CompileLevel::Phase3;
    }
    let meta = node.meta();
    let is_copy =
        (meta.name == "identity" || meta.name.starts_with("__port_")) && meta.outs.len() == 1;
    let has_kit = node
        .compiled_slot(
            wire_types,
            crate::compile::select::Engine::Closures(crate::compile::select::Provenance::Auto),
        )
        .is_some();
    if is_copy || node.compiled_u64().is_some() || has_kit {
        crate::ast::CompileLevel::Phase2
    } else {
        crate::ast::CompileLevel::Phase1
    }
}

/// The provenance of every buffer slot: which input slots reach it,
/// as an exact multi-word mask, for the pull-side cone guard of every
/// compiled kernel. `input_dependents` is indexed by input slot (a
/// multi-slot input repeats its list per slot) and lists the steps
/// downstream of that slot; `step_output_slots` gives each step's
/// output slots, which all take the step's mask. A coordinate slot's
/// provenance is itself.
pub(crate) fn slot_provenance(
    coord_count: usize,
    total_slots: usize,
    step_output_slots: &[&[usize]],
    input_dependents: &[Vec<usize>],
) -> Vec<crate::kernel::ProvMask> {
    use crate::kernel::ProvMask;
    let step_count = step_output_slots.len();
    let mut step_prov: Vec<ProvMask> = (0..step_count).map(|_| ProvMask::empty()).collect();
    for (input_slot, deps) in input_dependents.iter().enumerate() {
        for &step in deps {
            if step < step_count {
                step_prov[step].set(input_slot);
            }
        }
    }
    let mut slots: Vec<ProvMask> = (0..total_slots).map(|_| ProvMask::empty()).collect();
    for (i, slot) in slots.iter_mut().enumerate().take(coord_count) {
        slot.set(i);
    }
    for (step, outs) in step_output_slots.iter().enumerate() {
        for &slot in outs.iter() {
            if slot < slots.len() {
                slots[slot] = step_prov[step].clone();
            }
        }
    }
    slots
}

/// The coordinates a host set last on a compiled kernel and whether
/// they have been evaluated: what the [`Kernel`](crate::kernel::Kernel)
/// trait's `set_inputs` and `pull` keep between calls.
#[derive(Clone, Default)]
pub(crate) struct Drive {
    pub(crate) coords: Vec<u64>,
    pub(crate) stale: bool,
}

/// The slot surface of a compiled kernel: the extended API, over and
/// above the [`Kernel`](crate::kernel::Kernel) trait every engine
/// answers.
///
/// Every compiled engine lays its program out over one flat `u64` slot
/// buffer (engines.md ยง6). That layout is an implementation detail, and
/// this trait is where it is admitted: a slot index instead of an
/// output name, a raw `u64` instead of a `Value`, a borrow into the
/// scratch a by-reference output writes. The interpreter does not
/// implement it and cannot โ€” its buffers are typed `Value`s and it has
/// no slot to name โ€” which is the point: the shape of this trait *is*
/// the thing the compiled tiers share and the interpreter does not.
///
/// **This is not the surface for running a program.** Driving a kernel
/// is `Kernel`, on every engine, and a host that never names an engine
/// never sees this trait. Reach for it when the implementation detail
/// is the subject: a differential test asserting on what was laid out,
/// a benchmark measuring a tier without the `Value` construction and
/// the name lookup a `pull` pays, a diagnostic reporting on a slot.
///
/// It is a subtrait rather than a wider `Kernel`, so it is opt-in at
/// the import: a caller who does not write `use SlotKernel` does not
/// have these methods on their kernel at all. And it is reachable
/// without naming a kernel type, through
/// [`PolydatAssembler::compile_slots`](crate::compile::assembly::PolydatAssembler::compile_slots),
/// which hands back a `Box<dyn SlotKernel>` that upcasts to
/// `Box<dyn Kernel>` wherever the ordinary surface will do.
pub trait SlotKernel: crate::kernel::Kernel {
    /// The buffer slot a named output writes, resolved once so a
    /// caller reading the same output every cycle pays no lookup.
    fn resolve_output(&self, name: &str) -> Option<usize>;

    /// The raw `u64` in `slot`, as it stands: no evaluation, no
    /// decoding. Panics on a `Ref2` slot (axiom S2), which has no
    /// scalar to read โ€” use the `read_vec_*` borrows.
    fn get_slot(&self, slot: usize) -> u64;

    /// [`Self::get_slot`] by output name.
    fn get(&self, name: &str) -> u64;

    /// A named output decoded by its port type, a `Ref2` output copied
    /// out through its pair so the caller never holds a pointer. Reads
    /// what is there; [`Kernel::pull`](crate::kernel::Kernel::pull)
    /// evaluates first.
    fn get_value(&self, name: &str) -> crate::ast::Value;

    /// Set the coordinates, evaluate what `slot` needs, and return its
    /// raw `u64`. The whole read in one call and one `u64`, which is
    /// what a tier benchmark wants: `pull_at` gives the same value
    /// through a `Value` it has to construct.
    fn eval_for_slot(&mut self, coords: &[u64], slot: usize) -> u64;

    /// Set the coordinates and run every step, the whole program in
    /// one call. [`Kernel::eval`](crate::kernel::Kernel::eval) is the
    /// same evaluation over coordinates already written with
    /// `set_inputs`; this is the form that takes them, which is what a
    /// loop over a coordinate range wants.
    fn eval_at(&mut self, coords: &[u64]);

    /// Borrow a `vec_f32` output's current contents. The borrow ties to
    /// `&self`, so holding one across the next evaluation is a compile
    /// error rather than a stale read (axiom S2).
    fn read_vec_f32(&self, slot: usize) -> &[f32];
    /// Borrow a `vec_f64` output's current contents.
    fn read_vec_f64(&self, slot: usize) -> &[f64];
    /// Borrow a `vec_f16` output's current contents.
    fn read_vec_f16(&self, slot: usize) -> &[half::f16];
    /// Borrow a `vec_i8` output's current contents.
    fn read_vec_i8(&self, slot: usize) -> &[i8];
    /// Borrow a `vec_i16` output's current contents.
    fn read_vec_i16(&self, slot: usize) -> &[i16];
    /// Borrow a `vec_i32` output's current contents.
    fn read_vec_i32(&self, slot: usize) -> &[i32];
    /// Borrow a `vec_i64` output's current contents.
    fn read_vec_i64(&self, slot: usize) -> &[i64];
}

/// [`SlotKernel`] for a compiled kernel, forwarding to the inherent
/// methods the type already has. The trait is the surface; the
/// inherent copies are what it forwards to and what this crate calls.
macro_rules! impl_slot_kernel {
    ($ty:ident) => {
        impl crate::compile::SlotKernel for $ty {
            fn resolve_output(&self, name: &str) -> Option<usize> {
                $ty::resolve_output(self, name)
            }
            fn get_slot(&self, slot: usize) -> u64 {
                $ty::get_slot(self, slot)
            }
            fn get(&self, name: &str) -> u64 {
                $ty::get(self, name)
            }
            fn get_value(&self, name: &str) -> crate::ast::Value {
                $ty::get_value(self, name)
            }
            fn eval_for_slot(&mut self, coords: &[u64], slot: usize) -> u64 {
                $ty::eval_for_slot(self, coords, slot)
            }
            fn eval_at(&mut self, coords: &[u64]) {
                $ty::eval(self, coords)
            }
            fn read_vec_f32(&self, slot: usize) -> &[f32] {
                $ty::read_vec_f32(self, slot)
            }
            fn read_vec_f64(&self, slot: usize) -> &[f64] {
                $ty::read_vec_f64(self, slot)
            }
            fn read_vec_f16(&self, slot: usize) -> &[half::f16] {
                $ty::read_vec_f16(self, slot)
            }
            fn read_vec_i8(&self, slot: usize) -> &[i8] {
                $ty::read_vec_i8(self, slot)
            }
            fn read_vec_i16(&self, slot: usize) -> &[i16] {
                $ty::read_vec_i16(self, slot)
            }
            fn read_vec_i32(&self, slot: usize) -> &[i32] {
                $ty::read_vec_i32(self, slot)
            }
            fn read_vec_i64(&self, slot: usize) -> &[i64] {
                $ty::read_vec_i64(self, slot)
            }
        }
    };
}
pub(crate) use impl_slot_kernel;

/// The [`Kernel`](crate::kernel::Kernel) impl every compiled kernel
/// shares: the type's inherent `eval_pending`, `pull_value`,
/// `pull_value_at`, `set_input`, `set_input_at`, `set_cursor`,
/// `mark_all_dirty`, and a `core` with `drive`, `externs`,
/// `coord_count`, `output_types`, `output_map`, `buffer`,
/// `traversals`, and `plan`/`invalidate_all`/`attach_cell`/
/// `slot_value`.
macro_rules! impl_kernel_trait {
    ($ty:ident) => {
        impl crate::kernel::Kernel for $ty {
            fn engine(&self) -> crate::compile::select::Engine {
                self.core.engine
            }
            fn set_inputs(&mut self, coords: &[u64]) {
                self.core.drive.coords.clear();
                self.core.drive.coords.extend_from_slice(coords);
                self.core.drive.stale = true;
            }
            fn set_input(
                &mut self,
                name: &str,
                value: crate::ast::Value,
            ) -> Result<(), crate::kernel::WriteError> {
                if self.core.externs.is_const_name(name) {
                    return Err(crate::kernel::WriteError::ConstSlot {
                        slot: name.to_string(),
                    });
                }
                self.core.drive.stale = true;
                $ty::set_input(self, name, value)
            }
            fn const_inits(&self) -> &[crate::kernel::ConstInit] {
                self.core.externs.const_inits()
            }
            fn init_input_at(
                &mut self,
                index: usize,
                value: crate::ast::Value,
            ) -> Result<(), crate::kernel::WriteError> {
                self.core.drive.stale = true;
                $ty::set_input_at(self, index, value)
            }
            fn set_cursor(
                &mut self,
                name: &str,
                partition: &crate::iteration::cursor_partition::Partition,
            ) -> Result<(), crate::kernel::WriteError> {
                self.core.drive.stale = true;
                $ty::set_cursor(self, name, partition)
            }
            fn eval(&mut self) {
                self.eval_pending();
                self.core.drive.stale = false;
            }
            fn pull(&mut self, name: &str) -> crate::ast::Value {
                self.pull_value(name)
            }
            fn input_names(&self) -> Vec<String> {
                self.core.externs.input_names().to_vec()
            }
            /// In declaration order, as the interpreter lists them: the
            /// assembler sets them on every compiled kernel.
            fn output_names(&self) -> Vec<String> {
                self.core.externs.output_names().to_vec()
            }
            fn output_type(&self, name: &str) -> Option<crate::ast::PortType> {
                self.core.output_types.get(name).copied()
            }
            fn externs(&self) -> Vec<(String, crate::ast::PortType)> {
                self.core
                    .externs
                    .names()
                    .into_iter()
                    .map(|(n, t)| (n.to_string(), t))
                    .collect()
            }
            fn cursor_schemas(&self) -> &[crate::iteration::source::SourceSchema] {
                self.core.externs.cursor_schemas()
            }
            fn input_value(&self, name: &str) -> Option<crate::ast::Value> {
                self.core.externs.value(name).or_else(|| {
                    let i = self
                        .core
                        .externs
                        .input_names()
                        .iter()
                        .position(|n| n == name)?;
                    if i < self.core.externs.coordinate_count() {
                        let pending = self.core.drive.coords.get(i).copied();
                        Some(crate::ast::Value::U64(
                            pending.unwrap_or(self.core.buffer[i]),
                        ))
                    } else {
                        None
                    }
                })
            }
            fn traversals(&self) -> &[crate::dsl::traversal::Traversal] {
                &self.core.traversals
            }
            fn plan(&self) -> crate::EnginePlan {
                self.core.plan()
            }
            fn input_index(&self, name: &str) -> Option<usize> {
                self.core
                    .externs
                    .input_names()
                    .iter()
                    .position(|n| n == name)
            }
            fn set_input_at(
                &mut self,
                index: usize,
                value: crate::ast::Value,
            ) -> Result<(), crate::kernel::WriteError> {
                if self.core.externs.is_const_index(index) {
                    return Err(crate::kernel::WriteError::ConstSlot {
                        slot: self.core.externs.input_names()[index].clone(),
                    });
                }
                self.core.drive.stale = true;
                $ty::set_input_at(self, index, value)
            }
            fn output_index(&self, name: &str) -> Option<usize> {
                self.core
                    .externs
                    .output_names()
                    .iter()
                    .position(|n| n == name)
            }
            fn pull_at(&mut self, index: usize) -> crate::ast::Value {
                self.pull_value_at(index)
            }
            fn traverse(&mut self, index: usize) -> Result<crate::kernel::TraversalStream, String> {
                let traversal = self.core.traversals.get(index).cloned().ok_or_else(|| {
                    format!(
                        "no traversal at index {index}; the program declares {}",
                        self.core.traversals.len()
                    )
                })?;
                crate::kernel::activation::open_traversal(self, traversal)
            }
            fn invalidate_all(&mut self) {
                self.mark_all_dirty();
                self.core.invalidate_all();
            }
            fn shared_cells(&self) -> Vec<crate::kernel::SharedCellEntry> {
                self.core.externs.shared_cells()
            }
            fn output_cell(&self, name: &str) -> Option<crate::kernel::SharedCell> {
                self.core.output_cell_for(name)
            }
            fn output_modifier(&self, name: &str) -> crate::dsl::ast::BindingModifier {
                self.core.externs.output_modifier(name)
            }
            fn cells_in_scope(&self) -> Vec<crate::kernel::SharedCellEntry> {
                self.core.externs.cells_in_scope()
            }
            fn set_transit_cells(&mut self, cells: Vec<crate::kernel::SharedCellEntry>) {
                self.core.externs.set_transit_cells(cells);
            }
            fn input_port_type(&self, name: &str) -> Option<crate::ast::PortType> {
                self.core.externs.input_port_type(name)
            }
            fn bind_input_cell(&mut self, name: &str, cell: crate::kernel::SharedCell) -> bool {
                let Some(slot) = self.core.externs.bind_cell(name, cell) else {
                    return false;
                };
                // The slot's value is the cell's from the next refresh,
                // so everything downstream of it reruns.
                self.core.dirty_input(slot);
                true
            }
            fn attach_shared_cell(
                &mut self,
                name: &str,
                cell: crate::kernel::SharedCell,
            ) -> Result<(), String> {
                self.core.attach_cell(name, cell)
            }
            fn into_program(
                mut self: Box<Self>,
            ) -> std::sync::Arc<dyn crate::kernel::KernelProgram> {
                self.mark_all_dirty();
                self.core.drive.stale = true;
                std::sync::Arc::new(crate::kernel::SharedKernel(*self))
            }
            fn ledger(&self) -> &std::sync::Arc<crate::kernel::CompileLedger> {
                self.core.externs.ledger()
            }
            fn resources(&self) -> &crate::resource::ResourceScope {
                self.core.externs.resources()
            }
            fn canonical_hash(&self) -> [u8; 32] {
                crate::kernel::program_identity(
                    self.core.externs.graph_identity(),
                    self.core.externs.inherited_outputs().iter(),
                    crate::kernel::Kernel::cursor_schemas(self),
                    crate::kernel::Kernel::traversals(self),
                )
            }
            fn coord_count(&self) -> usize {
                self.core.externs.coordinate_count()
            }
            fn input_value_at(&self, index: usize) -> Option<crate::ast::Value> {
                if index < self.core.externs.coordinate_count() {
                    let pending = self.core.drive.coords.get(index).copied();
                    return Some(crate::ast::Value::U64(
                        pending.unwrap_or(self.core.buffer[index]),
                    ));
                }
                self.core.externs.value_at(index)
            }
            fn input_default_at(&self, index: usize) -> Option<crate::ast::Value> {
                if index < self.core.externs.coordinate_count() {
                    return Some(crate::ast::Value::U64(0));
                }
                self.core.externs.default_at(index)
            }
            fn input_is_cell_bound(&self, index: usize) -> bool {
                self.core.externs.is_cell_bound_at(index)
            }
            fn reset_inputs(&mut self) {
                let count = self.core.externs.input_names().len();
                for index in self.core.externs.coordinate_count()..count {
                    if self.core.externs.is_cell_bound_at(index) {
                        continue;
                    }
                    let (Some(now), Some(default)) = (
                        self.core.externs.value_at(index),
                        self.core.externs.default_at(index),
                    ) else {
                        continue;
                    };
                    if now != default {
                        // The typed write, so what depends on the input
                        // is marked as any write marks it. A declared
                        // default satisfies its own slot.
                        let _ = crate::kernel::Kernel::set_input_at(self, index, default);
                    }
                }
            }
            fn fork(&self) -> Box<dyn crate::kernel::Kernel> {
                // A clone is a new state of the same program with this
                // one's values: shared slots keep their cells, transit
                // cells travel, and broadcast cells stay with the
                // original, which is what descendants are bound to.
                Box::new(self.clone())
            }
            fn publish_broadcasts(&mut self) {
                if !self.core.externs.broadcasts() {
                    return;
                }
                let names: Vec<String> = self.core.externs.output_names().to_vec();
                for name in names {
                    let Some(&slot) = self.core.output_map.get(&name) else {
                        continue;
                    };
                    if self.core.externs.published_output(slot).is_none() {
                        continue;
                    }
                    // The pull by name publishes through the cell. A
                    // failure is left for the pull that needs the value.
                    let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                        self.pull_value(&name);
                    }));
                }
            }
            fn commit_write_throughs(&mut self) -> Result<(), String> {
                let pairs = self.core.externs.write_throughs().to_vec();
                let mut pending = Vec::with_capacity(pairs.len());
                for (export, source) in &pairs {
                    let Some(slot_type) = self.core.externs.input_port_type(export) else {
                        continue;
                    };
                    let value = self.pull_value(source);
                    let value =
                        crate::kernel::check_write_through_type(export, source, slot_type, value)?;
                    pending.push((export.clone(), value));
                }
                for (export, value) in pending {
                    crate::kernel::Kernel::set_input(self, &export, value)
                        .map_err(|e| format!("write-through into `{export}`: {e}"))?;
                }
                Ok(())
            }
            fn program_id(&self) -> crate::kernel::ProgramId {
                crate::kernel::ProgramId(self.core.program_identity())
            }
            fn input_type_origin(&self, name: &str) -> Option<crate::kernel::TypeOrigin> {
                self.core.externs.input_type_origin(name)
            }
        }

        impl crate::kernel::KernelInternals for $ty {
            fn set_write_throughs(&mut self, pairs: Vec<(String, String)>) {
                self.core.externs.set_write_throughs(pairs);
            }
            fn set_inherited_outputs(&mut self, names: Vec<String>) {
                self.core.externs.set_inherited_outputs(names);
            }
            /// A compiled kernel keeps the traversals; each carries the
            /// comprehension its producer resolved to at compile time.
            fn set_traversals(
                &mut self,
                traversals: Vec<crate::dsl::traversal::Traversal>,
                _producers: Vec<crate::dsl::traversal::Producer>,
            ) {
                self.core.traversals = traversals.into();
            }
            fn slot_value(&self, slot: usize, ty: crate::ast::PortType) -> crate::ast::Value {
                self.core.slot_value(slot, ty)
            }
            /// Only for an output fixed for the kernel's life, a const or
            /// a value folded at build: a computed output's slot holds its
            /// last evaluated value, which is not the scope's.
            ///
            /// A `const` captured at initialization answers from its slot,
            /// which initialization writes, so its value is there before
            /// anything evaluates its output.
            fn folded_value(&self, name: &str) -> Option<crate::ast::Value> {
                if !self.core.externs.is_fixed_output(name) {
                    return None;
                }
                if let Some(c) = self
                    .core
                    .externs
                    .const_inits()
                    .iter()
                    .find(|c| c.name == name)
                {
                    return crate::kernel::Kernel::input_value_at(self, c.slot_index);
                }
                let slot = *self.core.output_map.get(name)?;
                let ty = *self.core.output_types.get(name)?;
                Some(self.core.slot_value(slot, ty))
            }
            fn set_cursor_extent(&mut self, index: usize, extent: u64) {
                self.core.externs.set_cursor_extent(index, extent);
            }
            fn reset_to_program(&mut self) {
                self.core.externs.reset_to_program(&mut self.core.buffer);
                self.mark_all_dirty();
            }
        }
    };
}
pub(crate) use impl_kernel_trait;

/// The bookkeeping every compiled engine keeps, whatever its steps
/// are: the evaluation round and what ran in it, the clean flags and
/// what a write dirties, the extern writes and the cell refresh, the
/// reference pairs a step publishes, and reading an output back.
///
/// Both compiled cores carry the same fields for these, and this macro
/// gives them one copy of the methods. None of them touches the step
/// list, which is the one thing the two tiers genuinely differ about:
/// a step on the closure tier is always a closure, and on the native
/// tier it is a closure or a run of native code. That difference lives
/// in the run loops, which stay per tier (engines.md ยง8).
macro_rules! shared_core_methods {
    () => {
        /// Axiom S2 typed accessor core: resolve a Ref pair's first
        /// slot to its kernel-owned scratch entry. The returned
        /// borrow ties to `&self`, so holding it across the next
        /// `eval(&mut self)` is a compile error โ€” stale reads are
        /// statically impossible.
        fn ref_entry(&self, slot: usize) -> &crate::ast::ScratchBuf {
            match self.ref_scratch.iter().find(|(s, _)| *s == slot) {
                Some(&(_, idx)) => &self.scratch[idx],
                None if self.ref_slots.get(slot).copied().unwrap_or(false) => panic!(
                    "slot {slot} is a Ref pair owned by the CALLER (a kernel \
                     input) โ€” read it on the caller side"
                ),
                None => panic!("slot {slot} is not a Ref2-colored slot"),
            }
        }

        /// Run `body` with the failure path armed: a panic inside a
        /// step is recorded quietly and re-raised enriched, as the
        /// interpreter re-raises a node's (engines.md ยง3.4), and every
        /// reference pair is checked afterwards in a debug build.
        ///
        /// `#[inline]` is load-bearing: this wraps every `eval`, and
        /// without it the native rung of the ladder pays a call and
        /// about seven percent.
        #[inline]
        fn run_guarded(&mut self, body: impl FnOnce(&mut Self)) {
            let capture = crate::kernel::engines::EvalPanicCaptureGuard::arm();
            let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| body(self)));
            drop(capture);
            if let Err(payload) = outcome {
                let sites = std::sync::Arc::clone(&self.sites);
                let node = self.failing_node();
                sites.reraise(payload, node, &self.buffer, Some(&self.none));
            }
            #[cfg(debug_assertions)]
            self.validate_refs();
        }

        /// Axiom S9: every reference pair in the buffer names the
        /// scratch entry that owns it. A slot is skipped when nothing
        /// has been published into it โ€” its step has not run, or it
        /// carries `None`.
        ///
        /// Gated to `debug_assertions` to match its call sites, which
        /// compile out in release.
        #[cfg(debug_assertions)]
        fn validate_refs(&self) {
            for &(slot, idx) in &self.ref_scratch {
                let unpublished = self.none[slot]
                    || matches!(self.slot_step.get(slot), Some(Some(step)) if self.ran[*step] == 0);
                if unpublished {
                    continue;
                }
                let (p, l) = self.scratch[idx].ptr_len();
                assert!(
                    self.buffer[slot] == p && self.buffer[slot + 1] == l,
                    "S9 ref-validator: slot pair ({slot}, {}) = ({:#x}, {}) \
                     does not match scratch[{idx}] = ({p:#x}, {l}) โ€” a slot \
                     op failed to republish or wrote the wrong slots",
                    slot + 1,
                    self.buffer[slot],
                    self.buffer[slot + 1],
                );
            }
        }

        fn attach_cell(
            &mut self,
            name: &str,
            cell: crate::kernel::SharedCell,
        ) -> Result<(), String> {
            let slot = self.externs.attach_cell(name, cell)?;
            self.dirty_input(slot);
            self.drive.stale = true;
            Ok(())
        }

        #[inline]
        fn begin_epoch(&mut self) {
            if self.externs.cells_dirty() {
                self.externs.refresh_cells(&mut self.buffer);
            }
            self.dirty_refreshed();
            self.epoch += 1;
            self.all_ran = false;
            for &i in self.volatile_steps.iter() {
                self.clean[i] = false;
            }
            self.drive.stale = false;
        }

        /// A read that begins no round still re-evaluates every volatile
        /// step its cone reaches, once, and the steps downstream of it
        /// (runtime_model.md R1.v); steps upstream of a volatile step
        /// keep their currency. A new round already leaves every
        /// volatile step unrun. Most programs have no volatile step and
        /// pay the emptiness check.
        #[inline]
        fn rearm_volatile(&mut self) {
            if self.volatile_steps.is_empty() {
                return;
            }
            for &i in self.volatile_steps.iter() {
                self.ran[i] = 0;
            }
            self.all_ran = false;
        }

        #[inline]
        fn dirty_input(&mut self, slot: usize) {
            if let Some(deps) = self.dirty.get(slot) {
                for &i in deps {
                    self.clean[i] = false;
                }
            }
        }

        /// Inlined into every evaluation, so only the check lives here:
        /// a cell refresh changing a slot is rare, and its work is kept
        /// out of line where it does not grow the hot path.
        #[inline]
        fn dirty_refreshed(&mut self) {
            if self.externs.has_changed() {
                self.dirty_refreshed_slots();
            }
        }

        #[cold]
        #[inline(never)]
        fn dirty_refreshed_slots(&mut self) {
            let changed = self.externs.take_changed();
            for &slot in &changed {
                // The cell's value is the slot's now: a slot that was
                // unset (an extern with no default, bound to a parent's
                // cell) holds a value, and one the cell cleared holds
                // none, as a direct write would leave it.
                if let Some(mask) = self.none.get_mut(slot) {
                    *mask = self.externs.slot_is_unset(slot);
                }
                if let Some(deps) = self.plan.input_dependents.get(slot) {
                    for &i in deps {
                        self.ran[i] = 0;
                        self.clean[i] = false;
                    }
                    self.all_ran = false;
                }
            }
            self.externs.return_changed(changed);
            let was = self.any_none;
            self.any_none = self.externs.any_unset();
            if was && !self.any_none {
                self.none.fill(false);
            }
        }

        #[inline]
        fn eval_all(&mut self) {
            let fresh = self.drive.stale;
            if fresh {
                self.begin_epoch();
            } else {
                self.refresh_cells();
                self.rearm_volatile();
            }
            if fresh && !self.use_clean && !self.any_none {
                self.run_guarded(|core| core.run_fresh());
            } else {
                let all = std::sync::Arc::clone(&self.all);
                self.run_steps(&all);
            }
        }

        fn extern_written(&mut self, slot: usize, unset: bool) {
            self.none[slot] = unset;
            let was = self.any_none;
            self.any_none = self.externs.any_unset();
            if was && !self.any_none {
                self.none.fill(false);
            }
            self.dirty_input(slot);
            self.drive.stale = true;
        }

        #[inline]
        fn guard_ref_slot(&self, slot: usize) {
            if self.ref_slots.get(slot).copied().unwrap_or(false) {
                panic!(
                    "S2 pointer containment: slot {slot} is Ref2-colored; raw u64 readers \
                     would leak an interior address. Use the typed borrow-checked accessor \
                     (read_vec_*), the boundary decode, or copy out."
                );
            }
        }

        fn invalidate_all(&mut self) {
            self.clean.fill(false);
            self.all_ran = false;
            self.drive.stale = true;
        }

        /// A pull by index publishes as a pull by name does, so a child
        /// bound to this output reads what the parent computed. The flag
        /// is checked before the pull rather than after it: holding the
        /// value across the check cost the native rungs 6 percent.
        #[inline]
        fn pull_at(&mut self, index: usize) -> crate::ast::Value {
            if self.externs.broadcasts() {
                return self.pull_at_publishing(index);
            }
            self.pull_at_value(index)
        }

        /// `pull_at` under a descendant: the pull, then the publish.
        #[cold]
        #[inline(never)]
        fn pull_at_publishing(&mut self, index: usize) -> crate::ast::Value {
            let value = self.pull_at_value(index);
            let slot = self.resolved_outputs[index]
                .as_ref()
                .expect("resolved by the pull")
                .0;
            self.publish_slot(slot, &value);
            value
        }

        #[inline(always)]
        fn pull_at_value(&mut self, index: usize) -> crate::ast::Value {
            if self.resolved_outputs.len() <= index {
                self.resolved_outputs.resize(index + 1, None);
            }
            if self.resolved_outputs[index].is_none() {
                let name = self
                    .externs
                    .output_names()
                    .get(index)
                    .cloned()
                    .unwrap_or_else(|| {
                        panic!(
                            "no output at index {index}; this kernel declares {}",
                            self.externs.output_names().len()
                        )
                    });
                let slot = self.output_map[&name];
                let ty = self
                    .output_types
                    .get(&name)
                    .copied()
                    .unwrap_or(crate::ast::PortType::U64);
                let cone = self
                    .plan
                    .cones
                    .get(&name)
                    .map(|c| std::sync::Arc::<[usize]>::from(c.as_slice()));
                let can_fail = cone
                    .as_ref()
                    .is_some_and(|c| c.iter().any(|&i| self.step_can_fail(i)));
                self.resolved_outputs[index] = Some((slot, ty, cone, can_fail));
            }
            if self.drive.stale {
                self.begin_epoch();
            } else {
                self.refresh_cells();
                self.rearm_volatile();
            }
            let resolved = self.resolved_outputs[index]
                .as_ref()
                .expect("resolved above");
            let (slot, ty, can_fail) = (resolved.0, resolved.1, resolved.3);
            if let Some(order) = &resolved.2 {
                // Borrowed across the run rather than cloned: the order
                // lives behind an `Arc` this state holds, and running
                // steps never touches the resolved outputs.
                let order: *const [usize] = &**order;
                let order = unsafe { &*order };
                if can_fail {
                    self.run_steps(order);
                } else {
                    // No step of the cone can fail, so there is no
                    // failure to capture and attribute.
                    self.run_order(order);
                }
            }
            self.slot_value(slot, ty)
        }

        /// Publish the value at `slot` through its broadcast cell, if a
        /// descendant asked for one.
        fn publish_slot(&self, slot: usize, value: &crate::ast::Value) {
            if let Some(cell) = self.externs.published_output(slot) {
                cell.publish(value.clone());
            }
        }

        fn pull_named(&mut self, name: &str) -> crate::ast::Value {
            if self.drive.stale {
                self.begin_epoch();
            } else {
                self.refresh_cells();
                self.rearm_volatile();
            }
            let plan = std::sync::Arc::clone(&self.plan);
            if let Some(order) = plan.cones.get(name) {
                self.run_steps(order);
            }
            let value = self.value_of(name);
            self.broadcast(name, &value);
            value
        }

        /// Publish a freshly computed output through its broadcast cell,
        /// if a descendant asked for one, so a child that bound its
        /// matching input slot to the same cell reads the new value
        /// (cross_fiber_invalidation.md ยง3.1, "broadcast outputs").
        ///
        /// A program nobody built a subscope under has no cells at all,
        /// and pays the emptiness check.
        #[inline]
        fn broadcast(&mut self, name: &str, value: &crate::ast::Value) {
            if !self.externs.broadcasts() {
                return;
            }
            if let Some(&slot) = self.output_map.get(name) {
                self.publish_slot(slot, value);
            }
        }

        /// The broadcast cell for a named output, created on the first
        /// ask. The interpreter seeds one per output at construction;
        /// a compiled kernel makes them only when a descendant binds to
        /// one, so a program with no subscope under it allocates none.
        ///
        /// Keyed by the output's slot, which is what `output_map`
        /// answers and what the buffer is indexed by, so the vector is
        /// as long as the buffer rather than as long as the output list.
        fn output_cell_for(&self, name: &str) -> Option<crate::kernel::SharedCell> {
            let slot = *self.output_map.get(name)?;
            // An output no step has computed yet holds its type's zero
            // in the buffer; the cell starts at `None`, as the
            // interpreter's does, until the first pull publishes.
            let uncomputed = !self.all_ran
                && matches!(self.slot_step.get(slot), Some(Some(step)) if self.ran[*step] == 0);
            let initial = if uncomputed {
                crate::ast::Value::None
            } else {
                self.value_of(name)
            };
            Some(self.externs.output_cell(slot, initial))
        }

        #[inline]
        fn refresh_cells(&mut self) {
            if self.externs.cells_dirty() {
                self.externs.refresh_cells(&mut self.buffer);
                self.dirty_refreshed();
            }
        }

        fn republish_refs(&mut self) {
            for &(slot, idx) in &self.ref_scratch {
                let (p, l) = self.scratch[idx].ptr_len();
                self.buffer[slot] = p;
                self.buffer[slot + 1] = l;
            }
            self.externs.seed(&mut self.buffer, None);
        }

        #[inline]
        fn run_steps(&mut self, order: &[usize]) {
            self.run_guarded(|core| core.run_order(order));
        }

        /// `run_steps` for the build-time constant fold: the same steps
        /// under the same guard, but a failure comes back as the
        /// message [`Attribution::reraise`] would have raised. A step
        /// that fails here fails before any kernel exists, so it is an
        /// error the builder returns rather than a panic out of a
        /// constructor.
        fn fold_steps(&mut self, order: &[usize]) -> Result<(), crate::KernelError> {
            let capture = crate::kernel::engines::EvalPanicCaptureGuard::arm();
            let outcome =
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.run_order(order)));
            drop(capture);
            if let Err(payload) = outcome {
                let sites = std::sync::Arc::clone(&self.sites);
                let node = self.failing_node();
                return Err(crate::KernelError::ConstantFold {
                    reason: sites.describe(payload, node, &self.buffer, Some(&self.none)),
                });
            }
            Ok(())
        }

        fn set_extern(
            &mut self,
            name: &str,
            value: crate::ast::Value,
        ) -> Result<usize, crate::kernel::WriteError> {
            let (slot, unset) = self.externs.set(name, value, &mut self.buffer)?;
            self.extern_written(slot, unset);
            Ok(slot)
        }

        fn set_extern_at(
            &mut self,
            index: usize,
            value: crate::ast::Value,
        ) -> Result<usize, crate::kernel::WriteError> {
            let (slot, unset) = self.externs.set_at(index, value, &mut self.buffer)?;
            self.extern_written(slot, unset);
            Ok(slot)
        }

        fn slot_value(&self, slot: usize, ty: crate::ast::PortType) -> crate::ast::Value {
            if self.none.get(slot).copied().unwrap_or(false) {
                return crate::ast::Value::None;
            }
            crate::compile::marshal::decode_output(&self.buffer, slot, ty)
        }

        fn value_of(&self, name: &str) -> crate::ast::Value {
            let slot = self.output_map[name];
            let ty = self
                .output_types
                .get(name)
                .copied()
                .unwrap_or(crate::ast::PortType::U64);
            self.slot_value(slot, ty)
        }
    };
}
pub(crate) use shared_core_methods;

/// The dirty-register plan of a compiled kernel: which steps each input
/// slot invalidates when it changes, and which steps each named output
/// needs. The evaluation loops consume only this, and provenance derives
/// it, so a narrower plan would need no change to the loops
/// (engines.md ยง3.1).
pub(crate) struct Invalidation {
    /// Per input slot (coordinates and externs alike), the steps that
    /// depend on it, transitively.
    pub(crate) input_dependents: Vec<Vec<usize>>,
    /// Per named output, the steps of its cone in evaluation order.
    pub(crate) cones: std::collections::HashMap<String, Vec<usize>>,
}

impl Invalidation {
    /// The plan provenance gives: every step downstream of an input is
    /// invalidated by it, and every step upstream of an output is in
    /// its cone. `inputs` and `outputs` are each step's slots;
    /// `output_slots` names the outputs.
    pub(crate) fn from_provenance(
        input_dependents: Vec<Vec<usize>>,
        step_inputs: &[&[usize]],
        step_outputs: &[&[usize]],
        output_slots: &std::collections::HashMap<String, usize>,
        total_slots: usize,
    ) -> Self {
        let step_count = step_inputs.len();
        let mut slot_step: Vec<Option<usize>> = vec![None; total_slots];
        for (i, outs) in step_outputs.iter().enumerate() {
            for &s in outs.iter() {
                slot_step[s] = Some(i);
            }
        }
        let cones = output_slots
            .iter()
            .map(|(name, &slot)| {
                let mut wanted = vec![false; step_count];
                let mut stack: Vec<usize> = slot_step[slot].into_iter().collect();
                while let Some(i) = stack.pop() {
                    if wanted[i] {
                        continue;
                    }
                    wanted[i] = true;
                    stack.extend(step_inputs[i].iter().filter_map(|&s| slot_step[s]));
                }
                (
                    name.clone(),
                    (0..step_count).filter(|&i| wanted[i]).collect(),
                )
            })
            .collect();
        Self {
            input_dependents,
            cones,
        }
    }
}

/// Where each compiled step came from, for the failure path only
/// (engines.md ยง3.4). A step's panic is caught at the step
/// boundary and re-raised enriched exactly as the interpreter enriches
/// a node's: the node's name, the outputs it feeds, the program's
/// diagnostic context, and its input values decoded from the buffer
/// where the slot types allow. `sites` is indexed by program node:
/// the closure and pure-native kernels have one step per node, and
/// the hybrid kernel names the failing member of a segment through
/// its tracker slot.
#[derive(Default)]
pub(crate) struct Attribution {
    pub(crate) sites: Vec<NodeSite>,
    /// The program's diagnostic context (`PolydatProgram::context`).
    pub(crate) context: String,
}

/// One node's identity for the failure path.
pub(crate) struct NodeSite {
    pub(crate) name: String,
    /// The declared outputs the node feeds, sorted.
    pub(crate) outputs: Vec<String>,
    /// `(first slot, port type)` of every input port, in port order.
    pub(crate) inputs: Vec<(usize, crate::ast::PortType)>,
}

impl Attribution {
    /// The inputs of `step` as diagnostic text, from the buffer, each
    /// copied out and printed as the interpreter prints the same value:
    /// `None` where the mask says so, and the port type alone where the
    /// slot cannot be decoded, so the report itself never fails.
    fn inputs_of(&self, step: usize, buffer: &[u64], none: Option<&[bool]>) -> Vec<String> {
        let Some(site) = self.sites.get(step) else {
            return Vec::new();
        };
        let _quiet = crate::kernel::engines::EvalPanicCaptureGuard::arm();
        site.inputs
            .iter()
            .map(|&(slot, ty)| {
                if none.is_some_and(|m| m.get(slot).copied().unwrap_or(false)) {
                    return "None".to_string();
                }
                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
                    crate::kernel::engines::format_value_for_diag(&marshal::decode_output(
                        buffer, slot, ty,
                    ))
                }))
                .unwrap_or_else(|_| format!("{ty:?}"))
            })
            .collect()
    }

    /// Re-raise a step's panic enriched as the interpreter enriches a
    /// node's (`kernel::engines::enrich_panic`). `step` beyond the
    /// sites (native code that failed before naming a step) reports an
    /// unknown node, as the interpreter does for an index it lacks.
    pub(crate) fn reraise(
        &self,
        payload: Box<dyn std::any::Any + Send>,
        step: usize,
        buffer: &[u64],
        none: Option<&[bool]>,
    ) -> ! {
        crate::kernel::engines::reraise_enriched(self.describe(payload, step, buffer, none))
    }

    /// The same message [`Self::reraise`] raises, returned instead. The
    /// build-time constant fold uses it: a step that fails there fails
    /// before any kernel exists, so it is an error the builder returns
    /// and not a panic out of a constructor.
    pub(crate) fn describe(
        &self,
        payload: Box<dyn std::any::Any + Send>,
        step: usize,
        buffer: &[u64],
        none: Option<&[bool]>,
    ) -> String {
        let site = self.sites.get(step);
        let name = site
            .map(|s| s.name.clone())
            .unwrap_or_else(|| format!("<unknown node #{step}>"));
        let outputs: Vec<&str> = site
            .map(|s| s.outputs.iter().map(String::as_str).collect())
            .unwrap_or_default();
        let inputs = self.inputs_of(step, buffer, none);
        crate::kernel::engines::enrich_panic(payload, &name, &outputs, &self.context, &inputs)
    }
}