polydat 0.6.0

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
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
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Type-adapter-transform fuzz tests.
//!
//! Two test strategies share the same goal: surface cases where the
//! Polydat compiler's auto-inserted edge adapters are wrong, missing, or
//! silently lossy.
//!
//! 1. **Adapter-table sweep** ([`adapter_table_is_consistent`]).
//!    Curated producer/consumer pairs for each [`PortType`], run
//!    through the compiler, and the result is checked against an
//!    in-test mirror of [`polydat::compile::assembly::auto_adapter`]. If the
//!    compiler disagrees with the expected table — either by
//!    rejecting a pair we think should bridge, or by silently
//!    accepting a pair we think should error — the test fails with
//!    the full pair and source so the regression is easy to
//!    reproduce.
//!
//! 2. **Random-DAG fuzz** ([`random_dags_compile_or_fail_cleanly`]).
//!    A tiny deterministic RNG picks native registry entries and
//!    wires their outputs together irrespective of type compatibility.
//!    Each generated module is fed to `compile_polydat_interpreter_with_log`; the
//!    compile must never panic, every error string must be non-empty
//!    and free of panic-style wording, and every Ok result whose
//!    event log mentions a `TypeAdapterInserted` must refer to a
//!    pair we also consider legal. The FUZZ_SEED env var seeds the
//!    RNG; FUZZ_ITERATIONS controls iteration count.
//!
//! 3. **Superfuzz** ([`superfuzz_sampler`], ignored). It enumerates
//!    the generator's dimensions instead of drawing them: the anchor
//!    node, every fuzzable registry signature; the module size, 3 to
//!    10 bindings with the anchor last; the anchor's optional
//!    parameters, all or none; its extra variadic repetitions, 0 to 5
//!    taken modulo each arity's own range; and its wire arguments,
//!    from `cycle` or from earlier bindings. The bindings before the
//!    anchor are random from the combination's seed. Each module goes
//!    through invariants 1 to 3 and, on every combination, the engine
//!    sweep of invariants 4 and 5.
//!
//!    The combinations run in the stratified order of
//!    `common::superfuzz`, which reaches every value of every
//!    dimension, module sizes included, within the first round, as
//!    many combinations as there are fuzzable nodes. The run stops at
//!    1000 combinations or 60 seconds, whichever comes first;
//!    `SUPERFUZZ_MAX_COMBINATIONS` and `SUPERFUZZ_MAX_SECONDS` change
//!    the limits (0 keeps the default, a large number lifts the
//!    limit). `SUPERFUZZ_SEEDS` is the number of seeds run per
//!    combination (default 1), `FUZZ_SEED` is the base seed, and
//!    `FUZZ_ENGINE_SWEEP` is the stride over combinations of the
//!    engine sweep (default 1; 0 turns it off).

use polydat::ast::{PortType, SlotType};
use polydat::dsl::compile::{
    compile_polydat_interpreter, compile_polydat_interpreter_with_log, compile_polydat_with,
};
use polydat::dsl::events::{CompileEvent, CompileEventLog};
use polydat::dsl::registry::{self, FuncSig};

// ─── Expected-adapter table ───────────────────────────────────────
//
// The compiler's own `auto_adapter` is the table. A hand mirror of it
// here would fall behind whenever the generator reaches a type pair the
// mirror lacks, such as the class-A `U8→Bytes`. Review of the table is `adapter_catalog_invariants::doc_matrix_matches_catalog`'s
// job: a catalog change fails CI until type_system.md §3 shows it.

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Adapt {
    /// Source and sink are identical — no adapter needed.
    Identity,
    /// Compiler should insert an auto-adapter and compile OK.
    Inserted,
    /// No known-safe coercion; compiler should reject with `type mismatch`.
    None,
}

fn expected_adapt(src: PortType, dst: PortType) -> Adapt {
    if src == dst {
        Adapt::Identity
    } else if polydat::compile::assembly::auto_adapter(src, dst).is_some() {
        Adapt::Inserted
    } else {
        Adapt::None
    }
}

// ─── Adapter-table sweep ──────────────────────────────────────────
//
// Producers emit a specific [`PortType`] from the cycle input.
// Consumers read a specific wire type and produce any output. Each
// recipe is a pair of Polydat snippets chained via the `source` and
// `sink` bindings; the test assembles them with the cycle coordinate
// and compiles.

struct TypeRecipe {
    /// Polydat expression that produces [`src`] from scratch (may reference
    /// `cycle`).
    produce: &'static str,
    src: PortType,
}

struct SinkRecipe {
    /// Polydat expression template where `{}` is substituted with the
    /// source binding name. Produces some output (thrown away); its
    /// *wire-input* type is [`dst`].
    consume_tmpl: &'static str,
    dst: PortType,
}

/// Curated producer set. One entry per [`PortType`] we can reliably
/// synthesize from `cycle`. Missing variants (Bytes, Ext, narrow
/// ints) simply get skipped below.
fn producers() -> Vec<TypeRecipe> {
    use PortType::*;
    vec![
        TypeRecipe {
            produce: "cycle",
            src: U64,
        },
        TypeRecipe {
            produce: "to_f64(cycle)",
            src: F64,
        },
        TypeRecipe {
            produce: "format_u64(cycle, 10)",
            src: Str,
        },
        TypeRecipe {
            produce: "to_json(cycle)",
            src: Json,
        },
    ]
}

/// Curated consumer set. `{}` in the template is replaced with the
/// producer's binding name before compile.
fn consumers() -> Vec<SinkRecipe> {
    use PortType::*;
    vec![
        SinkRecipe {
            consume_tmpl: "add({}, 1)",
            dst: U64,
        },
        SinkRecipe {
            consume_tmpl: "clamp_f64({}, 0.0, 1.0)",
            dst: F64,
        },
        SinkRecipe {
            consume_tmpl: "json_to_str({})",
            dst: Json,
        },
    ]
}

