Skip to main content

gam_math/
jet_tower.rs

1//! Taylor-jet tower algebra: write each family's row log-likelihood ONCE,
2//! derive the entire `RowKernel<K>` derivative tower mechanically (#932).
3//!
4//! # The object
5//!
6//! [`Tower4<K>`] is a truncated multivariate Taylor scalar in `K` primary
7//! variables, carrying the value and ALL partial derivatives through fourth
8//! order as full (unsymmetrized) tensors:
9//!
10//! ```text
11//!   v        ℓ
12//!   g[a]     ∂ℓ/∂p_a
13//!   h[a][b]  ∂²ℓ/∂p_a∂p_b
14//!   t3[abc]  ∂³ℓ/∂p_a∂p_b∂p_c
15//!   t4[abcd] ∂⁴ℓ/∂p_a∂p_b∂p_c∂p_d
16//! ```
17//!
18//! Arithmetic (`+ − × ÷`, scalar mixes) propagates the tower by the exact
19//! Leibniz rule; unary transcendentals propagate by the exact multivariate
20//! Faà di Bruno formula given a `[f, f′, f″, f‴, f⁗]` stack evaluated at the
21//! inner value. This is truncated Taylor ALGEBRA — exact derivatives of the
22//! evaluated expression, not finite differences, not an approximation —
23//! fully compatible with the exact-REML-only policy.
24//!
25//! One evaluation of a row NLL program at seeded variables yields, in a
26//! single pass, every channel the [`super::row_kernel::RowKernel`] trait
27//! demands: `row_kernel` (value/∇/H), `row_third_contracted(dir)` (contract
28//! `t3` with `dir`), and `row_fourth_contracted(u, v)` (contract `t4` with
29//! `u` and `v`). The directional cross-channels that hand-written towers
30//! drop (#736's residual gap) cannot be dropped here: there is no separate
31//! "channel" to forget — every derivative of the one expression is carried.
32//!
33//! # Why this exists (the bug genus)
34//!
35//! Every family today hand-writes its tower: value in one function,
36//! gradient in another, `pdfthird_derivative`/`pdffourth_derivative`,
37//! entry/exit-specific cross blocks — thousands of lines of calculus that
38//! drift. #736 was a sign flip in a hand-written cross-Hessian block,
39//! invisible until a new consumer touched it; #948 is a derivative path
40//! that is not the derivative of the evaluated row loss (clamped-μ
41//! surrogate); the objective↔gradient desync class is the same disease at
42//! the criterion level. A tower-derived kernel is exact-by-construction:
43//! the value channel IS the production loss expression, so its derivative
44//! channels cannot desync from it.
45//!
46//! # Relation to `jet_partitions::MultiDirJet`
47//!
48//! The tree already carries a *directional* jet (bitmask coefficients over
49//! distinct seeded directions, heap-allocated, Bell-partition compose) used
50//! inside the marginal-slope and latent-survival families. It answers "the
51//! derivative along THESE specific directions" and must be re-seeded and
52//! re-evaluated per direction tuple (e.g. 10 symmetric `(a,b)` pairs for a
53//! K=4 fourth contraction). `Tower4` answers ALL of them from one
54//! evaluation: contraction happens AFTER differentiation, as plain linear
55//! algebra on the stored tensors. Use `MultiDirJet` when you need a handful
56//! of directions of a huge-K expression; use `Tower4` when you need the
57//! complete small-K tower — which is exactly the `RowKernel<K≤4>` shape.
58//! The `[f64; 5]` unary-derivative stacks
59//! (`unary_derivatives_neglog_phi`, …) are signature-compatible with
60//! [`Tower4::compose_unary`], so the families' existing special-function
61//! stacks are directly reusable.
62//!
63//! # Stability discipline (why this is NOT autodiff)
64//!
65//! Differentiating the primal code path inherits its instabilities: a jet
66//! pushed through a naive `ln(1 + e^η)` is garbage in the saturated tail
67//! even though the true derivative σ(η) is benign there. This module
68//! therefore splits responsibility: **humans own primitive stability,
69//! the algebra owns combinatorics**. Tail-critical special functions enter
70//! a program ONLY as hand-certified `[f64; 5]` derivative stacks through
71//! [`Tower4::compose_unary`] — the same stacks the families already write
72//! (`unary_derivatives_neglog_phi` and friends, built on erfcx/log_ndtr) —
73//! and the tower mechanizes only the Leibniz/Faà di Bruno composition,
74//! which is where hand-written towers actually fail (#736 was a
75//! composition sign flip, not a primitive error). Program authors must use
76//! a stable primitive stack wherever the f64 production loss does; the
77//! convenience methods (`exp`, `ln`, `sqrt`, …) are for expressions whose
78//! arguments are tame by construction.
79//!
80//! # Storage convention
81//!
82//! Tensors are stored FULL, not symmetric-packed: `t4` for K=4 is 256
83//! doubles where 35 would do. This is deliberate clarity-over-speed for the
84//! oracle role — indexing is trivially auditable, contraction loops are
85//! obvious, and the redundancy is itself a checked invariant (the algebra
86//! only ever writes symmetric values). Symmetric packing is a later,
87//! profile-justified optimization behind the same API.
88//!
89//! # Deployment ladder (#932)
90//!
91//! 1. This module: the algebra + the program seam + the oracle.
92//! 2. Universal oracle: every hand-written `RowKernel` gains a CI test
93//!    asserting channel-by-channel agreement with a [`RowProgram`] written
94//!    once — see [`verify_kernel_channels`]. This alone would have caught
95//!    #736 at introduction.
96//! 3. Derive every channel through [`program_row_kernel`],
97//!    [`program_third_contracted`], [`program_fourth_contracted`], or
98//!    [`program_full_tower`], selecting only the representation its consumer
99//!    needs while retaining one expression.
100//! 4. New families (#914/#916/#917 ZI/ordinal/expectile, #921's location-
101//!    scale port) implement ONLY [`RowProgram`] and get an exact fourth-order
102//!    tower for the price of writing the likelihood.
103
104use crate::jet_algebra;
105
106/// Truncated fourth-order multivariate Taylor scalar in `K` variables.
107///
108/// See the module documentation for semantics and conventions. `Copy` is
109/// intentional despite the size (2 KiB at K=4): towers are per-row
110/// temporaries that live entirely in registers/stack during a row program,
111/// and value semantics keep program code readable (`a * b + c`).
112#[derive(Clone, Copy, Debug)]
113pub struct Tower4<const K: usize> {
114    /// Value ℓ.
115    pub v: f64,
116    /// Gradient ∂ℓ/∂p_a.
117    pub g: [f64; K],
118    /// Hessian ∂²ℓ/∂p_a∂p_b (symmetric).
119    pub h: [[f64; K]; K],
120    /// Third derivatives ∂³ℓ/∂p_a∂p_b∂p_c (fully symmetric).
121    pub t3: [[[f64; K]; K]; K],
122    /// Fourth derivatives ∂⁴ℓ/∂p_a∂p_b∂p_c∂p_d (fully symmetric).
123    pub t4: [[[[f64; K]; K]; K]; K],
124}
125
126impl<const K: usize> Tower4<K> {
127    /// The additive identity.
128    pub fn zero() -> Self {
129        Self {
130            v: 0.0,
131            g: [0.0; K],
132            h: [[0.0; K]; K],
133            t3: [[[0.0; K]; K]; K],
134            t4: [[[[0.0; K]; K]; K]; K],
135        }
136    }
137
138    /// A constant: value `c`, all derivatives zero.
139    pub fn constant(c: f64) -> Self {
140        let mut out = Self::zero();
141        out.v = c;
142        out
143    }
144
145    /// The seeded variable `p_idx` with current value `value`:
146    /// unit first derivative in slot `idx`, zero elsewhere and above.
147    pub fn variable(value: f64, idx: usize) -> Self {
148        let mut out = Self::constant(value);
149        out.g[idx] = 1.0;
150        out
151    }
152
153    /// Read the (fully symmetric) derivative tensor entry whose differentiation
154    /// axes are `labels` (length 0..=4): value, `g`, `h`, `t3`, `t4`.
155    #[inline]
156    fn deriv(&self, labels: &[usize]) -> f64 {
157        assert!(
158            labels.len() <= 4,
159            "Tower4 carries at most fourth-order derivatives"
160        );
161        match labels.len() {
162            0 => self.v,
163            1 => self.g[labels[0]],
164            2 => self.h[labels[0]][labels[1]],
165            3 => self.t3[labels[0]][labels[1]][labels[2]],
166            _ => self.t4[labels[0]][labels[1]][labels[2]][labels[3]],
167        }
168    }
169
170    /// Exact truncated Leibniz product `D_S(ab) = Σ_{T ⊆ S} D_T(a) · D_{S∖T}(b)`.
171    ///
172    /// # Codegen
173    ///
174    /// Each output entry's `2^m` subset sum is written as a compact straight-line
175    /// expression instead of the shared [`jet_algebra::leibniz_product`] subset
176    /// walker (which, per entry, builds `SlotBuf`s and `match`-dispatches the
177    /// `deriv` closure across all `2^m` subsets). The loop nest over `(i,j,k,l)`
178    /// is unchanged — only the inner per-entry sum is unrolled — so this does NOT
179    /// unroll over `K` and does NOT bloat code: on a `Tower4<9>` mul-and-read
180    /// consumer the new form is faster AND smaller (asm: 34 outlined walker `bl`
181    /// calls → 0, 21.1 KiB → 14.3 KiB, +100 NEON `.2d` ops).
182    ///
183    /// BIT-IDENTICAL to the walker: each entry's terms are in the walker's exact
184    /// subset-enumeration order (subset bit `b` ↔ position `b`, `sub = 0..2^m`),
185    /// and the per-entry `acc` accumulator mirrors the walker's `total = 0.0`
186    /// start so a signed-zero leading product collapses to `+0.0` identically —
187    /// which matters because real jets carry exact-`0.0` channels
188    /// (`constant`/`variable` towers). Proven `to_bits`-identical on
189    /// `v`/`g`/`h`/`t3`/`t4` across `K ∈ {2,3,4,9}`, 5000 inputs each with ~30 %
190    /// exact-`0.0` channels and signed values (a no-leading-`0.0` form fails this
191    /// stress — the accumulator start is load-bearing).
192    pub fn mul(&self, o: &Self) -> Self {
193        let a = self;
194        let b = o;
195        let mut out = Self::zero();
196        out.v = a.v * b.v;
197        for i in 0..K {
198            // subsets of {i}: {} {i}
199            let mut acc = 0.0;
200            acc += a.v * b.g[i];
201            acc += a.g[i] * b.v;
202            out.g[i] = acc;
203        }
204        // Hessian is symmetric under i↔j; compute the upper triangle and mirror
205        // (see [`Tower2::mul`] — same term order, enforces exact symmetry).
206        for i in 0..K {
207            for j in i..K {
208                // subsets of {i,j}: {} {i} {j} {ij}
209                let mut acc = 0.0;
210                acc += a.v * b.h[i][j];
211                acc += a.g[i] * b.g[j];
212                acc += a.g[j] * b.g[i];
213                acc += a.h[i][j] * b.v;
214                out.h[i][j] = acc;
215                out.h[j][i] = acc;
216            }
217        }
218        for i in 0..K {
219            for j in 0..K {
220                for k in 0..K {
221                    // subsets of {i,j,k}: {} {i} {j} {ij} {k} {ik} {jk} {ijk}
222                    let mut acc = 0.0;
223                    acc += a.v * b.t3[i][j][k];
224                    acc += a.g[i] * b.h[j][k];
225                    acc += a.g[j] * b.h[i][k];
226                    acc += a.h[i][j] * b.g[k];
227                    acc += a.g[k] * b.h[i][j];
228                    acc += a.h[i][k] * b.g[j];
229                    acc += a.h[j][k] * b.g[i];
230                    acc += a.t3[i][j][k] * b.v;
231                    out.t3[i][j][k] = acc;
232                }
233            }
234        }
235        for i in 0..K {
236            for j in 0..K {
237                for k in 0..K {
238                    for l in 0..K {
239                        // subsets of {i,j,k,l} in bit order sub = 0..16
240                        let mut acc = 0.0;
241                        acc += a.v * b.t4[i][j][k][l];
242                        acc += a.g[i] * b.t3[j][k][l];
243                        acc += a.g[j] * b.t3[i][k][l];
244                        acc += a.h[i][j] * b.h[k][l];
245                        acc += a.g[k] * b.t3[i][j][l];
246                        acc += a.h[i][k] * b.h[j][l];
247                        acc += a.h[j][k] * b.h[i][l];
248                        acc += a.t3[i][j][k] * b.g[l];
249                        acc += a.g[l] * b.t3[i][j][k];
250                        acc += a.h[i][l] * b.h[j][k];
251                        acc += a.h[j][l] * b.h[i][k];
252                        acc += a.t3[i][j][l] * b.g[k];
253                        acc += a.h[k][l] * b.h[i][j];
254                        acc += a.t3[i][k][l] * b.g[j];
255                        acc += a.t3[j][k][l] * b.g[i];
256                        acc += a.t4[i][j][k][l] * b.v;
257                        out.t4[i][j][k][l] = acc;
258                    }
259                }
260            }
261        }
262        out
263    }
264
265    /// Ref-taking elementwise sum, the by-ref twin of the `std::ops::Add`
266    /// operator (which consumes by value). Mirrors the inherent `mul`/`scale`
267    /// API so a chain like `a.mul(&b).add(&c)` reads uniformly without moving
268    /// out of the borrowed operands.
269    pub fn add(&self, o: &Self) -> Self {
270        *self + *o
271    }
272
273    /// Ref-taking elementwise difference, the by-ref twin of `std::ops::Sub`.
274    pub fn sub(&self, o: &Self) -> Self {
275        *self + o.scale(-1.0)
276    }
277
278    /// Exact multivariate Faà di Bruno composition `f ∘ self`.
279    ///
280    /// `d = [f(u), f′(u), f″(u), f‴(u), f⁗(u)]` evaluated at `u = self.v` —
281    /// the SAME `[f64; 5]` stack shape the families' existing
282    /// `unary_derivatives_*` helpers produce, so those special-function
283    /// stacks (Φ, log-Φ, normal pdf, …) plug in directly.
284    ///
285    /// The order-m output sums over the set partitions of the m indices
286    /// (Bell(3) = 5 terms at order 3, Bell(4) = 15 at order 4), grouped by
287    /// block count: each partition into r blocks contributes
288    /// `f⁽ʳ⁾ · Π_blocks D_block(u)`.
289    ///
290    /// # Codegen
291    ///
292    /// Evaluated as a compact closed form (the Bell(4)=15 set-partitions of
293    /// `t4`, Bell(3)=5 of `t3`, …) instead of routing through the recursive
294    /// [`jet_algebra::faa_di_bruno`] walker (per-output `for_each_partition`
295    /// recursion + per-block `SlotBuf` + closure dispatch). The loop nest is
296    /// identical to the walker's (`for i,j,k,l`); only the per-entry partition
297    /// sum is straight-line, so this does NOT unroll over `K` and does NOT
298    /// bloat code — measured on a `Tower4<9>` compose-and-read consumer the new
299    /// form is both faster and SMALLER (asm: 94 outlined walker `bl` calls → 0,
300    /// 47.5 KiB → 16.7 KiB, +197 NEON `.2d` ops).
301    ///
302    /// BIT-IDENTICAL to the walker: each channel's terms are emitted in the
303    /// walker's exact partition-enumeration order, each term's block products
304    /// are left-associated exactly as the walker's `prod *= block`, and the
305    /// per-channel `acc` accumulator mirrors the walker's `total = 0.0` start
306    /// (so signed-zero products collapse to `+0.0` identically). The order-4
307    /// term sequence was generated from the walker's own enumeration. Proven
308    /// `to_bits`-identical on `v`/`g`/`h`/`t3`/`t4` across `K ∈ {2,3,4,9}`,
309    /// 5000 random inputs each (zeroed / sign-varied stacks included).
310    pub fn compose_unary(&self, d: [f64; 5]) -> Self {
311        let mut out = Self::zero();
312        out.v = d[0];
313        for i in 0..K {
314            let mut acc = 0.0;
315            acc += d[1] * self.g[i];
316            out.g[i] = acc;
317        }
318        for i in 0..K {
319            for j in 0..K {
320                let mut acc = 0.0;
321                acc += d[1] * self.h[i][j];
322                acc += d[2] * self.g[i] * self.g[j];
323                out.h[i][j] = acc;
324            }
325        }
326        for i in 0..K {
327            for j in 0..K {
328                for k in 0..K {
329                    // walker partitions: {ijk} {ij}{k} {ik}{j} {i}{jk} {i}{j}{k}
330                    let mut acc = 0.0;
331                    acc += d[1] * self.t3[i][j][k];
332                    acc += d[2] * self.h[i][j] * self.g[k];
333                    acc += d[2] * self.h[i][k] * self.g[j];
334                    acc += d[2] * self.g[i] * self.h[j][k];
335                    acc += d[3] * self.g[i] * self.g[j] * self.g[k];
336                    out.t3[i][j][k] = acc;
337                }
338            }
339        }
340        for i in 0..K {
341            for j in 0..K {
342                for k in 0..K {
343                    for l in 0..K {
344                        // Bell(4)=15 partitions, walker enumeration order.
345                        let mut acc = 0.0;
346                        acc += d[1] * self.t4[i][j][k][l];
347                        acc += d[2] * self.t3[i][j][k] * self.g[l];
348                        acc += d[2] * self.t3[i][j][l] * self.g[k];
349                        acc += d[2] * self.h[i][j] * self.h[k][l];
350                        acc += d[3] * self.h[i][j] * self.g[k] * self.g[l];
351                        acc += d[2] * self.t3[i][k][l] * self.g[j];
352                        acc += d[2] * self.h[i][k] * self.h[j][l];
353                        acc += d[3] * self.h[i][k] * self.g[j] * self.g[l];
354                        acc += d[2] * self.h[i][l] * self.h[j][k];
355                        acc += d[2] * self.g[i] * self.t3[j][k][l];
356                        acc += d[3] * self.g[i] * self.h[j][k] * self.g[l];
357                        acc += d[3] * self.h[i][l] * self.g[j] * self.g[k];
358                        acc += d[3] * self.g[i] * self.h[j][l] * self.g[k];
359                        acc += d[3] * self.g[i] * self.g[j] * self.h[k][l];
360                        acc += d[4] * self.g[i] * self.g[j] * self.g[k] * self.g[l];
361                        out.t4[i][j][k][l] = acc;
362                    }
363                }
364            }
365        }
366        out
367    }
368
369    /// Compose with a unary special-function whose `[f64; 5]` derivative stack is
370    /// built from the base value through `stack_fn`. Evaluates `stack_fn(self.v)`
371    /// once and forwards to [`Self::compose_unary`], so it is bit-identical to the
372    /// explicit `self.compose_unary(stack_fn(self.v))` form.
373    #[inline]
374    pub fn compose_unary_with(&self, stack_fn: impl Fn(f64) -> [f64; 5]) -> Self {
375        self.compose_unary(stack_fn(self.v))
376    }
377
378    /// Single-active-slot fast path for [`Self::compose_unary`].
379    ///
380    /// When the inner jet `self` has derivative support ONLY on the all-`slot`
381    /// diagonal channels — i.e. it is a univariate jet in primary `slot`
382    /// scattered into the `K`-wide layout (`g[a] = 0`, `h[a][b] = 0`,
383    /// `t3 = 0`, `t4 = 0` for any axis `≠ slot`) — the multivariate Faà di
384    /// Bruno walk collapses. Every output channel whose axis tuple contains an
385    /// axis `≠ slot` is structurally `0`: each set-partition has a block
386    /// covering that axis, that block reads an off-`slot` derivative of `self`
387    /// (which is `0`), so the block product and the whole partition vanish, and
388    /// the channel sums to the walker's `total = 0.0` start, i.e. `+0.0`. Only
389    /// the five diagonal channels (`v`, `g[slot]`, `h[slot][slot]`,
390    /// `t3[slot]³`, `t4[slot]⁴`) survive.
391    ///
392    /// This computes exactly those five as STRAIGHT-LINE accumulations, each in
393    /// the EXACT term order of [`Self::compose_unary`]'s diagonal
394    /// (`i = j = k = l = slot`) case — so they are BIT-IDENTICAL to
395    /// [`Self::compose_unary`] on the diagonal — and leaves every other channel
396    /// at the zero-init `+0.0`, which the full walk also produces (the
397    /// off-`slot` collapse is `to_bits`-`+0.0`, signed-zero products included;
398    /// proven across `K ∈ {2,3,4,9}`, 5000 single-slot inputs each). At any
399    /// `K ≥ 2` this is far fewer floating-point operations than materialising
400    /// the full `1 + K + K² + K³ + K⁴` channel set whose off-diagonal entries
401    /// are all zero, and far cheaper than the recursive set-partition walker the
402    /// diagonal channels previously routed through (a measured ~9.5× speedup vs
403    /// the full `compose_unary`, recovering a 5.9× walker regression at the
404    /// `K ∈ {2,3}` BMS tower widths).
405    ///
406    /// `#[inline]` so an adopting consumer pays no `bl` call (uninlined, the
407    /// five-channel build does not amortise the call/spill overhead).
408    ///
409    /// # Precondition
410    ///
411    /// The caller guarantees the single-active-slot structure. If it does not
412    /// hold, the off-`slot` channels would be wrongly zeroed; use the full
413    /// [`Self::compose_unary`] in that case.
414    #[inline]
415    pub fn compose_unary_single_slot(&self, d: [f64; 5], slot: usize) -> Self {
416        let mut out = Self::zero();
417        let s = slot;
418        let g = self.g[s];
419        let h = self.h[s][s];
420        let t3 = self.t3[s][s][s];
421        let t4 = self.t4[s][s][s][s];
422        out.v = d[0];
423        // g (i=s): d1*g
424        out.g[s] = {
425            let mut acc = 0.0;
426            acc += d[1] * g;
427            acc
428        };
429        // h (i=j=s): d1*h + d2*g*g
430        out.h[s][s] = {
431            let mut acc = 0.0;
432            acc += d[1] * h;
433            acc += d[2] * g * g;
434            acc
435        };
436        // t3 (i=j=k=s): exact term order of compose_unary's inner loop.
437        out.t3[s][s][s] = {
438            let mut acc = 0.0;
439            acc += d[1] * t3;
440            acc += d[2] * h * g;
441            acc += d[2] * h * g;
442            acc += d[2] * g * h;
443            acc += d[3] * g * g * g;
444            acc
445        };
446        // t4 (i=j=k=l=s): exact term order of compose_unary's inner loop.
447        out.t4[s][s][s][s] = {
448            let mut acc = 0.0;
449            acc += d[1] * t4;
450            acc += d[2] * t3 * g;
451            acc += d[2] * t3 * g;
452            acc += d[2] * h * h;
453            acc += d[3] * h * g * g;
454            acc += d[2] * t3 * g;
455            acc += d[2] * h * h;
456            acc += d[3] * h * g * g;
457            acc += d[2] * h * h;
458            acc += d[2] * g * t3;
459            acc += d[3] * g * h * g;
460            acc += d[3] * h * g * g;
461            acc += d[3] * g * h * g;
462            acc += d[3] * g * g * h;
463            acc += d[4] * g * g * g * g;
464            acc
465        };
466        out
467    }
468
469    /// Multiply every channel by a plain scalar.
470    pub fn scale(&self, s: f64) -> Self {
471        let mut out = *self;
472        out.v *= s;
473        for i in 0..K {
474            out.g[i] *= s;
475            for j in 0..K {
476                out.h[i][j] *= s;
477                for k in 0..K {
478                    out.t3[i][j][k] *= s;
479                    for l in 0..K {
480                        out.t4[i][j][k][l] *= s;
481                    }
482                }
483            }
484        }
485        out
486    }
487
488    /// e^self.
489    pub fn exp(&self) -> Self {
490        let e = self.v.exp();
491        self.compose_unary([e, e, e, e, e])
492    }
493
494    /// ln(self). Caller guarantees positivity (likelihood programs do).
495    pub fn ln(&self) -> Self {
496        let u = self.v;
497        let r = 1.0 / u;
498        self.compose_unary([u.ln(), r, -r * r, 2.0 * r * r * r, -6.0 * r * r * r * r])
499    }
500
501    /// 1/self.
502    pub fn recip(&self) -> Self {
503        let r = 1.0 / self.v;
504        let r2 = r * r;
505        self.compose_unary([r, -r2, 2.0 * r2 * r, -6.0 * r2 * r2, 24.0 * r2 * r2 * r])
506    }
507
508    /// √self. Caller guarantees positivity.
509    pub fn sqrt(&self) -> Self {
510        let u = self.v;
511        let s = u.sqrt();
512        self.compose_unary([
513            s,
514            0.5 / s,
515            -0.25 / (u * s),
516            0.375 / (u * u * s),
517            -0.9375 / (u * u * u * s),
518        ])
519    }
520
521    /// self^a for real exponent `a`. Caller guarantees a positive base.
522    pub fn powf(&self, a: f64) -> Self {
523        let u = self.v;
524        let f0 = u.powf(a);
525        let f1 = a * u.powf(a - 1.0);
526        let f2 = a * (a - 1.0) * u.powf(a - 2.0);
527        let f3 = a * (a - 1.0) * (a - 2.0) * u.powf(a - 3.0);
528        let f4 = a * (a - 1.0) * (a - 2.0) * (a - 3.0) * u.powf(a - 4.0);
529        self.compose_unary([f0, f1, f2, f3, f4])
530    }
531
532    /// ln Γ(self). Caller guarantees positivity.
533    pub fn ln_gamma(&self) -> Self {
534        self.compose_unary(ln_gamma_derivative_stack(self.v))
535    }
536
537    /// ψ(self), the digamma function. Caller guarantees positivity.
538    pub fn digamma(&self) -> Self {
539        self.compose_unary(digamma_derivative_stack(self.v))
540    }
541
542    /// ψ′(self), the trigamma function. Caller guarantees positivity.
543    pub fn trigamma(&self) -> Self {
544        self.compose_unary(trigamma_derivative_stack(self.v))
545    }
546
547    /// Contract `t3` with one primary-space direction:
548    /// `out[a][b] = Σ_c t3[a][b][c] · dir[c]` — exactly the
549    /// `row_third_contracted` shape.
550    ///
551    /// The output is symmetric in `(a, b)`: `t3` is fully index-symmetric, so
552    /// `t3[a][b][c] == t3[b][a][c]` and the `Σ_c` contraction gives
553    /// `out[a][b] == out[b][a]` term-for-term, in the same `c` order. We compute
554    /// only the upper triangle `a ≤ b` (the inner contraction is unchanged and
555    /// stays contiguous/vectorisable) and mirror into the lower triangle — this
556    /// is BIT-IDENTICAL to the full `a, b ∈ 0..K` nest while doing ~2× fewer
557    /// inner contractions, with no dense scatter (the mirror is a `K × K` copy).
558    pub fn third_contracted(&self, dir: &[f64; K]) -> [[f64; K]; K] {
559        let mut out = [[0.0; K]; K];
560        for a in 0..K {
561            for b in a..K {
562                let mut acc = 0.0;
563                for c in 0..K {
564                    acc += self.t3[a][b][c] * dir[c];
565                }
566                out[a][b] = acc;
567                out[b][a] = acc;
568            }
569        }
570        out
571    }
572
573    /// Contract `t4` with two primary-space directions:
574    /// `out[a][b] = Σ_{c,d} t4[a][b][c][d] · u[c] · v[d]` — exactly the
575    /// `row_fourth_contracted` shape.
576    ///
577    /// As in [`Self::third_contracted`], the output is symmetric in `(i, j)`
578    /// (`t4[j][i][k][l] == t4[i][j][k][l]`, contracted in the same `(k, l)`
579    /// order), so the upper triangle `i ≤ j` is computed and mirrored —
580    /// BIT-IDENTICAL to the full nest, ~2× fewer inner `Σ_{k,l}` contractions,
581    /// and the inner double loop stays the original contiguous/vectorisable form.
582    pub fn fourth_contracted(&self, u: &[f64; K], w: &[f64; K]) -> [[f64; K]; K] {
583        let mut out = [[0.0; K]; K];
584        for i in 0..K {
585            for j in i..K {
586                let mut acc = 0.0;
587                for k in 0..K {
588                    for l in 0..K {
589                        acc += self.t4[i][j][k][l] * u[k] * w[l];
590                    }
591                }
592                out[i][j] = acc;
593                out[j][i] = acc;
594            }
595        }
596        out
597    }
598}
599
600impl<const K: usize> jet_algebra::JetAlgebra<5> for Tower4<K> {
601    #[inline]
602    fn derivative(&self, labels: &[usize]) -> f64 {
603        self.deriv(labels)
604    }
605
606    fn map_derivatives<F>(&self, mut f: F) -> Self
607    where
608        F: FnMut(&[usize]) -> f64,
609    {
610        let mut out = Self::zero();
611        out.v = f(&[]);
612        for i in 0..K {
613            let labels = [i];
614            out.g[i] = f(&labels);
615        }
616        for i in 0..K {
617            for j in 0..K {
618                let labels = [i, j];
619                out.h[i][j] = f(&labels);
620            }
621        }
622        for i in 0..K {
623            for j in 0..K {
624                for k in 0..K {
625                    let labels = [i, j, k];
626                    out.t3[i][j][k] = f(&labels);
627                }
628            }
629        }
630        for i in 0..K {
631            for j in 0..K {
632                for k in 0..K {
633                    for l in 0..K {
634                        let labels = [i, j, k, l];
635                        out.t4[i][j][k][l] = f(&labels);
636                    }
637                }
638            }
639        }
640        out
641    }
642}
643
644/// Truncated SECOND-order multivariate Taylor scalar in `K` variables.
645///
646/// This is the value/gradient/Hessian-only sibling of [`Tower4`]. Every
647/// channel it carries (`v`, `g`, `h`) is computed by the SAME formulas
648/// [`Tower4`] uses for those orders, so for any program written over both
649/// towers the order-≤2 outputs are *bit-identical*: the order-2 Leibniz and
650/// Faà-di-Bruno terms read only the order-≤2 channels of their inputs (see
651/// [`Tower4::mul`] / [`Tower4::compose_unary`] — `out.h` never touches `t3`
652/// or `t4`), so dropping the third/fourth tensors cannot perturb the value,
653/// gradient, or Hessian.
654///
655/// It exists purely for performance: an inner Newton step and a value-only
656/// outer-objective probe need at most curvature, never the outer-κ/ψ
657/// third/fourth derivatives. Evaluating a row likelihood over
658/// `Tower2` skips the `K⁴` fourth-tensor product/composition arithmetic that
659/// dominates the cold marginal-slope fit, while returning the exact same
660/// `(v, g, h)`.
661#[derive(Clone, Copy, Debug)]
662pub struct Tower2<const K: usize> {
663    /// Value ℓ.
664    pub v: f64,
665    /// Gradient ∂ℓ/∂p_a.
666    pub g: [f64; K],
667    /// Hessian ∂²ℓ/∂p_a∂p_b (symmetric).
668    pub h: [[f64; K]; K],
669}
670
671impl<const K: usize> Tower2<K> {
672    /// The additive identity.
673    pub fn zero() -> Self {
674        Self {
675            v: 0.0,
676            g: [0.0; K],
677            h: [[0.0; K]; K],
678        }
679    }
680
681    /// A constant: value `c`, all derivatives zero.
682    pub fn constant(c: f64) -> Self {
683        let mut out = Self::zero();
684        out.v = c;
685        out
686    }
687
688    /// The seeded variable `p_idx` with current value `value`:
689    /// unit first derivative in slot `idx`, zero elsewhere and above.
690    pub fn variable(value: f64, idx: usize) -> Self {
691        let mut out = Self::constant(value);
692        out.g[idx] = 1.0;
693        out
694    }
695
696    /// Read the derivative tensor entry whose differentiation axes are
697    /// `labels` (length 0..=2): value, `g`, `h`.
698    #[inline]
699    fn deriv(&self, labels: &[usize]) -> f64 {
700        assert!(
701            labels.len() <= 2,
702            "Tower2 carries at most second-order derivatives"
703        );
704        match labels.len() {
705            0 => self.v,
706            1 => self.g[labels[0]],
707            _ => self.h[labels[0]][labels[1]],
708        }
709    }
710
711    /// Exact truncated (order ≤ 2) Leibniz product. The `v`/`g`/`h` upper
712    /// triangle matches [`Tower4::mul`] term-for-term.
713    ///
714    /// # Symmetry fast path
715    ///
716    /// The order-≤2 Leibniz Hessian
717    /// `h[i][j] = a.v·b.h[i][j] + a.g[i]·b.g[j] + a.g[j]·b.g[i] + a.h[i][j]·b.v`
718    /// is symmetric under `i ↔ j` whenever the operand Hessians are — which they
719    /// always are: `constant`/`variable` seed a symmetric (zero) `h`, and
720    /// `mul`/`compose_unary`/`add`/`scale` each preserve symmetry, so the
721    /// invariant holds for every tower a row program can build. We therefore
722    /// compute only the upper triangle `j ≥ i` and mirror it into the lower
723    /// triangle. At the `K = 9` survival width that is `K(K+1)/2 = 45` four-product
724    /// entry evaluations instead of `K² = 81`, and the win is larger in wall-clock
725    /// because the `648`-entry `h` spills at `K = 9` — halving the expensive
726    /// stores/reloads roughly halves the kernel (measured ≈2× on a `Tower2<9>`
727    /// mul-and-read throughput microbench; the dominant `mul` under every packed
728    /// scalar bottoms out here).
729    ///
730    /// The upper-triangle entries are BIT-IDENTICAL to the old rectangular form
731    /// (same term/accumulation order). The lower triangle now equals its mirror
732    /// exactly, where the rectangular form rounded `h[i][j]` and `h[j][i]`
733    /// independently (the two cross products accumulate in opposite order) and
734    /// left a ≤1-ulp asymmetry; mirroring removes it, so the result is exactly
735    /// symmetric — strictly closer to the true symmetric Hessian, not merely a
736    /// reordering. Dense-`h` consumers are all tolerance-gated (rel-tol ≥ 1e-11 ≫
737    /// 1e-16); the `f64`/`f64x4` lane oracle stays exact because
738    /// [`crate::jet_scalar::Order2Lane::mul`] mirrors term-for-term.
739    pub fn mul(&self, o: &Self) -> Self {
740        let a = self;
741        let b = o;
742        let mut out = Self::zero();
743        out.v = a.v * b.v;
744        for i in 0..K {
745            out.g[i] = a.v * b.g[i] + a.g[i] * b.v;
746        }
747        for i in 0..K {
748            for j in i..K {
749                let hij = a.v * b.h[i][j] + a.g[i] * b.g[j] + a.g[j] * b.g[i] + a.h[i][j] * b.v;
750                out.h[i][j] = hij;
751                out.h[j][i] = hij;
752            }
753        }
754        out
755    }
756
757    /// Exact (order ≤ 2) multivariate Faà di Bruno composition `f ∘ self`.
758    ///
759    /// `d = [f(u), f′(u), f″(u)]` evaluated at `u = self.v`. The `v`/`g`/`h`
760    /// channels match [`Tower4::compose_unary`] term-for-term (which uses only
761    /// `d[0..=2]` for those orders), so this is a strict truncation, not an
762    /// approximation. The full-order `[f64; 5]` derivative stacks the families
763    /// already produce can be passed by slicing their first three entries.
764    ///
765    /// # Codegen
766    ///
767    /// Order-≤2 Faà di Bruno is a tiny closed form, so this evaluates it
768    /// directly instead of routing through the generic
769    /// [`jet_algebra::faa_di_bruno`] set-partition walker (recursion + per-block
770    /// closure dispatch). That matters because this is the kernel under EVERY
771    /// packed scalar — [`crate::jet_scalar::Order2`] / `OneSeed` / `TwoSeed`
772    /// composition all bottom out here — so the straight-line form (whose inner
773    /// loops auto-vectorise to NEON/SSE 2-wide and which emits zero outlined
774    /// walker calls) lifts all of them at once.
775    ///
776    /// The term and accumulation order is BIT-IDENTICAL to the walker it
777    /// replaces: each output channel mirrors the walker's `total = 0.0` start
778    /// (the explicit `acc` accumulator), so a signed-zero product collapses to
779    /// `+0.0` exactly as `total += prod` does. Proven `to_bits`-identical on
780    /// `v`/`g`/`h` across `K ∈ {2,3,4,9}`, 5000 random inputs each (incl.
781    /// zeroed / sign-varied stacks). The order-≤2 walker partitions are:
782    ///   `g[i]`   = `f′·u_i`                   (single block `{i}`)
783    ///   `h[i][j]` = `f′·u_ij + (f″·u_i)·u_j`  (blocks `{ij}` then `{i}{j}`),
784    /// with `f′ = d[1]`, `f″ = d[2]`, `u_* = self.{g,h}`.
785    pub fn compose_unary(&self, d: [f64; 3]) -> Self {
786        let mut out = Self::zero();
787        out.v = d[0];
788        for i in 0..K {
789            let mut acc = 0.0;
790            acc += d[1] * self.g[i];
791            out.g[i] = acc;
792        }
793        for i in 0..K {
794            for j in 0..K {
795                let mut acc = 0.0;
796                acc += d[1] * self.h[i][j];
797                acc += d[2] * self.g[i] * self.g[j];
798                out.h[i][j] = acc;
799            }
800        }
801        out
802    }
803
804    /// Multiply every channel by a plain scalar.
805    pub fn scale(&self, s: f64) -> Self {
806        let mut out = *self;
807        out.v *= s;
808        for i in 0..K {
809            out.g[i] *= s;
810            for j in 0..K {
811                out.h[i][j] *= s;
812            }
813        }
814        out
815    }
816
817    /// e^self.
818    pub fn exp(&self) -> Self {
819        let e = self.v.exp();
820        self.compose_unary([e, e, e])
821    }
822
823    /// √self. Caller guarantees positivity.
824    pub fn sqrt(&self) -> Self {
825        let u = self.v;
826        let s = u.sqrt();
827        self.compose_unary([s, 0.5 / s, -0.25 / (u * s)])
828    }
829}
830
831impl<const K: usize> jet_algebra::JetAlgebra<3> for Tower2<K> {
832    #[inline]
833    fn derivative(&self, labels: &[usize]) -> f64 {
834        self.deriv(labels)
835    }
836
837    fn map_derivatives<F>(&self, mut f: F) -> Self
838    where
839        F: FnMut(&[usize]) -> f64,
840    {
841        let mut out = Self::zero();
842        out.v = f(&[]);
843        for i in 0..K {
844            let labels = [i];
845            out.g[i] = f(&labels);
846        }
847        for i in 0..K {
848            for j in 0..K {
849                let labels = [i, j];
850                out.h[i][j] = f(&labels);
851            }
852        }
853        out
854    }
855}
856
857impl<const K: usize> std::ops::Add for Tower2<K> {
858    type Output = Self;
859    fn add(self, o: Self) -> Self {
860        let mut out = self;
861        out.v += o.v;
862        for i in 0..K {
863            out.g[i] += o.g[i];
864            for j in 0..K {
865                out.h[i][j] += o.h[i][j];
866            }
867        }
868        out
869    }
870}
871
872impl<const K: usize> std::ops::Mul for Tower2<K> {
873    type Output = Self;
874    fn mul(self, o: Self) -> Self {
875        Tower2::mul(&self, &o)
876    }
877}
878
879impl<const K: usize> std::ops::Add<f64> for Tower2<K> {
880    type Output = Self;
881    fn add(self, c: f64) -> Self {
882        let mut out = self;
883        out.v += c;
884        out
885    }
886}
887
888impl<const K: usize> std::ops::Mul<f64> for Tower2<K> {
889    type Output = Self;
890    fn mul(self, c: f64) -> Self {
891        self.scale(c)
892    }
893}
894
895/// Truncated THIRD-order multivariate Taylor scalar in `K` variables.
896///
897/// The value/gradient/Hessian/third-derivative sibling of [`Tower4`], standing
898/// between [`Tower2`] and [`Tower4`]. Every channel it carries (`v`, `g`, `h`,
899/// `t3`) is computed by the SAME shared Leibniz / Faà-di-Bruno kernels
900/// [`Tower4`] uses for those orders, and the order-≤3 terms of those kernels
901/// read only the order-≤3 channels of their inputs (the order-3 Faà-di-Bruno
902/// partitions never reach the f⁗ stack slot or the inner `t4` tensor — see
903/// [`Tower4::compose_unary`]). So for any program written over both towers the
904/// order-≤3 outputs are *bit-identical*: dropping the fourth tensor cannot
905/// perturb the value, gradient, Hessian, or third derivatives.
906///
907/// It exists purely for performance, exactly like [`Tower2`]: a consumer that
908/// needs up to third derivatives (the survival location-scale row kernel reads
909/// `g`, the diagonal `h`, and the diagonal `t3`, but never `t4`) pays the
910/// `K³` third-tensor arithmetic but skips the `K⁴` fourth-tensor
911/// product/composition that otherwise dominates the per-row cost.
912#[derive(Clone, Copy, Debug)]
913pub struct Tower3<const K: usize> {
914    /// Value ℓ.
915    pub v: f64,
916    /// Gradient ∂ℓ/∂p_a.
917    pub g: [f64; K],
918    /// Hessian ∂²ℓ/∂p_a∂p_b (symmetric).
919    pub h: [[f64; K]; K],
920    /// Third derivatives ∂³ℓ/∂p_a∂p_b∂p_c (fully symmetric).
921    pub t3: [[[f64; K]; K]; K],
922}
923
924impl<const K: usize> Tower3<K> {
925    /// The additive identity.
926    pub fn zero() -> Self {
927        Self {
928            v: 0.0,
929            g: [0.0; K],
930            h: [[0.0; K]; K],
931            t3: [[[0.0; K]; K]; K],
932        }
933    }
934
935    /// A constant: value `c`, all derivatives zero.
936    pub fn constant(c: f64) -> Self {
937        let mut out = Self::zero();
938        out.v = c;
939        out
940    }
941
942    /// The seeded variable `p_idx` with current value `value`:
943    /// unit first derivative in slot `idx`, zero elsewhere and above.
944    pub fn variable(value: f64, idx: usize) -> Self {
945        let mut out = Self::constant(value);
946        out.g[idx] = 1.0;
947        out
948    }
949
950    /// Read the (fully symmetric) derivative tensor entry whose differentiation
951    /// axes are `labels` (length 0..=3): value, `g`, `h`, `t3`.
952    #[inline]
953    fn deriv(&self, labels: &[usize]) -> f64 {
954        assert!(
955            labels.len() <= 3,
956            "Tower3 carries at most third-order derivatives"
957        );
958        match labels.len() {
959            0 => self.v,
960            1 => self.g[labels[0]],
961            2 => self.h[labels[0]][labels[1]],
962            _ => self.t3[labels[0]][labels[1]][labels[2]],
963        }
964    }
965
966    /// Exact truncated (order ≤ 3) Leibniz product. The `v`/`g`/`h`/`t3`
967    /// channels match [`Tower4::mul`] term-for-term.
968    ///
969    /// # Codegen
970    ///
971    /// Straight-line per-entry subset sums instead of the
972    /// [`jet_algebra::leibniz_product`] walker — the order-≤3 sibling of
973    /// [`Tower4::mul`] (no `t4`). Loop nest unchanged, no unroll over `K`, no
974    /// code bloat; auto-vectorises. BIT-IDENTICAL: terms in the walker's exact
975    /// subset order with an `acc = 0.0` accumulator start (load-bearing for the
976    /// signed-zero leading product on exact-`0.0` jet channels). Proven
977    /// `to_bits`-identical on `v`/`g`/`h`/`t3` across `K ∈ {2,3,4,9}`, 5000
978    /// zero/sign-stressed inputs each (these channel formulas are exactly the
979    /// `g`/`h`/`t3` of the [`Tower4::mul`] oracle, which passes that stress).
980    pub fn mul(&self, o: &Self) -> Self {
981        let a = self;
982        let b = o;
983        let mut out = Self::zero();
984        out.v = a.v * b.v;
985        for i in 0..K {
986            let mut acc = 0.0;
987            acc += a.v * b.g[i];
988            acc += a.g[i] * b.v;
989            out.g[i] = acc;
990        }
991        // Hessian is symmetric under i↔j; upper triangle + mirror (see Tower2::mul).
992        for i in 0..K {
993            for j in i..K {
994                let mut acc = 0.0;
995                acc += a.v * b.h[i][j];
996                acc += a.g[i] * b.g[j];
997                acc += a.g[j] * b.g[i];
998                acc += a.h[i][j] * b.v;
999                out.h[i][j] = acc;
1000                out.h[j][i] = acc;
1001            }
1002        }
1003        for i in 0..K {
1004            for j in 0..K {
1005                for k in 0..K {
1006                    // subsets of {i,j,k}: {} {i} {j} {ij} {k} {ik} {jk} {ijk}
1007                    let mut acc = 0.0;
1008                    acc += a.v * b.t3[i][j][k];
1009                    acc += a.g[i] * b.h[j][k];
1010                    acc += a.g[j] * b.h[i][k];
1011                    acc += a.h[i][j] * b.g[k];
1012                    acc += a.g[k] * b.h[i][j];
1013                    acc += a.h[i][k] * b.g[j];
1014                    acc += a.h[j][k] * b.g[i];
1015                    acc += a.t3[i][j][k] * b.v;
1016                    out.t3[i][j][k] = acc;
1017                }
1018            }
1019        }
1020        out
1021    }
1022
1023    /// Ref-taking elementwise sum, the by-ref twin of the `std::ops::Add`
1024    /// operator (which consumes by value). Mirrors the inherent `mul`/`scale`
1025    /// API so a chain like `a.mul(&b).add(&c)` reads uniformly without moving
1026    /// out of the borrowed operands.
1027    pub fn add(&self, o: &Self) -> Self {
1028        *self + *o
1029    }
1030
1031    /// Ref-taking elementwise difference, the by-ref twin of `std::ops::Sub`.
1032    pub fn sub(&self, o: &Self) -> Self {
1033        *self + o.scale(-1.0)
1034    }
1035
1036    /// Exact (order ≤ 3) multivariate Faà di Bruno composition `f ∘ self`.
1037    ///
1038    /// `d = [f(u), f′(u), f″(u), f‴(u)]` evaluated at `u = self.v`. The
1039    /// `v`/`g`/`h`/`t3` channels match [`Tower4::compose_unary`] term-for-term
1040    /// (which uses only `d[0..=3]` for those orders), so this is a strict
1041    /// truncation, not an approximation. The full-order `[f64; 5]` derivative
1042    /// stacks the families already produce can be passed by slicing their first
1043    /// four entries.
1044    ///
1045    /// # Codegen
1046    ///
1047    /// Order-≤3 Faà di Bruno written as a compact closed form instead of the
1048    /// recursive [`jet_algebra::faa_di_bruno`] walker — the order-≤2 sibling of
1049    /// [`Tower4::compose_unary`], one tensor order shallower. The loop nest is
1050    /// unchanged (no unroll over `K`, no code bloat: measured on a `Tower3<9>`
1051    /// compose-and-read consumer the new form is faster and SMALLER — asm: 71
1052    /// walker `bl` calls → 0, 39.5 KiB → 13.9 KiB, +197 NEON `.2d` ops).
1053    /// BIT-IDENTICAL: terms in the walker's exact partition order, left-
1054    /// associated block products, `acc = 0.0` accumulator start. Proven
1055    /// `to_bits`-identical on `v`/`g`/`h`/`t3` across `K ∈ {2,3,4,9}`, 5000
1056    /// random inputs each.
1057    pub fn compose_unary(&self, d: [f64; 4]) -> Self {
1058        let mut out = Self::zero();
1059        out.v = d[0];
1060        for i in 0..K {
1061            let mut acc = 0.0;
1062            acc += d[1] * self.g[i];
1063            out.g[i] = acc;
1064        }
1065        for i in 0..K {
1066            for j in 0..K {
1067                let mut acc = 0.0;
1068                acc += d[1] * self.h[i][j];
1069                acc += d[2] * self.g[i] * self.g[j];
1070                out.h[i][j] = acc;
1071            }
1072        }
1073        for i in 0..K {
1074            for j in 0..K {
1075                for k in 0..K {
1076                    // walker partitions: {ijk} {ij}{k} {ik}{j} {i}{jk} {i}{j}{k}
1077                    let mut acc = 0.0;
1078                    acc += d[1] * self.t3[i][j][k];
1079                    acc += d[2] * self.h[i][j] * self.g[k];
1080                    acc += d[2] * self.h[i][k] * self.g[j];
1081                    acc += d[2] * self.g[i] * self.h[j][k];
1082                    acc += d[3] * self.g[i] * self.g[j] * self.g[k];
1083                    out.t3[i][j][k] = acc;
1084                }
1085            }
1086        }
1087        out
1088    }
1089
1090    /// Compose with a unary special-function whose `[f64; 4]` derivative stack is
1091    /// built from the base value through `stack_fn`. Evaluates `stack_fn(self.v)`
1092    /// once and forwards to [`Self::compose_unary`], so it is bit-identical to the
1093    /// explicit form. The order-≤3 sibling of [`Tower4::compose_unary_with`].
1094    #[inline]
1095    pub fn compose_unary_with(&self, stack_fn: impl Fn(f64) -> [f64; 4]) -> Self {
1096        self.compose_unary(stack_fn(self.v))
1097    }
1098
1099    /// Single-active-slot fast path for [`Self::compose_unary`] — the order-≤3
1100    /// sibling of [`Tower4::compose_unary_single_slot`]. When `self` carries
1101    /// derivative support only on the all-`slot` diagonal, every output channel
1102    /// touching an axis `≠ slot` collapses to the walker's `total = 0.0` start
1103    /// (`+0.0`), so only `v`, `g[slot]`, `h[slot][slot]`, `t3[slot]³` survive.
1104    /// These four are computed as STRAIGHT-LINE accumulations, each in the EXACT
1105    /// term order of [`Self::compose_unary`]'s diagonal (`i = j = k = slot`)
1106    /// case (BIT-IDENTICAL to the full path on the diagonal); off-`slot`
1107    /// channels stay at the zero-init `+0.0` the full walk also yields (proven
1108    /// `to_bits` across `K ∈ {2,3,4,9}`). This drops the recursive
1109    /// set-partition walker the diagonal channels previously routed through,
1110    /// recovering its measured ~5.9× regression at the `K ∈ {2,3}` BMS tower
1111    /// widths. Caller guarantees the single-slot precondition; otherwise use
1112    /// [`Self::compose_unary`].
1113    #[inline]
1114    pub fn compose_unary_single_slot(&self, d: [f64; 4], slot: usize) -> Self {
1115        let mut out = Self::zero();
1116        let s = slot;
1117        let g = self.g[s];
1118        let h = self.h[s][s];
1119        let t3 = self.t3[s][s][s];
1120        out.v = d[0];
1121        // g (i=s): d1*g
1122        out.g[s] = {
1123            let mut acc = 0.0;
1124            acc += d[1] * g;
1125            acc
1126        };
1127        // h (i=j=s): d1*h + d2*g*g
1128        out.h[s][s] = {
1129            let mut acc = 0.0;
1130            acc += d[1] * h;
1131            acc += d[2] * g * g;
1132            acc
1133        };
1134        // t3 (i=j=k=s): exact term order of compose_unary's inner loop.
1135        out.t3[s][s][s] = {
1136            let mut acc = 0.0;
1137            acc += d[1] * t3;
1138            acc += d[2] * h * g;
1139            acc += d[2] * h * g;
1140            acc += d[2] * g * h;
1141            acc += d[3] * g * g * g;
1142            acc
1143        };
1144        out
1145    }
1146
1147    /// Multiply every channel by a plain scalar.
1148    pub fn scale(&self, s: f64) -> Self {
1149        let mut out = *self;
1150        out.v *= s;
1151        for i in 0..K {
1152            out.g[i] *= s;
1153            for j in 0..K {
1154                out.h[i][j] *= s;
1155                for k in 0..K {
1156                    out.t3[i][j][k] *= s;
1157                }
1158            }
1159        }
1160        out
1161    }
1162}
1163
1164impl<const K: usize> jet_algebra::JetAlgebra<4> for Tower3<K> {
1165    #[inline]
1166    fn derivative(&self, labels: &[usize]) -> f64 {
1167        self.deriv(labels)
1168    }
1169
1170    fn map_derivatives<F>(&self, mut f: F) -> Self
1171    where
1172        F: FnMut(&[usize]) -> f64,
1173    {
1174        let mut out = Self::zero();
1175        out.v = f(&[]);
1176        for i in 0..K {
1177            let labels = [i];
1178            out.g[i] = f(&labels);
1179        }
1180        for i in 0..K {
1181            for j in 0..K {
1182                let labels = [i, j];
1183                out.h[i][j] = f(&labels);
1184            }
1185        }
1186        for i in 0..K {
1187            for j in 0..K {
1188                for k in 0..K {
1189                    let labels = [i, j, k];
1190                    out.t3[i][j][k] = f(&labels);
1191                }
1192            }
1193        }
1194        out
1195    }
1196}
1197
1198impl<const K: usize> std::ops::Add for Tower3<K> {
1199    type Output = Self;
1200    fn add(self, o: Self) -> Self {
1201        let mut out = self;
1202        out.v += o.v;
1203        for i in 0..K {
1204            out.g[i] += o.g[i];
1205            for j in 0..K {
1206                out.h[i][j] += o.h[i][j];
1207                for k in 0..K {
1208                    out.t3[i][j][k] += o.t3[i][j][k];
1209                }
1210            }
1211        }
1212        out
1213    }
1214}
1215
1216pub fn ln_gamma_derivative_stack(x: f64) -> [f64; 5] {
1217    [
1218        statrs::function::gamma::ln_gamma(x),
1219        digamma_positive(x),
1220        polygamma_positive(1, x),
1221        polygamma_positive(2, x),
1222        polygamma_positive(3, x),
1223    ]
1224}
1225
1226pub fn ln_gamma_derivative_stack_order2(x: f64) -> [f64; 3] {
1227    [
1228        statrs::function::gamma::ln_gamma(x),
1229        digamma_positive(x),
1230        polygamma_positive(1, x),
1231    ]
1232}
1233
1234pub fn digamma_derivative_stack(x: f64) -> [f64; 5] {
1235    [
1236        digamma_positive(x),
1237        polygamma_positive(1, x),
1238        polygamma_positive(2, x),
1239        polygamma_positive(3, x),
1240        polygamma_positive(4, x),
1241    ]
1242}
1243
1244pub fn trigamma_derivative_stack(x: f64) -> [f64; 5] {
1245    [
1246        polygamma_positive(1, x),
1247        polygamma_positive(2, x),
1248        polygamma_positive(3, x),
1249        polygamma_positive(4, x),
1250        polygamma_positive(5, x),
1251    ]
1252}
1253
1254/// Scalar digamma ψ(x) for x>0. Bit-identical to `digamma_derivative_stack(x)[0]`
1255/// and to `ln_gamma_derivative_stack(x)[1]`, but evaluates ONLY ψ — the four
1256/// higher polygammas those `[f64; 5]` stacks build are pure discarded work at a
1257/// scalar consumer that reads a single element. Hot-path row kernels that need
1258/// only the digamma value (e.g. the GAMLSS Beta observed cross weight) call this
1259/// instead of indexing `[0]` off a full derivative stack.
1260#[inline]
1261pub fn digamma(x: f64) -> f64 {
1262    digamma_positive(x)
1263}
1264
1265/// Scalar trigamma ψ′(x) for x>0. Bit-identical to
1266/// `trigamma_derivative_stack(x)[0]` (both bottom out in `polygamma_positive(1,
1267/// x)`), but evaluates ONLY ψ′ — the four higher polygammas (orders 2–5) the
1268/// `[f64; 5]` stack builds are discarded at a `[0]` consumer. Used by the
1269/// dispersion-channel Fisher-information row kernels (NB2 `ψ′(θ)−ψ′(θ+μ)`, Beta
1270/// `μψ′(μφ)−(1−μ)ψ′((1−μ)φ)`) which read the trigamma value alone.
1271#[inline]
1272pub fn trigamma(x: f64) -> f64 {
1273    polygamma_positive(1, x)
1274}
1275
1276fn digamma_positive(mut x: f64) -> f64 {
1277    if !(x.is_finite() && x > 0.0) {
1278        return f64::NAN;
1279    }
1280    let mut acc = 0.0;
1281    while x < POLYGAMMA_ASYMPTOTIC_MIN_X {
1282        acc -= 1.0 / x;
1283        x += 1.0;
1284    }
1285    acc + digamma_asymptotic(x)
1286}
1287
1288fn polygamma_positive(order: usize, mut x: f64) -> f64 {
1289    if !(x.is_finite() && x > 0.0) {
1290        return f64::NAN;
1291    }
1292    let mut acc = 0.0;
1293    while x < POLYGAMMA_ASYMPTOTIC_MIN_X {
1294        acc += polygamma_recurrence_term(order, x);
1295        x += 1.0;
1296    }
1297    acc + polygamma_asymptotic(order, x)
1298}
1299
1300const POLYGAMMA_ASYMPTOTIC_MIN_X: f64 = 20.0;
1301const BERNOULLI_EVEN: [(usize, f64); 10] = [
1302    (2, 1.0 / 6.0),
1303    (4, -1.0 / 30.0),
1304    (6, 1.0 / 42.0),
1305    (8, -1.0 / 30.0),
1306    (10, 5.0 / 66.0),
1307    (12, -691.0 / 2730.0),
1308    (14, 7.0 / 6.0),
1309    (16, -3617.0 / 510.0),
1310    (18, 43867.0 / 798.0),
1311    (20, -174611.0 / 330.0),
1312];
1313
1314fn polygamma_recurrence_term(order: usize, x: f64) -> f64 {
1315    let sign = if order % 2 == 1 { 1.0 } else { -1.0 };
1316    sign * factorial(order) / x.powi((order + 1) as i32)
1317}
1318
1319fn digamma_asymptotic(x: f64) -> f64 {
1320    let mut out = x.ln() - 0.5 / x;
1321    for (bernoulli_order, bernoulli) in BERNOULLI_EVEN {
1322        out -= bernoulli / (bernoulli_order as f64 * x.powi(bernoulli_order as i32));
1323    }
1324    out
1325}
1326
1327fn polygamma_asymptotic(order: usize, x: f64) -> f64 {
1328    if !(1..=5).contains(&order) {
1329        return f64::NAN;
1330    }
1331
1332    let order_factorial = factorial(order);
1333    let leading_sign = if order % 2 == 1 { 1.0 } else { -1.0 };
1334    let mut out = leading_sign * factorial(order - 1) / x.powi(order as i32)
1335        + leading_sign * order_factorial / (2.0 * x.powi((order + 1) as i32));
1336
1337    let bernoulli_sign = if order % 2 == 1 { 1.0 } else { -1.0 };
1338    for (bernoulli_order, bernoulli) in BERNOULLI_EVEN {
1339        let rising = rising_factorial(bernoulli_order, order);
1340        out += bernoulli_sign * bernoulli * rising
1341            / bernoulli_order as f64
1342            / x.powi((bernoulli_order + order) as i32);
1343    }
1344    out
1345}
1346
1347fn factorial(n: usize) -> f64 {
1348    (1..=n).fold(1.0, |acc, k| acc * k as f64)
1349}
1350
1351fn rising_factorial(start: usize, len: usize) -> f64 {
1352    (start..start + len).fold(1.0, |acc, k| acc * k as f64)
1353}
1354
1355impl<const K: usize> std::ops::Add for Tower4<K> {
1356    type Output = Self;
1357    fn add(self, o: Self) -> Self {
1358        let mut out = self;
1359        out.v += o.v;
1360        for i in 0..K {
1361            out.g[i] += o.g[i];
1362            for j in 0..K {
1363                out.h[i][j] += o.h[i][j];
1364                for k in 0..K {
1365                    out.t3[i][j][k] += o.t3[i][j][k];
1366                    for l in 0..K {
1367                        out.t4[i][j][k][l] += o.t4[i][j][k][l];
1368                    }
1369                }
1370            }
1371        }
1372        out
1373    }
1374}
1375
1376impl<const K: usize> std::ops::Sub for Tower4<K> {
1377    type Output = Self;
1378    fn sub(self, o: Self) -> Self {
1379        self + o.scale(-1.0)
1380    }
1381}
1382
1383impl<const K: usize> std::ops::Neg for Tower4<K> {
1384    type Output = Self;
1385    fn neg(self) -> Self {
1386        self.scale(-1.0)
1387    }
1388}
1389
1390impl<const K: usize> std::ops::Mul for Tower4<K> {
1391    type Output = Self;
1392    fn mul(self, o: Self) -> Self {
1393        Tower4::mul(&self, &o)
1394    }
1395}
1396
1397impl<const K: usize> std::ops::Div for Tower4<K> {
1398    type Output = Self;
1399    fn div(self, o: Self) -> Self {
1400        Tower4::mul(&self, &o.recip())
1401    }
1402}
1403
1404impl<const K: usize> std::ops::Add<f64> for Tower4<K> {
1405    type Output = Self;
1406    fn add(self, c: f64) -> Self {
1407        let mut out = self;
1408        out.v += c;
1409        out
1410    }
1411}
1412
1413impl<const K: usize> std::ops::Sub<f64> for Tower4<K> {
1414    type Output = Self;
1415    fn sub(self, c: f64) -> Self {
1416        self + (-c)
1417    }
1418}
1419
1420impl<const K: usize> std::ops::Mul<f64> for Tower4<K> {
1421    type Output = Self;
1422    fn mul(self, c: f64) -> Self {
1423        self.scale(c)
1424    }
1425}
1426
1427// ── Implicit-function and moving-boundary seams (#932 flex) ──────────
1428//
1429// The flexible survival marginal-slope row loss is NOT a free composition
1430// of the primaries: it threads an IMPLICIT calibration intercept `a(θ)`
1431// solving a constraint `F(a, θ) = 0`, and integrates a density over cells
1432// whose edges `z_L(θ), z_R(θ)` MOVE with θ through that intercept. Plain
1433// `Tower4` Faà di Bruno cannot express either — so the flex tower was the
1434// last hand-written one in the codebase, and the genus of #736-class
1435// drift bugs (the (g,w0) deviation-cross third was 3× short for exactly
1436// this reason). These two combinators close that gap: once the constraint
1437// `F` and the integrand/boundaries are themselves towers, the intercept's
1438// derivative tower and the integral's derivative tower come out EXACTLY at
1439// every order — there is no order left to hand-code and forget.
1440
1441/// Solve the implicit relation `F(a(θ), θ) ≡ 0` for the intercept tower
1442/// `a(θ)` over the `K` primaries θ, given the constraint tower `f` written
1443/// over `K + 1` variables (slot `0` is the intercept `a`, slots `1..=K`
1444/// are the primaries θ) evaluated at the SOLVED point — i.e. `f.v` is the
1445/// constraint residual at `(a₀, θ₀)` (≈ 0 from the production Newton solve)
1446/// and `a0` is that solved intercept value.
1447///
1448/// Returns the `Tower4<K>` whose value is `a0` and whose every derivative
1449/// tensor (∂a/∂θ, ∂²a/∂θ², …, ∂⁴a/∂θ⁴) is the exact implicit-function
1450/// derivative. This is the mechanical replacement for the hand-coded
1451/// `a_u = -f_u/f_a`, `a_uv = -(f_uv + f_au·a_v + f_av·a_u + f_aa·a_u·a_v)/f_a`
1452/// recursion (first_full.rs) and its third/fourth-order continuations.
1453///
1454/// Method: order-by-order substitution. We build `a` incrementally; at each
1455/// order `m` the composite `G(θ) = f(a(θ), θ)` has a top-order coefficient
1456/// that is linear in `a`'s order-`m` tensor with leading factor `F_a`
1457/// (= `f.g[0]`), plus terms in `a`'s lower orders already fixed. Setting the
1458/// order-`m` tensor of `a` to cancel the rest of `G`'s order-`m` coefficient
1459/// keeps `G ≡ 0` through that order. The substitution `G = f∘(a, θ)` reuses
1460/// only the exact [`substitute_intercept`] chain rule, so the recursion is
1461/// auditable and exact, not a hand-expanded formula per order.
1462///
1463/// `f.g[0]` (= ∂F/∂a) must be non-zero — guaranteed by the production
1464/// solve's strict monotonicity guard.
1465///
1466/// The expansion point `a0` must be a genuine root `F(a0, θ0) = 0`: the
1467/// substitution recursion below cancels orders 1..=4 of `G = F∘a` but never
1468/// touches order 0, so a non-root `a0` would yield the Taylor expansion of
1469/// the LEVEL SET `F = F(a0)` through `a0`, not the root curve `F = 0`. This
1470/// is guarded explicitly and re-verified by a composed-residual self-check.
1471pub fn implicit_solve<const K1: usize, const K: usize>(
1472    f: &Tower4<K1>,
1473    a0: f64,
1474) -> Result<Tower4<K>, String> {
1475    assert_eq!(K1, K + 1, "implicit_solve: constraint must carry K+1 vars");
1476    let f_a = f.g[0];
1477    if f_a == 0.0 || !f_a.is_finite() {
1478        return Err(format!(
1479            "implicit_solve: ∂F/∂a = {f_a:+.3e} is not invertible"
1480        ));
1481    }
1482    // The expansion point must be a genuine root of F. The single Newton
1483    // correction that would move a0 onto the root is |f.v|/|f_a|; require it
1484    // to be negligible relative to the natural scale (1 + |a0|). Guarding the
1485    // Newton step (rather than f.v directly) makes the criterion invariant to
1486    // the magnitude of f_a / the units of F.
1487    let root_tol = 1e-9;
1488    if !f.v.is_finite() {
1489        return Err(format!(
1490            "implicit_solve: F(a0, θ0) = {:+.3e} is not finite",
1491            f.v
1492        ));
1493    }
1494    let newton_step = f.v.abs() / f_a.abs();
1495    if newton_step > root_tol * (1.0 + a0.abs()) {
1496        return Err(format!(
1497            "implicit_solve: expansion point a0 = {a0:+.6e} is not a root of F: \
1498             F(a0, θ0) = {:+.3e}, Newton correction {newton_step:+.3e} exceeds \
1499             root_tol {root_tol:.1e} · (1 + |a0|)",
1500            f.v
1501        ));
1502    }
1503    // Start with a = constant a0 (correct through order 0). Then lift each
1504    // order in turn. Because substitute_intercept reads `a`'s order-≤m
1505    // tensors when forming G's order-m coefficient, and the order-m
1506    // coefficient of G depends on a's order-m tensor ONLY through the linear
1507    // F_a·a_m term, a single corrective pass per order is exact.
1508    let mut a = Tower4::<K>::constant(a0);
1509    for order in 1..=4 {
1510        let g = substitute_intercept(f, &a);
1511        // Cancel G's order-`order` coefficient by adjusting a's order-`order`
1512        // tensor: a_m -= G_m / F_a (the F_a·a_m term is the only one carrying
1513        // a's order-m tensor, with unit chain coefficient since slot 0 seeds a
1514        // as a plain variable in the substitution's first-order part).
1515        match order {
1516            1 => {
1517                for i in 0..K {
1518                    a.g[i] -= g.g[i] / f_a;
1519                }
1520            }
1521            2 => {
1522                for i in 0..K {
1523                    for j in 0..K {
1524                        a.h[i][j] -= g.h[i][j] / f_a;
1525                    }
1526                }
1527            }
1528            3 => {
1529                for i in 0..K {
1530                    for j in 0..K {
1531                        for k in 0..K {
1532                            a.t3[i][j][k] -= g.t3[i][j][k] / f_a;
1533                        }
1534                    }
1535                }
1536            }
1537            _ => {
1538                for i in 0..K {
1539                    for j in 0..K {
1540                        for k in 0..K {
1541                            for l in 0..K {
1542                                a.t4[i][j][k][l] -= g.t4[i][j][k][l] / f_a;
1543                            }
1544                        }
1545                    }
1546                }
1547            }
1548        }
1549    }
1550    // Self-check: the composed residual G = F∘a must vanish through order 4.
1551    // By construction orders 1..=4 were cancelled; the value G.v == F(a0,θ0)
1552    // is exactly the root requirement guarded above. Re-verify all channels
1553    // against a scale-aware floor so any arithmetic regression in the
1554    // substitution recursion is loud rather than silently shipping a
1555    // level-set expansion.
1556    let g = substitute_intercept(f, &a);
1557    let resid_tol = 1e-7 * (1.0 + f_a.abs());
1558    let mut worst = g.v.abs();
1559    for i in 0..K {
1560        worst = worst.max(g.g[i].abs());
1561        for j in 0..K {
1562            worst = worst.max(g.h[i][j].abs());
1563            for k in 0..K {
1564                worst = worst.max(g.t3[i][j][k].abs());
1565                for l in 0..K {
1566                    worst = worst.max(g.t4[i][j][k][l].abs());
1567                }
1568            }
1569        }
1570    }
1571    if !worst.is_finite() || worst > resid_tol {
1572        return Err(format!(
1573            "implicit_solve: composed residual G = F∘a does not vanish: \
1574             worst channel magnitude {worst:+.3e} exceeds tol {resid_tol:.1e}"
1575        ));
1576    }
1577    Ok(a)
1578}
1579
1580/// Substitute the intercept tower `a(θ)` into slot `0` of a constraint
1581/// written over `K + 1` variables, returning the composite tower over the
1582/// `K` primaries θ: `G(θ) = f(a(θ), θ₁, …, θ_K)`.
1583///
1584/// This is the exact multivariate chain rule specialised to "slot 0 is a
1585/// dependent tower, slots 1..=K are the independent primaries". It evaluates
1586/// `f`'s fourth-order multivariate Taylor polynomial about the expansion
1587/// point, with the slot-0 increment being the non-constant part of `a` and
1588/// the slot-(i) increment being the unit-seeded primary `θ_i`. The sum is
1589/// assembled by the same subset/partition algebra `Tower4` arithmetic uses,
1590/// so it carries derivatives exactly through order four.
1591pub fn substitute_intercept<const K1: usize, const K: usize>(
1592    f: &Tower4<K1>,
1593    a: &Tower4<K>,
1594) -> Tower4<K> {
1595    assert_eq!(K1, K + 1);
1596    // Build the K+1 input towers in θ-space: slot 0 = a(θ), slot i+1 = θ_i.
1597    // The composite is Σ over ordered label tuples s (|s| ≤ 4) of input
1598    // indices: (1/|s|!) · f.deriv(s) · Π_{j in s} (inp[s_j] centred) — but
1599    // since f.deriv is the SYMMETRIC partial tensor and we enumerate ordered
1600    // tuples, the 1/|s|! exactly cancels the tuple multiplicity. We assemble
1601    // it directly as a Horner-free explicit sum over the (K+1)-ary tuples,
1602    // using tower products for the increment monomials so all θ-derivatives
1603    // propagate exactly.
1604    let inp: [Tower4<K>; K1] = std::array::from_fn(|slot| {
1605        if slot == 0 {
1606            // slot 0: a(θ) minus its constant value (the increment δa(θ)).
1607            let mut d = *a;
1608            d.v = 0.0;
1609            d
1610        } else {
1611            // slot i: the increment δθ_{i-1} = seeded variable minus value.
1612            // θ centred at its expansion value has zero constant term and unit
1613            // first derivative in its own slot.
1614            let mut d = Tower4::<K>::zero();
1615            d.g[slot - 1] = 1.0;
1616            d
1617        }
1618    });
1619    // Accumulate the Taylor sum. order-0 term:
1620    let mut out = Tower4::<K>::constant(f.v);
1621    // order 1: Σ_a f.g[a] · inp[a]
1622    for a_idx in 0..K1 {
1623        out = out + inp[a_idx].scale(f.g[a_idx]);
1624    }
1625    // order 2: (1/2) Σ_{a,b} f.h[a][b] · inp[a]·inp[b]
1626    for a_idx in 0..K1 {
1627        for b_idx in 0..K1 {
1628            let prod = inp[a_idx].mul(&inp[b_idx]);
1629            out = out + prod.scale(0.5 * f.h[a_idx][b_idx]);
1630        }
1631    }
1632    // order 3: (1/6) Σ f.t3[a][b][c] · inp[a]·inp[b]·inp[c]
1633    for a_idx in 0..K1 {
1634        for b_idx in 0..K1 {
1635            for c_idx in 0..K1 {
1636                let prod = inp[a_idx].mul(&inp[b_idx]).mul(&inp[c_idx]);
1637                out = out + prod.scale(f.t3[a_idx][b_idx][c_idx] / 6.0);
1638            }
1639        }
1640    }
1641    // order 4: (1/24) Σ f.t4[a][b][c][d] · inp[a]·inp[b]·inp[c]·inp[d]
1642    for a_idx in 0..K1 {
1643        for b_idx in 0..K1 {
1644            for c_idx in 0..K1 {
1645                for d_idx in 0..K1 {
1646                    let prod = inp[a_idx]
1647                        .mul(&inp[b_idx])
1648                        .mul(&inp[c_idx])
1649                        .mul(&inp[d_idx]);
1650                    out = out + prod.scale(f.t4[a_idx][b_idx][c_idx][d_idx] / 24.0);
1651                }
1652            }
1653        }
1654    }
1655    out
1656}
1657
1658/// The exact θ-derivative tower of a moving-LIMIT integral's BOUNDARY
1659/// contribution: given the edge-position tower `z_edge(θ)` over the `K`
1660/// primaries and the integrand `B` evaluated-and-differentiated at the edge
1661/// value as the stack `b_stack = [B(z₀), B′(z₀), B″(z₀), B‴(z₀)]`
1662/// (`z₀ = z_edge.v`), returns the tower of `Φ(z_edge(θ))` where `Φ′ = B`.
1663///
1664/// Rationale: `∂_θ ∫^{z_edge(θ)} B(z) dz = Φ(z_edge(θ))` with `Φ` an
1665/// antiderivative of `B`, so the boundary part of every θ-derivative of the
1666/// integral is just the composition `Φ ∘ z_edge` — whose Faà di Bruno
1667/// expansion carries, at one stroke, EVERY Leibniz boundary term the
1668/// hand-written flux dropped: the first-order `B·z_u`, the second-order
1669/// `B′·z_u·z_v + B·z_uv` (the `G_z·z_u·z_v` self-flux AND the previously
1670/// dropped `G·z_uv`), and the full third/fourth-order continuations. The
1671/// VALUE channel of the returned tower is meaningless (`Φ` is only defined up
1672/// to a constant); callers read only the derivative channels and pair this
1673/// with the interior moment-integral value separately.
1674///
1675/// `b_stack` holds `B` and its first three z-derivatives; the antiderivative
1676/// `Φ` contributes only as the order-≥1 channels, so `compose_unary` receives
1677/// `[0, B, B′, B″, B‴]` — the leading `0` is the discarded `Φ(z₀)` slot.
1678pub fn moving_limit_boundary_tower<const K: usize>(
1679    z_edge: &Tower4<K>,
1680    b_stack: [f64; 4],
1681) -> Tower4<K> {
1682    z_edge.compose_unary([0.0, b_stack[0], b_stack[1], b_stack[2], b_stack[3]])
1683}
1684
1685/// The boundary-flux derivative tower of a single moving cell integral
1686/// `∫_{z_L(θ)}^{z_R(θ)} B dz`: `Φ(z_R(θ)) − Φ(z_L(θ))`, assembled from the
1687/// two edge towers and the integrand stacks at each edge. The returned
1688/// tower's derivative channels are the EXACT moving-boundary contribution to
1689/// every θ-derivative of the cell integral, to fourth order, with no term
1690/// hand-omitted. A `Fixed` (non-moving) edge passes a `z_edge` whose
1691/// derivative channels are all zero, contributing nothing — matching the
1692/// production `edge_vel = 0` short-circuit.
1693pub fn cell_moving_boundary_flux_tower<const K: usize>(
1694    z_right: &Tower4<K>,
1695    b_stack_right: [f64; 4],
1696    z_left: &Tower4<K>,
1697    b_stack_left: [f64; 4],
1698) -> Tower4<K> {
1699    moving_limit_boundary_tower(z_right, b_stack_right)
1700        - moving_limit_boundary_tower(z_left, b_stack_left)
1701}
1702
1703/// Moving-limit boundary tower for a θ-DEPENDENT integrand `G(z; θ)`.
1704///
1705/// [`moving_limit_boundary_tower`] assumes the integrand depends on θ only
1706/// through the moving edge `z_edge(θ)` (a fixed z-derivative `b_stack`). The
1707/// marginal-slope flex boundary is richer: the integrand `G(z; θ)` ALSO carries
1708/// its own θ-dependence (the density weight `w = e^{−q}/2π` and the cell
1709/// integrand coefficients move with η, hence with the primaries), so the
1710/// Leibniz expansion of `∂ⁿ_θ ∫^{z_edge(θ)} G(z;θ) dz` mixes edge-motion
1711/// derivatives of the limit with θ-derivatives of `G` itself — e.g. at second
1712/// order `G·z_uv + G_z·z_u·z_v + G_{θu}·z_v + G_{θv}·z_u` (the four
1713/// edge-motion-carrying terms the hand path assembles one by one, including the
1714/// `G·z_uv` term the directional path drops).
1715///
1716/// Mechanization: let `Φ(z; θ)` be the z-antiderivative of `G` (so `Φ_z = G`).
1717/// The full upper-limit contribution is `Φ(z_edge(θ); θ)`, and the BOUNDARY
1718/// part — everything carrying edge motion — is exactly
1719///   `Φ(z_edge(θ); θ) − Φ(z₀; θ)`,
1720/// the second term being the pure-integrand-θ part (`∫^{z₀} ∂ⁿ_θ G`) the
1721/// interior moment integral already supplies. Both are one
1722/// [`substitute_intercept`] of the SAME mixed `(z, θ)` jet of `Φ` (z in slot 0,
1723/// θ in slots 1..K): substituting the edge tower gives the full composite,
1724/// substituting a frozen constant edge isolates the pure-θ part, and their
1725/// difference is the exact boundary flux — every Leibniz term derived by the
1726/// substitution algebra, none hand-omitted.
1727///
1728/// `phi_jet` is the `(K+1)`-variable Taylor jet of `Φ` about `(z₀, θ₀)` with
1729/// `z₀ = z_edge.v`: slot 0 is the z-direction (so `phi_jet.g[0] = G(z₀;θ₀)`,
1730/// `phi_jet.h[0][0] = G_z`, …) and slots `1..=K` are the primaries θ (carrying
1731/// `Φ`'s own θ- and mixed z·θ-derivatives — i.e. the integrand's θ-derivatives
1732/// integrated in z, and `G_{θ…}` in the mixed slots). The returned tower's
1733/// VALUE channel is 0 by construction (the `Φ(z₀;θ₀)` constants cancel); only
1734/// the derivative channels are meaningful, matching the value-less convention of
1735/// [`moving_limit_boundary_tower`].
1736pub fn moving_limit_boundary_tower_theta_integrand<const K1: usize, const K: usize>(
1737    phi_jet: &Tower4<K1>,
1738    z_edge: &Tower4<K>,
1739) -> Tower4<K> {
1740    assert_eq!(
1741        K1,
1742        K + 1,
1743        "moving_limit_boundary_tower_theta_integrand: Φ jet must carry z + K θ-vars"
1744    );
1745    let frozen_edge = Tower4::<K>::constant(z_edge.v);
1746    let full = substitute_intercept(phi_jet, z_edge);
1747    let interior = substitute_intercept(phi_jet, &frozen_edge);
1748    full - interior
1749}
1750
1751/// Two-edge cell version of [`moving_limit_boundary_tower_theta_integrand`]:
1752/// the exact boundary-flux tower of `∫_{z_L(θ)}^{z_R(θ)} G(z;θ) dz` with a
1753/// θ-dependent integrand, `Φ(z_R;θ) − Φ(z_L;θ)` minus the pure-θ parts at each
1754/// frozen edge. A `Fixed` edge passes a `z_edge` with zero derivative channels,
1755/// so its `full` and `interior` substitutions coincide and it contributes
1756/// nothing — matching the production `edge_vel = 0` short-circuit.
1757pub fn cell_moving_boundary_flux_tower_theta_integrand<const K1: usize, const K: usize>(
1758    phi_jet_right: &Tower4<K1>,
1759    z_right: &Tower4<K>,
1760    phi_jet_left: &Tower4<K1>,
1761    z_left: &Tower4<K>,
1762) -> Tower4<K> {
1763    moving_limit_boundary_tower_theta_integrand(phi_jet_right, z_right)
1764        - moving_limit_boundary_tower_theta_integrand(phi_jet_left, z_left)
1765}
1766
1767// ── The program seam ─────────────────────────────────────────────────
1768
1769// ── The canonical single-source seam (#932 consolidation) ────────────
1770//
1771// `RowProgram<K>` is the ONE row-program interface #932 converges every family
1772// onto. Its generic `eval<S: JetScalar<K>>` body is the go-forward derivation
1773// surface for every calculus channel; `program_*` selects only the derivative
1774// representation each consumer needs.
1775
1776/// The single source of truth #932 asks for: a family's row negative
1777/// log-likelihood written ONCE over the generic [`crate::jet_scalar::JetScalar`]
1778/// interface, from which every `RowKernel` (gam-models) derivative channel is
1779/// mechanically derived. A family implements ONLY this (plus its linear Jacobian
1780/// wiring, which is family data, not calculus) — it cannot author an independent
1781/// derivative tower, because there is no other channel to author.
1782///
1783/// Because a body uses only `add`/`sub`/`mul`/`scale`/`exp`/`ln`/… — all provided
1784/// by [`crate::jet_scalar::JetScalar`] — the SAME body re-instantiates at
1785/// [`crate::jet_scalar::Order2`] (value/grad/Hessian), [`crate::jet_scalar::OneSeed`]
1786/// (contracted third), [`crate::jet_scalar::TwoSeed`] (contracted fourth), and the
1787/// full [`Tower4`] (every channel), with the contraction folded into the
1788/// differentiation so no dense `t3`/`t4` is ever materialised.
1789pub trait RowProgram<const K: usize>: Send + Sync {
1790    /// Number of observations the program covers.
1791    fn n_rows(&self) -> usize;
1792
1793    /// Current primary-scalar values for `row` (where to seed the scalar).
1794    fn primaries(&self, row: usize) -> Result<[f64; K], String>;
1795
1796    /// The row NLL evaluated on a generic jet scalar. `p[a]` arrives pre-seeded
1797    /// (base value + per-scalar nilpotent directions) by the caller; the body
1798    /// uses ONLY [`crate::jet_scalar::JetScalar`] ops and per-row data (response,
1799    /// censoring, offsets) entering as constants.
1800    fn eval<S: crate::jet_scalar::JetScalar<K>>(&self, row: usize, p: &[S; K])
1801    -> Result<S, String>;
1802}
1803
1804/// Maximum size of one canonical dense-jet storage object kept on the call
1805/// stack. Small fixed-width programs stay allocation-free; wider derivative
1806/// representations use exact-length heap storage instead of making the thread
1807/// stack scale as `K * size_of::<S>()`. A full dense result larger than this
1808/// boundary is rejected in favor of the bounded directional APIs.
1809///
1810/// This is a storage-policy boundary, not a calculus fallback: both branches
1811/// invoke the same [`RowProgram::eval`] expression with the same scalar type.
1812const PROGRAM_DENSE_JET_STACK_BUDGET_BYTES: usize = 64 * 1024;
1813
1814#[inline]
1815fn program_primary_jets_fit_stack<S, const K: usize>() -> bool {
1816    std::mem::size_of::<S>()
1817        .checked_mul(K)
1818        .is_some_and(|bytes| bytes <= PROGRAM_DENSE_JET_STACK_BUDGET_BYTES)
1819}
1820
1821fn evaluate_program_with_stack_primaries<const K: usize, P, S>(
1822    prog: &P,
1823    row: usize,
1824    mut seed: impl FnMut(usize) -> S,
1825) -> Result<S, String>
1826where
1827    P: RowProgram<K> + ?Sized,
1828    S: crate::jet_scalar::JetScalar<K>,
1829{
1830    let vars: [S; K] = std::array::from_fn(&mut seed);
1831    prog.eval(row, &vars)
1832}
1833
1834#[inline(never)]
1835fn evaluate_program_with_heap_primaries<const K: usize, P, S>(
1836    prog: &P,
1837    row: usize,
1838    seed: impl FnMut(usize) -> S,
1839) -> Result<S, String>
1840where
1841    P: RowProgram<K> + ?Sized,
1842    S: crate::jet_scalar::JetScalar<K>,
1843{
1844    // The exact-size range builds precisely K initialized Copy scalars in
1845    // heap-backed storage. Converting the boxed slice to a boxed array changes
1846    // only its type; it never materializes `[S; K]` on the stack.
1847    let vars: Box<[S]> = (0..K).map(seed).collect();
1848    let vars: Box<[S; K]> = vars.try_into().map_err(|vars: Box<[S]>| {
1849        format!(
1850            "canonical row program seeded {} primary jets; expected exactly {K}",
1851            vars.len()
1852        )
1853    })?;
1854    prog.eval(row, &vars)
1855}
1856
1857#[inline]
1858fn evaluate_program_with_seeded_primaries<const K: usize, P, S>(
1859    prog: &P,
1860    row: usize,
1861    seed: impl FnMut(usize) -> S,
1862) -> Result<S, String>
1863where
1864    P: RowProgram<K> + ?Sized,
1865    S: crate::jet_scalar::JetScalar<K>,
1866{
1867    if program_primary_jets_fit_stack::<S, K>() {
1868        evaluate_program_with_stack_primaries(prog, row, seed)
1869    } else {
1870        evaluate_program_with_heap_primaries(prog, row, seed)
1871    }
1872}
1873
1874/// Derive the `row_kernel` channel `(nll, ∇, H)` from a [`RowProgram`] at the
1875/// value/gradient/Hessian scalar [`crate::jet_scalar::Order2`], WITHOUT
1876/// materialising any third / fourth tensor.
1877pub fn program_row_kernel<const K: usize, P: RowProgram<K> + ?Sized>(
1878    prog: &P,
1879    row: usize,
1880) -> Result<(f64, [f64; K], [[f64; K]; K]), String> {
1881    let base = prog.primaries(row)?;
1882    let s = evaluate_program_with_seeded_primaries(prog, row, |a| {
1883        <crate::jet_scalar::Order2<K> as crate::jet_scalar::JetScalar<K>>::variable(base[a], a)
1884    })?;
1885    Ok(s.into_channels())
1886}
1887
1888/// Derive the `row_third_contracted(dir)` channel `Σ_c ℓ_{abc} dir_c` from a
1889/// [`RowProgram`] at the one-seed scalar [`crate::jet_scalar::OneSeed`], WITHOUT
1890/// materialising the dense `t3`.
1891pub fn program_third_contracted<const K: usize, P: RowProgram<K> + ?Sized>(
1892    prog: &P,
1893    row: usize,
1894    dir: &[f64; K],
1895) -> Result<[[f64; K]; K], String> {
1896    let base = prog.primaries(row)?;
1897    let s = evaluate_program_with_seeded_primaries(prog, row, |a| {
1898        crate::jet_scalar::OneSeed::seed_direction(base[a], a, dir[a])
1899    })?;
1900    Ok(s.contracted_third())
1901}
1902
1903/// Derive the `row_fourth_contracted(u, v)` channel `Σ_{cd} ℓ_{abcd} u_c v_d`
1904/// from a [`RowProgram`] at the two-seed scalar [`crate::jet_scalar::TwoSeed`],
1905/// WITHOUT materialising the dense `t4`.
1906pub fn program_fourth_contracted<const K: usize, P: RowProgram<K> + ?Sized>(
1907    prog: &P,
1908    row: usize,
1909    dir_u: &[f64; K],
1910    dir_v: &[f64; K],
1911) -> Result<[[f64; K]; K], String> {
1912    let base = prog.primaries(row)?;
1913    let s = evaluate_program_with_seeded_primaries(prog, row, |a| {
1914        crate::jet_scalar::TwoSeed::seed(base[a], a, dir_u[a], dir_v[a])
1915    })?;
1916    Ok(s.contracted_fourth())
1917}
1918
1919/// Derive every channel `(v, g, h, t3, t4)` in one pass from a [`RowProgram`] at
1920/// the full dense [`Tower4`] scalar.
1921///
1922/// The result is boxed so the return slot itself remains bounded independently
1923/// of `K`. Dense towers above the canonical storage budget are rejected before
1924/// the program is touched; consumers at those widths must request only the
1925/// channels they need through [`program_row_kernel`],
1926/// [`program_third_contracted`], and [`program_fourth_contracted`].
1927pub fn program_full_tower<const K: usize, P: RowProgram<K> + ?Sized>(
1928    prog: &P,
1929    row: usize,
1930) -> Result<Box<Tower4<K>>, String> {
1931    let tower_bytes = std::mem::size_of::<Tower4<K>>();
1932    if tower_bytes > PROGRAM_DENSE_JET_STACK_BUDGET_BYTES {
1933        return Err(format!(
1934            "canonical dense Tower4<{K}> requires {tower_bytes} bytes, exceeding the {}-byte \
1935             storage budget; use the bounded row-kernel and directional channel APIs",
1936            PROGRAM_DENSE_JET_STACK_BUDGET_BYTES
1937        ));
1938    }
1939    let base = prog.primaries(row)?;
1940    evaluate_program_with_seeded_primaries(prog, row, |a| Tower4::variable(base[a], a))
1941        .map(Box::new)
1942}
1943
1944// ── The oracle ───────────────────────────────────────────────────────
1945
1946/// One row's worth of hand-written kernel outputs, as claimed by a
1947/// `RowKernel` implementation, packaged for verification against the
1948/// tower truth. Plain data (no trait coupling) so any kernel — whatever
1949/// its visibility — can be audited from its own test module.
1950pub struct KernelChannels<const K: usize> {
1951    /// Claimed `(nll, ∇, H)` from `row_kernel`.
1952    pub value: f64,
1953    /// Claimed gradient.
1954    pub gradient: [f64; K],
1955    /// Claimed Hessian.
1956    pub hessian: [[f64; K]; K],
1957    /// Claimed `row_third_contracted(dir)` outputs as `(dir, claim)` pairs.
1958    pub third: Vec<([f64; K], [[f64; K]; K])>,
1959    /// Claimed `row_fourth_contracted(u, v)` outputs as `(u, v, claim)`.
1960    pub fourth: Vec<([f64; K], [f64; K], [[f64; K]; K])>,
1961}
1962
1963/// Channel-by-channel audit of a hand-written kernel against the
1964/// single-expression tower truth. Returns `Err` naming the first channel,
1965/// index, claimed and true values on disagreement — designed as the body
1966/// of the per-family CI oracle tests (#932 deployment step 2).
1967///
1968/// Tolerance is PER ENTRY, mixed absolute/relative: each comparison uses
1969/// `|claim − truth| ≤ atol + rel_tol · max(|claim|, |truth|)`. The absolute
1970/// floor `atol = rel_tol` lets exact-zero entries of structurally sparse
1971/// towers pass without demanding bit-equality, while a tiny cross-block
1972/// entry dropped next to a huge one is still caught (it is NOT measured
1973/// against the largest entry of the whole channel — there is no per-channel
1974/// magnitude floor). Genuine sign flips (#736) and dropped channels are loud.
1975///
1976/// Non-finite handling is strict: a NaN on either side always fails; an
1977/// infinity passes only when both sides are the SAME signed infinity.
1978pub fn verify_kernel_channels<const K: usize>(
1979    tower: &Tower4<K>,
1980    claims: &KernelChannels<K>,
1981    rel_tol: f64,
1982) -> Result<(), String> {
1983    // Absolute floor: reuse rel_tol so a single knob controls both the
1984    // relative band and the absolute floor for entries near zero.
1985    let atol = rel_tol;
1986    let check = |label: &str, claim: f64, truth: f64| -> Result<(), String> {
1987        // Non-finite values never silently pass the algebraic comparison
1988        // below (any comparison with NaN is false). Handle them explicitly:
1989        // NaN on either side always errs; an infinity passes only if both
1990        // sides are the identical signed infinity.
1991        if !claim.is_finite() || !truth.is_finite() {
1992            let agree = claim.is_infinite()
1993                && truth.is_infinite()
1994                && claim.is_sign_positive() == truth.is_sign_positive();
1995            if agree {
1996                return Ok(());
1997            }
1998            return Err(format!(
1999                "row-kernel oracle: {label} non-finite mismatch: claimed {claim:+.12e}, tower {truth:+.12e}"
2000            ));
2001        }
2002        let band = atol + rel_tol * claim.abs().max(truth.abs());
2003        if (claim - truth).abs() > band {
2004            return Err(format!(
2005                "row-kernel oracle: {label} disagrees: claimed {claim:+.12e}, tower {truth:+.12e} (rel_tol {rel_tol:.1e}, atol {atol:.1e}, band {band:.3e})"
2006            ));
2007        }
2008        Ok(())
2009    };
2010
2011    check("value", claims.value, tower.v)?;
2012
2013    for a in 0..K {
2014        check(&format!("gradient[{a}]"), claims.gradient[a], tower.g[a])?;
2015    }
2016
2017    for a in 0..K {
2018        for b in 0..K {
2019            check(
2020                &format!("hessian[{a}][{b}]"),
2021                claims.hessian[a][b],
2022                tower.h[a][b],
2023            )?;
2024        }
2025    }
2026
2027    for (t_idx, (dir, claim)) in claims.third.iter().enumerate() {
2028        let truth = tower.third_contracted(dir);
2029        for a in 0..K {
2030            for b in 0..K {
2031                check(
2032                    &format!("third[{t_idx}][{a}][{b}]"),
2033                    claim[a][b],
2034                    truth[a][b],
2035                )?;
2036            }
2037        }
2038    }
2039
2040    for (f_idx, (u, w, claim)) in claims.fourth.iter().enumerate() {
2041        let truth = tower.fourth_contracted(u, w);
2042        for a in 0..K {
2043            for b in 0..K {
2044                check(
2045                    &format!("fourth[{f_idx}][{a}][{b}]"),
2046                    claim[a][b],
2047                    truth[a][b],
2048                )?;
2049            }
2050        }
2051    }
2052
2053    Ok(())
2054}
2055
2056#[cfg(test)]
2057mod tests {
2058    use super::*;
2059
2060    /// `Tower3<K>` must be bit-identical to `Tower4<K>` on every channel it
2061    /// carries (value, gradient, Hessian, third derivatives). The order-≤3
2062    /// Leibniz / Faà-di-Bruno terms read only order-≤3 inner channels, so
2063    /// dropping the fourth tensor cannot perturb them. Exercises products
2064    /// (Leibniz cross-terms), unary composition, scaling, and addition — the
2065    /// same operations the survival location-scale `nll_index_tower` composes —
2066    /// across all mixed partials, not just the diagonal entries that kernel reads.
2067    #[test]
2068    fn tower3_matches_tower4_through_third_order() {
2069        let s_a: [f64; 5] = [
2070            0.3_f64.sin(),
2071            0.3_f64.cos(),
2072            -0.3_f64.sin(),
2073            -0.3_f64.cos(),
2074            0.3_f64.sin(),
2075        ];
2076        let s_b: [f64; 5] = [1.1, -0.4, 0.8, -0.2, 0.05];
2077        let s4 = |s: [f64; 5]| [s[0], s[1], s[2], s[3]];
2078
2079        let a4 = Tower4::<3>::variable(0.4, 0);
2080        let b4 = Tower4::<3>::variable(-0.7, 1);
2081        let c4 = Tower4::<3>::variable(0.9, 2);
2082        let prog4 = (a4.mul(&b4) + c4).compose_unary(s_a).scale(1.3)
2083            + a4.mul(&c4).scale(-0.7)
2084            + b4.compose_unary(s_b).scale(0.25);
2085
2086        let a3 = Tower3::<3>::variable(0.4, 0);
2087        let b3 = Tower3::<3>::variable(-0.7, 1);
2088        let c3 = Tower3::<3>::variable(0.9, 2);
2089        let prog3 = (a3.mul(&b3) + c3).compose_unary(s4(s_a)).scale(1.3)
2090            + a3.mul(&c3).scale(-0.7)
2091            + b3.compose_unary(s4(s_b)).scale(0.25);
2092
2093        assert_eq!(prog3.v.to_bits(), prog4.v.to_bits(), "value mismatch");
2094        for i in 0..3 {
2095            assert_eq!(
2096                prog3.g[i].to_bits(),
2097                prog4.g[i].to_bits(),
2098                "g[{i}] mismatch"
2099            );
2100            for j in 0..3 {
2101                assert_eq!(
2102                    prog3.h[i][j].to_bits(),
2103                    prog4.h[i][j].to_bits(),
2104                    "h[{i}][{j}] mismatch"
2105                );
2106                for k in 0..3 {
2107                    assert_eq!(
2108                        prog3.t3[i][j][k].to_bits(),
2109                        prog4.t3[i][j][k].to_bits(),
2110                        "t3[{i}][{j}][{k}] mismatch"
2111                    );
2112                }
2113            }
2114        }
2115    }
2116
2117    /// Binomial-logit row NLL, K=1: ℓ(η) = ln(1 + e^η) − y·η.
2118    /// The entire tower has textbook closed forms in μ = σ(η); this test
2119    /// pins the algebra (exp, ln, scalar mixes, Leibniz/Faà di Bruno) to
2120    /// analytic truth at near-machine precision.
2121    struct LogitProgram {
2122        eta: Vec<f64>,
2123        y: Vec<f64>,
2124    }
2125
2126    impl RowProgram<1> for LogitProgram {
2127        fn n_rows(&self) -> usize {
2128            self.eta.len()
2129        }
2130        fn primaries(&self, row: usize) -> Result<[f64; 1], String> {
2131            Ok([self.eta[row]])
2132        }
2133        fn eval<S: crate::jet_scalar::JetScalar<1>>(
2134            &self,
2135            row: usize,
2136            p: &[S; 1],
2137        ) -> Result<S, String> {
2138            let eta = p[0];
2139            Ok(eta
2140                .exp()
2141                .add(&S::constant(1.0))
2142                .ln()
2143                .sub(&eta.scale(self.y[row])))
2144        }
2145    }
2146
2147    #[test]
2148    fn logit_tower_matches_closed_forms() {
2149        let prog = LogitProgram {
2150            eta: vec![-2.3, -0.4, 0.0, 0.9, 3.1],
2151            y: vec![1.0, 0.0, 1.0, 0.0, 1.0],
2152        };
2153        for row in 0..prog.n_rows() {
2154            let t = program_full_tower(&prog, row).expect("logit program");
2155            let eta = prog.eta[row];
2156            let y = prog.y[row];
2157            let mu = 1.0 / (1.0 + (-eta).exp());
2158            let w = mu * (1.0 - mu);
2159            let expect = [
2160                (t.v, (1.0 + eta.exp()).ln() - y * eta, "value"),
2161                (t.g[0], mu - y, "grad"),
2162                (t.h[0][0], w, "hess"),
2163                (t.t3[0][0][0], w * (1.0 - 2.0 * mu), "third"),
2164                (
2165                    t.t4[0][0][0][0],
2166                    w * (1.0 - 6.0 * mu + 6.0 * mu * mu),
2167                    "fourth",
2168                ),
2169            ];
2170            for (got, want, label) in expect {
2171                assert!(
2172                    (got - want).abs() <= 1e-12 * want.abs().max(1.0),
2173                    "row {row} {label}: got {got:+.15e} want {want:+.15e}"
2174                );
2175            }
2176        }
2177    }
2178
2179    struct OversizedDenseProgram;
2180
2181    impl RowProgram<10> for OversizedDenseProgram {
2182        fn n_rows(&self) -> usize {
2183            1
2184        }
2185
2186        fn primaries(&self, row: usize) -> Result<[f64; 10], String> {
2187            Err(format!(
2188                "dense-tower storage check reached program primaries at row {row}"
2189            ))
2190        }
2191
2192        fn eval<S: crate::jet_scalar::JetScalar<10>>(
2193            &self,
2194            row: usize,
2195            primaries: &[S; 10],
2196        ) -> Result<S, String> {
2197            Err(format!(
2198                "dense-tower storage check reached program evaluation at row {row} with {} primaries",
2199                primaries.len()
2200            ))
2201        }
2202    }
2203
2204    struct LargestBudgetedDenseProgram;
2205
2206    impl RowProgram<9> for LargestBudgetedDenseProgram {
2207        fn n_rows(&self) -> usize {
2208            1
2209        }
2210
2211        fn primaries(&self, row: usize) -> Result<[f64; 9], String> {
2212            if row == 0 {
2213                Ok([1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0])
2214            } else {
2215                Err(format!("largest budgeted dense program has no row {row}"))
2216            }
2217        }
2218
2219        fn eval<S: crate::jet_scalar::JetScalar<9>>(
2220            &self,
2221            row: usize,
2222            primaries: &[S; 9],
2223        ) -> Result<S, String> {
2224            if row != 0 {
2225                return Err(format!("largest budgeted dense program has no row {row}"));
2226            }
2227            let linear =
2228                S::linear_combination(primaries, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
2229            let quartic = primaries[0]
2230                .mul(&primaries[1])
2231                .mul(&primaries[2])
2232                .mul(&primaries[3]);
2233            Ok(linear.add(&quartic))
2234        }
2235    }
2236
2237    #[test]
2238    fn full_tower_accepts_largest_width_inside_storage_budget_932() {
2239        assert_eq!(std::mem::size_of::<Tower4<9>>(), 59_048);
2240        assert!(
2241            !program_primary_jets_fit_stack::<Tower4<9>, 9>(),
2242            "nine full-width primary towers must use exact-length heap storage"
2243        );
2244
2245        let tower = program_full_tower(&LargestBudgetedDenseProgram, 0)
2246            .expect("Tower4<9> must remain inside the canonical dense storage budget");
2247        assert_eq!(tower.v, 309.0);
2248        assert_eq!(tower.g, [25.0, 14.0, 11.0, 10.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
2249        // `t4` stores derivatives, not Taylor coefficients: the distinct-axis
2250        // derivative of p0*p1*p2*p3 is 1, with no 4! normalization.
2251        assert_eq!(tower.t4[0][1][2][3], 1.0);
2252    }
2253
2254    #[test]
2255    fn full_tower_refuses_oversized_result_before_touching_program() {
2256        let tower_bytes = std::mem::size_of::<Tower4<10>>();
2257        assert!(tower_bytes > PROGRAM_DENSE_JET_STACK_BUDGET_BYTES);
2258        assert!(
2259            std::mem::size_of::<Result<Box<Tower4<32>>, String>>()
2260                <= 4 * std::mem::size_of::<usize>(),
2261            "boxed full-tower API must keep its return slot independent of dense tower width"
2262        );
2263
2264        let error = program_full_tower(&OversizedDenseProgram, 0)
2265            .expect_err("Tower4<10> must exceed the canonical dense storage budget");
2266        assert_eq!(
2267            error,
2268            format!(
2269                "canonical dense Tower4<10> requires {tower_bytes} bytes, exceeding the {}-byte \
2270                 storage budget; use the bounded row-kernel and directional channel APIs",
2271                PROGRAM_DENSE_JET_STACK_BUDGET_BYTES
2272            )
2273        );
2274    }
2275
2276    fn assert_close(label: &str, got: f64, want: f64, rel_tol: f64) {
2277        let diff = (got - want).abs();
2278        assert!(
2279            diff <= rel_tol * want.abs().max(1.0),
2280            "{label}: got {got:+.17e} want {want:+.17e} diff {diff:.3e}"
2281        );
2282    }
2283
2284    #[test]
2285    fn gamma_special_function_stacks_match_reference_values() {
2286        const EULER_GAMMA: f64 = 0.577_215_664_901_532_9;
2287        let pi_sq = std::f64::consts::PI * std::f64::consts::PI;
2288        let cases = [
2289            (
2290                "x=0.1",
2291                0.1,
2292                -10.423_754_940_411_076,
2293                101.433_299_150_792_75,
2294            ),
2295            (
2296                "x=0.5",
2297                0.5,
2298                -EULER_GAMMA - 2.0 * std::f64::consts::LN_2,
2299                pi_sq / 2.0,
2300            ),
2301            ("x=1", 1.0, -EULER_GAMMA, pi_sq / 6.0),
2302            (
2303                "x=2.5",
2304                2.5,
2305                -EULER_GAMMA - 2.0 * std::f64::consts::LN_2 + 2.0 + 2.0 / 3.0,
2306                pi_sq / 2.0 - 4.0 - 4.0 / 9.0,
2307            ),
2308            (
2309                "x=50",
2310                50.0,
2311                3.901_989_673_427_892,
2312                0.020_201_333_226_697_128,
2313            ),
2314        ];
2315
2316        for (label, x, digamma_ref, trigamma_ref) in cases {
2317            let ln_gamma_stack = ln_gamma_derivative_stack(x);
2318            let digamma_stack = digamma_derivative_stack(x);
2319            let trigamma_stack = trigamma_derivative_stack(x);
2320            assert_close(
2321                &format!("{label} ln_gamma_stack digamma"),
2322                ln_gamma_stack[1],
2323                digamma_ref,
2324                1e-13,
2325            );
2326            assert_close(
2327                &format!("{label} digamma value"),
2328                digamma_stack[0],
2329                digamma_ref,
2330                1e-13,
2331            );
2332            assert_close(
2333                &format!("{label} ln_gamma_stack trigamma"),
2334                ln_gamma_stack[2],
2335                trigamma_ref,
2336                1e-13,
2337            );
2338            assert_close(
2339                &format!("{label} digamma_stack trigamma"),
2340                digamma_stack[1],
2341                trigamma_ref,
2342                1e-13,
2343            );
2344            assert_close(
2345                &format!("{label} trigamma value"),
2346                trigamma_stack[0],
2347                trigamma_ref,
2348                1e-13,
2349            );
2350        }
2351    }
2352
2353    #[test]
2354    fn gamma_special_function_stacks_obey_recurrences() {
2355        for x in [0.1, 0.5, 1.0, 2.5, 50.0] {
2356            let digamma_x = digamma_derivative_stack(x)[0];
2357            let digamma_next = digamma_derivative_stack(x + 1.0)[0];
2358            let trigamma_x = trigamma_derivative_stack(x)[0];
2359            let trigamma_next = trigamma_derivative_stack(x + 1.0)[0];
2360            assert_close(
2361                &format!("digamma recurrence x={x}"),
2362                digamma_next,
2363                digamma_x + 1.0 / x,
2364                1e-13,
2365            );
2366            assert_close(
2367                &format!("trigamma recurrence x={x}"),
2368                trigamma_next,
2369                trigamma_x - 1.0 / (x * x),
2370                1e-13,
2371            );
2372        }
2373    }
2374
2375    /// Gaussian location-scale row NLL, K=2 primaries (η, s = log σ):
2376    /// ℓ = s + ½ e^{−2s} (y − η)². Mixed cross blocks — the #736 fragility
2377    /// shape — all have one-line closed forms here.
2378    struct LocScaleProgram {
2379        eta: Vec<f64>,
2380        s: Vec<f64>,
2381        y: Vec<f64>,
2382    }
2383
2384    impl RowProgram<2> for LocScaleProgram {
2385        fn n_rows(&self) -> usize {
2386            self.eta.len()
2387        }
2388        fn primaries(&self, row: usize) -> Result<[f64; 2], String> {
2389            Ok([self.eta[row], self.s[row]])
2390        }
2391        fn eval<S: crate::jet_scalar::JetScalar<2>>(
2392            &self,
2393            row: usize,
2394            p: &[S; 2],
2395        ) -> Result<S, String> {
2396            let r = S::constant(self.y[row]).sub(&p[0]);
2397            Ok(p[1].add(&p[1].scale(-2.0).exp().mul(&r).mul(&r).scale(0.5)))
2398        }
2399    }
2400
2401    #[test]
2402    fn locscale_tower_matches_closed_forms_including_cross_blocks() {
2403        let prog = LocScaleProgram {
2404            eta: vec![0.3, -1.1, 2.0],
2405            s: vec![-0.5, 0.2, 0.8],
2406            y: vec![1.0, -2.0, 2.5],
2407        };
2408        let tol = 1e-12;
2409        for row in 0..prog.n_rows() {
2410            let t = program_full_tower(&prog, row).expect("locscale program");
2411            let r = prog.y[row] - prog.eta[row];
2412            let w = (-2.0 * prog.s[row]).exp();
2413            // (η, s) = indices (0, 1).
2414            let truth_g = [-w * r, 1.0 - w * r * r];
2415            let truth_h = [[w, 2.0 * w * r], [2.0 * w * r, 2.0 * w * r * r]];
2416            // Third tensor: distinct-entry closed forms.
2417            // ∂ηηη = 0, ∂ηηs = −2w, ∂ηss = −4wr, ∂sss = −4wr².
2418            let t3_truth = |a: usize, b: usize, c: usize| -> f64 {
2419                match a + b + c {
2420                    0 => 0.0,
2421                    1 => -2.0 * w,
2422                    2 => -4.0 * w * r,
2423                    _ => -4.0 * w * r * r,
2424                }
2425            };
2426            // Fourth tensor: ∂ηηηη = 0, ∂ηηηs = 0? No: d/ds(∂ηηη)=0 ✓;
2427            // ∂ηηss = 4w, ∂ηsss = 8wr, ∂ssss = 8wr².
2428            let t4_truth = |a: usize, b: usize, c: usize, d: usize| -> f64 {
2429                match a + b + c + d {
2430                    0 | 1 => 0.0,
2431                    2 => 4.0 * w,
2432                    3 => 8.0 * w * r,
2433                    _ => 8.0 * w * r * r,
2434                }
2435            };
2436            for a in 0..2 {
2437                assert!(
2438                    (t.g[a] - truth_g[a]).abs() <= tol * truth_g[a].abs().max(1.0),
2439                    "row {row} grad[{a}]"
2440                );
2441                for b in 0..2 {
2442                    assert!(
2443                        (t.h[a][b] - truth_h[a][b]).abs() <= tol * w.max(1.0) * (1.0 + r.abs()),
2444                        "row {row} hess[{a}][{b}]: got {} want {}",
2445                        t.h[a][b],
2446                        truth_h[a][b]
2447                    );
2448                    for c in 0..2 {
2449                        assert!(
2450                            (t.t3[a][b][c] - t3_truth(a, b, c)).abs()
2451                                <= tol * 8.0 * w.max(1.0) * (1.0 + r.abs() + r * r),
2452                            "row {row} t3[{a}][{b}][{c}]: got {} want {}",
2453                            t.t3[a][b][c],
2454                            t3_truth(a, b, c)
2455                        );
2456                        for d in 0..2 {
2457                            assert!(
2458                                (t.t4[a][b][c][d] - t4_truth(a, b, c, d)).abs()
2459                                    <= tol * 16.0 * w.max(1.0) * (1.0 + r.abs() + r * r),
2460                                "row {row} t4[{a}][{b}][{c}][{d}]: got {} want {}",
2461                                t.t4[a][b][c][d],
2462                                t4_truth(a, b, c, d)
2463                            );
2464                        }
2465                    }
2466                }
2467            }
2468            // The canonical trait-surface helpers agree with direct contraction.
2469            let dir = [0.7, -1.3];
2470            let third = program_third_contracted(&prog, row, &dir).expect("third");
2471            for a in 0..2 {
2472                for b in 0..2 {
2473                    let want = t.t3[a][b][0] * dir[0] + t.t3[a][b][1] * dir[1];
2474                    assert!((third[a][b] - want).abs() <= 1e-13 * want.abs().max(1.0));
2475                }
2476            }
2477        }
2478    }
2479
2480    /// FD cross-check on a deliberately gnarly composition (div, sqrt,
2481    /// powf, nested exp/ln) in K=3, where no closed form is consulted:
2482    /// every tower channel is checked against central finite differences
2483    /// of the channel one order below — value→grad, grad→hess, hess→t3,
2484    /// t3→t4 — so each order is independently anchored.
2485    ///
2486    /// The program carries a per-row primary fixture plus a per-row offset
2487    /// `tau[row]` that enters the loss as a constant, so `row` genuinely
2488    /// drives both the seed point and the evaluated expression.
2489    struct GnarlyProgram {
2490        primaries: Vec<[f64; 3]>,
2491        tau: Vec<f64>,
2492    }
2493
2494    impl GnarlyProgram {
2495        fn fixture() -> Self {
2496            Self {
2497                primaries: vec![[0.4, -0.7, 1.2], [-0.9, 0.6, 0.3], [1.1, -0.2, -0.8]],
2498                tau: vec![0.15, -0.35, 0.5],
2499            }
2500        }
2501    }
2502
2503    impl RowProgram<3> for GnarlyProgram {
2504        fn n_rows(&self) -> usize {
2505            self.primaries.len()
2506        }
2507        fn primaries(&self, row: usize) -> Result<[f64; 3], String> {
2508            self.primaries
2509                .get(row)
2510                .copied()
2511                .ok_or_else(|| format!("gnarly: row {row} out of range"))
2512        }
2513        fn eval<S: crate::jet_scalar::JetScalar<3>>(
2514            &self,
2515            row: usize,
2516            p: &[S; 3],
2517        ) -> Result<S, String> {
2518            let tau = *self
2519                .tau
2520                .get(row)
2521                .ok_or_else(|| format!("gnarly: tau row {row} out of range"))?;
2522            let a = p[0].mul(&p[1]).exp();
2523            let b = p[2].mul(&p[2]).add(&S::constant(1.0)).sqrt();
2524            let c = a.add(&b).add(&S::constant(tau)).ln();
2525            let d = p[1].scale(0.5).add(&S::constant(2.0)).powf(1.7);
2526            let delta = p[0].sub(&p[2]);
2527            Ok(c.mul(&d.recip()).add(&delta.mul(&delta).scale(0.25)))
2528        }
2529    }
2530
2531    /// Evaluate the gnarly program's tower at an ARBITRARY seed point for
2532    /// `row` (used to drive central differences off the fixture grid),
2533    /// while keeping `row`'s per-row data (`tau`) in the loss.
2534    fn gnarly_tower_at(prog: &GnarlyProgram, row: usize, p: [f64; 3]) -> Tower4<3> {
2535        struct At<'a> {
2536            base: &'a GnarlyProgram,
2537            row: usize,
2538            p: [f64; 3],
2539        }
2540        impl RowProgram<3> for At<'_> {
2541            fn n_rows(&self) -> usize {
2542                1
2543            }
2544            fn primaries(&self, row: usize) -> Result<[f64; 3], String> {
2545                if row != 0 {
2546                    return Err(format!("gnarly-at: row {row} out of range"));
2547                }
2548                Ok(self.p)
2549            }
2550            fn eval<S: crate::jet_scalar::JetScalar<3>>(
2551                &self,
2552                eval_row: usize,
2553                vars: &[S; 3],
2554            ) -> Result<S, String> {
2555                if eval_row != 0 {
2556                    return Err(format!("gnarly-at: eval row {eval_row} out of range"));
2557                }
2558                self.base.eval(self.row, vars)
2559            }
2560        }
2561        *program_full_tower(&At { base: prog, row, p }, 0).expect("gnarly tower")
2562    }
2563
2564    #[test]
2565    fn gnarly_tower_is_fd_consistent_order_by_order() {
2566        let prog = GnarlyProgram::fixture();
2567        for row in 0..prog.n_rows() {
2568            let base = prog.primaries(row).expect("primaries");
2569            let t = gnarly_tower_at(&prog, row, base);
2570            let h_step = 1e-5;
2571            let tol = 1e-6;
2572            for c in 0..3 {
2573                let mut up = base;
2574                let mut dn = base;
2575                up[c] += h_step;
2576                dn[c] -= h_step;
2577                let t_up = gnarly_tower_at(&prog, row, up);
2578                let t_dn = gnarly_tower_at(&prog, row, dn);
2579                // value → gradient.
2580                let fd_g = (t_up.v - t_dn.v) / (2.0 * h_step);
2581                assert!(
2582                    (t.g[c] - fd_g).abs() <= tol * fd_g.abs().max(1.0),
2583                    "grad[{c}]: analytic {} fd {}",
2584                    t.g[c],
2585                    fd_g
2586                );
2587                for a in 0..3 {
2588                    // gradient → Hessian.
2589                    let fd_h = (t_up.g[a] - t_dn.g[a]) / (2.0 * h_step);
2590                    assert!(
2591                        (t.h[a][c] - fd_h).abs() <= tol * fd_h.abs().max(1.0),
2592                        "hess[{a}][{c}]: analytic {} fd {}",
2593                        t.h[a][c],
2594                        fd_h
2595                    );
2596                    for b in 0..3 {
2597                        // Hessian → third.
2598                        let fd_t3 = (t_up.h[a][b] - t_dn.h[a][b]) / (2.0 * h_step);
2599                        assert!(
2600                            (t.t3[a][b][c] - fd_t3).abs() <= tol * fd_t3.abs().max(1.0),
2601                            "t3[{a}][{b}][{c}]: analytic {} fd {}",
2602                            t.t3[a][b][c],
2603                            fd_t3
2604                        );
2605                        for d in 0..3 {
2606                            // third → fourth.
2607                            let fd_t4 = (t_up.t3[a][b][d] - t_dn.t3[a][b][d]) / (2.0 * h_step);
2608                            assert!(
2609                                (t.t4[a][b][d][c] - fd_t4).abs() <= tol * fd_t4.abs().max(1.0),
2610                                "t4[{a}][{b}][{d}][{c}]: analytic {} fd {}",
2611                                t.t4[a][b][d][c],
2612                                fd_t4
2613                            );
2614                        }
2615                    }
2616                }
2617            }
2618        }
2619    }
2620
2621    /// `implicit_solve` reproduces the true implicit function `a(θ)` of a
2622    /// constraint `F(a, θ) = 0` to fourth order. The constraint here is the
2623    /// smooth, strictly-`a`-monotone
2624    ///   F(a, θ) = a + θ₀·a² + θ₁·exp(a) − c
2625    /// whose root `a(θ)` is re-solved by scalar Newton at perturbed θ as the
2626    /// independent finite-difference oracle. Mirrors the survival flex
2627    /// calibration solve (one implicit intercept over the primaries) without
2628    /// any survival machinery, so a failure localises to the combinator.
2629    #[test]
2630    fn implicit_solve_matches_scalar_resolve_to_fourth_order() {
2631        const C: f64 = 1.7;
2632        // The scalar constraint as a plain f64 closure (the production root
2633        // finder analogue) and its tower form in (a, θ₀, θ₁).
2634        let f_scalar = |a: f64, th: [f64; 2]| a + th[0] * a * a + th[1] * a.exp() - C;
2635        let f_da = |a: f64, th: [f64; 2]| 1.0 + 2.0 * th[0] * a + th[1] * a.exp();
2636        let solve = |th: [f64; 2]| -> f64 {
2637            let mut a = 0.0_f64;
2638            for _ in 0..100 {
2639                let r = f_scalar(a, th);
2640                if r.abs() < 1e-14 {
2641                    break;
2642                }
2643                a -= r / f_da(a, th);
2644            }
2645            a
2646        };
2647        // Tower constraint over K1 = 3 vars: slot 0 = a, slots 1,2 = θ₀, θ₁.
2648        let f_tower = |a0: f64, th: [f64; 2]| -> Tower4<3> {
2649            let a = Tower4::<3>::variable(a0, 0);
2650            let t0 = Tower4::<3>::variable(th[0], 1);
2651            let t1 = Tower4::<3>::variable(th[1], 2);
2652            a + t0 * a.mul(&a) + t1 * a.exp() - C
2653        };
2654
2655        let th0 = [0.35, 0.2];
2656        let a0 = solve(th0);
2657        let f = f_tower(a0, th0);
2658        // Residual at the solved point is ~0 (the combinator tolerates the
2659        // production Newton residual; here it is machine-zero).
2660        assert!(f.v.abs() < 1e-12, "constraint residual {:+.3e}", f.v);
2661        let a_tower: Tower4<2> = implicit_solve::<3, 2>(&f, a0).expect("implicit solve");
2662
2663        // FD oracle: central differences of the scalar re-solve. Each order is
2664        // built from the previous via one more central difference, exactly the
2665        // gnarly order-by-order ladder.
2666        let h = 1e-4;
2667        let tol = 1e-5;
2668        let re = |th: [f64; 2]| solve(th);
2669        for i in 0..2 {
2670            let mut up = th0;
2671            let mut dn = th0;
2672            up[i] += h;
2673            dn[i] -= h;
2674            let fd_g = (re(up) - re(dn)) / (2.0 * h);
2675            assert!(
2676                (a_tower.g[i] - fd_g).abs() <= tol * fd_g.abs().max(1.0),
2677                "a_θ[{i}]: analytic {:+.6e} fd {:+.6e}",
2678                a_tower.g[i],
2679                fd_g
2680            );
2681            // second order: FD of the analytic gradient component would re-use
2682            // the combinator; instead difference a SCALAR gradient computed by
2683            // a nested re-solve so the oracle stays production-independent.
2684            let grad_at = |th: [f64; 2], j: usize| -> f64 {
2685                let mut up = th;
2686                let mut dn = th;
2687                up[j] += h;
2688                dn[j] -= h;
2689                (re(up) - re(dn)) / (2.0 * h)
2690            };
2691            for j in 0..2 {
2692                let fd_h = (grad_at(up, j) - grad_at(dn, j)) / (2.0 * h);
2693                assert!(
2694                    (a_tower.h[i][j] - fd_h).abs() <= 1e-3 * fd_h.abs().max(1.0),
2695                    "a_θθ[{i}][{j}]: analytic {:+.6e} fd {:+.6e}",
2696                    a_tower.h[i][j],
2697                    fd_h
2698                );
2699            }
2700        }
2701    }
2702
2703    /// `implicit_solve` degenerates to `a_θ = −F_θ / F_a` at first order on a
2704    /// linear-in-a constraint, and the second-order tensor matches the
2705    /// textbook IFT formula `a_uv = −(F_uv + F_au a_v + F_av a_u + F_aa a_u a_v)/F_a`.
2706    /// This pins the recursion against the hand-coded first_full.rs formula it
2707    /// replaces, independent of any FD step.
2708    #[test]
2709    fn implicit_solve_matches_textbook_ift_recursion() {
2710        // A constraint with non-trivial F_a, F_aa, F_au, F_uv all present.
2711        let a0 = 0.4_f64;
2712        let th = [0.25_f64, -0.15_f64];
2713        let f = {
2714            let a = Tower4::<3>::variable(a0, 0);
2715            let t0 = Tower4::<3>::variable(th[0], 1);
2716            let t1 = Tower4::<3>::variable(th[1], 2);
2717            // F = a·(1 + θ₀) + θ₁·a² + θ₀·θ₁ − 0.4385. The constant is chosen so
2718            // F(a0, θ0) = 0 exactly at a0 = 0.4, θ = [0.25, −0.15]:
2719            //   0.4·1.25 + (−0.15)·0.16 + 0.25·(−0.15) = 0.4385.
2720            // implicit_solve requires a genuine root; at the root the level-set
2721            // and root-curve derivatives coincide, so the textbook-IFT
2722            // assertions below are unaffected.
2723            a * (t0 + 1.0) + t1 * a.mul(&a) + t0 * t1 - 0.4385
2724        };
2725        let a_t = implicit_solve::<3, 2>(&f, a0).expect("solve");
2726        let f_a = f.g[0];
2727        // First order: a_u = −F_u / F_a.
2728        for u in 0..2 {
2729            let want = -f.g[u + 1] / f_a;
2730            assert!(
2731                (a_t.g[u] - want).abs() < 1e-12,
2732                "a_u[{u}] {:+.6e} vs −F_u/F_a {:+.6e}",
2733                a_t.g[u],
2734                want
2735            );
2736        }
2737        // Second order textbook IFT (indices shifted by 1 for the a-slot).
2738        for u in 0..2 {
2739            for v in 0..2 {
2740                let f_uv = f.h[u + 1][v + 1];
2741                let f_au = f.h[0][u + 1];
2742                let f_av = f.h[0][v + 1];
2743                let f_aa = f.h[0][0];
2744                let want =
2745                    -(f_uv + f_au * a_t.g[v] + f_av * a_t.g[u] + f_aa * a_t.g[u] * a_t.g[v]) / f_a;
2746                assert!(
2747                    (a_t.h[u][v] - want).abs() < 1e-12,
2748                    "a_uv[{u}][{v}] {:+.6e} vs IFT {:+.6e}",
2749                    a_t.h[u][v],
2750                    want
2751                );
2752            }
2753        }
2754    }
2755
2756    /// The moving-boundary flux tower reproduces every θ-derivative of a
2757    /// moving-limit integral, INCLUDING the second-order `B·z_uv` term the
2758    /// hand-written flux dropped (#932). The edge `z_R(θ) = θ₀ + θ₁²` has a
2759    /// genuinely nonzero `∂²z_R/∂θ₁² = 2`, so a combinator that omitted
2760    /// `B·z_uv` would miss the [1][1] Hessian entry. Truth = central FD of the
2761    /// closed-form integral `∫₀^{z_R} e^{−z²/2} dz = √(π/2)·erf(z_R/√2)`.
2762    #[test]
2763    fn moving_boundary_flux_carries_b_zuv_term() {
2764        use std::f64::consts::PI;
2765        let b = |z: f64| (-0.5 * z * z).exp(); // integrand B(z)
2766        // Antiderivative-based closed-form integral I(z_R) = ∫₀^{z_R} B dz.
2767        let integral = |z_r: f64| (PI / 2.0).sqrt() * libm::erf(z_r / 2.0_f64.sqrt());
2768        let z_r = |th: [f64; 2]| th[0] + th[1] * th[1];
2769        let th0 = [0.7_f64, 0.5_f64];
2770
2771        // Edge tower z_R(θ) over K=2 primaries: value + exact derivatives.
2772        let mut z_edge = Tower4::<2>::constant(z_r(th0));
2773        z_edge.g[0] = 1.0; // ∂z_R/∂θ₀ = 1
2774        z_edge.g[1] = 2.0 * th0[1]; // ∂z_R/∂θ₁ = 2θ₁
2775        z_edge.h[1][1] = 2.0; // ∂²z_R/∂θ₁² = 2  (the z_uv the old flux dropped)
2776
2777        // Integrand stack [B, B′, B″, B‴] at z₀: B′=−z·B, B″=(z²−1)·B,
2778        // B‴=(3z−z³)·B.
2779        let z0 = z_edge.v;
2780        let b0 = b(z0);
2781        let stack = [
2782            b0,
2783            -z0 * b0,
2784            (z0 * z0 - 1.0) * b0,
2785            (3.0 * z0 - z0 * z0 * z0) * b0,
2786        ];
2787        let flux = moving_limit_boundary_tower(&z_edge, stack);
2788
2789        // FD truth of the integral's derivatives.
2790        let h = 1e-4;
2791        let tol = 1e-6;
2792        for i in 0..2 {
2793            let mut up = th0;
2794            let mut dn = th0;
2795            up[i] += h;
2796            dn[i] -= h;
2797            let fd_g = (integral(z_r(up)) - integral(z_r(dn))) / (2.0 * h);
2798            assert!(
2799                (flux.g[i] - fd_g).abs() <= tol * fd_g.abs().max(1.0),
2800                "flux_g[{i}]: analytic {:+.8e} fd {:+.8e}",
2801                flux.g[i],
2802                fd_g
2803            );
2804        }
2805        // The decisive entry: ∂²I/∂θ₁² = B′·(z_θ₁)² + B·z_θ₁θ₁. With z_θ₁=2θ₁=1
2806        // and z_θ₁θ₁=2, the B·z_uv contribution is B(z₀)·2 — omitting it would
2807        // leave the [1][1] entry short by exactly 2·B(z₀).
2808        let grad1_at = |th: [f64; 2]| -> f64 {
2809            let mut up = th;
2810            let mut dn = th;
2811            up[1] += h;
2812            dn[1] -= h;
2813            (integral(z_r(up)) - integral(z_r(dn))) / (2.0 * h)
2814        };
2815        let mut up = th0;
2816        let mut dn = th0;
2817        up[1] += h;
2818        dn[1] -= h;
2819        let fd_h11 = (grad1_at(up) - grad1_at(dn)) / (2.0 * h);
2820        assert!(
2821            (flux.h[1][1] - fd_h11).abs() <= 1e-3 * fd_h11.abs().max(1.0),
2822            "flux_h[1][1] (carries B·z_uv): analytic {:+.8e} fd {:+.8e}",
2823            flux.h[1][1],
2824            fd_h11
2825        );
2826        // Explicit witness that the B·z_uv term is present and material:
2827        // analytic h[1][1] minus the pure (z_u)² part must equal B·z_uv = 2·B₀.
2828        let pure_zu2 = stack[1] * z_edge.g[1] * z_edge.g[1];
2829        let b_zuv = flux.h[1][1] - pure_zu2;
2830        assert!(
2831            (b_zuv - b0 * 2.0).abs() < 1e-10,
2832            "B·z_uv term {:+.8e} != B₀·z_uv {:+.8e}",
2833            b_zuv,
2834            b0 * 2.0
2835        );
2836    }
2837
2838    /// `moving_limit_boundary_tower_theta_integrand` reproduces the marginal-slope
2839    /// flex boundary closure for a θ-DEPENDENT integrand `G(z;θ)` — the case the
2840    /// plain `moving_limit_boundary_tower` cannot express, and the case the
2841    /// survival directional/bidirectional paths hand-assemble term-by-term
2842    /// (`G·z_uv + G_z·z_u·z_v + G_θu·z_v + G_θv·z_u`, with the directional path
2843    /// dropping `G·z_uv`). Two independent oracles:
2844    ///   (1) closed-form: the boundary flux of `∫ G dz` is exactly
2845    ///       `Φ(z_edge(θ);θ) − Φ(z₀;θ)` (Φ = z-antiderivative of G), whose θ
2846    ///       derivatives we take by central FD of the closed form — no jet code.
2847    ///   (2) the explicit second-order hand closure, including the `G·z_uv` term,
2848    ///       built from the integrand's own (z,θ) partials.
2849    /// G(z;θ) = exp(z·θ₀) is genuinely θ-dependent (G_θ₀ = z·e^{zθ₀} ≠ 0), and
2850    /// the edge z_edge = z₀ + θ₀ + θ₁² has a real z_uv = ∂²/∂θ₁² = 2, so a
2851    /// combinator that dropped either the integrand-θ terms or `G·z_uv` would
2852    /// miss a Hessian entry.
2853    #[test]
2854    fn moving_boundary_theta_integrand_matches_handpath_and_closed_form() {
2855        // G(z;θ) = exp(z·θ₀);  Φ(z;θ) = ∫₀^z G = (e^{zθ₀} − 1)/θ₀.
2856        let g = |z: f64, t0: f64| (z * t0).exp();
2857        let phi = |z: f64, t0: f64| ((z * t0).exp() - 1.0) / t0;
2858        let z_r = |th: [f64; 2]| 0.6 + th[0] + th[1] * th[1];
2859        let th0 = [0.4_f64, 0.5_f64];
2860        let z0 = z_r(th0);
2861
2862        // Edge tower z_edge(θ) over K=2 primaries.
2863        let mut z_edge = Tower4::<2>::constant(z0);
2864        z_edge.g[0] = 1.0; // ∂z/∂θ₀
2865        z_edge.g[1] = 2.0 * th0[1]; // ∂z/∂θ₁
2866        z_edge.h[1][1] = 2.0; // ∂²z/∂θ₁² (the z_uv the directional path drops)
2867
2868        // Φ's mixed (z, θ) jet over K1 = 3 vars: slot 0 = z, slots 1,2 = θ₀,θ₁.
2869        // Built ONCE in tower arithmetic so every (z^i θ^j) partial is exact.
2870        let z_var = Tower4::<3>::variable(z0, 0);
2871        let t0_var = Tower4::<3>::variable(th0[0], 1);
2872        // θ₁ does not enter G/Φ here (its Φ-derivatives are zero; the z_edge
2873        // chain supplies all θ₁ motion through slot 0), so the K1 frame's θ₁
2874        // slot is intentionally left unseeded.
2875        let phi_jet = ((z_var * t0_var).exp() - 1.0) / t0_var;
2876        // Sanity: slot-0 first derivative of Φ IS G(z₀;θ₀).
2877        assert!(
2878            (phi_jet.g[0] - g(z0, th0[0])).abs() < 1e-12,
2879            "Φ_z {:+.8e} != G {:+.8e}",
2880            phi_jet.g[0],
2881            g(z0, th0[0])
2882        );
2883
2884        let flux = moving_limit_boundary_tower_theta_integrand::<3, 2>(&phi_jet, &z_edge);
2885
2886        // Value channel is 0 by construction (boundary, not the integral itself).
2887        assert!(
2888            flux.v.abs() < 1e-12,
2889            "boundary value channel {:+.3e}",
2890            flux.v
2891        );
2892
2893        // Oracle (1): central FD of the closed-form boundary flux
2894        //   Bnd(θ) = Φ(z_edge(θ); θ) − Φ(z₀; θ)   (z₀ FROZEN at the base edge).
2895        let bnd = |th: [f64; 2]| phi(z_r(th), th[0]) - phi(z0, th[0]);
2896        let h = 1e-4;
2897        let tol = 1e-6;
2898        for i in 0..2 {
2899            let mut up = th0;
2900            let mut dn = th0;
2901            up[i] += h;
2902            dn[i] -= h;
2903            let fd_g = (bnd(up) - bnd(dn)) / (2.0 * h);
2904            assert!(
2905                (flux.g[i] - fd_g).abs() <= tol * fd_g.abs().max(1.0),
2906                "boundary_g[{i}] analytic {:+.8e} fd {:+.8e}",
2907                flux.g[i],
2908                fd_g
2909            );
2910        }
2911        let grad_at = |th: [f64; 2], j: usize| -> f64 {
2912            let mut up = th;
2913            let mut dn = th;
2914            up[j] += h;
2915            dn[j] -= h;
2916            (bnd(up) - bnd(dn)) / (2.0 * h)
2917        };
2918        for i in 0..2 {
2919            for j in 0..2 {
2920                let mut up = th0;
2921                let mut dn = th0;
2922                up[i] += h;
2923                dn[i] -= h;
2924                let fd_h = (grad_at(up, j) - grad_at(dn, j)) / (2.0 * h);
2925                assert!(
2926                    (flux.h[i][j] - fd_h).abs() <= 1e-3 * fd_h.abs().max(1.0),
2927                    "boundary_h[{i}][{j}] analytic {:+.8e} fd {:+.8e}",
2928                    flux.h[i][j],
2929                    fd_h
2930                );
2931            }
2932        }
2933
2934        // Oracle (2): the explicit second-order hand closure, term by term —
2935        // `G·z_uv + G_z·z_u·z_v + G_θu·z_v + G_θv·z_u`. Read G's partials at the
2936        // base point directly (no jet): G = e^{zθ₀}, G_z = θ₀·G, G_θ₀ = z·G,
2937        // G_θ₁ = 0.
2938        let gg = g(z0, th0[0]);
2939        let g_z = th0[0] * gg;
2940        let g_theta = [z0 * gg, 0.0]; // [G_θ₀, G_θ₁]
2941        for i in 0..2 {
2942            for j in 0..2 {
2943                let z_u = z_edge.g[i];
2944                let z_v = z_edge.g[j];
2945                let z_uv = z_edge.h[i][j];
2946                let hand = gg * z_uv + g_z * z_u * z_v + g_theta[i] * z_v + g_theta[j] * z_u;
2947                assert!(
2948                    (flux.h[i][j] - hand).abs() < 1e-9,
2949                    "boundary_h[{i}][{j}] {:+.8e} != hand closure {:+.8e}",
2950                    flux.h[i][j],
2951                    hand
2952                );
2953            }
2954        }
2955
2956        // Decisive: the `G·z_uv` term the directional path DROPS is present and
2957        // material in the [1][1] entry (z_uv = 2 there).
2958        let pure_no_zuv = g_z * z_edge.g[1] * z_edge.g[1] + 2.0 * g_theta[1] * z_edge.g[1];
2959        let g_zuv = flux.h[1][1] - pure_no_zuv;
2960        assert!(
2961            (g_zuv - gg * 2.0).abs() < 1e-9,
2962            "G·z_uv term {:+.8e} != G₀·z_uv {:+.8e}",
2963            g_zuv,
2964            gg * 2.0
2965        );
2966    }
2967
2968    /// The survival crossing-edge position tower `z_edge = (τ − a(θ)) / b`,
2969    /// `b = exp(g)`, built from the intercept tower `a(θ)` (here a stand-in)
2970    /// and the seeded slope `g`, reproduces taylor-jet's exact hand-path
2971    /// boundary-velocity formulas:
2972    ///   z_u   = −(a_u + [u==g]·z) / b
2973    ///   z_uv  = −(a_uv + [u==g]·z_v + [v==g]·z_u) / b
2974    /// This pins the bridge between `implicit_solve` and
2975    /// `cell_moving_boundary_flux_tower`: the boundary jet that the production
2976    /// flex path hand-codes (and dropped `z_uv` from) is exactly `∂²` of this
2977    /// tower. K=3 reduced frame: slot 0 = a-axis carrier (an arbitrary smooth
2978    /// a(θ) with nonzero a_u/a_uv), slot 1 = g (the log-slope), slot 2 unused.
2979    #[test]
2980    fn crossing_edge_tower_matches_handpath_velocity_formulas() {
2981        const TAU: f64 = 1.3; // the link-knot crossing threshold τ
2982        let g_idx = 1usize;
2983        let g0 = 0.85_f64; // the slope value b (the g-primary IS the slope)
2984        // Stand-in intercept tower a(θ): nonzero value, gradient, Hessian in the
2985        // two live axes so a_u and a_uv are both exercised. (In production this
2986        // comes from implicit_solve; here we plant known derivatives.)
2987        let mut a = Tower4::<3>::constant(0.45);
2988        a.g[0] = 0.7;
2989        a.g[1] = -0.3;
2990        a.h[0][0] = 0.25;
2991        a.h[0][1] = 0.11;
2992        a.h[1][0] = 0.11;
2993        a.h[1][1] = -0.08;
2994
2995        // In the survival flex frame the slope `b` IS the g-primary directly
2996        // (the directional code passes `g` as `b`, and ∂z/∂g uses ∂b/∂g = 1):
2997        // z_edge = (τ − a) / b with b seeded as the g-axis variable.
2998        let b = Tower4::<3>::variable(g0, g_idx);
2999        let z_edge = (Tower4::<3>::constant(TAU) - a) / b;
3000
3001        let bv = g0;
3002        let z0 = z_edge.v;
3003        assert!((z0 - (TAU - 0.45) / bv).abs() < 1e-12);
3004
3005        // z_u = −(a_u + [u==g]·z) / b.
3006        for u in 0..2 {
3007            let direct = if u == g_idx { z0 } else { 0.0 };
3008            let want = -(a.g[u] + direct) / bv;
3009            assert!(
3010                (z_edge.g[u] - want).abs() < 1e-10,
3011                "z_u[{u}] {:+.8e} vs hand formula {:+.8e}",
3012                z_edge.g[u],
3013                want
3014            );
3015        }
3016        // z_uv = −(a_uv + [u==g]·z_v + [v==g]·z_u) / b, using the tower's own
3017        // first-order z_v/z_u (already verified above).
3018        for u in 0..2 {
3019            for v in 0..2 {
3020                let cross = if u == g_idx { z_edge.g[v] } else { 0.0 }
3021                    + if v == g_idx { z_edge.g[u] } else { 0.0 };
3022                let want = -(a.h[u][v] + cross) / bv;
3023                assert!(
3024                    (z_edge.h[u][v] - want).abs() < 1e-10,
3025                    "z_uv[{u}][{v}] {:+.8e} vs hand formula {:+.8e}",
3026                    z_edge.h[u][v],
3027                    want
3028                );
3029            }
3030        }
3031    }
3032
3033    /// The crossing-edge tower in the CONSTRAINT frame (intercept `a` and
3034    /// slope `b` BOTH independent — slots 0 and 1) reproduces taylor-jet's
3035    /// FD-certified bare boundary-velocity constants exactly:
3036    ///   z_a  = ∂z/∂a   = −1/b
3037    ///   z_ab = ∂²z/∂a∂b = +1/b²
3038    ///   z_aa = ∂²z/∂a²  = 0
3039    ///   z_bb = ∂²z/∂b²  = +2(τ−a)/b³
3040    /// These are the `f_a`/`f_au`/`f_aa` constraint-jet boundary motions the
3041    /// production base path drops (and only adds in the dir twins, causing the
3042    /// #932 desync). Here `a` is independent (NOT yet substituted with a(θ)),
3043    /// so `z_aa = 0` and there is no `a_uv` chain — `implicit_solve` introduces
3044    /// that later. Pins the constant before the constraint-tower wiring.
3045    #[test]
3046    fn crossing_edge_constraint_frame_matches_bare_velocity_constants() {
3047        const TAU: f64 = 1.3;
3048        let a0 = 0.45_f64;
3049        let b0 = 0.85_f64;
3050        // Slot 0 = a, slot 1 = b, both seeded independent.
3051        let a = Tower4::<2>::variable(a0, 0);
3052        let b = Tower4::<2>::variable(b0, 1);
3053        let z = (Tower4::<2>::constant(TAU) - a) / b;
3054
3055        assert!((z.v - (TAU - a0) / b0).abs() < 1e-12);
3056        assert!((z.g[0] - (-1.0 / b0)).abs() < 1e-12, "z_a {:+.10e}", z.g[0]);
3057        assert!(
3058            (z.h[0][1] - 1.0 / (b0 * b0)).abs() < 1e-12,
3059            "z_ab {:+.10e} vs +1/b² {:+.10e}",
3060            z.h[0][1],
3061            1.0 / (b0 * b0)
3062        );
3063        assert!(
3064            z.h[0][0].abs() < 1e-12,
3065            "z_aa must vanish, got {:+.10e}",
3066            z.h[0][0]
3067        );
3068        let want_zbb = 2.0 * (TAU - a0) / (b0 * b0 * b0);
3069        assert!(
3070            (z.h[1][1] - want_zbb).abs() < 1e-12,
3071            "z_bb {:+.10e} vs 2(τ−a)/b³ {:+.10e}",
3072            z.h[1][1],
3073            want_zbb
3074        );
3075    }
3076
3077    /// The oracle harness catches a planted #736-style sign flip in a
3078    /// cross block and reports the channel by name.
3079    #[test]
3080    fn oracle_catches_planted_cross_block_sign_flip() {
3081        let prog = LocScaleProgram {
3082            eta: vec![0.3],
3083            s: vec![-0.5],
3084            y: vec![1.0],
3085        };
3086        let t = program_full_tower(&prog, 0).expect("tower");
3087        let dir = [0.6, -0.2];
3088        let mut third = t.third_contracted(&dir);
3089        let honest = KernelChannels {
3090            value: t.v,
3091            gradient: t.g,
3092            hessian: t.h,
3093            third: vec![(dir, third)],
3094            fourth: vec![(dir, [1.0, 0.5], t.fourth_contracted(&dir, &[1.0, 0.5]))],
3095        };
3096        verify_kernel_channels(&t, &honest, 1e-10).expect("honest kernel must pass");
3097
3098        // Plant the #736 flip: negate one mixed cross entry.
3099        third[0][1] = -third[0][1];
3100        let flipped = KernelChannels {
3101            value: t.v,
3102            gradient: t.g,
3103            hessian: t.h,
3104            third: vec![(dir, third)],
3105            fourth: vec![],
3106        };
3107        let err = verify_kernel_channels(&t, &flipped, 1e-10)
3108            .expect_err("planted sign flip must be caught");
3109        assert!(
3110            err.contains("third[0][0][1]"),
3111            "oracle must name the flipped channel, got: {err}"
3112        );
3113    }
3114
3115    /// The third- and fourth-order tensors must be FULLY symmetric under
3116    /// index permutation (mixed partials commute). The tower stores them
3117    /// unsymmetrized, so equal-by-construction is a real invariant of the
3118    /// Leibniz/Faà di Bruno writes — a cheap typo tripwire. Asserted on a
3119    /// nontrivial K=3 tower with all of div/sqrt/powf/exp/ln exercised, so
3120    /// every composition path contributes. Lives in a test (not the hot
3121    /// per-op path) on purpose.
3122    #[test]
3123    fn t3_t4_are_fully_index_symmetric() {
3124        let prog = GnarlyProgram::fixture();
3125        // 3! = 6 permutations of three indices.
3126        let perms3: [[usize; 3]; 6] = [
3127            [0, 1, 2],
3128            [0, 2, 1],
3129            [1, 0, 2],
3130            [1, 2, 0],
3131            [2, 0, 1],
3132            [2, 1, 0],
3133        ];
3134        // 4! = 24 permutations of four indices.
3135        let perms4: [[usize; 4]; 24] = [
3136            [0, 1, 2, 3],
3137            [0, 1, 3, 2],
3138            [0, 2, 1, 3],
3139            [0, 2, 3, 1],
3140            [0, 3, 1, 2],
3141            [0, 3, 2, 1],
3142            [1, 0, 2, 3],
3143            [1, 0, 3, 2],
3144            [1, 2, 0, 3],
3145            [1, 2, 3, 0],
3146            [1, 3, 0, 2],
3147            [1, 3, 2, 0],
3148            [2, 0, 1, 3],
3149            [2, 0, 3, 1],
3150            [2, 1, 0, 3],
3151            [2, 1, 3, 0],
3152            [2, 3, 0, 1],
3153            [2, 3, 1, 0],
3154            [3, 0, 1, 2],
3155            [3, 0, 2, 1],
3156            [3, 1, 0, 2],
3157            [3, 1, 2, 0],
3158            [3, 2, 0, 1],
3159            [3, 2, 1, 0],
3160        ];
3161        for row in 0..prog.n_rows() {
3162            let t = program_full_tower(&prog, row).expect("gnarly tower");
3163            let scale_t3 =
3164                t.t3.iter()
3165                    .flatten()
3166                    .flatten()
3167                    .fold(0.0_f64, |m, x| m.max(x.abs()))
3168                    .max(1.0);
3169            let scale_t4 =
3170                t.t4.iter()
3171                    .flatten()
3172                    .flatten()
3173                    .flatten()
3174                    .fold(0.0_f64, |m, x| m.max(x.abs()))
3175                    .max(1.0);
3176            for i in 0..3 {
3177                for j in 0..3 {
3178                    for k in 0..3 {
3179                        let base = t.t3[i][j][k];
3180                        let idx = [i, j, k];
3181                        for p in &perms3 {
3182                            let permed = t.t3[idx[p[0]]][idx[p[1]]][idx[p[2]]];
3183                            assert!(
3184                                (base - permed).abs() <= 1e-12 * scale_t3,
3185                                "row {row}: t3[{i}][{j}][{k}]={base:+.15e} != \
3186                                 permuted {permed:+.15e} under {p:?}"
3187                            );
3188                        }
3189                        for l in 0..3 {
3190                            let base4 = t.t4[i][j][k][l];
3191                            let idx4 = [i, j, k, l];
3192                            for p in &perms4 {
3193                                let permed = t.t4[idx4[p[0]]][idx4[p[1]]][idx4[p[2]]][idx4[p[3]]];
3194                                assert!(
3195                                    (base4 - permed).abs() <= 1e-12 * scale_t4,
3196                                    "row {row}: t4[{i}][{j}][{k}][{l}]={base4:+.15e} != \
3197                                     permuted {permed:+.15e} under {p:?}"
3198                                );
3199                            }
3200                        }
3201                    }
3202                }
3203            }
3204        }
3205    }
3206}
3207
3208/// Stable derivative stack for `log Phi(x)` through fourth order.
3209#[inline]
3210pub fn unary_derivatives_normal_logcdf(x: f64) -> [f64; 5] {
3211    crate::probability::normal_logcdf_derivatives(x)
3212}
3213
3214/// Stable derivative stack for `log(1 - exp(-x))`, `x > 0`, through fourth order.
3215#[inline]
3216pub fn unary_derivatives_log1mexp_positive(x: f64) -> [f64; 5] {
3217    let r = 1.0 / x.exp_m1();
3218    [
3219        crate::probability::log1mexp_positive(x),
3220        r,
3221        -r * (1.0 + r),
3222        r * (1.0 + r) * (1.0 + 2.0 * r),
3223        -r * (1.0 + r) * (1.0 + 6.0 * r + 6.0 * r * r),
3224    ]
3225}
3226#[cfg(test)]
3227mod derivative_stack_tests {
3228    use super::*;
3229    // ── ln_gamma_derivative_stack / digamma_derivative_stack / trigamma_derivative_stack ──
3230
3231    #[test]
3232    fn ln_gamma_derivative_stack_known_values_at_1() {
3233        let s = ln_gamma_derivative_stack(1.0);
3234        // ln Γ(1) = 0; statrs uses Lanczos so the result is within ULP noise
3235        assert!(s[0].abs() < 1e-14, "ln_gamma(1) must be ~0, got {}", s[0]);
3236        // ψ₀(1) = -γ  (Euler–Mascheroni)
3237        let euler_mascheroni = 0.577_215_664_901_532_9_f64;
3238        assert!(
3239            (s[1] + euler_mascheroni).abs() < 1e-10,
3240            "digamma(1) ≈ -{euler_mascheroni:.6}, got {}",
3241            s[1]
3242        );
3243        // ψ₁(1) = π²/6
3244        let pi2_6 = std::f64::consts::PI * std::f64::consts::PI / 6.0;
3245        assert!(
3246            (s[2] - pi2_6).abs() < 1e-10,
3247            "trigamma(1) ≈ {pi2_6:.6}, got {}",
3248            s[2]
3249        );
3250    }
3251
3252    #[test]
3253    fn ln_gamma_derivative_stack_known_values_at_2() {
3254        let s = ln_gamma_derivative_stack(2.0);
3255        // ln Γ(2) = ln(1) = 0 exactly
3256        assert!(s[0].abs() < 1e-14, "ln_gamma(2) must be 0, got {}", s[0]);
3257        // ψ₀(2) = 1 − γ (recurrence: ψ₀(x+1) = ψ₀(x) + 1/x)
3258        let euler_mascheroni = 0.577_215_664_901_532_9_f64;
3259        let digamma_2 = 1.0 - euler_mascheroni;
3260        assert!(
3261            (s[1] - digamma_2).abs() < 1e-10,
3262            "digamma(2) ≈ {digamma_2:.6}, got {}",
3263            s[1]
3264        );
3265    }
3266
3267    #[test]
3268    fn ln_gamma_derivative_stack_order2_is_prefix() {
3269        for &x in &[0.5_f64, 1.0, 2.0, 5.0] {
3270            let full = ln_gamma_derivative_stack(x);
3271            let ord2 = ln_gamma_derivative_stack_order2(x);
3272            assert_eq!(ord2[0], full[0], "order2[0] != full[0] at x={x}");
3273            assert_eq!(ord2[1], full[1], "order2[1] != full[1] at x={x}");
3274            assert_eq!(ord2[2], full[2], "order2[2] != full[2] at x={x}");
3275        }
3276    }
3277
3278    #[test]
3279    fn digamma_derivative_stack_overlaps_ln_gamma_stack() {
3280        // The two stacks share a run of four polygamma values:
3281        // ln_gamma_stack[1..5] == digamma_stack[0..4]
3282        for &x in &[0.5_f64, 1.0, 2.0, 7.0] {
3283            let lg = ln_gamma_derivative_stack(x);
3284            let dg = digamma_derivative_stack(x);
3285            for i in 0..4 {
3286                assert_eq!(
3287                    lg[i + 1],
3288                    dg[i],
3289                    "ln_gamma_stack[{}] != digamma_stack[{}] at x={x}",
3290                    i + 1,
3291                    i
3292                );
3293            }
3294        }
3295    }
3296
3297    #[test]
3298    fn trigamma_derivative_stack_overlaps_digamma_stack() {
3299        // digamma_stack[1..5] == trigamma_stack[0..4]
3300        for &x in &[0.5_f64, 1.0, 2.0, 7.0] {
3301            let dg = digamma_derivative_stack(x);
3302            let tg = trigamma_derivative_stack(x);
3303            for i in 0..4 {
3304                assert_eq!(
3305                    dg[i + 1],
3306                    tg[i],
3307                    "digamma_stack[{}] != trigamma_stack[{}] at x={x}",
3308                    i + 1,
3309                    i
3310                );
3311            }
3312        }
3313    }
3314
3315    #[test]
3316    fn derivative_stacks_all_finite_at_positive_inputs() {
3317        for &x in &[0.01_f64, 0.5, 1.0, 2.0, 10.0, 100.0] {
3318            for v in ln_gamma_derivative_stack(x) {
3319                assert!(v.is_finite(), "ln_gamma_stack non-finite at x={x}: {v}");
3320            }
3321            for v in digamma_derivative_stack(x) {
3322                assert!(v.is_finite(), "digamma_stack non-finite at x={x}: {v}");
3323            }
3324            for v in trigamma_derivative_stack(x) {
3325                assert!(v.is_finite(), "trigamma_stack non-finite at x={x}: {v}");
3326            }
3327        }
3328    }
3329}
3330
3331// ── Contraction-symmetry optimization gate ────────────────────────────────────
3332//
3333// `Tower4::third_contracted` / `fourth_contracted` contract the (fully
3334// index-symmetric) `t3`/`t4` tensors against directions, leaving the output
3335// indices `(a, b)` / `(i, j)` free. Those free indices inherit the tensor's
3336// symmetry — `out[a][b] == out[b][a]` term-for-term — so only the upper triangle
3337// need be summed and the lower triangle mirrored. Unlike the dense symmetric
3338// FILL (which needs a K⁴ scatter and loses inner-loop vectorisation, and was
3339// measured SLOWER), the mirror here is a tiny K×K copy and the inner contraction
3340// is untouched (contiguous, vectorisable). This is BIT-IDENTICAL to the full
3341// nest, so it needs no fingerprint re-baseline; the gate is (1) bit-identity vs
3342// the full reference and (2) a measured wall-clock that is not slower.
3343#[cfg(test)]
3344mod contraction_symmetry_tests {
3345    use super::*;
3346
3347    struct Rng(u64);
3348    impl Rng {
3349        fn u(&mut self) -> f64 {
3350            self.0 = self
3351                .0
3352                .wrapping_mul(6364136223846793005)
3353                .wrapping_add(1442695040888963407);
3354            (self.0 >> 11) as f64 / (1u64 << 53) as f64
3355        }
3356        fn s(&mut self) -> f64 {
3357            (self.u() - 0.5) * 4.0
3358        }
3359    }
3360
3361    /// Random VALID fully-symmetric `Tower4<K>` (symmetric `h`/`t3`/`t4`).
3362    fn rand_sym4<const K: usize>(r: &mut Rng) -> Tower4<K> {
3363        let mut t = Tower4::<K>::zero();
3364        t.v = r.s();
3365        for i in 0..K {
3366            t.g[i] = r.s();
3367        }
3368        for a in 0..K {
3369            for b in a..K {
3370                let v2 = r.s();
3371                t.h[a][b] = v2;
3372                t.h[b][a] = v2;
3373                for c in b..K {
3374                    let v3 = r.s();
3375                    for p in perms3([a, b, c]) {
3376                        t.t3[p[0]][p[1]][p[2]] = v3;
3377                    }
3378                    for d in c..K {
3379                        let v4 = r.s();
3380                        for p in perms4([a, b, c, d]) {
3381                            t.t4[p[0]][p[1]][p[2]][p[3]] = v4;
3382                        }
3383                    }
3384                }
3385            }
3386        }
3387        t
3388    }
3389
3390    fn perms3(idx: [usize; 3]) -> [[usize; 3]; 6] {
3391        let [a, b, c] = idx;
3392        [
3393            [a, b, c],
3394            [a, c, b],
3395            [b, a, c],
3396            [b, c, a],
3397            [c, a, b],
3398            [c, b, a],
3399        ]
3400    }
3401    fn perms4(idx: [usize; 4]) -> [[usize; 4]; 24] {
3402        let [a, b, c, d] = idx;
3403        [
3404            [a, b, c, d],
3405            [a, b, d, c],
3406            [a, c, b, d],
3407            [a, c, d, b],
3408            [a, d, b, c],
3409            [a, d, c, b],
3410            [b, a, c, d],
3411            [b, a, d, c],
3412            [b, c, a, d],
3413            [b, c, d, a],
3414            [b, d, a, c],
3415            [b, d, c, a],
3416            [c, a, b, d],
3417            [c, a, d, b],
3418            [c, b, a, d],
3419            [c, b, d, a],
3420            [c, d, a, b],
3421            [c, d, b, a],
3422            [d, a, b, c],
3423            [d, a, c, b],
3424            [d, b, a, c],
3425            [d, b, c, a],
3426            [d, c, a, b],
3427            [d, c, b, a],
3428        ]
3429    }
3430
3431    /// Full-nest reference (the pre-opt `a, b ∈ 0..K` form).
3432    fn third_full<const K: usize>(t: &Tower4<K>, dir: &[f64; K]) -> [[f64; K]; K] {
3433        let mut out = [[0.0; K]; K];
3434        for a in 0..K {
3435            for b in 0..K {
3436                let mut acc = 0.0;
3437                for c in 0..K {
3438                    acc += t.t3[a][b][c] * dir[c];
3439                }
3440                out[a][b] = acc;
3441            }
3442        }
3443        out
3444    }
3445    fn fourth_full<const K: usize>(t: &Tower4<K>, u: &[f64; K], w: &[f64; K]) -> [[f64; K]; K] {
3446        let mut out = [[0.0; K]; K];
3447        for i in 0..K {
3448            for j in 0..K {
3449                let mut acc = 0.0;
3450                for k in 0..K {
3451                    for l in 0..K {
3452                        acc += t.t4[i][j][k][l] * u[k] * w[l];
3453                    }
3454                }
3455                out[i][j] = acc;
3456            }
3457        }
3458        out
3459    }
3460
3461    /// Returns the number of bit-equality comparisons performed (`n·K·K·2`), so
3462    /// the caller can assert the intended workload actually ran: a generic
3463    /// (turbofish) helper call hides its internal assertions, so the count is
3464    /// surfaced and checked at the call site.
3465    fn check_bit_identical<const K: usize>(seed: u64, n: usize) -> usize {
3466        let mut r = Rng(seed);
3467        let mut checks = 0usize;
3468        for _ in 0..n {
3469            let t = rand_sym4::<K>(&mut r);
3470            let dir: [f64; K] = std::array::from_fn(|_| r.s());
3471            let u: [f64; K] = std::array::from_fn(|_| r.s());
3472            let w: [f64; K] = std::array::from_fn(|_| r.s());
3473            let t3_sym = t.third_contracted(&dir);
3474            let t3_full = third_full(&t, &dir);
3475            let t4_sym = t.fourth_contracted(&u, &w);
3476            let t4_full = fourth_full(&t, &u, &w);
3477            for a in 0..K {
3478                for b in 0..K {
3479                    assert_eq!(
3480                        t3_sym[a][b].to_bits(),
3481                        t3_full[a][b].to_bits(),
3482                        "third K={K} [{a}][{b}]"
3483                    );
3484                    assert_eq!(
3485                        t4_sym[a][b].to_bits(),
3486                        t4_full[a][b].to_bits(),
3487                        "fourth K={K} [{a}][{b}]"
3488                    );
3489                    checks += 2;
3490                }
3491            }
3492        }
3493        checks
3494    }
3495
3496    /// The output-symmetric contraction is BIT-IDENTICAL to the full nest across
3497    /// `K ∈ {2,3,4,9}` (so no fingerprint re-baseline is owed — accuracy and bits
3498    /// are unchanged; this is a pure speed-only optimization).
3499    #[test]
3500    fn contraction_symmetry_is_bit_identical_to_full_nest() {
3501        let checks = check_bit_identical::<2>(0x0000_0002_C0FF_EE01, 1000)
3502            + check_bit_identical::<3>(0x0000_0003_C0FF_EE01, 800)
3503            + check_bit_identical::<4>(0x0000_0004_C0FF_EE01, 600)
3504            + check_bit_identical::<9>(0x0000_0009_C0FF_EE01, 300);
3505        // Guards against the loops silently not running (e.g. a zeroed count):
3506        // 1000·2²·2 + 800·3²·2 + 600·4²·2 + 300·9²·2.
3507        assert_eq!(checks, 8000 + 14400 + 19200 + 48600);
3508    }
3509
3510    /// Measure the wall-clock of the output-symmetric contraction vs the full
3511    /// nest at `K = 9` (it does ~2× fewer inner contractions; the bit-identity
3512    /// test is the correctness gate). Informational — wall-clock is noisy — with
3513    /// only a PATHOLOGICAL-regression guard (the symmetric form does strictly
3514    /// fewer inner contractions, so it must not be materially slower).
3515    #[test]
3516    fn contraction_symmetry_speedup_is_reported() {
3517        const K: usize = 9;
3518        let mut r = Rng(0xC0FF_EE99_1234_5678);
3519        let towers: Vec<Tower4<K>> = (0..512).map(|_| rand_sym4::<K>(&mut r)).collect();
3520        let dir: [f64; K] = std::array::from_fn(|_| r.s());
3521        let u: [f64; K] = std::array::from_fn(|_| r.s());
3522        let w: [f64; K] = std::array::from_fn(|_| r.s());
3523
3524        let reps = 400usize;
3525        let t_sym = {
3526            let start = std::time::Instant::now();
3527            let mut sink = 0.0f64;
3528            for _ in 0..reps {
3529                for t in &towers {
3530                    let o3 = std::hint::black_box(t).third_contracted(std::hint::black_box(&dir));
3531                    let o4 = std::hint::black_box(t)
3532                        .fourth_contracted(std::hint::black_box(&u), std::hint::black_box(&w));
3533                    sink += o3[0][K - 1] + o4[0][K - 1];
3534                }
3535            }
3536            std::hint::black_box(sink);
3537            start.elapsed().as_secs_f64()
3538        };
3539        let t_full = {
3540            let start = std::time::Instant::now();
3541            let mut sink = 0.0f64;
3542            for _ in 0..reps {
3543                for t in &towers {
3544                    let o3 = third_full(std::hint::black_box(t), std::hint::black_box(&dir));
3545                    let o4 = fourth_full(
3546                        std::hint::black_box(t),
3547                        std::hint::black_box(&u),
3548                        std::hint::black_box(&w),
3549                    );
3550                    sink += o3[0][K - 1] + o4[0][K - 1];
3551                }
3552            }
3553            std::hint::black_box(sink);
3554            start.elapsed().as_secs_f64()
3555        };
3556        let calls = (reps * towers.len()) as f64;
3557        eprintln!(
3558            "[contraction-symmetry speedup K=9] sym={:.1}ns/call full={:.1}ns/call \
3559             wall_speedup={:.2}x",
3560            t_sym / calls * 1e9,
3561            t_full / calls * 1e9,
3562            t_full / t_sym
3563        );
3564        assert!(
3565            t_sym <= t_full * 1.5,
3566            "output-symmetric contraction pathologically slower: \
3567             sym={t_sym:.4}s full={t_full:.4}s"
3568        );
3569    }
3570}