leto-ops 0.45.2

Math, reduction, SIMD, and parallel kernels for Leto arrays
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
use super::rotation::TransposedFactors;
use super::sweep::qr_iterate;
use super::RealScalar;
use eunomia::RealField;

/// Backward-error bound for one bidiagonal QR reduction of order `k`:
/// `‖E‖₂ ≤ p·ε·‖B‖₂` and `‖UᵀU − I‖₂ ≤ p·ε`, with `p` modest in the order
/// (Golub & Van Loan, *Matrix Computations* 4th ed., §8.6.3 — the sweep is a
/// product of plane rotations, each contributing `O(ε)`, and `O(k)` of them
/// touch any one entry). `p = 8k` is used throughout; Weyl's theorem carries
/// the same bound to every `|σ̂ᵢ − σᵢ|`, and to a `σ` whose exact value is 0.
///
/// Returns `(absolute, relative)`: the absolute bound scaled by `‖B‖₂ ≈ σ₁`
/// for singular values and reconstruction, the bare relative one for
/// orthonormality (`UᵀU − I` is already dimensionless).
fn error_bounds<T: RealScalar + RealField>(k: usize, norm: f64) -> (f64, f64) {
    let order = u32::try_from(k).expect("invariant: test orders fit in u32");
    let relative = 8.0 * f64::from(order) * <T as RealField>::EPSILON.to_f64();
    (relative * norm, relative)
}

/// Run the iteration on the bidiagonal `(diag, superdiag)` with `U`/`V`
/// initialized to the identity, then assert the singular values against
/// `expected` (analytic, descending, trailing zeros included), the
/// reconstruction `B = U Σ Vᵀ` of the **input** bidiagonal, and orthonormality
/// of both accumulated factors.
///
/// Reconstructing the input is what makes this a test of the rotations rather
/// than only of the deflation: a chase that zeroes the right entries but
/// accumulates into the wrong plane, the wrong row pair, or with the wrong
/// sign leaves the singular values correct and the reconstruction wrong.
pub(super) fn check_bidiagonal<T: RealScalar + RealField>(
    diag: &[f64],
    superdiag: &[f64],
    expected: &[f64],
) {
    let k = diag.len();
    let mut d: Vec<T> = diag.iter().map(|&x| T::from_f64(x)).collect();
    let mut e: Vec<T> = (0..k)
        .map(|i| T::from_f64(superdiag.get(i).copied().unwrap_or(0.0)))
        .collect();
    let mut ut = vec![T::ZERO; k * k];
    let mut vt = vec![T::ZERO; k * k];
    for i in 0..k {
        ut[i * k + i] = T::ONE;
        vt[i * k + i] = T::ONE;
    }

    qr_iterate::<T, true>(
        &mut d,
        &mut e,
        k,
        &mut TransposedFactors::new(&mut ut, k, &mut vt, k),
    )
    .expect("the bidiagonal iteration converges on a zero diagonal");

    let (absolute, relative) = error_bounds::<T>(k, expected[0]);

    let mut sigma: Vec<f64> = d.iter().map(|x| x.abs().to_f64()).collect();
    sigma.sort_by(|a, b| b.total_cmp(a));
    for (got, want) in sigma.iter().zip(expected) {
        assert!(
            (got - want).abs() <= absolute,
            "σ {got} vs {want} exceeds {absolute:e}"
        );
    }

    // Column `i` of `U`/`V` is row `i` of `ut`/`vt` (see `rotate_row_pair`).
    for row in 0..k {
        for col in 0..k {
            let value: f64 = (0..k)
                .map(|i| ut[i * k + row].to_f64() * d[i].to_f64() * vt[i * k + col].to_f64())
                .sum();
            let target = if col == row {
                diag[row]
            } else if col == row + 1 {
                superdiag[row]
            } else {
                0.0
            };
            assert!(
                (value - target).abs() <= absolute,
                "B[{row}][{col}] reconstructs as {value} not {target}"
            );
        }
    }

    for (name, factor) in [("U", &ut), ("V", &vt)] {
        for a in 0..k {
            for b in 0..k {
                let dot: f64 = (0..k)
                    .map(|r| factor[a * k + r].to_f64() * factor[b * k + r].to_f64())
                    .sum();
                let target = f64::from(u8::from(a == b));
                assert!(
                    (dot - target).abs() <= relative,
                    "{name}ᵀ{name}[{a}][{b}] = {dot} not {target}"
                );
            }
        }
    }
}

