polydat-nodes 0.11.2

Polydat node library: hashing, sampling, strings, encodings, noise, vectors, and more
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
// Copyright 2024-2026 Jonathan Shook
// SPDX-License-Identifier: Apache-2.0

//! Element-wise vector math nodes (type_system_alignment.md §8.2).
//!
//! These are the first compute-shaped (rather than I/O-shaped)
//! consumers of the typed-vector family: perturbing query vectors,
//! computing ground-truth distances in evaluations, normalizing
//! embeddings. On `jit` builds the f32 hot loops execute through
//! the cranelift-SIMD kernels (`compile::jit::simd` — F32X4
//! chunked with scalar tails); without `jit`, or if host ISA
//! construction fails, the scalar reference loops below run
//! instead. SIMD accumulation reassociates float addition, so dot
//! products may differ from the scalar reference in the final
//! ulps — both orders are equally valid IEEE 754 sums.
//!
//! Length mismatches panic with both lengths named: silently
//! truncating to the shorter operand would corrupt distance
//! semantics ("never ignore silently").

use polydat::ast::PortType;
use polydat::dsl::registry::{Overload, OverloadForm};
pub use polydat::numeric::vector::{
    add_f32, add_f32_into, check_lens, cosine_f32, dot_f32, dot_scalar, hash_vec_into, l2sq_f32,
    l2sq_scalar, lid_mle_of, norm_f32_into, scale_f32, scale_f32_into, xxhash3_vec_into,
};

// ── Library nodes ──────────────────────────────────────────────
//
// Each node over vector operands has an f32 and an f64 form, and its
// unsuffixed name is an overload of the two
// (`polydat::dsl::registry::Overload`): a call builds the form its
// operands' types agree with, and operands agreeing with neither reach
// the f32 form through the assembler's adapters, as the unsuffixed
// name did before it had an f64 form.

/// `vec_add_f32(a, b)` — element-wise sum of two f32 vectors.
/// Panics when the lengths differ.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_add_f32(a: &[f32], b: &[f32]) -> Vec<f32> {
    check_lens("vec_add_f32", a.len(), b.len());
    add_f32(a, b)
}

/// `vec_add_f64(a, b)` — element-wise sum of two f64 vectors.
/// Panics when the lengths differ.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_add_f64(a: &[f64], b: &[f64]) -> Vec<f64> {
    check_lens("vec_add_f64", a.len(), b.len());
    a.iter().zip(b).map(|(x, y)| x + y).collect()
}

/// `vec_scale_f32(a, k)` — multiply every element of an f32 vector by
/// scalar `k` (applied at f32 precision).
#[polydat::polydat_node(category = Arithmetic)]
fn vec_scale_f32(a: &[f32], k: f64) -> Vec<f32> {
    scale_f32(a, k as f32)
}

/// `vec_scale_f64(a, k)` — multiply every element of an f64 vector by
/// scalar `k`.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_scale_f64(a: &[f64], k: f64) -> Vec<f64> {
    a.iter().map(|x| x * k).collect()
}

// ── Distances ──────────────────────────────────────────────────

/// `vec_dot_f32(a, b)` — dot product of two f32 vectors, widened to
/// f64 on the output wire. Panics when the lengths differ.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_dot_f32(a: &[f32], b: &[f32]) -> f64 {
    check_lens("vec_dot_f32", a.len(), b.len());
    dot_f32(a, b) as f64
}

/// `vec_dot_f64(a, b)` — dot product of two f64 vectors. Panics when
/// the lengths differ.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_dot_f64(a: &[f64], b: &[f64]) -> f64 {
    check_lens("vec_dot_f64", a.len(), b.len());
    a.iter().zip(b).map(|(x, y)| x * y).sum()
}

/// `vec_l2_f32(a, b)` — Euclidean (L2) distance between two f32
/// vectors. Panics when the lengths differ.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_l2_f32(a: &[f32], b: &[f32]) -> f64 {
    check_lens("vec_l2_f32", a.len(), b.len());
    (l2sq_f32(a, b) as f64).sqrt()
}