#[test]
fn adapter_table_is_consistent() {
    let mut mismatches: Vec<String> = Vec::new();
    for p in producers() {
        for c in consumers() {
            let source = format!(
                "input cycle: u64\n\
                 src_val := {}\n\
                 sink_val := {}\n",
                p.produce,
                c.consume_tmpl.replace("{}", "src_val"),
            );
            let expected = expected_adapt(p.src, c.dst);
            let mut log = CompileEventLog::new();
            let result =
                compile_polydat_interpreter_with_log(&source, &mut log).map_err(|e| e.to_string());
            let observed = classify_result(&result, &log);
            if !adapt_agrees(expected, observed) {
                mismatches.push(format!(
                    "pair {:?} -> {:?}\n\
                     expected {expected:?}, observed {observed:?}\n\
                     result: {}\n\
                     source:\n{source}",
                    p.src,
                    c.dst,
                    match &result {
                        Ok(_) => "<compiled>".to_string(),
                        Err(e) => e.clone(),
                    },
                ));
            }
        }
    }
    assert!(
        mismatches.is_empty(),
        "adapter-table disagreements:\n\n{}",
        mismatches.join("\n---\n")
    );
}

/// Classify a compile outcome into the same vocabulary as `Adapt`.
///
/// - Ok with no TypeAdapterInserted event → `Identity`
/// - Ok with at least one TypeAdapterInserted event → `Inserted`
/// - Err containing `"type mismatch"` → `None`
/// - Err with anything else → `Inserted` placeholder so the test
///   surfaces a `not-agrees` diagnostic rather than treating an
///   unrelated error as a success.
fn classify_result<T>(result: &Result<T, String>, log: &CompileEventLog) -> Adapt {
    match result {
        Ok(_) => {
            let has_adapter = log.events().iter().any(|e| {
                matches!(
                    e,
                    CompileEvent::TypeAdapterInserted { .. } | CompileEvent::TypeWidening { .. }
                )
            });
            if has_adapter {
                Adapt::Inserted
            } else {
                Adapt::Identity
            }
        }
        Err(msg) => {
            if msg.contains("type mismatch") {
                Adapt::None
            } else {
                // Unrelated error — return a sentinel the caller will
                // flag. Reusing `Inserted` here would make a parse
                // error look like an Ok path; return `None` so the
                // diagnostic shows "expected Inserted, got None" and
                // the actual error string is visible in the output.
                Adapt::None
            }
        }
    }
}

fn adapt_agrees(expected: Adapt, observed: Adapt) -> bool {
    match (expected, observed) {
        // Identity is a specific kind of pass — observing it is
        // also fine when we expected an `Inserted` for a same-type
        // pair, which shouldn't happen, but the sweep only calls
        // this function for distinct pairs drawn from the curated
        // producer/consumer sets.
        (Adapt::Identity, Adapt::Identity) => true,
        (Adapt::Inserted, Adapt::Inserted) => true,
        (Adapt::None, Adapt::None) => true,
        _ => false,
    }
}

// ─── Random-DAG fuzz ──────────────────────────────────────────────

/// Simple splitmix64 RNG. Deterministic, zero-dep, sufficient for
/// test inputs — we don't need cryptographic quality.
struct Rng(u64);
impl Rng {
    fn new(seed: u64) -> Self {
        Rng(seed.wrapping_mul(0x9E37_79B9_7F4A_7C15).wrapping_add(1))
    }
    fn next_u64(&mut self) -> u64 {
        self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
        let mut z = self.0;
        z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
        z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
        z ^ (z >> 31)
    }
    fn range(&mut self, n: usize) -> usize {
        if n == 0 {
            return 0;
        }
        (self.next_u64() as usize) % n
    }
    fn f64(&mut self) -> f64 {
        // Integer range chosen so consts look like the kind of
        // values real workloads would pass.
        (self.next_u64() % 1000) as f64 / 10.0
    }
}

/// Nodes we can safely instantiate from the fuzzer without needing
/// specific runtime fixtures. Filters out:
///
/// - anything variadic (generator doesn't model group arity yet);
/// - anything with a `Vec<..>` constant (those need bracket-literal
///   array syntax);
/// - `dynamic-output` entries (`outputs == 0`) which need coordinate
///   resolution past what the fuzzer provides;
/// - context nodes that require runtime fixtures (metric queries,
///   control sets, fiber context) that aren't present in a unit test.
///
/// The `__` adapter nodes are drawn like any other, since every real
/// program runs these conversions and native code carries a second
/// copy of them; `fuzz_conversions` fuzzes the table directly, and
/// here they turn up in the middle of random programs as well.
fn fuzzable_sigs() -> Vec<FuncSig> {
    let mut sigs = registry::registry()
        .into_iter()
        // A dynamic-output node (`outputs == 0`) decides its own count
        // from its arguments, which the generator cannot know; every
        // fixed count, one or many, it can bind names for.
        .filter(|s| s.outputs >= 1)
        // No fuzzable signature actually declares a `ConstVec*`
        // slot type today; the filter is kept for forward-
        // compatibility — the generator below would have to
        // synthesize array literals (`[1, 2, 3]`) for those.
        .filter(|s| {
            !s.params.iter().any(|p| {
                matches!(
                    p.slot_type,
                    SlotType::ConstVecU64 | SlotType::ConstVecF64 | SlotType::ConstVec
                )
            })
        })
        // One name, and it earns the exclusion by *writing*:
        // `fft_analyze` emits JSONL to the path its string arg names,
        // so random filenames would litter the working directory. A
        // node the fuzzer can only observe by the files it leaves
        // behind is not one a fuzzer should call.
        //
        // The `csv_*` / `jsonl_*` nodes are fuzzed: a missing file is
        // `csv_row: construction failed: ... cannot find the file`,
        // a sentence and not a panic, which is what invariant 2 asks
        // of any error.
        .filter(|s| s.name != "fft_analyze")
        .collect::<Vec<_>>();
    // In name order. The registry comes in link order, which differs by
    // platform, so a seed drew different programs on Linux and Windows:
    // CI's failure on seed `0xdeadbeef` did not reproduce from its own
    // reproduction line on another machine. Sorted, a seed is one
    // sequence of programs for a given feature set, wherever it runs.
    sigs.sort_by_key(|s| s.name);
    sigs
}