/// A **trailing** zero diagonal: `B = [[3, 4], [0, 0]]`, exactly rank 1.
///
/// This is the reduced form of the downstream reproducer — `[[1,2],[2,4],[3,6]]`
/// bidiagonalizes at `f32` to `d = [−3.7416573, 0]`, `e = [−7.4833145]`, an
/// *exact* zero (`B`'s signs are unique only up to the reflectors' signs;
/// a length-1 right reflector is skipped, not a sign flip). Shifted QR alone cannot deflate it: the implicit `BᵀB` is
/// singular, the Wilkinson shift takes its nonzero eigenvalue, and the sweep
/// converges to the fixed point `d = (0, 0)` with `|e|` preserved, which the
/// `scale + |e| == scale` test never accepts. Measured before the trailing
/// column chase existed: `d[0]` decayed `2.4e-7 → 2.8e-14 → … → 6e-45` (the
/// smallest subnormal) while `|e[0]|` stayed pinned at `8.3666`, spinning to
/// the 4000-iteration cap and returning a non-convergence error.
///
/// `σ = (‖(3, 4)‖, 0) = (5, 0)`: row 0 is the only nonzero row, so `σ₁` is its
/// 2-norm and the second singular value is exactly zero.
#[test]
fn trailing_zero_diagonal_deflates_to_the_row_norm() {
    check_bidiagonal::<f32>(&[3.0, 0.0], &[4.0], &[5.0, 0.0]);
    check_bidiagonal::<f64>(&[3.0, 0.0], &[4.0], &[5.0, 0.0]);
}

/// An **interior** zero diagonal: `B = [[0,5,0],[0,3,6],[0,0,4]]` — `d[0] = 0`
/// with `p = 0 < q = 2`, which takes the left-rotation row chase rather than
/// the trailing-column one. Both branches are therefore covered.
///
/// Oracle: column 0 is zero, so `σ₃ = 0` and the remaining singular values are
/// those of `M = [[5,0],[3,6],[0,4]]`, i.e. `√λ` for the eigenvalues of the
/// 2×2 `MᵀM = [[34, 18], [18, 52]]` — a closed form independent of this code.
#[test]
fn interior_zero_diagonal_chases_out_of_the_block() {
    let (trace, det) = (86.0f64, 1444.0f64);
    let discriminant = trace.mul_add(trace, -4.0 * det).sqrt();
    let expected = [
        ((trace + discriminant) / 2.0).sqrt(),
        ((trace - discriminant) / 2.0).sqrt(),
        0.0,
    ];
    check_bidiagonal::<f32>(&[0.0, 3.0, 4.0], &[5.0, 6.0], &expected);
    check_bidiagonal::<f64>(&[0.0, 3.0, 4.0], &[5.0, 6.0], &expected);
}

/// The chase writes `T::ZERO` into the deflated diagonal and nothing touches
/// it afterwards, so a zero reached that way is bit-exact rather than a
/// rounding residue. Pinning it distinguishes the structural fix from the
/// prohibited alternative of widening `scale + |e| == scale`, which would
/// leave the deficient direction at `O(ε‖B‖)` instead.
#[test]
fn chased_zero_singular_value_is_bit_exact() {
    for (diag, superdiag) in [
        (vec![3.0f64, 0.0], vec![4.0]),           // trailing-column chase
        (vec![0.0f64, 3.0, 4.0], vec![5.0, 6.0]), // interior row chase
    ] {
        let k = diag.len();
        let mut d: Vec<f32> = diag.iter().map(|&x| x as f32).collect();
        let mut e: Vec<f32> = (0..k)
            .map(|i| superdiag.get(i).copied().unwrap_or(0.0) as f32)
            .collect();
        qr_iterate::<f32, false>(&mut d, &mut e, k, &mut TransposedFactors::none()).unwrap();
        assert!(
            d.contains(&0.0),
            "the chased direction must be exactly zero, got {d:?}"
        );
    }
}