/// `vec_l2_f64(a, b)` — Euclidean (L2) distance between two f64
/// vectors. Panics when the lengths differ.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_l2_f64(a: &[f64], b: &[f64]) -> f64 {
    check_lens("vec_l2_f64", a.len(), b.len());
    a.iter()
        .zip(b)
        .map(|(x, y)| (x - y) * (x - y))
        .sum::<f64>()
        .sqrt()
}

/// `vec_cosine_f32(a, b)` — cosine similarity of two f32 vectors:
/// `dot(a,b) / (|a| * |b|)`. Returns 0.0 when either vector has
/// zero magnitude (the conventional degenerate-case value: no
/// direction, no similarity). Panics when the lengths differ.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_cosine_f32(a: &[f32], b: &[f32]) -> f64 {
    check_lens("vec_cosine_f32", a.len(), b.len());
    cosine_f32(a, b)
}

/// `vec_cosine_f64(a, b)` — cosine similarity of two f64 vectors:
/// `dot(a,b) / (|a| * |b|)`, and 0.0 when either vector has zero
/// magnitude, as `vec_cosine_f32` answers. Panics when the lengths
/// differ.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_cosine_f64(a: &[f64], b: &[f64]) -> f64 {
    check_lens("vec_cosine_f64", a.len(), b.len());
    let (dot, aa, bb) = dot_and_squares(a, b);
    if aa == 0.0 || bb == 0.0 {
        0.0
    } else {
        dot / (aa.sqrt() * bb.sqrt())
    }
}

/// `vec_distance_f32(metric, a, b)` — the distance between two f32
/// vectors as a dataset's ground truth records it, accumulated in
/// f64. Smaller is closer under every metric:
///
/// - `EUCLIDEAN`: squared Euclidean distance (the square root is
///   monotonic, so ground truth leaves it out);
/// - `COSINE`: `1 − a·b / (|a|·|b|)`, and `1.0` when either operand
///   has zero length;
/// - `DOT_PRODUCT`: `−a·b`, so a larger inner product is closer;
/// - `MANHATTAN`: `Σ|aᵢ − bᵢ|`.
///
/// `metric` is a name as `dataset_distance_function` returns it, so a
/// host recomputes a stored neighbor distance with
/// `vec_distance(dataset_distance_function(group), query, base)`.
/// Any other name panics naming it, as do differing lengths: a
/// distance under a guessed metric would make every comparison
/// against the stored one meaningless.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_distance_f32(metric: &str, a: &[f32], b: &[f32]) -> f64 {
    ground_truth_distance("vec_distance_f32", metric, a, b)
}

/// `vec_distance_f64(metric, a, b)` — the distance between two f64
/// vectors as a dataset's ground truth records it, under the metrics
/// and conventions of `vec_distance_f32`.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_distance_f64(metric: &str, a: &[f64], b: &[f64]) -> f64 {
    ground_truth_distance("vec_distance_f64", metric, a, b)
}

/// The distance `metric` puts between `a` and `b`, smaller being
/// closer, accumulated in f64: the body of the `vec_distance` forms,
/// which `node` names in a panic.
fn ground_truth_distance<T: Copy + Into<f64>>(node: &str, metric: &str, a: &[T], b: &[T]) -> f64 {
    check_lens(node, a.len(), b.len());
    let pairs = || a.iter().zip(b).map(|(x, y)| ((*x).into(), (*y).into()));
    match metric {
        "EUCLIDEAN" => pairs().map(|(x, y): (f64, f64)| (x - y) * (x - y)).sum(),
        "COSINE" => {
            let (dot, aa, bb) = dot_and_squares(a, b);
            if aa == 0.0 || bb == 0.0 {
                1.0
            } else {
                1.0 - dot / (aa.sqrt() * bb.sqrt())
            }
        }
        "DOT_PRODUCT" => -pairs().map(|(x, y): (f64, f64)| x * y).sum::<f64>(),
        "MANHATTAN" => pairs().map(|(x, y): (f64, f64)| (x - y).abs()).sum(),
        other => panic!(
            "{node}: unknown metric {other:?}; expected EUCLIDEAN, COSINE, DOT_PRODUCT or MANHATTAN"
        ),
    }
}