/// Build a random module that declares `n_bindings` bindings in
/// sequence. Each binding calls one random function from `sigs`,
/// picking each wire arg as either `cycle` or an already-defined
/// binding, and each const arg as a random literal of the right
/// kind. No type-compatibility check is applied, so ~most generated
/// modules will exercise either the adapter insertion path or the
/// type-mismatch error path.
///
/// For `VariadicWires` sigs, the generator picks a random arity
/// in `[min_wires, min_wires + 5]` and emits that many wire args.
/// Other variadic shapes are filtered out at `fuzzable_sigs` time
/// because their positional invariants (pairs, groups) can't be
/// satisfied by random independent draws.
fn generate_module(rng: &mut Rng, sigs: &[FuncSig], n_bindings: usize) -> String {
    let mut out = String::from("input cycle: u64\n");
    let mut defined: Vec<String> = Vec::new();
    for i in 0..n_bindings {
        let sig = &sigs[rng.range(sigs.len())];
        out.push_str(&binding(rng, sig, i, &mut defined, None));
    }
    out
}

/// The superfuzz's fixed choices for its anchor binding.
#[derive(Clone, Copy, Debug)]
struct AnchorPlan {
    /// Every optional parameter, or none of them.
    optionals: bool,
    /// Extra variadic repetitions, `0..VARIADIC_EXTRA`, taken modulo
    /// each arity's own range (wires 0..=5, constants 0..=3, groups
    /// 0..=2).
    extra: usize,
    /// Wire arguments from earlier bindings, or all from `cycle`.
    wires_from_bindings: bool,
}

/// The widest range of extra variadic repetitions the generator draws.
const VARIADIC_EXTRA: usize = 6;
/// The fewest and most bindings in a generated module.
const MIN_BINDINGS: usize = 3;
const MAX_BINDINGS: usize = 10;

/// A module of `n_bindings - 1` random bindings and then one call of
/// `anchor` under `plan`.
fn generate_anchored_module(
    rng: &mut Rng,
    sigs: &[FuncSig],
    anchor: &FuncSig,
    n_bindings: usize,
    plan: AnchorPlan,
) -> String {
    let mut out = String::from("input cycle: u64\n");
    let mut defined: Vec<String> = Vec::new();
    for i in 0..n_bindings - 1 {
        let sig = &sigs[rng.range(sigs.len())];
        out.push_str(&binding(rng, sig, i, &mut defined, None));
    }
    out.push_str(&binding(
        rng,
        anchor,
        n_bindings - 1,
        &mut defined,
        Some(plan),
    ));
    out
}

/// One binding line `b{i} := sig(...)`, its wire arguments drawn from
/// `cycle` and `defined`, and the names it binds appended to
/// `defined`. A `plan` fixes the optional parameters, the variadic
/// extras, and the wire sources; `None` draws them.
fn binding(
    rng: &mut Rng,
    sig: &FuncSig,
    i: usize,
    defined: &mut Vec<String>,
    plan: Option<AnchorPlan>,
) -> String {
    let name = format!("b{i}");
    let mut args: Vec<String> = Vec::new();

    let pick_wire = |rng: &mut Rng, defined: &[String]| -> String {
        let from_cycle = match plan {
            Some(p) => !p.wires_from_bindings || defined.is_empty(),
            None => defined.is_empty() || rng.range(3) == 0,
        };
        if from_cycle {
            "cycle".to_string()
        } else {
            defined[rng.range(defined.len())].clone()
        }
    };
    let materialize =
        |rng: &mut Rng, p: &polydat::dsl::registry::ParamSpec, defined: &[String]| -> String {
            match p.slot_type {
                SlotType::Wire => pick_wire(rng, defined),
                SlotType::ConstU64 => format!("{}", rng.next_u64() % 100),
                SlotType::ConstF64 => format!("{:.2}", rng.f64()),
                SlotType::ConstStr => format!("\"s{}\"", rng.range(100)),
                SlotType::ConstVecU64 | SlotType::ConstVecF64 | SlotType::ConstVec => {
                    unreachable!()
                }
            }
        };

    // Fill the declared params (skip optional ones at random).
    let chosen: Vec<&_> = sig
        .params
        .iter()
        .filter(|p| {
            p.required
                || match plan {
                    Some(pl) => pl.optionals,
                    None => rng.range(2) == 0,
                }
        })
        .collect();
    for param in chosen {
        args.push(materialize(rng, param, defined));
    }

    // For `VariadicWires`, top up with a random number of
    // additional wire args. The trailing wire param shape is
    // declared once in `params` — we just emit more of the
    // same wire type past the fixed positions.
    match sig.arity {
        registry::Arity::VariadicWires { min_wires } => {
            // 0..=5 extra wires.
            let extra = plan.map_or_else(|| rng.range(6), |p| p.extra % 6);
            let total_wires_needed = min_wires.saturating_sub(args.len()) + extra;
            for _ in 0..total_wires_needed {
                args.push(pick_wire(rng, defined));
            }
        }
        // Trailing constants repeat. The shape is what the
        // generator owes — a count at or above the minimum, of the
        // trailing const's own kind. Whether the *values* mean
        // anything to the node is the node's to say, and saying it
        // in a sentence rather than a panic is invariant 2.
        registry::Arity::VariadicConsts { min_consts } => {
            let trailing = sig
                .params
                .iter()
                .rev()
                .find(|p| p.slot_type != SlotType::Wire);
            if let Some(p) = trailing {
                let extra = plan.map_or_else(|| rng.range(4), |p| p.extra % 4);
                for _ in 0..(min_consts.saturating_sub(1) + extra) {
                    args.push(materialize(rng, p, defined));
                }
            }
        }
        // A repeating group of slot types, emitted in the declared
        // order so each repetition is positionally well formed.
        registry::Arity::VariadicGroup { group, min_repeats } => {
            let repeats = min_repeats + plan.map_or_else(|| rng.range(3), |p| p.extra % 3);
            for _ in 0..repeats {
                for slot in group {
                    let p = sig
                        .params
                        .iter()
                        .find(|p| p.slot_type == *slot)
                        .unwrap_or(&sig.params[0]);
                    args.push(materialize(rng, p, defined));
                }
            }
        }
        registry::Arity::Fixed => {}
    }

    // A node with more than one output binds a name per output.
    // Dynamic-output nodes (`outputs == 0`, the count following
    // the arguments) stay out: how many names to write is the
    // node's own rule, and the generator does not know it.
    let targets = if sig.outputs > 1 {
        let names: Vec<String> = (0..sig.outputs).map(|k| format!("{name}_{k}")).collect();
        let line = format!("({})", names.join(", "));
        defined.extend(names);
        line
    } else {
        defined.push(name.clone());
        name
    };

    format!("{targets} := {}({})\n", sig.name, args.join(", "))
}