/// `dbdsqr`'s forward test splits at `|eᵢ| ≤ tol·μ` with
/// `tol = tolmul·ε`, `tolmul = min(100, ε^(−1/8)) ≈ 90.5` in `f64`: in
/// `d = (1, 1, 1)`, `e = (50ε, ½)` the recurrence starts at
/// `μ = |d₀| = 1`, so `e₀` splits before any rotation, and row 0 of both
/// accumulated factors stays exactly `e₀ᵀ` (the `½` couples only the
/// trailing pair). With `tol = ε` the block stays whole and the sweep's
/// rotations mix row 0 by `O(e₀)`.
#[test]
fn forward_test_splits_at_tolmul_eps() {
    let mut d = vec![1.0f64, 1.0, 1.0];
    let mut e = vec![50.0 * f64::EPSILON, 0.5, 0.0];
    let identity = |n: usize| -> Vec<f64> {
        (0..n * n)
            .map(|i| if i % (n + 1) == 0 { 1.0 } else { 0.0 })
            .collect()
    };
    let (mut u, mut v) = (identity(3), identity(3));
    qr_iterate::<f64, true>(
        &mut d,
        &mut e,
        3,
        &mut TransposedFactors::new(&mut u, 3, &mut v, 3),
    )
    .unwrap();
    assert_eq!(&u[..3], &[1.0, 0.0, 0.0], "U row 0: {u:?}");
    assert_eq!(&v[..3], &[1.0, 0.0, 0.0], "V row 0: {v:?}");
}

/// The SVD gate keeps the joint floor `√k·safmin` within `ε·‖A‖_F`:
/// F16, `k = 64`, entries `0.3` and `0.225` (`‖A‖_F/‖A‖_max = 1.25`,
/// `r = 1`, `l = 0`); the floor end `2^(3 − l)·smlnum = 0.5` moves `0.3`
/// up, where crediting `r` would leave it at the root end `0.25`.
#[test]
fn gate_keeps_the_deflation_floor_below_epsilon_times_the_norm() {
    use super::svd_bound;
    use crate::application::linalg::scaling;
    use eunomia::{FloatElement, NumericElement, F16};
    let k = 64;
    let mut values = vec![F16::from_f64(0.0); k * k];
    values[0] = F16::from_f64(0.3);
    values[1] = F16::from_f64(0.225);
    let frobenius = |scale: i32| {
        values
            .iter()
            .map(|v| v.scale_binary(scale).to_f64().powi(2))
            .sum::<f64>()
            .sqrt()
    };
    let (safmin, eps) = (2.0_f64.powi(-14), 2.0_f64.powi(-10));
    let joint_floor = (k as f64).sqrt() * safmin;
    assert!(joint_floor > eps * frobenius(0), "the input must violate");
    let exponent = scaling::gate_exponent(&values, 2, svd_bound(k, k))
        .expect("the range is non-empty")
        .expect("0.3 is below the floor end");
    assert!(joint_floor <= eps * frobenius(-exponent), "{exponent}");
    // `0.3·ones(64)`: `l = 5` credits `‖A‖_F = 64·‖A‖_max`, the floor end
    // falls to `2⁻⁶` below the root end `¼`, and the input stays in place;
    // without the credit the floor end `0.5` would move it.
    let ones = vec![F16::from_f64(0.3); k * k];
    let unmoved = scaling::gate_exponent(&ones, 2, svd_bound(k, k)).expect("non-empty");
    assert_eq!(unmoved, None);
}

/// `dbdsqr`'s second zero-shift test: on `d = (1, 1, 10⁻⁹)`,
/// `e = (½, 10⁻⁹)` the Wilkinson shift is `≈ 10⁻¹⁸`, below `ε·d₀²`, so
/// the step is exactly the zero-shift sweep (a shifted step with that
/// shift rounds differently).
#[test]
fn negligible_shift_takes_the_zero_shift_sweep() {
    use super::chase::Down;
    use super::sweep::{qr_step, SweepWindows};
    use super::zero_shift::zero_shift_sweep;
    let windows = SweepWindows::<f64>::new();
    let (mut d, mut e) = (vec![1.0, 1.0, 1e-9], vec![0.5, 1e-9, 0.0]);
    let (mut d0, mut e0) = (d.clone(), e.clone());
    qr_step::<f64, false, Down>(
        &mut d,
        &mut e,
        0,
        2,
        &mut TransposedFactors::none(),
        windows,
    );
    zero_shift_sweep::<f64, false, Down>(
        &mut d0,
        &mut e0,
        0,
        2,
        &mut TransposedFactors::none(),
        windows.rotation,
    );
    assert_eq!((d, e), (d0, e0));
}