/// `(a·b, a·a, b·b)` accumulated in f64, for the cosine forms.
fn dot_and_squares<T: Copy + Into<f64>>(a: &[T], b: &[T]) -> (f64, f64, f64) {
    a.iter()
        .zip(b)
        .map(|(x, y)| ((*x).into(), (*y).into()))
        .fold((0.0, 0.0, 0.0), |(d, aa, bb), (x, y): (f64, f64)| {
            (d + x * y, aa + x * x, bb + y * y)
        })
}

/// The overload `name` of an f32 form and an f64 form, each with the
/// wire types it takes.
macro_rules! float_overload {
    ($name:literal: [$($w32:ident),*] => $f32:literal, [$($w64:ident),*] => $f64:literal) => {
        polydat::inventory::submit! {
            Overload::new(
                $name,
                &[
                    OverloadForm::new(&[$(PortType::$w32),*], $f32),
                    OverloadForm::new(&[$(PortType::$w64),*], $f64),
                ],
            )
        }
    };
}

float_overload!("vec_add": [VecF32, VecF32] => "vec_add_f32", [VecF64, VecF64] => "vec_add_f64");
float_overload!("vec_scale": [VecF32, F64] => "vec_scale_f32", [VecF64, F64] => "vec_scale_f64");
float_overload!("vec_norm": [VecF32] => "vec_norm_f32", [VecF64] => "vec_norm_f64");
float_overload!("vec_dot": [VecF32, VecF32] => "vec_dot_f32", [VecF64, VecF64] => "vec_dot_f64");
float_overload!("vec_l2": [VecF32, VecF32] => "vec_l2_f32", [VecF64, VecF64] => "vec_l2_f64");
float_overload!("vec_cosine": [VecF32, VecF32] => "vec_cosine_f32", [VecF64, VecF64] => "vec_cosine_f64");
float_overload!(
    "vec_distance": [Str, VecF32, VecF32] => "vec_distance_f32",
    [Str, VecF64, VecF64] => "vec_distance_f64"
);

/// `vec_norm_f32(a)` — scale an f32 vector to unit L2 magnitude.
/// A zero vector passes through unchanged (there is no direction
/// to normalize onto, and emitting NaNs would poison downstream
/// distance math silently).
#[polydat::polydat_node(category = Arithmetic)]
fn vec_norm_f32(a: &[f32]) -> Vec<f32> {
    let mut out = Vec::new();
    norm_f32_into(a, &mut out);
    out
}

/// `vec_norm_f64(a)` — scale an f64 vector to unit L2 magnitude, a
/// zero vector passing through unchanged as `vec_norm_f32` passes it.
#[polydat::polydat_node(category = Arithmetic)]
fn vec_norm_f64(a: &[f64]) -> Vec<f64> {
    let mag = a.iter().map(|x| x * x).sum::<f64>().sqrt();
    if mag == 0.0 {
        a.to_vec()
    } else {
        a.iter().map(|x| x / mag).collect()
    }
}