/// One fuzz pass: `iterations` random modules drawn from `seed`.
/// Returns human-readable invariant violations (empty = clean),
/// each carrying the seed and a reproduction line. Shared by the
/// per-commit sample test and the manual superfuzz sweep.
///
/// NOTE the draw pool is the REGISTRY, so the same seed explores
/// different programs per feature set — `cargo test --workspace`
/// (feature unification, largest registry) is a strictly stronger
/// surface than `cargo test -p polydat`.
/// How often the engine sweep runs, as a stride over iterations.
/// `FUZZ_ENGINE_SWEEP=0` disables it, `1` sweeps every module.
fn engine_sweep_stride(default: usize) -> usize {
    std::env::var("FUZZ_ENGINE_SWEEP")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(default)
}

/// Every engine a build can name, the interpreter first so it is the
/// oracle the rest are compared against.
fn sweep_engines() -> Vec<polydat::Engine> {
    use polydat::{Engine, JitMode, Provenance};
    let mut all = vec![
        // The oracle: no cones, so every node runs its own body.
        Engine::Interpreter(JitMode::Off),
        // Cones on is a *different* engine for this purpose — a fused
        // cone runs native code for nodes the interpreter would
        // otherwise run itself, where a lowering can skip a check its
        // node's body makes.
        Engine::Interpreter(JitMode::Auto),
        Engine::Closures(Provenance::Raw),
        Engine::Closures(Provenance::Auto),
    ];
    if cfg!(feature = "jit") {
        all.push(Engine::Native(Provenance::Raw));
        all.push(Engine::Native(Provenance::Auto));
        all.push(Engine::PureNative(Provenance::Auto));
    }
    all
}

/// Drive one cycle and read every output, catching a panic the way the
/// compile path is caught: a garbage program is expected to fail at
/// evaluation, and what matters is that it fails the same way on every
/// engine rather than only on some.
fn drive_once(kernel: &mut dyn polydat::Kernel) -> Result<Vec<polydat::ast::Value>, String> {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        kernel.set_inputs(&[7]);
        let names = kernel.output_names();
        names.iter().map(|n| kernel.pull(n)).collect::<Vec<_>>()
    }))
    .map_err(|p| {
        p.downcast_ref::<String>()
            .cloned()
            .or_else(|| p.downcast_ref::<&str>().map(|s| (*s).to_string()))
            .unwrap_or_else(|| "<non-string panic>".to_string())
    })
}

/// Whether two reads of the same program agree.
///
/// `==` first, which is the answer for everything that has one. A
/// generated program reaches `asin(7)` soon enough, and `NaN != NaN`,
/// so a float that is *equally* undefined on two engines would read as
/// a disagreement forever; falling back to the rendering makes two
/// `NaN`s agree without making anything else agree that should not.
/// `-0.0` and `0.0` still pass on the fast path, as `==` says they do.
fn values_agree(a: &[polydat::ast::Value], b: &[polydat::ast::Value]) -> bool {
    a == b || format!("{a:?}") == format!("{b:?}")
}

/// Invariants 4 and 5 — the differential half.
///
/// The generator above is engine-blind: it produces programs the
/// interpreter compiles, and asks nothing of the tiers a host actually
/// runs on. This fuzzer covers the compiled-only mechanisms — the
/// native lowerings, the kits, the `Ref2` scratch, segment fusion —
/// where a helper such as `jit_shuffle` carries its own copy of a node
/// body and can fail where the node does not.
///
/// Two invariants, both stated against the interpreter as oracle:
///
/// - **I4.** A program the interpreter compiled either compiles on
///   every other engine or is *refused* there. An engine may decline a
///   program ([engines.md](../docs/design/engines.md) §8 names the
///   refusals); what it may not do is fail some other way, or fail with
///   a message that reads as a crash.
/// - **I5.** When the program is deterministic and compiled everywhere,
///   one cycle reads the same on every engine — values, or the same
///   failure. Nondeterministic programs are skipped rather than
///   compared, since disagreeing is what they are for.
fn engine_sweep_failures(source: &str) -> Vec<String> {
    use polydat::KernelError;
    let mut out = Vec::new();

    // Only a deterministic program can be compared by value. `random`,
    // a clock or a counter is meant to differ. Asking the interpreter's
    // concrete kernel is the one thing only it can answer, and the
    // documented reason to hold a `PolydatKernel` rather than a
    // `dyn Kernel`.
    let deterministic = match compile_polydat_interpreter(source) {
        Ok(k) => k.program().is_deterministic(),
        // The interpreter did not accept it; invariants 1 and 2 already
        // judged that, and there is nothing to compare against.
        Err(_) => return out,
    };
    // The oracle is the *first* engine of the sweep, so that whatever
    // the list holds is what the rest are measured against. Taking it
    // from a different compile than the list names is how cones-on went
    // uncompared while being the reference.
    let mut reference = match compile_polydat_with(source, sweep_engines()[0]) {
        Ok(k) => k,
        Err(_) => return out,
    };
    let want = drive_once(reference.as_mut());

    for engine in sweep_engines().into_iter().skip(1) {
        let mut kernel = match compile_polydat_with(source, engine) {
            Ok(k) => k,
            Err(KernelError::Refused { .. }) => continue,
            Err(e) => {
                let msg = e.to_string();
                let cryptic = msg.is_empty()
                    || msg.to_lowercase().contains("panic")
                    || msg.to_lowercase().contains("index out of bounds")
                    || msg.to_lowercase().contains("unreachable");
                if cryptic {
                    out.push(format!(
                        "I4: {engine} failed a program the interpreter compiled, and not \
                         as a refusal:\n  error: {msg}"
                    ));
                }
                continue;
            }
        };
        if !deterministic {
            continue;
        }
        let got = drive_once(kernel.as_mut());
        match (&want, &got) {
            (Ok(a), Ok(b)) if values_agree(a, b) => {}
            (Err(_), Err(_)) => {}
            (a, b) => out.push(format!(
                "I5: {engine} disagrees with the interpreter on a deterministic \
                 program:\n  interpreter: {a:?}\n  {engine}: {b:?}"
            )),
        }
    }
    out
}