/// `dbdsqr`'s first zero-shift test scales with the order: `k = 3`,
/// `d = (1, 1, x)`, `e = 0` gives `σ̃_min/σ_max = x` and `tol ≈ 90.5ε` in
/// `f64`, so the test fires for `x ≤ 1/(3·90.5) ≈ 1/272`. At `x = 1/150`
/// it must not fire (without the order factor it would, `90.5/150 < 1`);
/// at `x = 1/400` it must.
fn zero_shift_test_scales_with_the_order_for<C: super::chase::Chase>() {
    use super::chase::Oriented;
    use super::deflation::Deflation;
    for (x, fires) in [(1.0 / 150.0, false), (1.0 / 400.0, true)] {
        let (d, e) = (vec![1.0f64, 1.0, x], vec![0.0, 0.0, 0.0]);
        let (mut d, mut e) = (d, e);
        let deflation = Deflation::new(&d, &e, 3);
        let block = Oriented::<f64, C>::new(&mut d, &mut e, 0, 2);
        assert_eq!(deflation.shift_ruins_accuracy(&block), fires, "x = {x}");
    }
}

#[test]
fn zero_shift_test_scales_with_the_order_in_both_directions() {
    use super::chase::{Down, Up};
    zero_shift_test_scales_with_the_order_for::<Down>();
    zero_shift_test_scales_with_the_order_for::<Up>();
}

fn split_reads_oriented_bounds<C: super::chase::Chase>() -> usize {
    use super::chase::Oriented;
    use super::deflation::Deflation;

    let mut d = vec![1.0f64; 5];
    let mut e = vec![1.0f64; 4];
    let deflation = Deflation::new(&d, &e, 5);
    let mut block = Oriented::<f64, C>::new(&mut d, &mut e, 1, 3);
    block.set_e(2, 0.0);
    let stored = block.stored_superdiagonal(2);
    assert_eq!(deflation.split(&block), Some(stored));
    stored
}

#[test]
fn split_reads_oriented_bounds_in_both_directions() {
    use super::chase::{Down, Up};
    assert_eq!(split_reads_oriented_bounds::<Down>(), 2);
    assert_eq!(split_reads_oriented_bounds::<Up>(), 1);
}

/// [`Oriented::largest_entry`] reads exactly the active block `[p, q]`:
/// three sub-cases each make a different one of the block's boundary
/// elements — `d(p)`, `d(q)`, and the interior `e(q-1)` — the block's
/// unique in-block maximum, with every other in-block entry smaller. The
/// four *outside*-the-block entries (`d[0]`, `d[4]`, `e[0]`, `e[3]`) are
/// four pairwise-distinct values, each larger in magnitude than the
/// in-block maximum: a correct scan never reads them (bounded by `[p, q]`
/// regardless of their magnitude), so any mutant that reads even one —
/// dropping `d(p)`/`d(q)`/`e(q-1)` in favor of an off-by-one that reaches
/// past the block, or scanning the whole array — picks up a decoy larger
/// than `5.0` and is caught, distinguishable from every other decoy by its
/// distinct value. `LETO-BIDIAGONAL-SMAX-SCOPE-2026-09-27`.
fn largest_entry_reads_every_boundary_of_the_active_block<T: RealScalar>() {
    use super::chase::{Down, Oriented};
    // Block is [1, 3] inside a length-5 array; outside entries (indices 0,
    // 4 and the e's at 0, 3) are four distinct decoys, each larger than
    // the in-block maximum of 5, so an over-scanning mutant is caught.
    let (five, one, half) = (T::from_count(5), T::ONE, T::ONE.div(T::from_count(2)));
    let (d0, e0, e3, d4) = (
        T::from_count(101),
        T::from_count(103),
        T::from_count(107),
        T::from_count(109),
    );

    // d(p) = d(1) uniquely largest in-block.
    let mut d = vec![d0, five, one, half, d4];
    let mut e = vec![
        e0,
        T::from_count(2).div(T::from_count(10)),
        T::from_count(3).div(T::from_count(10)),
        e3,
    ];
    let block = Oriented::<T, Down>::new(&mut d, &mut e, 1, 3);
    assert_eq!(block.largest_entry(), five, "d(p) must be read");

    // d(q) = d(3) uniquely largest in-block.
    let mut d = vec![d0, half, one, five, d4];
    let mut e = vec![
        e0,
        T::from_count(2).div(T::from_count(10)),
        T::from_count(3).div(T::from_count(10)),
        e3,
    ];
    let block = Oriented::<T, Down>::new(&mut d, &mut e, 1, 3);
    assert_eq!(block.largest_entry(), five, "d(q) must be read");

    // e(q-1) = e(2), the interior superdiagonal, uniquely largest in-block.
    let seven_tenths = T::from_count(7).div(T::from_count(10));
    let mut d = vec![d0, half, one, seven_tenths, d4];
    let mut e = vec![e0, T::from_count(2).div(T::from_count(10)), five, e3];
    let block = Oriented::<T, Down>::new(&mut d, &mut e, 1, 3);
    assert_eq!(block.largest_entry(), five, "e(q-1) must be read");
}