/// `lid_mle(distances, k)` — Levina–Bickel maximum-likelihood estimate of
/// the **local intrinsic dimensionality** at one query point, from its
/// sorted ground-truth nearest-neighbor distances.
///
/// Given ascending distances `r_1 ≤ … ≤ r_k` to the `k` nearest neighbors,
///
/// ```text
///     d̂ = m / Σ_{j=1..m} ln(r_k / r_j)        (m = number of valid terms)
/// ```
///
/// the standard MLE (Levina & Bickel, NIPS 2004) with `r_k` as the cutoff
/// radius. `k` is clamped to the available length. Terms with a
/// non-positive `r_j` (exact duplicates / self-matches at distance 0, where
/// `ln(r_k/r_j)` is undefined) are skipped — the conventional handling.
/// Returns `0.0` for a degenerate query (fewer than one valid term, or a
/// non-positive log-sum, e.g. all-duplicate neighbors) so the caller can
/// filter it out of the aggregate.
///
/// Reporting the *distribution* of this per-query estimate (mean / p50 /
/// p90) characterizes both the intrinsic dimension and its heterogeneity —
/// the quantity that governs whether a 1-D locality ordering can work (a
/// low, tight LID favors it; a high or skewed LID does not).
///
/// ASSUMES `distances` are true metric distances in ascending order (the
/// dataset's `neighbor_distances` / `filtered_neighbor_distances` facet).
/// If that facet stores *squared* distances the estimate is scaled by ½
/// (double it); if it stores *similarities* (higher = closer) the result is
/// meaningless — validate against the dataset's metric first.
#[polydat::polydat_node(category = Arithmetic)]
fn lid_mle(distances: &[f32], k: f64) -> f64 {
    lid_mle_of(distances, k)
}

/// `hash_vec(seed, dim)` — deterministic synthetic f32 vector:
/// element `i` is the SplitMix64 hash of `(seed, i)` mapped into
/// `[-1, 1)`. The canonical generator for synthetic embeddings —
/// equal seeds always produce the identical vector, so dataset-
/// free vector workloads stay replayable. Pairs with `vec_norm`
/// for unit vectors.
#[polydat::polydat_node(category = Hashing)]
fn hash_vec(seed: u64, dim: u64) -> Vec<f32> {
    let mut out = Vec::new();
    hash_vec_into(seed, dim, &mut out);
    out
}