fn run_fuzz_pass(seed: u64, iterations: usize, sweep_stride: usize) -> Vec<String> {
    // Per-seed failure cap: a systematic defect (e.g. one node
    // panicking on every draw) floods the report without adding
    // signal; eight distinct repros per seed is plenty.
    const MAX_FAILURES_PER_SEED: usize = 8;

    let sigs = fuzzable_sigs();
    assert!(
        !sigs.is_empty(),
        "no fuzzable signatures found — registry wiring broken?"
    );

    let mut rng = Rng::new(seed);
    let mut failures: Vec<String> = Vec::new();

    for i in 0..iterations {
        if failures.len() >= MAX_FAILURES_PER_SEED {
            failures.push(format!(
                "[seed {seed:#x}] … stopping this seed after {MAX_FAILURES_PER_SEED} failures"
            ));
            break;
        }
        let n = MIN_BINDINGS + rng.range(MAX_BINDINGS - MIN_BINDINGS + 1);
        let source = generate_module(&mut rng, &sigs, n);
        let tag = format!("[seed {seed:#x}] iteration {i}");
        let repro = format!(
            "reproduce: FUZZ_SEED={seed} FUZZ_ITERATIONS={} cargo test --workspace \
             --test suite fuzz_type_adapters::random_dags",
            i + 1
        );
        let sweep = sweep_stride != 0 && i % sweep_stride == 0;
        failures.extend(check_module(&source, sweep, &tag, &repro));
    }
    failures
}

/// Invariants 1 to 5 over one generated module. `sweep` runs the
/// engine sweep (invariants 4 and 5). Each failure starts with `tag`
/// and ends with `repro`.
fn check_module(source: &str, sweep: bool, tag: &str, repro: &str) -> Vec<String> {
    let mut failures: Vec<String> = Vec::new();
    let mut log = CompileEventLog::new();
    let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        compile_polydat_interpreter_with_log(source, &mut log)
    }));

    // Invariant 1: compiler never panics on any input. A panic
    // here is always a bug in the compiler — even when the input
    // is bananas, the error path should be a returned `Err`, not
    // a process-level abort.
    let result = match result {
        Ok(r) => r,
        Err(panic) => {
            failures.push(format!(
                "{tag}: the compiler panicked:\n  source:\n{source}\n  \
                     panic: {:?}\n  {}",
                panic
                    .downcast_ref::<&str>()
                    .copied()
                    .or_else(|| panic.downcast_ref::<String>().map(|s| s.as_str()))
                    .unwrap_or("<non-string panic>"),
                repro,
            ));
            return failures;
        }
    };

    match result {
        Err(msg) => {
            // Invariant 2: every error is either a recognised
            // structural diagnostic (type mismatch, bad
            // constant, undeclared reference, unknown function,
            // variadic-arity issue, …) or a well-formed
            // sentence. We're not prescribing *which* error
            // fires — the fuzzer routinely builds garbage —
            // only that the compiler classified it rather than
            // leaking panics or raw backtraces. A structured
            // `bad constant …` message proves the opt-in
            // assembly-time validator of const-constraint
            // metadata rejected the literal
            // before the node's constructor saw it.
            if msg.to_string().is_empty()
                || msg.to_string().to_lowercase().contains("panic")
                || msg
                    .to_string()
                    .to_lowercase()
                    .contains("index out of bounds")
                || msg.to_string().to_lowercase().contains("unreachable")
            {
                failures.push(format!(
                    "{tag} produced a cryptic error message.\n  \
                         error: {msg}\n  source:\n{source}\n  {repro}"
                ));
            }
        }
        Ok(_) => {
            // Invariants 4 and 5: the same program on every engine.
            // Sampled — a sweep compiles the module five more
            // times, twice through Cranelift, so running it on
            // every iteration would cost more than the generator
            // is worth. `FUZZ_ENGINE_SWEEP` is the stride; 0 turns
            // it off, 1 sweeps everything, and the superfuzz sets
            // it to 1 because that is the run that can afford it.
            if sweep {
                for detail in engine_sweep_failures(source) {
                    failures.push(format!("{tag}: {detail}\n  source:\n{source}\n  {repro}"));
                }
            }

            // Invariant 3: every adapter the compiler auto-inserts
            // must be one we know about. Anything else is a rogue
            // entry — probably a new adapter added to the
            // compiler without an entry in this test's mirror.
            for e in log.events() {
                if let CompileEvent::TypeAdapterInserted { adapter, .. } = e
                    && !adapter_label_is_known(adapter)
                {
                    failures.push(format!(
                        "{tag} inserted an unrecognised \
                                 adapter '{adapter}'.\n\
                                 Update `expected_adapt`/`adapter_label_is_known` and the \
                                 compiler's\n`auto_adapter` table together.\n  \
                                 source:\n{source}\n  {repro}"
                    ));
                }
            }
        }
    }
    failures
}