#[test]
fn largest_entry_reads_every_boundary_of_the_active_block_across_scalar_types() {
    use eunomia::{Bf16, F16};
    largest_entry_reads_every_boundary_of_the_active_block::<f32>();
    largest_entry_reads_every_boundary_of_the_active_block::<f64>();
    largest_entry_reads_every_boundary_of_the_active_block::<F16>();
    largest_entry_reads_every_boundary_of_the_active_block::<Bf16>();
}

/// `SMAX` in `dbdsqr`'s first zero-shift test is taken over the active
/// block's own scan, not the whole bidiagonal (LAPACK 3.12.0 `dbdsqr.f`
/// lines 453–462: `SMAX = ABS(D(M))`, then `DO 70 LLL = 1, M-1` /
/// `LL = M-LLL`, negligible at line 460, else `SMAX = MAX(SMAX, ABSS,
/// ABSE)`; on the negligible branch `E(LL) = ZERO` at line 467 splits the
/// matrix and `LL = LL + 1` at line 479 fixes the new block's lower bound
/// — so the scan and the `SMAX` it feeds cover `[LL+1, M]` at that point).
///
/// A block `[1, 3]` of `d = (1, 1, x)` inside a length-5 bidiagonal whose
/// *outside* entries (`d[0]`, `d[4]`, `e[0]`, `e[3]`) are `1000×` the
/// block's own scale must not fire the zero-shift test at an `x` just
/// above the block-scoped cutoff `bound/(n·tol)` (`bound = max(ε,
/// tol/100)`, `tol = tolmul·ε`) — a whole-bidiagonal `SMAX` instead makes
/// the denominator `1000×` too large, driving `n·tol·(σ̃/σ_max)` far below
/// `bound` and firing regardless of `x`. Generic over every shipped
/// scalar type: `tolmul` (hence the cutoff) differs by type — `f64`'s
/// `ε^(-1/8) ≈ 90.5` versus the `10` floor `f32`/`F16`/`Bf16` all hit —
/// and `1000×` a block of scale `1` stays representable even in `F16`
/// (max ≈ 65504). `LETO-BIDIAGONAL-SMAX-SCOPE-2026-09-27`.
fn zero_shift_test_scopes_smax_to_the_active_block<T: RealScalar>() {
    use super::chase::{Down, Oriented};
    use super::deflation::Deflation;
    use crate::application::linalg::thresholds;

    // `dbdsqr`'s tolmul/tol/bound, exactly as `Deflation::new` derives them.
    let eps = thresholds::machine_epsilon::<T>();
    let eighth_root = T::ONE.div(eps).sqrt().sqrt().sqrt();
    let (ten, hundred) = (T::from_count(10), T::from_count(100));
    let capped = if eighth_root < hundred {
        eighth_root
    } else {
        hundred
    };
    let tolmul = if capped > ten { capped } else { ten };
    let tol = tolmul.mul(eps);
    let hundredth = tol.div(T::from_count(100));
    let bound = if eps > hundredth { eps } else { hundredth };

    let n = 5usize;
    let outside = T::from_count(1000);
    // Block-scoped SMAX is 1: the zero-shift test fires when
    // `n·tol·x ≤ bound`, i.e. `x ≤ bound/(n·tol)`. Pick `x` at twice that
    // cutoff so the correctly-scoped test does not fire.
    let cutoff = bound.div(T::from_count(n).mul(tol));
    let x = cutoff.add(cutoff);
    assert!(
        x < T::ONE,
        "construction invariant: x must stay below the block's own scale of 1"
    );

    let mut d = vec![outside, T::ONE, T::ONE, x, outside];
    let mut e = vec![outside, T::ZERO, T::ZERO, outside];
    // `Deflation::new` reads the whole array for `tol`/`order` (LAPACK's `N`,
    // not the block size — dbdsqr.f's `N*TOL*(SMINL/SMAX)` test), unaffected
    // by this fix; only `SMAX` (`largest_entry`) is at issue here.
    let deflation = Deflation::new(&d, &e, n);
    let block = Oriented::<T, Down>::new(&mut d, &mut e, 1, 3);
    assert_eq!(
        block.largest_entry(),
        T::ONE,
        "SMAX must come from the block [1, 3], not the outside entries"
    );
    assert!(
        !deflation.shift_ruins_accuracy(&block),
        "a whole-bidiagonal SMAX would fire the zero-shift test regardless of x; \
         the block's own SMAX of 1 must not, at this construction's x"
    );
}