/// `xxhash3_vec(seed, dim)` — deterministic synthetic f32 vector using xxHash3.
#[polydat::polydat_node(category = Hashing)]
fn xxhash3_vec(seed: u64, dim: u64) -> Vec<f32> {
    let mut out = Vec::new();
    xxhash3_vec_into(seed, dim, &mut out);
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use polydat::ast::{PolydatNode, SliceArc, Value};

    fn vecv(v: Vec<f32>) -> Value {
        Value::VecF32(SliceArc::from_vec(v))
    }

    fn test_vec(n: usize, seed: u64) -> Vec<f32> {
        (0..n)
            .map(|i| {
                let h = xxhash_rust::xxh3::xxh3_64(&(seed ^ i as u64).to_le_bytes());
                (h as f64 / u64::MAX as f64 * 2.0 - 1.0) as f32
            })
            .collect()
    }

    fn eval2<N: PolydatNode>(node: &N, a: Vec<f32>, b: Vec<f32>) -> Value {
        let mut out = [Value::None];
        node.eval(&[vecv(a), vecv(b)], &mut out);
        out[0].clone()
    }

    #[test]
    fn vec_math_matches_scalar_reference() {
        // 1029 = 257 SIMD chunks + 1 tail element.
        let a = test_vec(1029, 1);
        let b = test_vec(1029, 2);

        let dot = eval2(&VecDotF32::new(), a.clone(), b.clone()).as_f64();
        let dot_ref = dot_scalar(&a, &b) as f64;
        assert!((dot - dot_ref).abs() / dot_ref.abs().max(1e-6) < 1e-4);

        let l2 = eval2(&VecL2F32::new(), a.clone(), b.clone()).as_f64();
        let l2_ref = (l2sq_scalar(&a, &b) as f64).sqrt();
        assert!((l2 - l2_ref).abs() / l2_ref.max(1e-6) < 1e-4);

        let sum = eval2(&VecAddF32::new(), a.clone(), b.clone());
        let sum = sum.as_vec_f32();
        for i in 0..a.len() {
            assert_eq!(sum[i], a[i] + b[i], "vec_add lane {i}");
        }

        let cos_self = eval2(&VecCosineF32::new(), a.clone(), a.clone()).as_f64();
        assert!((cos_self - 1.0).abs() < 1e-4, "self-cosine = {cos_self}");
    }

    fn vecd(v: Vec<f32>) -> Value {
        Value::VecF64(SliceArc::from_vec(v.into_iter().map(f64::from).collect()))
    }

    /// `node` over `a` and `b` as f32 vectors and as f64 vectors: the two
    /// forms of one distance, with any leading wires in `lead`.
    fn both_forms<N32: PolydatNode, N64: PolydatNode>(
        f32_form: &N32,
        f64_form: &N64,
        lead: &[Value],
        a: Vec<f32>,
        b: Vec<f32>,
    ) -> (f64, f64) {
        let eval = |node: &dyn PolydatNode, a: Value, b: Value| {
            let mut ins = lead.to_vec();
            ins.extend([a, b]);
            let mut out = [Value::None];
            node.eval(&ins, &mut out);
            out[0].as_f64()
        };
        (
            eval(f32_form, vecv(a.clone()), vecv(b.clone())),
            eval(f64_form, vecd(a), vecd(b)),
        )
    }

    /// The f64 forms compute what the f32 forms do, on vectors whose
    /// products and sums are exact in both widths.
    #[test]
    fn the_f64_forms_agree_with_the_f32_forms() {
        let (a, b) = (vec![1.0, 2.0, 3.0], vec![4.0, -2.0, 2.0]);
        let (d32, d64) = both_forms(
            &VecDotF32::new(),
            &VecDotF64::new(),
            &[],
            a.clone(),
            b.clone(),
        );
        assert_eq!((d32, d64), (6.0, 6.0));
        let (l32, l64) = both_forms(
            &VecL2F32::new(),
            &VecL2F64::new(),
            &[],
            a.clone(),
            b.clone(),
        );
        assert_eq!((l32, l64), (26f64.sqrt(), 26f64.sqrt()));
        let (c32, c64) = both_forms(
            &VecCosineF32::new(),
            &VecCosineF64::new(),
            &[],
            vec![3.0, 4.0],
            vec![4.0, 3.0],
        );
        assert_eq!((c32, c64), (24.0 / 25.0, 24.0 / 25.0));
        let (z32, z64) = both_forms(
            &VecCosineF32::new(),
            &VecCosineF64::new(),
            &[],
            vec![0.0, 0.0],
            vec![4.0, 3.0],
        );
        assert_eq!((z32, z64), (0.0, 0.0));
    }

    /// `vec_distance` under `metric` in both forms, which must agree.
    fn distance(metric: &str, a: Vec<f32>, b: Vec<f32>) -> f64 {
        let (d32, d64) = both_forms(
            &VecDistanceF32::new(),
            &VecDistanceF64::new(),
            &[Value::Str(metric.into())],
            a,
            b,
        );
        assert_eq!(d32, d64, "{metric}: the f32 and f64 forms differ");
        d32
    }

    /// Each metric in the ground-truth convention, smaller is closer,
    /// on vectors whose distances are exact in binary.
    #[test]
    fn vec_distance_follows_the_ground_truth_convention() {
        let (a, b) = (vec![1.0, 2.0, 0.0], vec![4.0, -2.0, 0.0]);
        assert_eq!(distance("EUCLIDEAN", a.clone(), b.clone()), 25.0);
        assert_eq!(distance("MANHATTAN", a.clone(), b.clone()), 7.0);
        assert_eq!(
            distance("DOT_PRODUCT", vec![1.0, 2.0], vec![3.0, 4.0]),
            -11.0
        );
        assert_eq!(
            distance("COSINE", vec![3.0, 4.0], vec![4.0, 3.0]),
            1.0 - 24.0 / 25.0
        );
        assert_eq!(distance("COSINE", vec![0.0, 0.0], vec![4.0, 3.0]), 1.0);
        // An f32 sift-scale distance is exact: integer coordinates.
        assert_eq!(
            distance("EUCLIDEAN", vec![0.0; 2], vec![200.0, 207.0]),
            82849.0
        );
    }

    #[test]
    #[should_panic(expected = "unknown metric \"euclidean\"")]
    fn vec_distance_refuses_an_unknown_metric() {
        distance("euclidean", vec![1.0], vec![2.0]);
    }

    #[test]
    fn vec_scale_and_norm() {
        let a = test_vec(37, 3);
        let mut out = [Value::None];
        VecScaleF32::new().eval(&[vecv(a.clone()), Value::F64(2.0)], &mut out);
        let scaled = out[0].as_vec_f32();
        for i in 0..a.len() {
            assert_eq!(scaled[i], a[i] * 2.0, "vec_scale lane {i}");
        }

        let mut out = [Value::None];
        VecNormF32::new().eval(&[vecv(a.clone())], &mut out);
        let unit = out[0].as_vec_f32().to_vec();
        let mag = (dot_scalar(&unit, &unit) as f64).sqrt();
        assert!((mag - 1.0).abs() < 1e-4, "norm magnitude = {mag}");

        // Zero vector passes through unchanged.
        let mut out = [Value::None];
        VecNormF32::new().eval(&[vecv(vec![0.0; 4])], &mut out);
        assert_eq!(out[0].as_vec_f32(), &[0.0, 0.0, 0.0, 0.0]);
    }

    #[test]
    fn lid_mle_matches_closed_form_and_handles_degenerate() {
        // r_j = e^{j}, j=0..9 → ln(r_k/r_j) = 9-j; Σ_{j=0}^{8}(9-j)=45,
        // 9 valid terms → d̂ = 9/45 = 0.2. Deterministic arithmetic check.
        let dists: Vec<f32> = (0..10).map(|j| (j as f32).exp()).collect();
        let mut out = [Value::None];
        LidMle::new().eval(&[vecv(dists), Value::F64(10.0)], &mut out);
        assert!(
            (out[0].as_f64() - 0.2).abs() < 1e-4,
            "got {}",
            out[0].as_f64()
        );

        // Fewer than 2 distances → degenerate → 0.0.
        let mut out = [Value::None];
        LidMle::new().eval(&[vecv(vec![1.0]), Value::F64(10.0)], &mut out);
        assert_eq!(out[0].as_f64(), 0.0);

        // All-zero (duplicate) neighbors, r_k = 0 → degenerate → 0.0.
        let mut out = [Value::None];
        LidMle::new().eval(&[vecv(vec![0.0, 0.0, 0.0]), Value::F64(3.0)], &mut out);
        assert_eq!(out[0].as_f64(), 0.0);

        // Zero-distance self-match at r_1 is skipped, not fatal: distances
        // [0, e, e^2] with k=3 → r_k=e^2 (ln=2), only r_2=e (ln=1) valid →
        // 1 term, logsum=1 → d̂ = 1.0.
        let mut out = [Value::None];
        let d: Vec<f32> = vec![
            0.0,
            std::f32::consts::E,
            std::f32::consts::E * std::f32::consts::E,
        ];
        LidMle::new().eval(&[vecv(d), Value::F64(3.0)], &mut out);
        assert!(
            (out[0].as_f64() - 1.0).abs() < 1e-4,
            "got {}",
            out[0].as_f64()
        );
    }

    #[test]
    fn hash_vec_is_deterministic_and_seed_sensitive() {
        let mut out = [Value::None];
        HashVec::new().eval(&[Value::U64(7), Value::U64(16)], &mut out);
        let v1 = out[0].as_vec_f32().to_vec();
        let mut out = [Value::None];
        HashVec::new().eval(&[Value::U64(7), Value::U64(16)], &mut out);
        assert_eq!(v1, out[0].as_vec_f32(), "same seed must reproduce");
        let mut out = [Value::None];
        HashVec::new().eval(&[Value::U64(8), Value::U64(16)], &mut out);
        assert_ne!(v1, out[0].as_vec_f32(), "different seed must differ");
        assert_eq!(v1.len(), 16);
        assert!(v1.iter().all(|x| (-1.0..1.0).contains(x)));
    }

    /// §8.4 layer 3 end-to-end: a vector dataflow (synthetic
    /// producer → element-wise math → horizontal reduce) rides
    /// compiled kernels via the (ptr, len) slot protocol with
    /// kernel-owned scratch, and must match typed eval. The same
    /// flow through the hybrid kernel runs the scalar segments as
    /// native JIT and the slice ops as slot closures (whose
    /// bodies already execute the cranelift-SIMD kernels).
    #[test]
    fn vec_flow_rides_compiled_kernels() {
        let src = r#"
            input cycle: u64
            a := hash_vec(cycle, 37)
            b := hash_vec(hash(cycle), 37)
            s := vec_add(a, b)
            out := vec_dot(s, b)
        "#;
        let mut p1 = polydat::dsl::compile_polydat(src).unwrap();

        let asm = polydat::dsl::compile::compile_polydat_to_assembler(src).unwrap();
        let mut p2 = asm
            .compile_slots(polydat_core::Engine::Closures(
                polydat_core::Provenance::Raw,
            ))
            .expect("slice-bearing nodes are P2-eligible via compiled_slot");

        for cycle in [0u64, 7, 0xFEED] {
            p1.set_inputs(&[cycle]);
            let want = p1.pull("out").as_f64();
            let slot = p2.resolve_output("out").unwrap();
            let got = f64::from_bits(p2.eval_for_slot(&[cycle], slot));
            assert_eq!(got, want, "P2 vec flow mismatch at cycle={cycle}");
        }

        #[cfg(feature = "jit")]
        {
            let asm = polydat::dsl::compile::compile_polydat_to_assembler(src).unwrap();
            let mut hy = asm
                .compile_slots(polydat_core::Engine::Native(
                    polydat_core::Provenance::PushPull,
                ))
                .unwrap();
            for cycle in [0u64, 7, 0xFEED] {
                p1.set_inputs(&[cycle]);
                let want = p1.pull("out").as_f64();
                let slot = hy.resolve_output("out").unwrap();
                hy.eval_at(&[cycle]);
                let got = f64::from_bits(hy.get_slot(slot));
                assert_eq!(got, want, "hybrid vec flow mismatch at cycle={cycle}");
            }
        }
    }

    /// Scratch reuse: re-evaluating the same compiled kernel must
    /// republish coherent (ptr, len) views even as vector contents
    /// change cycle to cycle.
    #[test]
    fn vec_scratch_reuses_across_evals() {
        let src = r#"
            input cycle: u64
            a := hash_vec(cycle, 16)
            out := vec_l2(a, vec_scale(a, 2.0))
        "#;
        let mut p1 = polydat::dsl::compile_polydat(src).unwrap();
        let asm = polydat::dsl::compile::compile_polydat_to_assembler(src).unwrap();
        let mut p2 = asm
            .compile_slots(polydat_core::Engine::Closures(
                polydat_core::Provenance::Raw,
            ))
            .expect("P2-eligible");
        let slot = p2.resolve_output("out").unwrap();
        // Interleave cycles so stale-scratch bugs would surface as
        // cross-cycle contamination.
        for cycle in [1u64, 9, 1, 42, 9, 1] {
            p1.set_inputs(&[cycle]);
            let want = p1.pull("out").as_f64();
            let got = f64::from_bits(p2.eval_for_slot(&[cycle], slot));
            assert_eq!(got, want, "scratch reuse mismatch at cycle={cycle}");
        }
    }

    #[test]
    fn vec_length_mismatch_panics() {
        let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            let mut out = [Value::None];
            VecDotF32::new().eval(&[vecv(vec![1.0]), vecv(vec![1.0, 2.0])], &mut out);
        }));
        assert!(r.is_err(), "vec_dot_f32 accepted mismatched lengths");
    }
}