#[test]
fn random_dags_compile_or_fail_cleanly() {
    let seed: u64 = std::env::var("FUZZ_SEED")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(0xDEAD_BEEFu64);
    let iterations: usize = std::env::var("FUZZ_ITERATIONS")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(500);
    // Sampled sweep: the per-commit run pays for one module in eight
    // on every engine.
    let failures = run_fuzz_pass(seed, iterations, engine_sweep_stride(8));
    assert!(
        failures.is_empty(),
        "fuzz invariants violated ({} failures):\n\n{}",
        failures.len(),
        failures.join("\n---\n")
    );
}

/// MANUAL SUPERFUZZ — every fuzzable node as the anchor of a module,
/// at every module size, under the shared budget:
///
/// ```text
/// cargo nextest run -p polydat --run-ignored only -E 'test(/superfuzz_sampler/)' --no-capture
/// ```
///
/// Use `--workspace` for the widest registry; a `-p polydat` run
/// fuzzes a strict subset.
#[test]
#[ignore = "manual superfuzz — up to a minute by default; run with `--run-ignored only`"]
fn superfuzz_sampler() {
    use super::common::superfuzz;
    let base: u64 = std::env::var("FUZZ_SEED")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(0xDEAD_BEEFu64);
    let seeds = superfuzz::seeds_per_combination();
    // Every module on every engine unless `FUZZ_ENGINE_SWEEP` sets a
    // stride over combinations: this is the run that can afford it,
    // and the cross-engine space is the point of it.
    let stride = engine_sweep_stride(1) as u64;
    let sigs = fuzzable_sigs();
    assert!(
        !sigs.is_empty(),
        "no fuzzable signatures found — registry wiring broken?"
    );
    superfuzz::run(
        "superfuzz_sampler",
        &[
            ("node", sigs.len()),
            ("bindings", MAX_BINDINGS - MIN_BINDINGS + 1),
            ("optionals", 2),
            ("extra", VARIADIC_EXTRA),
            ("wires", 2),
        ],
        |v, index| {
            let anchor = &sigs[v[0]];
            let n = MIN_BINDINGS + v[1];
            let plan = AnchorPlan {
                optionals: v[2] == 1,
                extra: v[3],
                wires_from_bindings: v[4] == 1,
            };
            let sweep = stride != 0 && index % stride == 0;
            let mut failures = Vec::new();
            for k in 0..seeds {
                let seed = superfuzz::seed_for(base, index, k);
                let mut rng = Rng::new(seed);
                let source = generate_anchored_module(&mut rng, &sigs, anchor, n, plan);
                let tag = format!(
                    "[{} anchor, {n} bindings, {plan:?}, seed {seed:#x}]",
                    anchor.name
                );
                failures.extend(check_module(&source, sweep, &tag, ""));
            }
            failures
        },
    );
}

/// Whether a `{SrcType:?}→{DstType:?}` label the compiler writes into
/// [`CompileEvent::TypeAdapterInserted`] names a conversion
/// `auto_adapter` makes. The label is read back into its two types
/// through their `Debug` names, and the table itself is asked, so a
/// conversion the assembler inserts that its own table would not is
/// the finding (an adapter inserted from anywhere else).
fn adapter_label_is_known(label: &str) -> bool {
    let port = |name: &str| {
        PortType::ALL
            .iter()
            .copied()
            .find(|t| format!("{t:?}") == name)
    };
    let Some((from, to)) = label.split_once('→') else {
        return false;
    };
    match (port(from), port(to)) {
        (Some(f), Some(t)) => polydat::compile::assembly::auto_adapter(f, t).is_some(),
        _ => false,
    }
}

// ─── Basic sanity for the harness itself ──────────────────────────

/// End-to-end M2+M3: a `mod_wire(x, y)` call under
/// `pragma strict_values` triggers an auto-inserted
/// `AssertValue` between the divisor source and `mod_wire`'s
/// `divisor` wire input. Without the pragma, no assertion is
/// inserted (the node trusts its inputs as default).
#[test]
fn strict_values_inserts_nonzero_assertion_on_mod_wire() {
    use polydat::dsl::events::CompileEvent;

    // Strict mode: assertion expected.
    let strict_source = "\
        pragma strict_values\n\
        \n\
        d := mod(hash(cycle), 100)\n\
        b := mod_wire(cycle, d)\n\
    ";
    let mut log = CompileEventLog::new();
    let result = compile_polydat_interpreter_with_log(strict_source, &mut log);
    assert!(result.is_ok(), "compile failed: {:?}", result.err());
    let assertion_inserts: Vec<&CompileEvent> = log
        .events()
        .iter()
        .filter(|e| matches!(e, CompileEvent::AssertionInserted { .. }))
        .collect();
    assert!(
        !assertion_inserts.is_empty(),
        "expected at least one AssertionInserted under strict_values; events: {:?}",
        log.events(),
    );

    // Non-strict mode: no assertion event.
    let lax_source = "\
        d := mod(hash(cycle), 100)\n\
        b := mod_wire(cycle, d)\n\
    ";
    let mut lax_log = CompileEventLog::new();
    let lax_result = compile_polydat_interpreter_with_log(lax_source, &mut lax_log);
    assert!(lax_result.is_ok(), "compile failed: {:?}", lax_result.err());
    let lax_inserts: Vec<&CompileEvent> = lax_log
        .events()
        .iter()
        .filter(|e| matches!(e, CompileEvent::AssertionInserted { .. }))
        .collect();
    assert!(
        lax_inserts.is_empty(),
        "no AssertionInserted expected without pragma; got: {lax_inserts:?}",
    );
}

/// When the divisor source is a constant that satisfies the port's
/// constraint, strict_values mode checks it at build and inserts no
/// assertion (graph_compiler.md §2, strict-wire assertions).
#[test]
fn strict_values_skips_assertion_when_source_is_constant() {
    use polydat::dsl::events::CompileEvent;
    let source = "\
        pragma strict_values\n\
        b := mod_wire(cycle, 7)\n\
    ";
    let mut log = CompileEventLog::new();
    let result = compile_polydat_interpreter_with_log(source, &mut log);
    assert!(result.is_ok(), "compile failed: {:?}", result.err());
    let inserts: Vec<&CompileEvent> = log
        .events()
        .iter()
        .filter(|e| matches!(e, CompileEvent::AssertionInserted { .. }))
        .collect();
    assert!(
        inserts.is_empty(),
        "constant source should skip assertion; got inserts: {inserts:?}",
    );
    let skips: Vec<&CompileEvent> = log
        .events()
        .iter()
        .filter(|e| matches!(e, CompileEvent::AssertionSkipped { .. }))
        .collect();
    assert!(
        !skips.is_empty(),
        "expected an AssertionSkipped event for constant source; events: {:?}",
        log.events(),
    );
}