#[test]
fn zero_shift_test_scopes_smax_to_the_active_block_across_scalar_types() {
    use eunomia::{Bf16, F16};
    zero_shift_test_scopes_smax_to_the_active_block::<f32>();
    zero_shift_test_scopes_smax_to_the_active_block::<f64>();
    zero_shift_test_scopes_smax_to_the_active_block::<F16>();
    zero_shift_test_scopes_smax_to_the_active_block::<Bf16>();
}

/// A `largest_entry` that dropped the superdiagonal from its scan (only
/// visiting `d(p)` and `d(j + 1)`, never `e(j)`) would still pass every
/// prior `largest_entry`/`SMAX` test here: the boundary-reading case pins
/// `e(q-1)` against decoy *outside* entries rather than an in-block `d`,
/// and the zero-shift case makes its in-block `e`s exactly zero (`e[1] =
/// e[2] = T::ZERO`), so neither can distinguish "reads `e`" from "reads
/// only `d`, and the outside entries never mattered."
///
/// This fixture is additionally the *reachable* form the prior zero-shift
/// case was not: `dbdsqr` isolates a block by driving its boundary
/// superdiagonal entry to exactly zero (LAPACK 3.12.0 `dbdsqr.f` line 467,
/// `E(LL) = ZERO`, once `ABS(E(LL))` tests negligible at line 460) — not by
/// leaving them at some large decoy scale. `e[0] = e[3] = 0` here severs
/// the block `[1, 3]` from `d[0]` and `d[4]` exactly as the real search
/// would, and the in-block superdiagonal `e[2]` is the block's unique
/// maximum, strictly larger than every in-block `d`. A scan that skips `e`
/// computes `1` (the in-block `d`s); the correct scan computes `e[2]`.
fn largest_entry_is_dominated_by_a_reachable_in_block_superdiagonal<T: RealScalar>() {
    use super::chase::{Down, Oriented};

    let (outside_d0, outside_d4) = (T::from_count(7), T::from_count(9).neg());
    let one = T::ONE;
    let mut d = vec![outside_d0, one, one, one, outside_d4];
    // e[0] = e[3] = 0: block [1, 3] is genuinely severed from d[0]/d[4],
    // as a real split would leave it. e[2] dominates every in-block d.
    let mut e = vec![
        T::ZERO,
        T::from_count(2).div(T::from_count(10)),
        T::from_count(5),
        T::ZERO,
    ];
    let block = Oriented::<T, Down>::new(&mut d, &mut e, 1, 3);
    assert_eq!(
        block.largest_entry(),
        T::from_count(5),
        "SMAX must be the in-block superdiagonal e[2], not the in-block d's"
    );
}

#[test]
fn largest_entry_is_dominated_by_a_reachable_in_block_superdiagonal_across_scalar_types() {
    use eunomia::{Bf16, F16};
    largest_entry_is_dominated_by_a_reachable_in_block_superdiagonal::<f32>();
    largest_entry_is_dominated_by_a_reachable_in_block_superdiagonal::<f64>();
    largest_entry_is_dominated_by_a_reachable_in_block_superdiagonal::<F16>();
    largest_entry_is_dominated_by_a_reachable_in_block_superdiagonal::<Bf16>();
}