polydat 0.6.2

Polydat — a variates construction engine
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
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Extension values on every engine. A host type that implements
//! `ReflectedValue` rides a wire as `Value::Ext`; nodes take and return
//! it through `Ext<T>`. Such a node has a slot kit (compiled_handles.md §5) that
//! reads the value through its pair and writes its own into the step's
//! scratch, which the closure tier runs as a step and native code calls
//! in place (compiled_handles.md §6).

use polydat::ast::{ReflectedValue, Value};
use polydat::derive_support::Ext;
use polydat::dsl::compile::compile_polydat_to_assembler;

#[derive(Debug, Clone, PartialEq)]
struct Span {
    lo: u64,
    hi: u64,
}

impl ReflectedValue for Span {
    fn type_name(&self) -> &str {
        "Span"
    }
    fn display(&self) -> String {
        format!("[{}, {})", self.lo, self.hi)
    }
    fn clone_reflected(&self) -> Box<dyn ReflectedValue> {
        Box::new(self.clone())
    }
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[polydat::polydat_node(category = Math, struct_name = SpanOf)]
fn span_of(center: u64, width: u64) -> Ext<Span> {
    Ext(Span {
        lo: center.saturating_sub(width),
        hi: center.saturating_add(width),
    })
}

#[polydat::polydat_node(category = Math)]
fn span_len(span: Ext<Span>) -> u64 {
    span.hi - span.lo
}

#[polydat::polydat_node(category = Math)]
fn span_shift(span: Ext<Span>, by: u64) -> Ext<Span> {
    Ext(Span {
        lo: span.lo + by,
        hi: span.hi + by,
    })
}

#[polydat::polydat_node(category = String)]
fn span_text(span: Ext<Span>) -> String {
    span.display()
}

/// `span_shift` with its extension argument and return written as
/// qualified paths, which the macro recognizes as `Ext` by their last
/// segment as it does the bare name.
#[polydat::polydat_node(category = Math)]
fn span_widen(
    span: polydat::derive_support::Ext<Span>,
    by: u64,
) -> polydat::derive_support::Ext<Span> {
    polydat::derive_support::Ext(Span {
        lo: span.lo.saturating_sub(by),
        hi: span.hi + by,
    })
}

/// A path-qualified `Ext<…>` argument and return take the slot kit,
/// so the node runs on the closure tier and native code and answers
/// as the interpreter does.
#[test]
fn a_path_qualified_extension_node_has_a_slot_kit() {
    use polydat::ast::{PolydatNode, PortType};
    let kit = SpanWiden::default().compiled_slot(
        &[PortType::Ext, PortType::U64],
        polydat::Engine::Closures(polydat::Provenance::Auto),
    );
    assert!(
        kit.is_some(),
        "a path-qualified Ext argument and return take the slot kit"
    );

    let src = "input cycle: u64\n\
               s := span_of(cycle, 2)\n\
               w := span_widen(s, 3)\n\
               n := span_len(w)\n\
               label := span_text(w)\n";
    let mut p1 = compile_polydat_to_assembler(src).unwrap();
    p1.set_jit_mode(polydat::JitMode::Off);
    let mut p1 = p1.compile().expect("P1");
    for engine in [
        polydat::Engine::Closures(polydat::Provenance::Raw),
        polydat::Engine::Native(polydat::Provenance::PushPull),
    ] {
        let mut k = compile_polydat_to_assembler(src)
            .unwrap()
            .compile_slots(engine)
            .unwrap_or_else(|_| panic!("{engine} refused a path-qualified extension node"));
        for cycle in 0..16u64 {
            p1.set_inputs(&[cycle]);
            k.eval_at(&[cycle]);
            assert_eq!(k.get("n"), p1.pull_ref("n").as_u64(), "{engine}: n");
            assert_eq!(
                k.get_value("label").as_str(),
                p1.pull_ref("label").as_str(),
                "{engine}: label at cycle {cycle}"
            );
        }
    }
}

const SRC: &str = "input cycle: u64\n\
    h := hash(cycle)\n\
    s := span_of(mod(h, 1000), mod(cycle, 7))\n\
    t := span_shift(s, 10)\n\
    n := span_len(t)\n\
    label := span_text(t)\n\
    doc := json_object(json_with(\"n\", n), json_with(\"label\", label))\n";

#[test]
fn extension_nodes_agree_between_interpreter_closures_and_hybrid() {
    let mut p1 = compile_polydat_to_assembler(SRC).unwrap();
    p1.set_jit_mode(polydat::JitMode::Off);
    let mut p1 = p1.compile().expect("P1");
    let mut p2 = compile_polydat_to_assembler(SRC)
        .unwrap()
        .compile_slots(polydat::Engine::Closures(polydat::Provenance::Raw))
        .unwrap_or_else(|_| panic!("the closure tier refused a program with extension nodes"));
    let mut hybrid = compile_polydat_to_assembler(SRC)
        .unwrap()
        .compile_slots(polydat::Engine::Native(polydat::Provenance::PushPull))
        .expect("hybrid");
    for cycle in 0..64u64 {
        p1.set_inputs(&[cycle]);
        let n = p1.pull_ref("n").as_u64();
        let label = p1.pull_ref("label").as_str().to_string();
        let doc = p1.pull_ref("doc").to_display_string();
        let Value::Ext(t) = p1.pull_ref("t").clone() else {
            panic!("t is an Ext wire")
        };
        let t = t.as_any().downcast_ref::<Span>().expect("a Span").clone();

        p2.eval_at(&[cycle]);
        assert_eq!(p2.get("n"), n, "cycle {cycle}: P2 n");
        assert_eq!(
            p2.get_value("label").as_str(),
            label,
            "cycle {cycle}: P2 label"
        );
        assert_eq!(
            p2.get_value("doc").to_display_string(),
            doc,
            "cycle {cycle}: P2 doc"
        );
        let Value::Ext(t2) = p2.get_value("t") else {
            panic!("P2 t is an Ext wire")
        };
        assert_eq!(
            t2.as_any().downcast_ref::<Span>(),
            Some(&t),
            "cycle {cycle}: P2 t"
        );

        hybrid.eval_at(&[cycle]);
        assert_eq!(hybrid.get("n"), n, "cycle {cycle}: hybrid n");
        assert_eq!(
            hybrid.get_value("label").as_str(),
            label,
            "cycle {cycle}: hybrid label"
        );
        assert_eq!(
            hybrid.get_value("doc").to_display_string(),
            doc,
            "cycle {cycle}: hybrid doc"
        );
        let Value::Ext(t3) = hybrid.get_value("t") else {
            panic!("hybrid t is an Ext wire")
        };
        assert_eq!(
            t3.as_any().downcast_ref::<Span>(),
            Some(&t),
            "cycle {cycle}: hybrid t"
        );
    }
}

/// An extension node runs as a slot call of its kit inside native
/// code (compiled_handles.md §6): the whole program is one segment on
/// the hybrid kernel and one function on pure native code, and the
/// extension value crosses nowhere as anything but the pair into its
/// producing step's scratch.
#[test]
fn extension_nodes_run_as_slot_calls_in_native_code() {
    // The engine builds in every configuration; what differs is how
    // much of it native code got, which is the plan and not the engine.
    let hybrid = compile_polydat_to_assembler(SRC)
        .unwrap()
        .compile_slots(polydat::Engine::Native(polydat::Provenance::PushPull))
        .expect("hybrid");
    // The per-node engine choice, through the trait every engine
    // answers rather than a tier-specific accessor.
    let plan = hybrid.plan();
    let (native, closures) = (plan.native_segments, plan.closure_steps);
    #[cfg(not(feature = "jit"))]
    {
        assert_eq!(native, 0, "nothing is native without the jit feature");
        assert!(closures >= 3, "the nodes are closure steps, got {closures}");
    }
    #[cfg(feature = "jit")]
    {
        assert_eq!(
            closures, 0,
            "every node has a kit, so none is a closure step"
        );
        assert!(
            native >= 1,
            "the program runs as native segments, got {native}"
        );
        let mut p1 = compile_polydat_to_assembler(SRC).unwrap();
        p1.set_jit_mode(polydat::JitMode::Off);
        let mut p1 = p1.compile().expect("P1");
        let mut pure = compile_polydat_to_assembler(SRC)
            .unwrap()
            .compile_slots(polydat::Engine::PureNative(polydat::Provenance::PushPull))
            .expect("pure native code calls the extension nodes' kits");
        for cycle in [0u64, 1, 1, 9] {
            p1.set_inputs(&[cycle]);
            pure.eval_at(&[cycle]);
            for name in ["n", "label", "doc"] {
                assert_eq!(
                    pure.get_value(name).to_display_string(),
                    p1.pull_ref(name).to_display_string(),
                    "cycle {cycle}: pure native `{name}`"
                );
            }
        }
    }
}

// ── Fallible construction and tuple returns on the closure tier ──

/// A fallible node runs its body once at construction and replays the
/// cached value; the closure kits write that value every run.
#[polydat::polydat_node(category = Math)]
fn fixed_seed(base: polydat::derive_support::Const<u64>) -> Result<u64, String> {
    if *base == 0 {
        Err("fixed_seed: base must be non-zero".into())
    } else {
        Ok(base.wrapping_mul(0x9E37_79B9_7F4A_7C15))
    }
}

#[polydat::polydat_node(category = String)]
fn fixed_label(prefix: polydat::derive_support::Const<&str>) -> Result<String, String> {
    if prefix.is_empty() {
        Err("fixed_label: empty prefix".into())
    } else {
        Ok(format!("{}-fixed", *prefix))
    }
}

#[polydat::polydat_node(category = Math, struct_name = FixedSpanNode)]
fn fixed_span(
    lo: polydat::derive_support::Const<u64>,
    hi: polydat::derive_support::Const<u64>,
) -> Result<Ext<Span>, String> {
    if *lo >= *hi {
        Err("fixed_span: empty".into())
    } else {
        Ok(Ext(Span { lo: *lo, hi: *hi }))
    }
}

#[polydat::polydat_node(category = Math)]
fn fixed_doc(
    n: polydat::derive_support::Const<u64>,
) -> Result<std::sync::Arc<serde_json::Value>, String> {
    Ok(std::sync::Arc::new(
        serde_json::json!({ "n": *n, "twice": *n * 2 }),
    ))
}

/// A tuple return with one element of every shape the handle kit
/// writes: a carrier, a string, an extension value, and JSON.
#[polydat::polydat_node(category = Math, output_names(len, text, moved, doc))]
fn span_parts(
    span: Ext<Span>,
    by: u64,
) -> (u64, String, Ext<Span>, std::sync::Arc<serde_json::Value>) {
    let moved = Span {
        lo: span.lo + by,
        hi: span.hi + by,
    };
    let doc = std::sync::Arc::new(serde_json::json!({ "lo": moved.lo, "hi": moved.hi }));
    (span.hi - span.lo, span.display(), Ext(moved), doc)
}

const SHAPES: &str = "input cycle: u64\n\
    h := hash(cycle)\n\
    seed := fixed_seed(7)\n\
    label := fixed_label(\"job\")\n\
    fs := fixed_span(10, 20)\n\
    fd := fixed_doc(3)\n\
    s := span_of(mod(h, 1000), mod(cycle, 7))\n\
    (len, text, moved, doc) := span_parts(s, mod(seed, 100))\n\
    tail := span_len(moved)\n\
    line := \"{label}/{len}/{text}/{tail}/{fs}/{fd}/{doc}\"\n";

#[test]
fn fallible_and_tuple_nodes_agree_between_interpreter_closures_and_hybrid() {
    let mut p1 = compile_polydat_to_assembler(SHAPES).unwrap();
    p1.set_jit_mode(polydat::JitMode::Off);
    let mut p1 = p1.compile().expect("P1");
    let mut p2 = compile_polydat_to_assembler(SHAPES)
        .unwrap()
        .compile_slots(polydat::Engine::Closures(polydat::Provenance::Raw))
        .unwrap_or_else(|e| panic!("the closure tier refused a fallible or tuple node: {e}"));
    let mut hybrid = compile_polydat_to_assembler(SHAPES)
        .unwrap()
        .compile_slots(polydat::Engine::Native(polydat::Provenance::PushPull))
        .expect("hybrid");
    let outputs = [
        "seed", "label", "fs", "fd", "len", "text", "moved", "doc", "tail", "line",
    ];
    for cycle in 0..64u64 {
        p1.set_inputs(&[cycle]);
        let want: Vec<(polydat::ast::PortType, String)> = outputs
            .iter()
            .map(|o| {
                let v = p1.pull_ref(o);
                (v.port_type(), v.to_display_string())
            })
            .collect();
        p2.eval_at(&[cycle]);
        for (i, o) in outputs.iter().enumerate() {
            let v = p2.get_value(o);
            assert_eq!(
                (v.port_type(), v.to_display_string()),
                want[i],
                "cycle {cycle}: P2 `{o}`"
            );
        }
        hybrid.eval_at(&[cycle]);
        for (i, o) in outputs.iter().enumerate() {
            let v = hybrid.get_value(o);
            assert_eq!(
                (v.port_type(), v.to_display_string()),
                want[i],
                "cycle {cycle}: hybrid `{o}`"
            );
        }
    }
    // The per-node engine choice, through the trait every engine
    // answers rather than a tier-specific accessor.
    let plan = hybrid.plan();
    let (native, closures) = (plan.native_segments, plan.closure_steps);
    #[cfg(feature = "jit")]
    assert!(
        native >= 1 && closures == 0,
        "the fallible and tuple nodes run as slot calls inside native segments, got \
         {native} native and {closures} closure steps"
    );
    #[cfg(not(feature = "jit"))]
    assert!(
        native == 0 && closures >= 5,
        "the fallible and tuple nodes run as closure steps, got {closures}"
    );
}

#[test]
fn a_failing_construction_is_a_compile_error_on_every_tier() {
    let src = "input cycle: u64\nseed := fixed_seed(0)\n";
    let err = compile_polydat_to_assembler(src)
        .err()
        .expect("construction fails at compile time");
    assert!(err.to_string().contains("base must be non-zero"), "{err}");
}

// ── Externs on every engine ──

/// A type the host defines, to carry through an extern.
#[derive(Debug, Clone, PartialEq)]
struct Region(String);

impl ReflectedValue for Region {
    fn type_name(&self) -> &str {
        "Region"
    }
    fn display(&self) -> String {
        self.0.clone()
    }
    fn clone_reflected(&self) -> Box<dyn ReflectedValue> {
        Box::new(self.clone())
    }
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

#[polydat::polydat_node(category = String)]
fn region_code(region: Ext<Region>, n: u64) -> String {
    format!("{}-{n}", (*region).0.to_uppercase())
}

/// Externs with defaults and externs the host sets, of every kind the
/// compiled engines carry: a carrier, a string, JSON, and an extension
/// value. Every engine seeds the defaults, takes a host value through
/// `set_input`, and agrees with the interpreter afterwards.
const EXTERNS: &str = "input cycle: u64\n\
    extern scale: u64 = 10\n\
    extern label: str = \"lbl\"\n\
    extern doc: json\n\
    extern region: ext\n\
    h := hash(cycle)\n\
    id := mod_wire(h, scale)\n\
    tag := str_concat(label, \"-\", id)\n\
    text := json_to_str(doc)\n\
    code := region_code(region, id)\n\
    line := \"{tag}/{text}/{code}\"\n";

fn host_values(doc_n: u64, region: &str) -> [(&'static str, Value); 4] {
    [
        ("scale", Value::U64(1000)),
        ("label", Value::Str("host".into())),
        (
            "doc",
            Value::Json(std::sync::Arc::new(serde_json::json!({ "n": doc_n }))),
        ),
        ("region", Value::Ext(Box::new(Region(region.to_string())))),
    ]
}

#[test]
fn externs_agree_between_interpreter_closures_hybrid_and_native() {
    let mut p1 = polydat::dsl::compile::compile_polydat(EXTERNS).expect("interpreter");
    let mut p2 = compile_polydat_to_assembler(EXTERNS)
        .unwrap()
        .compile_slots(polydat::Engine::Closures(polydat::Provenance::Raw))
        .unwrap_or_else(|_| panic!("the closure tier refused externs"));
    let mut p2pp = compile_polydat_to_assembler(EXTERNS)
        .unwrap()
        .compile_slots(polydat::Engine::Closures(polydat::Provenance::PushPull))
        .unwrap_or_else(|_| panic!("the push-pull closure tier refused externs"));
    let mut hybrid = compile_polydat_to_assembler(EXTERNS)
        .unwrap()
        .compile_slots(polydat::Engine::Native(polydat::Provenance::PushPull))
        .expect("hybrid");
    // `doc` and `region` have no default, so the host sets every extern
    // before the first run and again between rounds; the compiled
    // engines evaluate eagerly and refuse to start with an unset JSON
    // or extension extern.
    let read = ["id", "tag", "text", "code", "line"];
    for round in 0..3u64 {
        let (doc_n, region) = (round * 7, ["east", "west", "north"][round as usize]);
        for (name, value) in host_values(doc_n, region) {
            p1.set_input(name, value.clone()).expect("P1 set_input");
            p2.set_input(name, value.clone()).expect("P2 set_input");
            p2pp.set_input(name, value.clone())
                .expect("P2 push-pull set_input");
            hybrid.set_input(name, value).expect("hybrid set_input");
        }
        for cycle in [0u64, 1, 1, 2, 2, 0] {
            p1.set_inputs(&[cycle]);
            let want: Vec<(polydat::ast::PortType, String)> = read
                .iter()
                .map(|o| {
                    let v = p1.pull(o);
                    (v.port_type(), v.to_display_string())
                })
                .collect();
            p2.eval_at(&[cycle]);
            for (i, o) in read.iter().enumerate() {
                let v = p2.get_value(o);
                assert_eq!(
                    (v.port_type(), v.to_display_string()),
                    want[i],
                    "round {round} cycle {cycle}: P2 `{o}`"
                );
            }
            p2pp.eval_at(&[cycle]);
            for (i, o) in read.iter().enumerate() {
                let v = p2pp.get_value(o);
                assert_eq!(
                    (v.port_type(), v.to_display_string()),
                    want[i],
                    "round {round} cycle {cycle}: P2 push-pull `{o}`"
                );
            }
            hybrid.eval_at(&[cycle]);
            for (i, o) in read.iter().enumerate() {
                let v = hybrid.get_value(o);
                assert_eq!(
                    (v.port_type(), v.to_display_string()),
                    want[i],
                    "round {round} cycle {cycle}: hybrid `{o}`"
                );
            }
        }
    }
}

#[test]
fn an_extern_set_to_the_wrong_type_is_refused_by_name() {
    let mut p2 = compile_polydat_to_assembler(EXTERNS)
        .unwrap()
        .compile_slots(polydat::Engine::Closures(polydat::Provenance::Raw))
        .unwrap_or_else(|_| panic!("P2"));
    // The write rule refuses by variant, not by message text: the
    // structured error names the slot, what it wanted, and what it got.
    let err = p2
        .set_input("scale", Value::Str("ten".into()))
        .expect_err("a string is not a u64");
    assert_eq!(
        err,
        polydat::kernel::WriteError::TypeMismatch {
            slot: "scale".into(),
            expected: polydat::ast::PortType::U64,
            got: polydat::ast::PortType::Str,
        },
        "{err}"
    );
    let err = p2
        .set_input("nope", Value::U64(1))
        .expect_err("no such extern");
    match &err {
        polydat::kernel::WriteError::UnknownWire { key, known } => {
            assert_eq!(key, "nope");
            // The error carries what the caller could have meant.
            assert!(known.iter().any(|n| n == "scale"), "{known:?}");
        }
        other => panic!("expected an unknown-wire error, got {other:?}"),
    }
    assert_eq!(p2.externs().len(), 4);
}

/// Pure native code with externs. Carrier externs reach native code
/// through their slots; a string, JSON, or extension extern reaches it
/// as the pair into the value the state stores, and the nodes over
/// them run as slot calls inside the one native function
/// (compiled_handles.md §6). Every extern is set by the host between
/// runs.
#[cfg(feature = "jit")]
#[test]
fn externs_agree_between_interpreter_and_pure_native_code() {
    const SRC: &str = "input cycle: u64\n\
        extern scale: u64 = 10\n\
        extern offset: u64 = 3\n\
        h := hash(cycle)\n\
        id := mod_wire(h, scale)\n\
        n := u64_add(id, offset)\n\
        f := to_f64(n) / 2.0\n";
    let mut p1 = polydat::dsl::compile::compile_polydat(SRC).expect("interpreter");
    let mut p3 = compile_polydat_to_assembler(SRC)
        .unwrap()
        .compile_slots(polydat::Engine::PureNative(polydat::Provenance::PushPull))
        .expect("pure native code with carrier externs");
    let all = ["id", "n", "f"];
    for round in 0..3u64 {
        let host = [
            ("scale", Value::U64(100 + round)),
            ("offset", Value::U64(round * 7)),
        ];
        for (name, value) in host {
            p1.set_input(name, value.clone()).expect("P1 set_input");
            p3.set_input(name, value).expect("P3 set_input");
        }
        for cycle in [0u64, 1, 1, 2, 2, 0] {
            p1.set_inputs(&[cycle]);
            let want: Vec<(polydat::ast::PortType, String)> = all
                .iter()
                .map(|o| {
                    let v = p1.pull(o);
                    (v.port_type(), v.to_display_string())
                })
                .collect();
            p3.eval_at(&[cycle]);
            for (i, o) in all.iter().enumerate() {
                let v = p3.get_value(o);
                assert_eq!(
                    (v.port_type(), v.to_display_string()),
                    want[i],
                    "round {round} cycle {cycle}: P3 `{o}`"
                );
            }
        }
    }
    // Every kind of extern, read through by-reference nodes.
    let mut p1 = polydat::dsl::compile::compile_polydat(EXTERNS).expect("interpreter");
    let mut p3 = compile_polydat_to_assembler(EXTERNS)
        .unwrap()
        .compile_slots(polydat::Engine::PureNative(polydat::Provenance::PushPull))
        .expect("pure native code with string, JSON, and extension externs");
    let read = ["id", "tag", "text", "code", "line"];
    for round in 0..3u64 {
        let (doc_n, region) = (round * 7, ["east", "west", "north"][round as usize]);
        for (name, value) in host_values(doc_n, region) {
            p1.set_input(name, value.clone()).expect("P1 set_input");
            p3.set_input(name, value).expect("P3 set_input");
        }
        for cycle in [0u64, 1, 1, 2, 2, 0] {
            p1.set_inputs(&[cycle]);
            let want: Vec<(polydat::ast::PortType, String)> = read
                .iter()
                .map(|o| {
                    let v = p1.pull(o);
                    (v.port_type(), v.to_display_string())
                })
                .collect();
            p3.eval_at(&[cycle]);
            for (i, o) in read.iter().enumerate() {
                let v = p3.get_value(o);
                assert_eq!(
                    (v.port_type(), v.to_display_string()),
                    want[i],
                    "round {round} cycle {cycle}: pure native `{o}`"
                );
            }
        }
    }
}

/// A numeric vector through a *polymorphic* node, on every engine.
///
/// `Value`-typed nodes write their output through `write_poly`, which
/// only has a `Value` in hand and must find the slot form from the
/// port type. It knew the carriers and the by-reference singles —
/// `Str`, `Bytes`, `Json`, `Ext`, `Handle` — and not the numeric
/// vectors, though they are `Ref2` like the rest and the typed write
/// path always carried them. So a vector reaching a polymorphic node's
/// output compiled clean and panicked at the first pull, where the
/// interpreter carried it.
///
/// The empty vector is deliberately not the case under test: it passed
/// on every engine while the non-empty one did not, because filling the
/// entry is what moves the buffer the pair must be republished from.
#[test]
fn a_vector_rides_a_polymorphic_node_on_every_engine() {
    use polydat::dsl::compile::compile_polydat_with;
    use polydat::{Engine, JitMode, KernelError, Provenance};

    let src = "input cycle: u64\n\
               v := str_to_vec_i32(\"[11,22,33]\")\n\
               d := default_or(v, v)\n\
               n := vec_len_i32(d)\n\
               m := vec_max_i32(d)\n";

    let mut engines = vec![
        Engine::Interpreter(JitMode::Off),
        Engine::Interpreter(JitMode::Auto),
        Engine::Closures(Provenance::Raw),
        Engine::Closures(Provenance::Auto),
    ];
    if cfg!(feature = "jit") {
        engines.push(Engine::Native(Provenance::Raw));
        engines.push(Engine::PureNative(Provenance::Auto));
    }

    for engine in engines {
        let mut k = match compile_polydat_with(src, engine) {
            Ok(k) => k,
            Err(KernelError::Refused { .. }) => continue,
            Err(e) => panic!("{engine}: {e}"),
        };
        k.set_inputs(&[7]);
        // The vector itself survives the round trip, and the typed
        // readers downstream see the same three elements.
        assert_eq!(k.pull("n"), polydat::ast::Value::U64(3), "{engine}: length");
        assert_eq!(k.pull("m"), polydat::ast::Value::I64(33), "{engine}: max");
        match k.pull("d") {
            polydat::ast::Value::VecI32(s) => {
                assert_eq!(s.as_slice(), &[11, 22, 33], "{engine}: elements");
            }
            other => panic!("{engine}: expected a VecI32, got {other:?}"),
        }
    }
}

/// Every port type has a consistent slot form — checked over the type
/// list itself, not over the types whoever wrote the test remembered.
///
/// A value↔slot writer that misses a type fails only when a program
/// happens to use that type. Two things make coverage structural
/// instead:
///
/// - `write_poly` dispatches on [`SlotColor`], of which there are three
///   and the match is exhaustive, so a new type cannot fall through to
///   a panic — it lands in the arm its colour names.
/// - `PortType::ALL` is the whole list, kept whole by an exhaustive
///   match (`every_variant_is_listed`) that fails to compile when a
///   variant is added without being listed. Anything that must hold for
///   all types walks it.
///
/// What this asserts is the invariant those two rest on: a scratch
/// entry exists for exactly the by-reference colour, and the slot width
/// follows the colour. A `Ref2` type with no scratch element would
/// reach `write_poly`'s `Ref2` arm with no entry to fill, and this test
/// fails for it first.
#[test]
fn every_port_type_has_a_consistent_slot_form() {
    use polydat::ast::{PortType, SlotColor, SlotShape};

    assert_eq!(
        PortType::ALL.len(),
        35,
        "a port type was added or removed; check the writers that map a \
         value to slots still cover it, then update this count"
    );

    for &ty in PortType::ALL {
        assert!(
            ty.every_variant_is_listed(),
            "{ty:?} is not in PortType::ALL"
        );

        let color = ty.slot_color();
        let has_entry = ty.scratch_elem().is_some();
        assert_eq!(
            has_entry,
            color == SlotColor::Ref2,
            "{ty:?} is {color:?} but {} a scratch element; a by-reference \
             value needs an entry to be written into, and nothing else has one",
            if has_entry { "has" } else { "has no" }
        );

        let expected_width = if color == SlotColor::Imm1 { 1 } else { 2 };
        assert_eq!(ty.slot_width(), expected_width, "{ty:?} width vs {color:?}");
    }
}