/// A constant source that fails the sink port's constraint is a
/// compile error under strict_values, naming the port, the
/// constraint, and the value; without the pragma the program builds.
#[test]
fn strict_values_rejects_a_constant_that_fails_the_constraint() {
    let err = compile_polydat_interpreter("pragma strict_values\nb := mod_wire(cycle, 0)\n")
        .expect_err("a constant zero divisor must not build under strict_values");
    let text = err.to_string();
    assert!(
        text.contains("strict_values")
            && text.contains("'divisor'")
            && text.contains("non-zero")
            && text.contains("constant 0"),
        "{text}"
    );
    compile_polydat_interpreter("b := mod_wire(cycle, 0)\n").expect("builds without the pragma");
}

/// A nondeterministic zero-input node is never a constant: `counter()`
/// yields 0 on its first evaluation, and its wire gets a runtime guard
/// rather than a build-time verdict. A `volatile` binding is the same.
#[test]
fn strict_values_guards_a_nondeterministic_source() {
    for source in [
        "pragma strict_values\nd := counter()\nb := mod_wire(cycle, d)\n",
        "pragma strict_values\nvolatile d := 0\nb := mod_wire(cycle, d)\n",
    ] {
        let mut log = CompileEventLog::new();
        compile_polydat_interpreter_with_log(source, &mut log)
            .unwrap_or_else(|e| panic!("{source}: {e}"));
        let inserted = log
            .events()
            .iter()
            .filter(|e| matches!(e, CompileEvent::AssertionInserted { .. }))
            .count();
        assert_eq!(inserted, 1, "{source}: {:?}", log.events());
    }
}

/// A pragma in a `for` body applies to that body: its constant zero
/// divisor fails the build, while the same divisor in the program
/// around it, outside the pragma's scope, builds.
#[test]
fn a_for_body_pragma_applies_to_the_body_only() {
    let err = compile_polydat_interpreter(
        "input cycle: u64\n\
         for k in 1..3 {\n\
             pragma strict_values\n\
             c := mod_wire(k, 0)\n\
         }\n",
    )
    .expect_err("the body's pragma must check the body");
    assert!(err.to_string().contains("strict_values"), "{err}");
    compile_polydat_interpreter(
        "input cycle: u64\n\
         b := mod_wire(cycle, 0)\n\
         for k in 1..3 {\n\
             pragma strict_values\n\
             c := mod_wire(k, 7)\n\
         }\n",
    )
    .expect("the body's pragma must not reach the program");
}

/// A nested scope inherits the enclosing scope's pragmas: a program's
/// pragma checks a `for` body, and a body's pragma checks a `for`
/// nested in it.
#[test]
fn a_nested_scope_inherits_the_enclosing_pragmas() {
    for source in [
        "pragma strict_values\n\
         input cycle: u64\n\
         for k in 1..3 {\n\
             c := mod_wire(k, 0)\n\
         }\n",
        "input cycle: u64\n\
         for k in 1..3 {\n\
             pragma strict_values\n\
             for j in 1..3 {\n\
                 c := mod_wire(j, 0)\n\
             }\n\
         }\n",
    ] {
        let err = compile_polydat_interpreter(source)
            .expect_err("the enclosing pragma must check the nested body");
        assert!(err.to_string().contains("strict_values"), "{source}: {err}");
    }
}

/// A module's pragma applies to the module's own bindings and never to
/// its host.
#[test]
fn a_module_pragma_does_not_reach_its_host() {
    let module = |body: &str| {
        format!(
            "input cycle: u64\n\
             checked(a: u64) -> (out: u64) := {{\n\
                 pragma strict_values\n\
                 out := {body}\n\
             }}\n\
             s := checked(cycle)\n\
             b := mod_wire(cycle, 0)\n"
        )
    };
    compile_polydat_interpreter(&module("mod_wire(a, 7)"))
        .expect("the module's pragma must not check the host's divisor");
    let err = compile_polydat_interpreter(&module("mod_wire(a, 0)"))
        .expect_err("the module's pragma must check the module's divisor");
    assert!(err.to_string().contains("strict_values"), "{err}");
}

/// Pragma directives at the source head are recognised and recorded
/// in the compile event log — `strict_values` / `strict_types` /
/// `strict` produce advisories, unknown pragmas produce warnings,
/// and the pragma surface is forward-compatible (an unrecognised
/// pragma never blocks compilation). See polydat_grammar.md §14.
#[test]
fn pragmas_round_trip_through_compile() {
    use polydat::dsl::events::CompileEvent;
    let source = "\
        pragma strict\n\
        pragma warp_drive\n\
        \n\
        id := mod(hash(cycle), 1000)\n\
    ";
    let mut log = CompileEventLog::new();
    let result = compile_polydat_interpreter_with_log(source, &mut log);
    assert!(result.is_ok(), "compile failed: {:?}", result.err());
    let acknowledged: Vec<&str> = log
        .events()
        .iter()
        .filter_map(|e| match e {
            CompileEvent::PragmaAcknowledged { name, .. } => Some(name.as_str()),
            _ => None,
        })
        .collect();
    let unknown: Vec<&str> = log
        .events()
        .iter()
        .filter_map(|e| match e {
            CompileEvent::UnknownPragma { name, .. } => Some(name.as_str()),
            _ => None,
        })
        .collect();
    assert_eq!(
        acknowledged,
        vec!["strict"],
        "expected single ack for `strict`"
    );
    assert_eq!(
        unknown,
        vec!["warp_drive"],
        "expected unknown record for `warp_drive`"
    );
}

