polydat 0.1.0

Polydat — generation kernel for deterministic variate generation in nb-rs (formerly nbrs-variates)
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
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Adversarial and fuzz-style tests for the GK system.
//!
//! These tests exercise boundary conditions, malformed inputs,
//! edge cases in the lexer/parser/compiler/runtime pipeline,
//! and scope composition mechanics.

use polydat::dsl::compile::{compile_gk, compile_gk_strict};
use polydat::dsl::ast::BindingModifier;
use polydat::kernel::Construction;
use polydat::subcontext::GkMatter;

// =========================================================================
// Lexer / Parser adversarial inputs
// =========================================================================

#[test]
fn empty_source() {
    // Empty source is a valid zero-binding program (no inputs, no outputs)
    let result = compile_gk("");
    assert!(result.is_ok(), "empty source should compile as zero-binding program");
}

#[test]
fn whitespace_only() {
    let result = compile_gk("   \n\n  \t  \n  ");
    assert!(result.is_ok(), "whitespace-only source should compile as zero-binding program");
}

#[test]
fn comments_only() {
    let result = compile_gk("// just a comment\n# another comment\n/* block */");
    assert!(result.is_ok(), "comments-only source should compile as zero-binding program");
}

#[test]
fn unterminated_string() {
    let result = compile_gk(r#"
        input cycle: u64
        s := "unterminated
    "#);
    assert!(result.is_err(), "unterminated string should fail");
}

#[test]
fn unterminated_block_comment() {
    let result = compile_gk(r#"
        input cycle: u64
        /* never closed
        h := hash(cycle)
    "#);
    // The lexer may or may not detect unterminated block comments;
    // it's acceptable to either error or treat the rest as comment.
    // Just verify it doesn't panic.
    let _ = result;
}

#[test]
fn unexpected_token_at_toplevel() {
    let result = compile_gk("+ - * /");
    assert!(result.is_err());
}

#[test]
fn duplicate_inputs_declaration() {
    // Second declaration should override, not error
    let result = compile_gk(r#"
        input cycle: u64
        input cycle: u64
        h := hash(cycle)
    "#);
    assert!(result.is_ok(), "duplicate inputs should be accepted: {:?}", result.err());
}

#[test]
fn zero_inputs_explicit() {
    let result = compile_gk(r#"
        val := 42
    "#);
    // Explicit empty inputs is valid for constant-only programs
    assert!(result.is_ok(), "explicit empty inputs should work: {:?}", result.err());
}

#[test]
fn very_long_identifier() {
    let long_name: String = "a".repeat(1000);
    let src = format!("input cycle: u64\n{long_name} := hash(cycle)");
    let result = compile_gk(&src);
    assert!(result.is_ok(), "long identifier should work: {:?}", result.err());
}

#[test]
fn unicode_in_string_literal() {
    let result = compile_gk(r#"
        input cycle: u64
        emoji := "hello 🌍 world"
    "#);
    assert!(result.is_ok(), "unicode in strings should work: {:?}", result.err());
}

#[test]
fn deeply_nested_function_calls() {
    // hash(hash(hash(hash(hash(cycle)))))
    let src = r#"
        input cycle: u64
        deep := hash(hash(hash(hash(hash(cycle)))))
    "#;
    let mut kernel = compile_gk(src).unwrap();
    kernel.set_inputs(&[42]);
    let _ = kernel.pull("deep").as_u64();
}

#[test]
fn deeply_nested_arithmetic() {
    let src = r#"
        input cycle: u64
        v := ((((cycle + 1) * 2) + 3) * 4) + 5
    "#;
    let mut kernel = compile_gk(src).unwrap();
    kernel.set_inputs(&[10]);
    let result = kernel.pull("v").as_u64();
    // (((10+1)*2)+3)*4)+5 = ((11*2)+3)*4+5 = (22+3)*4+5 = 25*4+5 = 105
    assert_eq!(result, 105);
}

#[test]
fn hex_literals() {
    let src = r#"
        input cycle: u64
        v := mod(hash(cycle), 0xFF)
    "#;
    let mut kernel = compile_gk(src).unwrap();
    kernel.set_inputs(&[1]);
    assert!(kernel.pull("v").as_u64() < 255);
}

#[test]
fn negative_float_literal() {
    let src = r#"
        input cycle: u64
        v := -3.14
    "#;
    let mut kernel = compile_gk(src).unwrap();
    kernel.set_inputs(&[0]);
    let val = kernel.pull("v").as_f64();
    assert!((val - (-3.14)).abs() < 0.001);
}

// =========================================================================
// Unknown function / wiring errors
// =========================================================================

#[test]
fn unknown_function_name() {
    let result = compile_gk(r#"
        input cycle: u64
        v := nonexistent_function(cycle)
    "#);
    assert!(result.is_err(), "unknown function should fail");
    let err = result.unwrap_err();
    assert!(err.contains("nonexistent_function"), "error should name the function: {err}");
}

#[test]
fn unknown_wire_reference() {
    let result = compile_gk(r#"
        input cycle: u64
        v := hash(undefined_wire)
    "#);
    assert!(result.is_err(), "unknown wire should fail");
}

#[test]
fn wrong_arity_too_many() {
    let result = compile_gk(r#"
        input cycle: u64
        v := hash(cycle, cycle, cycle)
    "#);
    assert!(result.is_err(), "too many args should fail");
}

#[test]
fn self_referential_binding() {
    let result = compile_gk(r#"
        input cycle: u64
        x := hash(x)
    "#);
    // This should fail: x references itself before being defined
    assert!(result.is_err(), "self-referential binding should fail");
}

// =========================================================================
// Strict mode
// =========================================================================

#[test]
fn strict_requires_explicit_inputs() {
    let result = compile_gk_strict("h := hash(cycle)", None, true);
    assert!(result.is_err(), "strict mode should require explicit inputs");
}

#[test]
fn strict_accepts_explicit_inputs() {
    let result = compile_gk_strict(
        "input cycle: u64\nh := hash(cycle)",
        None,
        true,
    );
    assert!(result.is_ok(), "strict with explicit inputs should work: {:?}", result.err());
}

// =========================================================================
// Binding modifiers: shared / final
// =========================================================================

#[test]
fn shared_on_cycle_binding() {
    // `shared X := <literal>` compiles to a slot+passthrough
    // shareable cell. Non-literal RHS is rejected; see
    // `shared_non_literal_rejected` below.
    let src = r#"
        input cycle: u64
        shared counter := 0
    "#;
    let kernel = compile_gk(src).unwrap();
    assert_eq!(kernel.program().output_modifier("counter"), BindingModifier::SHARED);
}

#[test]
fn shared_non_literal_rejected() {
    let src = r#"
        input cycle: u64
        shared counter := hash(cycle)
    "#;
    let err = compile_gk(src).expect_err("non-literal shared const must error");
    assert!(err.contains("shared binding 'counter'"), "error: {err}");
    assert!(err.contains("literal"), "error: {err}");
}

#[test]
fn const_on_cycle_expr_rejected() {
    // `const` is a hard contract: the RHS must be folded at compile
    // time or materialised at scope-init from effectively-const
    // sources. Wiring it through a per-cycle `cycle` input is the
    // canonical violation — Plan A must reject.
    let src = r#"
        input cycle: u64
        const max := mod(hash(cycle), 100)
    "#;
    let err = compile_gk(src).expect_err("const wired to cycle must be rejected");
    assert!(err.contains("init contract") || err.contains("const"),
        "diagnostic should call out the const contract: {err}");
}

#[test]
fn shared_literal_cell() {
    let src = r#"
        input cycle: u64
        shared budget := 500
    "#;
    let kernel = compile_gk(src).unwrap();
    assert_eq!(kernel.program().output_modifier("budget"), BindingModifier::SHARED);
    assert_eq!(kernel.lookup("budget").unwrap().as_u64(), 500);
}

#[test]
fn const_literal_fold() {
    let src = r#"
        input cycle: u64
        const dim := 128
    "#;
    let kernel = compile_gk(src).unwrap();
    assert_eq!(kernel.program().output_modifier("dim"), BindingModifier::CONST);
    assert_eq!(kernel.get_constant("dim").unwrap().as_u64(), 128);
}

#[test]
fn mixed_modifiers() {
    let src = r#"
        input cycle: u64
        shared s := 0
        const f := 42
        plain := mod(hash(cycle), 100)
    "#;
    let kernel = compile_gk(src).unwrap();
    assert_eq!(kernel.program().output_modifier("s"), BindingModifier::SHARED);
    assert_eq!(kernel.program().output_modifier("f"), BindingModifier::CONST);
    assert_eq!(kernel.program().output_modifier("plain"), BindingModifier::NONE);
}

#[test]
fn shared_outputs_list() {
    let src = r#"
        input cycle: u64
        shared a := 0
        shared b := 0
        c := hash(cycle)
    "#;
    let kernel = compile_gk(src).unwrap();
    let mut shared = kernel.program().shared_outputs();
    shared.sort();
    assert_eq!(shared, vec!["a", "b"]);
}

#[test]
fn final_outputs_list() {
    let src = r#"
        input cycle: u64
        const x := 1
        const y := 2
        z := hash(cycle)
    "#;
    let kernel = compile_gk(src).unwrap();
    let mut finals = kernel.program().const_outputs();
    finals.sort();
    assert_eq!(finals, vec!["x", "y"]);
}

#[test]
fn no_modifiers_returns_empty_lists() {
    let src = r#"
        input cycle: u64
        h := hash(cycle)
    "#;
    let kernel = compile_gk(src).unwrap();
    assert!(kernel.program().shared_outputs().is_empty());
    assert!(kernel.program().const_outputs().is_empty());
}

// =========================================================================
// Extern declarations
// =========================================================================

#[test]
fn extern_u64_input_declared() {
    // Extern declarations register named inputs on the kernel
    let src = r#"
        input cycle: u64
        extern offset: u64
    "#;
    let kernel = compile_gk(src).unwrap();
    let idx = kernel.program().find_input("offset");
    assert!(idx.is_some(), "extern should create a named input");
}

#[test]
fn extern_usable_as_wire_argument() {
    // Externs should be usable directly in GK expressions
    let src = r#"
        input cycle: u64
        extern offset: u64
        result := hash(offset)
    "#;
    let mut kernel = compile_gk(src).unwrap();
    let idx = kernel.program().find_input("offset").unwrap();
    kernel.state().set_input(idx, polydat::node::Value::U64(100));
    kernel.set_inputs(&[42]);
    let v1 = kernel.pull("result").as_u64();

    // Different extern value should produce different hash
    kernel.state().set_input(idx, polydat::node::Value::U64(200));
    kernel.set_inputs(&[42]);
    let v2 = kernel.pull("result").as_u64();
    assert_ne!(v1, v2, "different extern values should hash differently");
}

#[test]
fn extern_in_arithmetic_expression() {
    let src = r#"
        input cycle: u64
        extern scale: u64
        result := cycle * scale
    "#;
    let mut kernel = compile_gk(src).unwrap();
    let idx = kernel.program().find_input("scale").unwrap();
    kernel.state().set_input(idx, polydat::node::Value::U64(10));
    kernel.set_inputs(&[5]);
    let v = kernel.pull("result").as_u64();
    assert_eq!(v, 50);
}

#[test]
fn extern_input_usable_as_output() {
    // Externs create passthrough outputs accessible via pull/get_constant
    let src = r#"
        input cycle: u64
        extern dim: u64
    "#;
    let mut kernel = compile_gk(src).unwrap();
    let idx = kernel.program().find_input("dim").unwrap();
    kernel.state().set_input(idx, polydat::node::Value::U64(128));
    kernel.set_inputs(&[0]);
    // The passthrough output should reflect the input value
    let val = kernel.pull("dim").as_u64();
    assert_eq!(val, 128);
}

#[test]
fn extern_f64_input() {
    let src = r#"
        input cycle: u64
        extern threshold: f64
    "#;
    let kernel = compile_gk(src).unwrap();
    assert!(kernel.program().find_input("threshold").is_some());
}

#[test]
fn extern_string_input() {
    let src = r#"
        input cycle: u64
        extern label: String
    "#;
    let kernel = compile_gk(src).unwrap();
    assert!(kernel.program().find_input("label").is_some());
}

// =========================================================================
// Scope composition: materialize_wiring_from_outer
// =========================================================================

#[test]
fn materialize_wiring_from_outer_copies_constants() {
    // Outer kernel has a constant
    let outer_src = r#"
        input cycle: u64
        dim := 128
    "#;
    let outer = compile_gk(outer_src).unwrap();
    assert_eq!(outer.get_constant("dim").unwrap().as_u64(), 128);

    // Inner kernel has an extern that matches the outer's output
    let inner_src = r#"
        input cycle: u64
        extern dim: u64
    "#;
    let inner_program = compile_gk(inner_src).unwrap().program().clone();
    let mut inner = outer.subscope(GkMatter::builder().program(inner_program).build().unwrap()).unwrap();

    // Verify the extern input was populated from outer scope
    let idx = inner.program().find_input("dim").unwrap();
    let val = inner.state().get_input(idx);
    assert_eq!(val.as_u64(), 128);

    // The passthrough output also reflects the bound value
    inner.set_inputs(&[0]);
    let pulled = inner.pull("dim").as_u64();
    assert_eq!(pulled, 128);
}

#[test]
fn materialize_wiring_from_outer_ignores_nonmatching() {
    let outer_src = r#"
        input cycle: u64
        dim := 128
    "#;
    let outer = compile_gk(outer_src).unwrap();

    // Inner kernel doesn't reference 'dim' — no extern
    let inner_src = r#"
        input cycle: u64
        h := hash(cycle)
    "#;
    let inner_program = compile_gk(inner_src).unwrap().program().clone();
    // Should not panic
    let _inner = outer.subscope(GkMatter::builder().program(inner_program).build().unwrap()).unwrap();
}

// =========================================================================
// Determinism under repeated evaluation
// =========================================================================

#[test]
fn deterministic_across_1000_cycles() {
    let src = r#"
        input cycle: u64
        h := hash(cycle)
        v := mod(h, 1000000)
    "#;
    let mut kernel = compile_gk(src).unwrap();

    // Collect values for first pass
    let mut first_pass = Vec::new();
    for i in 0..1000 {
        kernel.set_inputs(&[i]);
        first_pass.push(kernel.pull("v").as_u64());
    }

    // Verify second pass matches
    for i in 0..1000 {
        kernel.set_inputs(&[i]);
        let v = kernel.pull("v").as_u64();
        assert_eq!(v, first_pass[i as usize],
            "non-deterministic at cycle {i}: {v} != {}", first_pass[i as usize]);
    }
}

#[test]
fn deterministic_with_multiple_outputs() {
    let src = r#"
        input cycle: u64
        a := hash(cycle)
        b := mod(a, 100)
        c := mod(a, 1000)
    "#;
    let mut kernel = compile_gk(src).unwrap();

    for i in 0..100 {
        kernel.set_inputs(&[i]);
        let a1 = kernel.pull("a").as_u64();
        let b1 = kernel.pull("b").as_u64();
        let c1 = kernel.pull("c").as_u64();

        kernel.set_inputs(&[i]);
        let a2 = kernel.pull("a").as_u64();
        let b2 = kernel.pull("b").as_u64();
        let c2 = kernel.pull("c").as_u64();

        assert_eq!(a1, a2, "non-deterministic 'a' at cycle {i}");
        assert_eq!(b1, b2, "non-deterministic 'b' at cycle {i}");
        assert_eq!(c1, c2, "non-deterministic 'c' at cycle {i}");
    }
}

// =========================================================================
// Boundary values
// =========================================================================

#[test]
fn max_u64_input() {
    let src = r#"
        input cycle: u64
        h := hash(cycle)
    "#;
    let mut kernel = compile_gk(src).unwrap();
    kernel.set_inputs(&[u64::MAX]);
    let _ = kernel.pull("h").as_u64();
    // Should not panic
}

#[test]
fn zero_input() {
    let src = r#"
        input cycle: u64
        h := hash(cycle)
        v := mod(h, 100)
    "#;
    let mut kernel = compile_gk(src).unwrap();
    kernel.set_inputs(&[0]);
    assert!(kernel.pull("v").as_u64() < 100);
}

#[test]
fn mod_by_one() {
    let src = r#"
        input cycle: u64
        v := mod(hash(cycle), 1)
    "#;
    let mut kernel = compile_gk(src).unwrap();
    kernel.set_inputs(&[42]);
    assert_eq!(kernel.pull("v").as_u64(), 0);
}

#[test]
fn constant_only_program() {
    let src = r#"
        x := 42
        y := 3.14
        s := "hello"
    "#;
    let kernel = compile_gk(src).unwrap();
    assert_eq!(kernel.get_constant("x").unwrap().as_u64(), 42);
    assert!((kernel.get_constant("y").unwrap().as_f64() - 3.14).abs() < 0.001);
    assert_eq!(kernel.get_constant("s").unwrap().as_str(), "hello");
}

// =========================================================================
// Diagnostic source/context contract
// =========================================================================

#[test]
fn compiled_kernel_has_source_and_context() {
    let src = r#"
        input cycle: u64
        h := hash(cycle)
    "#;
    let kernel = compile_gk(src).unwrap();
    // Source should contain the original text
    assert!(kernel.program().source().contains("hash(cycle)"),
        "source should contain original text");
}

// =========================================================================
// Fuzz-style: random well-formed programs
// =========================================================================

/// Generate and compile many small random programs.
/// Tests that the compiler doesn't panic on valid programs.
#[test]
fn fuzz_random_hash_chains() {
    let functions = ["hash", "hash"];
    for seed in 0..200u64 {
        let depth = (seed % 5) + 1;
        let mut expr = "cycle".to_string();
        for _ in 0..depth {
            let func = functions[(seed as usize) % functions.len()];
            expr = format!("{func}({expr})");
        }
        let src = format!("input cycle: u64\nresult := mod({expr}, 1000)");
        let mut kernel = compile_gk(&src).unwrap_or_else(|e| {
            panic!("seed {seed}: compile failed: {e}\nsource:\n{src}")
        });
        kernel.set_inputs(&[seed]);
        let v = kernel.pull("result").as_u64();
        assert!(v < 1000, "seed {seed}: expected < 1000, got {v}");
    }
}

/// Fuzz arithmetic expression combinations.
#[test]
fn fuzz_arithmetic_expressions() {
    let ops = ["+", "-", "*"];
    for (_i, op) in ops.iter().enumerate() {
        for a in [0u64, 1, 42, 100, u64::MAX / 2] {
            let src = format!(
                "input cycle: u64\nresult := cycle {op} {a}"
            );
            let result = compile_gk(&src);
            assert!(result.is_ok(),
                "op={op} a={a}: compile failed: {:?}", result.err());
            let mut kernel = result.unwrap();
            // Don't test with values that might overflow — just verify it doesn't panic
            kernel.set_inputs(&[10]);
            let _ = kernel.pull("result");
        }
    }
}

/// Fuzz: compile many programs with varying numbers of bindings.
#[test]
fn fuzz_many_bindings() {
    for n in 1..=20 {
        let mut src = "input cycle: u64\n".to_string();
        let mut prev = "cycle".to_string();
        for i in 0..n {
            let name = format!("v{i}");
            src.push_str(&format!("{name} := hash({prev})\n"));
            prev = name;
        }
        let mut kernel = compile_gk(&src).unwrap_or_else(|e| {
            panic!("n={n}: compile failed: {e}\nsource:\n{src}")
        });
        kernel.set_inputs(&[42]);
        let _ = kernel.pull(&prev);
    }
}

/// Fuzz: programs with multiple outputs and destructuring.
#[test]
fn fuzz_multi_output_destructuring() {
    for n in [2, 3, 5, 10] {
        let names: Vec<String> = (0..n).map(|i| format!("d{i}")).collect();
        let targets = names.join(", ");
        let dims: Vec<String> = (0..n).map(|i| format!("{}", 10 + i)).collect();
        let dim_args = dims.join(", ");
        let src = format!(
            "input cycle: u64\n({targets}) := mixed_radix(cycle, {dim_args})"
        );
        let mut kernel = compile_gk(&src).unwrap_or_else(|e| {
            panic!("n={n}: compile failed: {e}\nsource:\n{src}")
        });
        kernel.set_inputs(&[12345]);
        for name in &names {
            let _ = kernel.pull(name);
        }
    }
}

/// Fuzz: stress test with 100 independent hash chains.
#[test]
fn fuzz_wide_graph() {
    let mut src = "input cycle: u64\n".to_string();
    for i in 0..100 {
        src.push_str(&format!("out_{i} := mod(hash(cycle + {i}), 1000)\n"));
    }
    let mut kernel = compile_gk(&src).unwrap();
    kernel.set_inputs(&[42]);
    for i in 0..100 {
        let v = kernel.pull(&format!("out_{i}")).as_u64();
        assert!(v < 1000, "out_{i} = {v}");
    }
}

// =========================================================================
// Error message quality
// =========================================================================

#[test]
fn error_includes_line_info() {
    let result = compile_gk(r#"
        input cycle: u64
        h := hash(cycle)
        bad := completely_bogus_function(h)
    "#);
    assert!(result.is_err());
    let err = result.unwrap_err();
    // Error should mention the bad function name
    assert!(err.contains("completely_bogus_function") || err.contains("unknown"),
        "error should be informative: {err}");
}

// =========================================================================
// Compile-time constant evaluation
// =========================================================================

#[test]
fn eval_const_integer_arithmetic() {
    let v = polydat::dsl::compile::eval_const_expr("4 * 4").unwrap();
    assert_eq!(v.as_u64(), 16);
}

#[test]
fn eval_const_float_arithmetic() {
    let v = polydat::dsl::compile::eval_const_expr("3.0 + 0.14").unwrap();
    assert!((v.as_f64() - 3.14).abs() < 0.001);
}

#[test]
fn eval_const_rejects_cycle_dependent() {
    let result = polydat::dsl::compile::eval_const_expr("hash(cycle)");
    assert!(result.is_err(), "cycle-dependent expr should not be const");
}

#[test]
fn eval_const_nested() {
    let v = polydat::dsl::compile::eval_const_expr("(2 + 3) * (4 + 1)").unwrap();
    assert_eq!(v.as_u64(), 25);
}

// =========================================================================
// String comparison / select desugar (==/!=, if() with String operands)
// =========================================================================

/// `==` between two String wires desugars to `str_eq`. Compiles +
/// pulls; the truth value is u64 (1 for equal, 0 for not).
#[test]
fn string_eq_compiles_and_evaluates() {
    let src = r#"
        input cycle: u64
        s := "LATENCY"
        eq := s == "LATENCY"
        ne := s == "RECALL"
    "#;
    let mut kernel = compile_gk(src).unwrap();
    kernel.set_inputs(&[0]);
    assert_eq!(kernel.pull("eq").as_u64(), 1);
    assert_eq!(kernel.pull("ne").as_u64(), 0);
}

/// `!=` between two String wires desugars to `str_ne`.
#[test]
fn string_ne_compiles_and_evaluates() {
    let src = r#"
        input cycle: u64
        s := "RECALL"
        ne := s != "LATENCY"
        eq := s != "RECALL"
    "#;
    let mut kernel = compile_gk(src).unwrap();
    kernel.set_inputs(&[0]);
    assert_eq!(kernel.pull("ne").as_u64(), 1);
    assert_eq!(kernel.pull("eq").as_u64(), 0);
}

/// `if(cond, str_a, str_b)` with String branches desugars to
/// `select_str` and produces a String output.
#[test]
fn if_with_string_branches_picks_str() {
    let src = r#"
        input cycle: u64
        s := "LATENCY"
        out := if(s == "LATENCY", "fast", "thorough")
    "#;
    let mut kernel = compile_gk(src).unwrap();
    kernel.set_inputs(&[0]);
    assert_eq!(kernel.pull("out").as_str(), "fast");
}

/// The motivating workload pattern from full_cql_vector.yaml's
/// ann_query: pick a numeric scaling factor based on a string
/// iteration variable.
#[test]
fn if_string_cond_picks_f64_branch() {
    let src = r#"
        input cycle: u64
        optimize_for := "LATENCY"
        latency_factor := 1.5
        recall_factor  := 9.5
        overscan := if(optimize_for == "LATENCY", latency_factor, recall_factor)
    "#;
    let mut kernel = compile_gk(src).unwrap();
    kernel.set_inputs(&[0]);
    assert!((kernel.pull("overscan").as_f64() - 1.5).abs() < 1e-9);
}

/// Ordered comparisons (<, >, <=, >=) on Strings are not supported;
/// they should fail with a clear error rather than miscompiling.
#[test]
fn string_ordered_comparison_errors() {
    let result = compile_gk(r#"
        input cycle: u64
        s := "LATENCY"
        bad := s < "RECALL"
    "#);
    assert!(result.is_err());
    let err = result.unwrap_err();
    assert!(
        err.contains("String") || err.contains("not supported"),
        "expected clear String-ordered-comparison error, got: {err}",
    );
}

/// Type-mismatch error messages should mention the user-level
/// LHS binding name (e.g. `overscan__anon_*`) instead of an
/// opaque counter (`__anon_14`). Helps users locate the failing
/// binding in their workload.
#[test]
fn type_mismatch_error_carries_binding_name() {
    // Synthetic mismatch: try to add a String to a u64-only sum.
    // Manual crafting: most direct path is to attempt unsupported
    // ordered comparison on Strings (compiler returns the binding
    // name in the message).
    let result = compile_gk(r#"
        input cycle: u64
        s := "x"
        my_named_binding := s < "y"
    "#);
    assert!(result.is_err());
    let err = result.unwrap_err();
    // The unsupported-comparison error path doesn't go through
    // anon_name (it's raised before nodes are assembled), so this
    // test verifies the friendlier path: a downstream type
    // mismatch carrying an anon node attributable to the binding.
    assert!(err.contains("String") || err.contains("not supported"),
        "got: {err}");
}

/// Type-mismatch errors involving anonymous compiler-generated
/// nodes should now name the user-level binding that owns them.
/// Before this fix, messages cited `__anon_14 ──(String)──▶ __anon_13`;
/// after, the prefix is the LHS binding (`overscan__anon_*`).
#[test]
fn type_mismatch_error_names_user_binding_via_prefix() {
    // Bitwise-shift a String — u64_shl wants u64 on both sides;
    // the LHS String operand triggers a type-mismatch and at
    // least one node in the path is auto-generated by the binding
    // compiler.
    let result = compile_gk(r#"
        input cycle: u64
        s := "LATENCY"
        overscan := s << 2
    "#);
    assert!(result.is_err());
    let err = result.unwrap_err();
    // The error must name the user-level binding the failure lives
    // in, somewhere in the message — either as the destination
    // node or as the prefix of an anon node.
    assert!(
        err.contains("overscan"),
        "expected error to mention the LHS binding name 'overscan', got:\n{err}",
    );
}