/// Guard against the test mis-firing: a plain same-type chain must
/// compile cleanly with no adapter events. If this ever fails, the
/// fuzz infrastructure itself is broken — check the compiler or the
/// event log machinery before chasing the other tests.
#[test]
fn sanity_same_type_chain_has_no_adapters() {
    let source = "\
        input cycle: u64\n\
        a := add(cycle, 1)\n\
        b := add(a, 2)\n\
    ";
    let mut log = CompileEventLog::new();
    let result = compile_polydat_interpreter_with_log(source, &mut log);
    assert!(
        result.is_ok(),
        "simple chain should compile: {:?}",
        result.err()
    );
    for e in log.events() {
        if let CompileEvent::TypeAdapterInserted { .. } = e {
            panic!("unexpected type adapter in same-type chain:\n{source}\nevent: {e:?}");
        }
    }
}

#[test]
fn sanity_u64_to_f64_is_reported_as_a_widening() {
    let source = "\
        input cycle: u64\n\
        a := clamp_f64(cycle, 0.0, 1.0)\n\
    ";
    let mut log = CompileEventLog::new();
    let result = compile_polydat_interpreter_with_log(source, &mut log);
    assert!(
        result.is_ok(),
        "u64→f64 widening should auto-adapt: {:?}",
        result.err()
    );
    let has_adapter = log.events().iter().any(|e| {
        matches!(
            e,
            CompileEvent::TypeWidening {
                from: "u64",
                to: "f64",
                ..
            }
        )
    });
    assert!(
        has_adapter,
        "expected a u64 to f64 widening event in log: {:?}",
        log.events()
    );
}

#[test]
fn sanity_f64_to_u64_rejects_without_cast() {
    // F64 → U64 is narrowing and must not auto-insert — the compiler
    // should report a type mismatch so the author is forced to pick
    // `f64_to_u64` / `round_to_u64` / `floor_to_u64` explicitly.
    let source = "\
        input cycle: u64\n\
        x := to_f64(cycle)\n\
        y := add(x, 1)\n\
    ";
    let err = compile_polydat_interpreter(source).expect_err("narrowing f64→u64 must not compile");
    assert!(
        err.to_string().contains("type mismatch"),
        "expected a type-mismatch error for narrowing, got: {err}"
    );
}

/// The strictness pragmas reach the graph on every entry point, so
/// `pragma strict_values` inserts its assertion under the logged
/// compile and under `compile_polydat` alike: the two programs have
/// the same node count on every path, and so does the default engine's.
#[test]
fn strict_pragmas_reach_every_compile_path() {
    let source = "\
        pragma strict_values\n\
        \n\
        d := mod(hash(cycle), 100)\n\
        b := mod_wire(cycle, d)\n\
    ";
    let lax = "\
        d := mod(hash(cycle), 100)\n\
        b := mod_wire(cycle, d)\n\
    ";
    let plain = compile_polydat_interpreter(source).expect("plain compile");
    let mut log = CompileEventLog::new();
    let logged = compile_polydat_interpreter_with_log(source, &mut log).expect("logged compile");
    let lax_kernel = compile_polydat_interpreter(lax).expect("lax compile");
    let plain_nodes = plain.program().node_count();
    assert_eq!(
        plain_nodes,
        logged.program().node_count(),
        "the plain and logged interpreter paths must build the same graph"
    );
    // The assertion node may be fused into a cone, whose label names
    // its members, so look for it by name rather than by node count.
    let has_assertion = |k: &polydat::kernel::PolydatKernel| {
        let p = k.program();
        (0..p.node_count()).any(|i| p.node_meta(i).name.contains("assert_u64_nonzero"))
    };
    assert!(
        has_assertion(&plain) && !has_assertion(&lax_kernel),
        "strict_values must insert the assertion on the plain path too"
    );
    let mut default_log = CompileEventLog::new();
    let compiled = polydat::dsl::compile::compile_polydat_kernel_with_options(
        source,
        &polydat::dsl::compile::CompileOptions::default(),
        Some(&mut default_log),
    )
    .expect("default-engine compile");
    let count = |log: &CompileEventLog| {
        log.events()
            .iter()
            .filter(|e| matches!(e, CompileEvent::AssertionInserted { .. }))
            .count()
    };
    assert_eq!(count(&log), count(&default_log));
    assert!(count(&log) > 0);
    drop(compiled);
}

/// The assertion `pragma strict_values` inserts fails the same way on
/// the interpreter and on the default engine: the same node, the same
/// message. Before the assertion nodes had a compiled form the default
/// engine refused every strict program outright.
#[test]
fn strict_value_assertion_fails_alike_on_every_engine() {
    use polydat::Kernel;
    let source = "\
        pragma strict_values\n\
        input cycle: u64\n\
        d := mod(cycle, 1)\n\
        b := mod_wire(cycle, d)\n\
    ";
    // The message less the line that names where the panic was raised,
    // which is the node's own eval on the interpreter and its compiled
    // form elsewhere.
    fn failure(kernel: &mut dyn Kernel) -> String {
        kernel.set_inputs(&[7]);
        let hit = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| kernel.pull("b")));
        let err = hit.expect_err("a zero divisor must trip the assertion");
        let text = err
            .downcast_ref::<String>()
            .cloned()
            .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
            .unwrap_or_default();
        text.lines()
            .filter(|l| !l.contains("panicked at"))
            .collect::<Vec<_>>()
            .join("\n")
    }
    let mut interpreter = compile_polydat_interpreter(source).expect("interpreter compile");
    let mut default = polydat::dsl::compile::compile_polydat_kernel_with_options(
        source,
        &polydat::dsl::compile::CompileOptions::default(),
        None,
    )
    .expect("default-engine compile");
    let on_interpreter = failure(&mut interpreter);
    let on_default = failure(default.as_mut());
    assert!(
        on_interpreter.contains("assert_u64_nonzero"),
        "interpreter failure names the assertion: {on_interpreter}"
    );
    assert_eq!(on_interpreter, on_default);
}