Skip to main content

gam_models/bms/
block_specs.rs

1use super::family::*;
2use super::gradient_paths::*;
3use super::hessian_paths::{new_cell_moment_cache_stats, new_cell_moment_lru_cache};
4use super::install_flex::validate_spec;
5use super::*;
6use crate::marginal_slope_orthogonal::influence_absorber_log_lambda;
7use faer::Side;
8use gam_linalg::faer_ndarray::{FaerEigh, fast_ab, fast_atb, fast_xt_diag_x};
9
10/// Sup-norm of the FITTED marginal linear predictor `η = X·β` at which the
11/// probit model becomes numerically degenerate. This is the decisive
12/// separation quantity — raw coefficient magnitude is NOT, because the
13/// thin-plate / Duchon marginal bases are non-orthonormal and ill-conditioned,
14/// so a smooth, bounded fitted surface can carry large-and-cancelling
15/// coefficients (e.g. `β=[60,-60]` on two collinear columns yields a bounded
16/// `Xβ`). The probit information `φ(η)²/[Φ(η)(1−Φ(η))]` only collapses once
17/// `|η|` is enormous: `Φ(−35) ≈ 1e−268` is still representable, but by `|η|≈38`
18/// the tail probability underflows to exactly 0 in `f64` and the per-row
19/// Fisher weight vanishes. We trip the guard at 35 — comfortably inside the
20/// representable range yet far beyond any legitimately fitted predictor (a
21/// converged penalized probit surface keeps `|η|` at single/low-double digits),
22/// so a true separating direction (whose `|η|→∞`) still trips it while a
23/// well-fitted ill-conditioned surface does not.
24pub(crate) const BMS_PROBIT_SEPARATION_ETA_INF: f64 = 35.0;
25
26// ── Canonical-gauge priority ladder (issue #322) ─────────────────────────────
27//
28// The priority-ordered RRQR in `canonicalize_for_identifiability` presents
29// higher-priority blocks first and routes any shared cross-block alias drop
30// into the lowest-priority block that still spans the aliased direction. The
31// values below form a single ordered ladder so the relationships that the
32// architecture depends on (anchors > parametric surfaces > flex deviations,
33// marginal > logslope, score_warp > link_dev) are expressed once here rather
34// than re-derived from comments at each `gauge_priority:` site. The ladder
35// mirrors the survival marginal-slope entry (time=200 / marginal=150 /
36// logslope=120 / score_warp=80 / link_dev=60).
37
38/// Audit-only anchor blocks sit at the top of the ladder so the candidate
39/// flex block always yields to them in the cross-block identifiability audit.
40pub(super) const GAUGE_PRIORITY_ANCHOR: u8 = 200;
41/// Marginal surface: strictly above the logslope surface so a shared affine
42/// direction is demoted out of logslope, never out of marginal.
43pub(super) const GAUGE_PRIORITY_MARGINAL: u8 = 150;
44/// Logslope surface: one rung below the marginal surface.
45pub(super) const GAUGE_PRIORITY_LOGSLOPE: u8 = 120;
46/// Candidate flex block under audit: below every parametric anchor so the
47/// audit demotes the candidate when it aliases an anchor.
48pub(super) const GAUGE_PRIORITY_CANDIDATE_FLEX: u8 = 100;
49/// `score_warp_dev`: above `link_dev` because in mixed-flex configurations
50/// link_dev is the residualised block and should yield first.
51pub(super) const GAUGE_PRIORITY_SCORE_WARP_DEV: u8 = 80;
52/// Default for any deviation auxiliary block not otherwise named; below the
53/// parametric default so shared affine directions never demote a parametric
54/// block.
55pub(super) const GAUGE_PRIORITY_DEVIATION_DEFAULT: u8 = 70;
56/// `link_dev`: lowest rung, yields first among the flex deviation blocks.
57pub(super) const GAUGE_PRIORITY_LINK_DEV: u8 = 60;
58
59/// Floor on the relative outer tolerance used by the exact-joint spatial
60/// length-scale optimiser. The user's `rel_tol` drives most of the fit, but
61/// the exact spatial outer loop is a coarse 1-D search over a smooth profiled
62/// objective; tightening it below this floor only burns cycles on noise in the
63/// inner-solve-reported objective without moving the selected length scale.
64pub(crate) const EXACT_SPATIAL_OUTER_TOL_FLOOR: f64 = 1e-6;
65
66// ── BlockEffectiveJacobian impls for BMS ─────────────────────────────────────
67//
68// BMS has a single Bernoulli output per row (n_outputs = 1). The observed η is
69//
70//   η_i = q_i · c_i + s·g_i · z_i
71//
72// where
73//   q_i   = marginal_design[i,:] · β_m + offset_m[i]      (marginal η)
74//   g_i   = logslope_design[i,:] · β_s + offset_s[i]      (log-slope η)
75//   s     = probit_frailty_scale(gaussian_frailty_sd)
76//   c_i   = sqrt(1 + (s·g_i)²)
77//
78// Per-block Jacobians ∂η_i / ∂β_block:
79//
80//   Marginal block  → ∂η_i/∂β_m = c_i · M_i
81//     (M_i = marginal_design row i; c_i is β-dependent but does not involve β_m)
82//
83//   Logslope block  → ∂η_i/∂β_s = (q_i · s²·g_i / c_i + s·z_i) · G_i
84//     (G_i = logslope_design row i)
85//
86// score_warp_dev and link_dev blocks use IFT-corrected η, but their
87// contribution to the identifiability audit is captured by the raw design
88// columns (the IFT correction adds a direction already in the anchor span at
89// compile time). These blocks leave jacobian_callback = None and rely on
90// effective_design (= raw design) for the flat audit.
91
92/// β-dependent Jacobian for the BMS marginal block.
93///
94/// ∂η_i/∂β_m = c_i · M[i,:]
95/// where c_i = sqrt(1 + (s · g_i)²),
96///       g_i = G[i,:] · β_s + offset_s[i],
97///       s   = state.probit_frailty_scale.
98///
99/// `probit_frailty_scale` is read from the evaluation state at call time (not
100/// captured at construction) so the callback remains correct across outer-loop
101/// σ updates without rebuilding the block spec.
102///
103/// Designs are pre-densified at construction to avoid repeated materialisation.
104pub struct BmsMarginalJacobian {
105    /// Dense marginal design: n × p_m.
106    pub marginal_dense: Arc<Array2<f64>>,
107    /// Dense logslope design: n × p_s.
108    pub logslope_dense: Arc<Array2<f64>>,
109    pub offset_m: Array1<f64>,
110    pub offset_s: Array1<f64>,
111    /// Number of marginal columns (= size of β_m slice in the full β vector).
112    pub p_marginal: usize,
113}
114
115impl BmsMarginalJacobian {
116    pub fn new(
117        marginal_dense: Arc<Array2<f64>>,
118        logslope_dense: Arc<Array2<f64>>,
119        offset_m: Array1<f64>,
120        offset_s: Array1<f64>,
121        p_marginal: usize,
122    ) -> Self {
123        Self {
124            marginal_dense,
125            logslope_dense,
126            offset_m,
127            offset_s,
128            p_marginal,
129        }
130    }
131}
132
133impl BlockEffectiveJacobian for BmsMarginalJacobian {
134    fn effective_jacobian_rows(
135        &self,
136        state: &FamilyLinearizationState<'_>,
137        rows: std::ops::Range<usize>,
138    ) -> Result<Array2<f64>, String> {
139        let beta = state.beta;
140        let s = state.probit_frailty_scale;
141        let p_m = self.p_marginal;
142        let p_s_block = self.logslope_dense.ncols();
143        let beta_s_raw = if beta.len() > p_m {
144            &beta[p_m..]
145        } else {
146            &[][..]
147        };
148        let p_s_use = p_s_block.min(beta_s_raw.len());
149        let beta_s = &beta_s_raw[..p_s_use];
150        let n = self.marginal_dense.nrows();
151        let rows = rows.start.min(n)..rows.end.min(n);
152        let p_block = self.marginal_dense.ncols();
153
154        // ∂η_i/∂β_m = c_i · M[i,:], with c_i = sqrt(1 + (s·g_i)²) and
155        //   g_i = G[i, :p_s_use] · β_s + offset_s[i].
156        //
157        // This block owns the logslope design and offset, so g_i — and hence
158        // c_i — is fully self-computable at the current β for every row,
159        // including β = 0 (where g_i = offset_s[i], which carries the fitted
160        // logslope baseline and is generically nonzero).  There is no external
161        // scalar this block cannot reconstruct, so the Jacobian is evaluated
162        // directly from owned data with no caller-supplied contract.
163        let mut out = Array2::<f64>::zeros((rows.end - rows.start, p_block));
164        for i in rows.clone() {
165            let g_i = self.offset_s[i]
166                + self
167                    .logslope_dense
168                    .row(i)
169                    .slice(ndarray::s![..p_s_use])
170                    .dot(&ArrayView1::from(beta_s));
171            let sg = s * g_i;
172            let c_i = (1.0 + sg * sg).sqrt();
173            // J[i,:] = c_i · M[i,:]
174            let m_row = self.marginal_dense.row(i);
175            out.row_mut(i - rows.start).assign(&m_row.mapv(|x| c_i * x));
176        }
177        Ok(out)
178    }
179
180    fn n_outputs(&self) -> usize {
181        1
182    }
183
184    fn locks_raw_width_reduction(&self) -> bool {
185        // The BMS family reads its raw-width internal `marginal_design` and
186        // `validate_exact_block_state_shapes` asserts `beta.len() ==
187        // marginal_design.ncols()`. The block's spec carries the real (non
188        // zero-placeholder) marginal design, so the `#933` gauge-composed
189        // reduction cannot silently absorb a dropped column into the callback —
190        // a reduced β would desynchronise the raw-width layout the family reads.
191        // Keep it at raw width and let the robust Jeffreys curvature regularise
192        // any weak cross-block direction (mirrors the survival marginal-slope
193        // time-wiggle block).
194        true
195    }
196}
197
198/// β-dependent Jacobian for the BMS logslope block.
199///
200/// ∂η_i/∂β_s = (q_i · s²·g_i / c_i + s·z_i) · G[i,:]
201/// where q_i = M[i,:] · β_m + offset_m[i],
202///       g_i = G[i,:] · β_s + offset_s[i],
203///       c_i = sqrt(1 + (s·g_i)²),
204///       s   = state.probit_frailty_scale.
205///
206/// `probit_frailty_scale` is read from the evaluation state at call time.
207///
208/// Designs are pre-densified at construction to avoid repeated materialisation.
209pub struct BmsLogslopeJacobian {
210    /// Dense marginal design: n × p_m.
211    pub marginal_dense: Arc<Array2<f64>>,
212    /// Dense logslope design: n × p_s.
213    pub logslope_dense: Arc<Array2<f64>>,
214    pub offset_m: Array1<f64>,
215    pub offset_s: Array1<f64>,
216    pub z: Arc<Array1<f64>>,
217    /// Number of marginal columns (= start of β_s in the full β vector).
218    pub p_marginal: usize,
219}
220
221impl BmsLogslopeJacobian {
222    pub fn new(
223        marginal_dense: Arc<Array2<f64>>,
224        logslope_dense: Arc<Array2<f64>>,
225        offset_m: Array1<f64>,
226        offset_s: Array1<f64>,
227        z: Arc<Array1<f64>>,
228        p_marginal: usize,
229    ) -> Self {
230        Self {
231            marginal_dense,
232            logslope_dense,
233            offset_m,
234            offset_s,
235            z,
236            p_marginal,
237        }
238    }
239}
240
241impl BlockEffectiveJacobian for BmsLogslopeJacobian {
242    fn effective_jacobian_rows(
243        &self,
244        state: &FamilyLinearizationState<'_>,
245        rows: std::ops::Range<usize>,
246    ) -> Result<Array2<f64>, String> {
247        let beta = state.beta;
248        let s = state.probit_frailty_scale;
249        let p_m = self.p_marginal;
250        let p_m_use = p_m.min(beta.len());
251        let beta_m = &beta[..p_m_use];
252        let beta_s_raw = if beta.len() > p_m {
253            &beta[p_m..]
254        } else {
255            &[][..]
256        };
257        let p_s_block = self.logslope_dense.ncols();
258        let p_s_use = p_s_block.min(beta_s_raw.len());
259        let beta_s = &beta_s_raw[..p_s_use];
260        let n = self.logslope_dense.nrows();
261        let rows = rows.start.min(n)..rows.end.min(n);
262
263        // ∂η_i/∂β_s = (q_i · s²·g_i / c_i + s·z_i) · G[i,:] where
264        //   q_i = M[i,:] · β_m + offset_m[i],
265        //   g_i = G[i,:] · β_s + offset_s[i],
266        //   c_i = sqrt(1 + (s·g_i)²),
267        //   z_i = self.z[i].
268        //
269        // This block owns the marginal design, logslope design, both offsets,
270        // and z, so q_i, g_i, c_i, z_i are all closed-form functions of the
271        // current β and owned data — for every row at every β, including β = 0
272        // (where g_i = offset_s[i] carries the nonzero fitted logslope
273        // baseline).  The Jacobian is therefore evaluated directly from owned
274        // data with no caller-supplied scalar contract.
275        let mut out = Array2::<f64>::zeros((rows.end - rows.start, p_s_block));
276        for i in rows.clone() {
277            let q_i = self.offset_m[i]
278                + self
279                    .marginal_dense
280                    .row(i)
281                    .slice(ndarray::s![..p_m_use])
282                    .dot(&ArrayView1::from(beta_m));
283            let g_i = self.offset_s[i]
284                + self
285                    .logslope_dense
286                    .row(i)
287                    .slice(ndarray::s![..p_s_use])
288                    .dot(&ArrayView1::from(beta_s));
289            let sg = s * g_i;
290            let c_i = (1.0 + sg * sg).sqrt();
291            let z_i = self.z[i];
292            // per-row scalar factor: q_i · s²·g_i / c_i + s·z_i
293            let factor = q_i * s * s * g_i / c_i + s * z_i;
294            // J[i,:] = factor · G[i,:]
295            let g_row = self.logslope_dense.row(i);
296            out.row_mut(i - rows.start)
297                .assign(&g_row.mapv(|x| factor * x));
298        }
299        Ok(out)
300    }
301
302    fn n_outputs(&self) -> usize {
303        1
304    }
305
306    fn locks_raw_width_reduction(&self) -> bool {
307        // The BMS family reads its raw-width internal `logslope_design` and
308        // `validate_exact_block_state_shapes` asserts `beta.len() ==
309        // logslope_design.ncols()`. An intercept-only logslope (`logslope_formula
310        // = "1"`) is a constant column perfectly aliased with the marginal
311        // intercept; the effective reduced-reparam leaves a width-1 block at raw
312        // width (a zero-width reduction would delete the score-effect surface), so
313        // the canonicaliser would otherwise column-reduce this block to width 0
314        // and hand the family a length-0 β against a width-1 design. Lock it to
315        // raw width — the robust Jeffreys curvature regularises the weak aliased
316        // direction (mirrors the survival marginal-slope time-wiggle block).
317        true
318    }
319}
320
321/// Horizontally stack the absorbed influence columns `Z̃_infl` onto the raw
322/// marginal design `M`, yielding the widened additive marginal-index design
323/// `[M | Z̃_infl]` (#461). When `influence_columns` is `None` the original
324/// dense design is returned unchanged. The influence columns shift the marginal
325/// index `α(x)` additively, so the de-nested probit kernel — which reads the
326/// marginal index from `block_states[0].eta` and reconstructs `∂q/∂β_m` from
327/// `self.marginal_design` (a matched (design, β) pair) — picks them up with no
328/// kernel-site change; the widened `p_marginal` keeps every per-row Jacobian /
329/// gradient / Hessian projection consistent.
330pub(crate) fn widen_marginal_dense_with_influence(
331    marginal_dense: &Arc<Array2<f64>>,
332    influence_columns: Option<&Array2<f64>>,
333) -> Result<Arc<Array2<f64>>, String> {
334    let Some(z_infl) = influence_columns else {
335        return Ok(Arc::clone(marginal_dense));
336    };
337    let n = marginal_dense.nrows();
338    if z_infl.nrows() != n {
339        return Err(format!(
340            "influence block: residualised columns have {} rows, marginal design has {n}",
341            z_infl.nrows()
342        ));
343    }
344    let p_m = marginal_dense.ncols();
345    let p1 = z_infl.ncols();
346    let mut widened = Array2::<f64>::zeros((n, p_m + p1));
347    widened
348        .slice_mut(s![.., ..p_m])
349        .assign(marginal_dense.as_ref());
350    widened.slice_mut(s![.., p_m..]).assign(z_infl);
351    Ok(Arc::new(widened))
352}
353
354/// Tolerance (relative to the dominant retained eigenvalue) below which a
355/// reduced-basis direction of the W-orthogonalised effective logslope Gram is
356/// treated as a confounded null direction and dropped. Directions whose
357/// effective weighted image is (near-)explained by the marginal span collapse to
358/// ~0 eigenvalue in `Gtt` (see [`build_reduced_logslope_reparam`]); this keeps
359/// the cut well above floating-point noise but well below any genuine surviving
360/// logslope curvature.
361pub(crate) const LOGSLOPE_REDUCED_BASIS_RELATIVE_TOL: f64 = 1.0e-6;
362
363/// An exact reduced-basis reparameterization of the BMS logslope design through
364/// the family's OWN internal `logslope_design` geometry, expressed as a single
365/// linear map `T` (`p_logslope × r`, `r ≤ p_logslope`).
366///
367/// # Why a reduced basis (not a dense design swap)
368///
369/// The structural confound is that the score-weighted logslope channel
370/// `diag(factor)·G·β_s` overlaps the effective marginal channel `diag(c)·M·β_m`
371/// in the PIRLS row metric `W`, leaving the joint penalised Hessian rank-soft
372/// along the shared direction. The shared-solver primitive
373/// [`OrthogonalReparam`](gam_solve::orthogonal_reparam::OrthogonalReparam)
374/// forms `C̃ = C − M·B`, exactly W-orthogonal to `span(M)` — but `C̃` is a dense
375/// design the BMS family's row kernel does NOT consume: the family reads
376/// `η_logslope = G·β_s` from its own `logslope_design` and reconstructs the
377/// per-row Jacobian `factor_i · G_i` from that same matrix. A block-level design
378/// swap is therefore ignored by the family, and feeding a rank-deficient `C̃` at
379/// full width desynchronises the inner identifiable-subspace reduction from the
380/// stored design width.
381///
382/// This builds instead a TRUE reparameterization the family consumes: a
383/// full-rank reduced logslope design `G_reduced = G·T` (width `r`) plus the
384/// penalty projection `S_reduced = Tᵀ S T`. The map is constructed so that the
385/// directions of raw logslope coefficient space whose effective weighted image
386/// is W-explained by the marginal span are removed (they carry ~zero curvature
387/// in the W-orthogonalised effective Gram), and the surviving `r` directions are
388/// full-rank.
389///
390/// # The math
391///
392/// At the rigid pilot, the effective Jacobians are
393///
394/// ```text
395///     M_eff = diag(c) · M        (n × p_m),   c_i = sqrt(1 + (s·g_i)²)
396///     G_eff = diag(f) · G        (n × p_g),   f_i = q_i·s²·g_i/c_i + s·z_i
397/// ```
398///
399/// In the row metric `W` the component of the effective logslope design that is
400/// W-orthogonal to `span(M_eff)` has the raw-coordinate Gram
401///
402/// ```text
403///     Gtt = G_effᵀ W G_eff − (G_effᵀ W M_eff)(M_effᵀ W M_eff + εI)⁻¹(M_effᵀ W G_eff)
404/// ```
405///
406/// (a `p_g × p_g` PSD matrix in the raw logslope coefficient coordinates). Its
407/// range = the logslope directions that survive the confound removal; its null
408/// space = the confounded directions absorbed by the marginal span. The reduced
409/// transform `T` is the orthonormal eigenbasis of `Gtt` for eigenvalues above a
410/// relative tolerance; `r = rank(Gtt)`. The new design `G_reduced = G·T`, the
411/// reparameterized penalty `S_reduced = Tᵀ S T`, and the round-trip
412/// `β_logslope = T·β'` make the family's geometry consistent at width `r` and
413/// recover the original-basis logslope coefficients for prediction/reporting.
414#[derive(Debug, Clone)]
415pub(super) struct ReducedLogslopeReparam {
416    /// Reduced transform `T` (`p_logslope × r`). `G_reduced = G·T`,
417    /// `β_logslope = T·β'`, `S_reduced = Tᵀ S T`.
418    transform: Array2<f64>,
419}
420
421impl ReducedLogslopeReparam {
422    /// Original (full) logslope width `p_logslope`.
423    #[inline]
424    pub(super) fn original_cols(&self) -> usize {
425        self.transform.nrows()
426    }
427
428    /// Reduced width `r`.
429    #[inline]
430    pub(super) fn reduced_cols(&self) -> usize {
431        self.transform.ncols()
432    }
433
434    /// Map a reduced-basis logslope coefficient `β'` (length `r`) back to the
435    /// original logslope basis `β_logslope = T·β'` (length `p_logslope`), so
436    /// prediction/reporting are unchanged-in-meaning.
437    pub(super) fn recover_original_logslope_beta(
438        &self,
439        beta_reduced: &Array1<f64>,
440    ) -> Result<Array1<f64>, String> {
441        if beta_reduced.len() != self.reduced_cols() {
442            return Err(format!(
443                "reduced logslope reparam: β' length ({}) != reduced width ({})",
444                beta_reduced.len(),
445                self.reduced_cols()
446            ));
447        }
448        Ok(self.transform.dot(beta_reduced))
449    }
450}
451
452/// Build the reduced-basis logslope reparameterization (see
453/// [`ReducedLogslopeReparam`]) from the rigid-pilot EFFECTIVE Jacobian geometry,
454/// in the PIRLS row metric `W`. Extracts the dense pilot designs and delegates
455/// the geometry to [`reduced_logslope_transform_effective`]. Returns `Ok(None)`
456/// when there is no logslope/marginal span or no effective-confounded direction
457/// to remove (`r == p_g`); the caller then keeps the raw design. A fully
458/// confounded block (`r == 0`: the entire effective logslope image is
459/// W-explained by the effective marginal span) is an error: the data identify
460/// only the sum of the marginal and score-slope surfaces, so any fitted
461/// decomposition would be an arbitrary penalty artifact.
462fn build_reduced_logslope_reparam(
463    marginal_design: &TermCollectionDesign,
464    logslope_design: &TermCollectionDesign,
465    z: &Array1<f64>,
466    row_metric: &Array1<f64>,
467    marginal_offset: &Array1<f64>,
468    logslope_offset: &Array1<f64>,
469    marginal_baseline: f64,
470    logslope_baseline: f64,
471    probit_scale: f64,
472) -> Result<Option<ReducedLogslopeReparam>, String> {
473    let marginal = marginal_design
474        .design
475        .try_to_dense_arc("build_reduced_logslope_reparam::marginal")?;
476    let logslope = logslope_design
477        .design
478        .try_to_dense_arc("build_reduced_logslope_reparam::logslope")?;
479    let n = marginal.nrows();
480    if logslope.nrows() != n
481        || z.len() != n
482        || row_metric.len() != n
483        || marginal_offset.len() != n
484        || logslope_offset.len() != n
485    {
486        return Err(format!(
487            "reduced logslope reparam row mismatch: marginal={}, logslope={}, z={}, row_metric={}, marginal_offset={}, logslope_offset={}",
488            marginal.nrows(),
489            logslope.nrows(),
490            z.len(),
491            row_metric.len(),
492            marginal_offset.len(),
493            logslope_offset.len(),
494        ));
495    }
496    let p_m = marginal.ncols();
497    let p_g = logslope.ncols();
498    if p_m == 0 || p_g == 0 {
499        return Ok(None);
500    }
501    if !marginal_baseline.is_finite()
502        || !logslope_baseline.is_finite()
503        || !probit_scale.is_finite()
504        || probit_scale <= 0.0
505        || z.iter().any(|v| !v.is_finite())
506        || row_metric.iter().any(|v| !v.is_finite() || *v < 0.0)
507        || marginal_offset.iter().any(|v| !v.is_finite())
508        || logslope_offset.iter().any(|v| !v.is_finite())
509    {
510        return Err(
511            "reduced logslope reparam requires finite pilot geometry and finite non-negative row metric"
512                .to_string(),
513        );
514    }
515
516    // The joint Hessian the inner solve factorises is built from the EFFECTIVE
517    // BMS Jacobians, not the raw design. At the rigid pilot,
518    //   ∂η_i/∂β_m = c_i · M_i,   c_i = sqrt(1 + (s·g_i)²)
519    //   ∂η_i/∂β_s = f_i · G_i,   f_i = q_i·s²·g_i/c_i + s·z_i
520    // so a raw logslope direction `v` is rank-soft in the joint Hessian iff its
521    // EFFECTIVE image `diag(f)·G·v` is W-explained by `span(diag(c)·M)` — NOT iff
522    // raw `G·v` is W-explained by `span(M)`. Auditing the raw design removes the
523    // wrong directions; the reduced basis is built from the effective Schur Gram.
524    // The pure-array geometry lives in `reduced_logslope_transform_effective` so
525    // it can be unit-tested directly against the raw-vs-effective counterexample.
526    match reduced_logslope_transform_effective(
527        marginal.view(),
528        logslope.view(),
529        z,
530        row_metric,
531        marginal_offset,
532        logslope_offset,
533        marginal_baseline,
534        logslope_baseline,
535        probit_scale,
536    )? {
537        ReducedLogslopeOutcome::Reduced(transform) => {
538            Ok(Some(ReducedLogslopeReparam { transform }))
539        }
540        ReducedLogslopeOutcome::FullRank => Ok(None),
541        ReducedLogslopeOutcome::FullyConfounded => Err(
542            "BMS score-slope block is fully confounded with the marginal index: every \
543             effective logslope direction diag(f)·G·v is W-explained by the effective \
544             marginal span at the rigid pilot, so the data identify only the sum of the \
545             marginal and score-slope surfaces and the smoothing penalty would select an \
546             arbitrary decomposition between them. Refusing to fit; remove the score-slope \
547             terms or supply covariates that separate them from the marginal index."
548                .to_string(),
549        ),
550    }
551}
552
553/// Distinct outcomes of the effective logslope confound audit. `FullRank`
554/// (nothing to reduce, `r == p_g`) and `FullyConfounded` (`r == 0`) must not
555/// share a signal: keeping the raw design is correct for the former, while for
556/// the latter the data identify only a combination of the marginal and
557/// score-slope surfaces, and silently retaining the raw columns would let the
558/// penalty pick an arbitrary decomposition and report it as an estimate.
559#[derive(Debug)]
560pub(crate) enum ReducedLogslopeOutcome {
561    /// Every effective logslope direction carries its own curvature; keep the
562    /// raw design.
563    FullRank,
564    /// `0 < r < p_g`: the reduced basis `T` (`p_g × r`) spanning the
565    /// identifiable directions.
566    Reduced(Array2<f64>),
567    /// `r == 0`: the entire effective logslope image is W-explained by the
568    /// effective marginal span — the block is unidentified.
569    FullyConfounded,
570}
571
572/// Build the reduced logslope basis `T` (p_g × r) from the EFFECTIVE BMS pilot
573/// geometry, in the PIRLS row metric `W`. `T`'s columns span the raw logslope
574/// coefficient directions whose effective image `diag(f)·G·v` is NOT W-explained
575/// by `span(diag(c)·M)` — i.e. the directions the joint Hessian retains real
576/// curvature along. Returns [`ReducedLogslopeOutcome::FullRank`] when there is
577/// nothing to reduce (`r == p_g`, raw design kept) and
578/// [`ReducedLogslopeOutcome::FullyConfounded`] when the entire effective
579/// logslope image collapses into the effective marginal span (`r == 0`), so the
580/// caller can refuse the unidentified block instead of conflating the two
581/// cases.
582///
583/// At the rigid pilot the effective Jacobians are
584///     M_eff = diag(c) · M,   c_i = sqrt(1 + (s·g_i)²)
585///     G_eff = diag(f) · G,   f_i = q_i·s²·g_i/c_i + s·z_i
586/// and the raw-coordinate Gram of the logslope component W-orthogonal to
587/// `span(M_eff)` is the Schur complement
588///     Gtt = G_effᵀ W G_eff − (G_effᵀ W M_eff)(M_effᵀ W M_eff + εI)⁻¹(M_effᵀ W G_eff).
589/// `T` is the orthonormal eigenbasis of `Gtt` for eigenvalues above a tolerance
590/// relative to the effective logslope energy scale.
591pub(crate) fn reduced_logslope_transform_effective(
592    marginal: ArrayView2<'_, f64>,
593    logslope: ArrayView2<'_, f64>,
594    z: &Array1<f64>,
595    row_metric: &Array1<f64>,
596    marginal_offset: &Array1<f64>,
597    logslope_offset: &Array1<f64>,
598    marginal_baseline: f64,
599    logslope_baseline: f64,
600    probit_scale: f64,
601) -> Result<ReducedLogslopeOutcome, String> {
602    let n = marginal.nrows();
603    let p_m = marginal.ncols();
604    let p_g = logslope.ncols();
605    if p_m == 0 || p_g == 0 {
606        return Ok(ReducedLogslopeOutcome::FullRank);
607    }
608
609    // Effective pilot Jacobians M_eff = diag(c)·M and G_eff = diag(f)·G.
610    let mut m_eff = Array2::<f64>::zeros((n, p_m));
611    let mut g_eff = Array2::<f64>::zeros((n, p_g));
612    for i in 0..n {
613        let q_i = marginal_offset[i] + marginal_baseline;
614        let g_i = logslope_offset[i] + logslope_baseline;
615        let sg = probit_scale * g_i;
616        let c_i = (1.0 + sg * sg).sqrt();
617        let f_i = q_i * probit_scale * probit_scale * g_i / c_i + probit_scale * z[i];
618        for j in 0..p_m {
619            m_eff[[i, j]] = c_i * marginal[[i, j]];
620        }
621        for j in 0..p_g {
622            g_eff[[i, j]] = f_i * logslope[[i, j]];
623        }
624    }
625
626    // C = G_effᵀ W G_eff (raw-coordinate effective logslope Gram); its diagonal
627    // sets the energy scale for the relative kept-direction tolerance.
628    let c_gram = fast_xt_diag_x(&g_eff, row_metric);
629    let energy_scale = (0..p_g).map(|i| c_gram[[i, i]]).fold(0.0_f64, f64::max);
630    if !energy_scale.is_finite() {
631        return Err(
632            "reduced logslope reparam: effective logslope Gram produced non-finite energy"
633                .to_string(),
634        );
635    }
636    if energy_scale <= 0.0 {
637        // A zero effective logslope image (f_i·G_i ≡ 0 in W) carries no joint-
638        // Hessian curvature at all — trivially W-explained by any span.
639        return Ok(ReducedLogslopeOutcome::FullyConfounded);
640    }
641
642    // A = M_effᵀ W M_eff + εI (ridge relative to the marginal effective energy so
643    // the Schur solve is well-posed even when the marginal pilot Gram is
644    // rank-soft; the ridge only under-removes, i.e. is conservative).
645    let mut a_gram = fast_xt_diag_x(&m_eff, row_metric);
646    let a_scale = (0..p_m).map(|i| a_gram[[i, i]]).fold(0.0_f64, f64::max);
647    let a_ridge = (a_scale * LOGSLOPE_REDUCED_BASIS_RELATIVE_TOL).max(f64::EPSILON);
648    for i in 0..p_m {
649        a_gram[[i, i]] += a_ridge;
650    }
651
652    // B = M_effᵀ W G_eff (p_m × p_g);  Gtt = C − Bᵀ A⁻¹ B (p_g × p_g, PSD).
653    let b_cross = gam_linalg::faer_ndarray::fast_xt_diag_y(&m_eff, row_metric, &g_eff);
654    let a_view = gam_linalg::faer_ndarray::FaerArrayView::new(&a_gram);
655    let a_factor =
656        gam_linalg::faer_ndarray::factorize_symmetricwith_fallback(a_view.as_ref(), Side::Lower)
657            .map_err(|e| {
658                format!(
659                    "reduced logslope reparam: effective marginal Gram factorization failed: {e}"
660                )
661            })?;
662    let b_view = gam_linalg::faer_ndarray::FaerArrayView::new(&b_cross);
663    let solved = a_factor.solve(b_view.as_ref()); // A⁻¹ B  (p_m × p_g)
664    let a_inv_b = Array2::from_shape_fn((p_m, p_g), |(i, j)| solved[(i, j)]);
665    let schur = fast_atb(&b_cross, &a_inv_b); // Bᵀ A⁻¹ B  (p_g × p_g)
666    let mut stt = &c_gram - &schur;
667    stt = (&stt + &stt.t()) * 0.5;
668    if stt.iter().any(|v| !v.is_finite()) {
669        return Err(
670            "reduced logslope reparam: effective Schur Gram produced non-finite entries"
671                .to_string(),
672        );
673    }
674
675    let (evals, evecs) = stt
676        .eigh(Side::Lower)
677        .map_err(|e| format!("reduced logslope reparam: eigendecomposition failed: {e:?}"))?;
678    // A `Gtt` eigenvalue far below the effective logslope energy scale means that
679    // direction's effective logslope column is W-explained by the effective
680    // marginal span — exactly the joint-Hessian rank-soft confounded direction.
681    let tol = energy_scale * LOGSLOPE_REDUCED_BASIS_RELATIVE_TOL;
682    let mut kept: Vec<usize> = (0..evals.len()).filter(|&i| evals[i] > tol).collect();
683    kept.sort_by(|&a, &b| {
684        evals[b]
685            .partial_cmp(&evals[a])
686            .unwrap_or(std::cmp::Ordering::Equal)
687    });
688    let r = kept.len();
689    // r == p_g: no effective-confounded direction to remove — keep the raw
690    // design. r == 0: the whole effective logslope image is in the effective
691    // marginal span — a distinct outcome the caller must refuse, never a
692    // keep-the-raw-design signal (the raw columns would be an arbitrary
693    // penalty-selected decomposition of an unidentified sum).
694    if r == p_g {
695        return Ok(ReducedLogslopeOutcome::FullRank);
696    }
697    if r == 0 {
698        return Ok(ReducedLogslopeOutcome::FullyConfounded);
699    }
700    let mut transform = Array2::<f64>::zeros((p_g, r));
701    for (out_col, &src) in kept.iter().enumerate() {
702        transform.column_mut(out_col).assign(&evecs.column(src));
703    }
704    if transform.iter().any(|v| !v.is_finite()) {
705        return Err(
706            "reduced logslope reparam: reduced transform produced non-finite entries".to_string(),
707        );
708    }
709    Ok(ReducedLogslopeOutcome::Reduced(transform))
710}
711
712/// Apply a [`ReducedLogslopeReparam`] to a logslope `TermCollectionDesign`,
713/// producing a new design at the reduced width `r`: the design becomes
714/// `G_reduced = G·T`, and every blockwise penalty `S` is reparameterized to
715/// `S_reduced = Tᵀ S T` over the full reduced column range `0..r`. The reduced
716/// penalty's null space is recomputed from its numerical rank so the REML
717/// log-determinant accounting stays consistent at the reduced width.
718fn reparameterize_logslope_design_reduced(
719    logslope_design: &TermCollectionDesign,
720    reparam: &ReducedLogslopeReparam,
721) -> Result<TermCollectionDesign, String> {
722    let g = logslope_design
723        .design
724        .try_to_dense_arc("reparameterize_logslope_design_reduced::logslope")?;
725    let p_g = g.ncols();
726    if p_g != reparam.original_cols() {
727        return Err(format!(
728            "reduced logslope reparam width mismatch: design has {p_g} cols, transform expects {}",
729            reparam.original_cols()
730        ));
731    }
732    let t = &reparam.transform;
733    let r = reparam.reduced_cols();
734    // G_reduced = G·T   (n × r).
735    let g_reduced = fast_ab(&g, t);
736
737    // Reparameterize each penalty: embed its local block at full width p_g, then
738    // form S_reduced = Tᵀ S T (r × r) over the whole reduced column range.
739    let mut new_penalties: Vec<gam_terms::smooth::BlockwisePenalty> =
740        Vec::with_capacity(logslope_design.penalties.len());
741    let mut new_nullspace_dims: Vec<usize> = Vec::with_capacity(logslope_design.penalties.len());
742    for bp in &logslope_design.penalties {
743        let mut full = Array2::<f64>::zeros((p_g, p_g));
744        full.slice_mut(s![bp.col_range.clone(), bp.col_range.clone()])
745            .assign(&bp.local);
746        // S_reduced = Tᵀ (S) T.
747        let st = fast_ab(&full, t); // p_g × r
748        let mut s_reduced = fast_atb(t, &st); // r × r
749        s_reduced = (&s_reduced + &s_reduced.t()) * 0.5;
750        // Null-space dimension of the reduced penalty = r − rank(S_reduced).
751        let (evals, _) = s_reduced
752            .eigh(Side::Lower)
753            .map_err(|e| format!("reduced logslope penalty eigendecomposition failed: {e:?}"))?;
754        let max_eval = evals.iter().fold(0.0_f64, |acc, &v| acc.max(v.abs()));
755        let pen_tol = (max_eval * 1.0e-12).max(f64::EPSILON);
756        let rank = evals.iter().filter(|&&v| v.abs() > pen_tol).count();
757        let nullspace_dim = r.saturating_sub(rank);
758        new_penalties.push(gam_terms::smooth::BlockwisePenalty::new(0..r, s_reduced));
759        new_nullspace_dims.push(nullspace_dim);
760    }
761
762    let new_design = DesignMatrix::Dense(gam_linalg::matrix::DenseDesignMatrix::from(g_reduced));
763    // The reduced logslope block is a single dense smooth-like surface over the
764    // reparameterized coordinates; it carries no parametric/random-effect/
765    // intercept structure of its own (those live in the marginal block), so the
766    // structural ranges collapse to empty and the smooth metadata is cleared.
767    // The penalties + nullspace_dims above are what the joint REML consumes.
768    Ok(TermCollectionDesign {
769        design: new_design,
770        penalties: new_penalties,
771        nullspace_dims: new_nullspace_dims,
772        penaltyinfo: Vec::new(),
773        dropped_penaltyinfo: Vec::new(),
774        coefficient_lower_bounds: None,
775        linear_constraints: None,
776        intercept_range: 0..0,
777        linear_ranges: Vec::new(),
778        random_effect_ranges: Vec::new(),
779        random_effect_levels: Vec::new(),
780        smooth: gam_terms::smooth::SmoothDesign {
781            term_designs: Vec::new(),
782            penalties: Vec::new(),
783            nullspace_dims: Vec::new(),
784            penaltyinfo: Vec::new(),
785            dropped_penaltyinfo: Vec::new(),
786            terms: Vec::new(),
787            coefficient_lower_bounds: None,
788            linear_constraints: None,
789        },
790    })
791}
792
793/// Re-embed the term-collection marginal penalties at the (possibly widened)
794/// block dimension `p_m [+ p₁]`, then append the #461 fixed-ridge absorber:
795///
796///  (#461, only with influence columns) the REML-learned absorber identity on
797///  the influence columns `p_m..p_m+p₁`.
798///
799/// The two former gam#754 pinned ridges — the marginal nullspace-shrinkage ridge
800/// and the marginal↔logslope overlap ridge — are DELETED: robustness is now
801/// unconditional, so the full-identifiable-span Jeffreys term (`Z_J = I`, see
802/// `jeffreys_subspace_from_penalty`) supplies automatic O(n)-scaled curvature on
803/// every under-identified direction (subsuming the nullspace ridge), and the
804/// exact orthogonal reparameterization of the logslope design (now unconditional,
805/// see `build_reduced_logslope_reparam`) resolves the marginal↔logslope confound
806/// by construction (subsuming the overlap ridge).
807///
808/// The genuine marginal smooth penalties keep their `col_range` (marginal
809/// columns stay in `0..p_m`). Returns `(penalties, nullspace_dims,
810/// initial_log_lambdas)` to install on the marginal block. With influence
811/// columns present, `rho_marginal` carries one TRAILING coordinate for the
812/// absorber ridge: its precision is REML-learned like every other penalty
813/// (SPEC: shrinkage is explicit or REML-selected, never a pinned magic
814/// constant), seeded at the ln(n) leakage scale by `joint_setup`.
815pub(crate) fn marginal_penalties_with_influence_ridge(
816    design: &TermCollectionDesign,
817    rho_marginal: &Array1<f64>,
818    influence_columns: Option<&Array2<f64>>,
819) -> Result<(Vec<PenaltyMatrix>, Vec<usize>, Array1<f64>), String> {
820    let p_m = design.design.ncols();
821    let p1 = influence_columns.map(|z| z.ncols()).unwrap_or(0);
822    let total_dim = p_m + p1;
823    let expected_rho = design.penalties.len() + usize::from(p1 > 0);
824    if rho_marginal.len() != expected_rho {
825        return Err(format!(
826            "marginal rho width {} != smooth penalties {} + absorber slot {}",
827            rho_marginal.len(),
828            design.penalties.len(),
829            usize::from(p1 > 0),
830        ));
831    }
832    // Re-embed each marginal penalty at the (widened) total dimension (col_range
833    // unchanged: marginal columns remain 0..p_m).
834    let mut penalties: Vec<PenaltyMatrix> = design
835        .penalties
836        .iter()
837        .map(|bp| bp.to_penalty_matrix(total_dim))
838        .collect();
839    let mut nullspace_dims = design.nullspace_dims.clone();
840    let log_lambdas = rho_marginal.to_vec();
841
842    // (#461) absorber ridge: identity on the influence columns only. Full rank
843    // (nullspace 0); its log λ is the trailing `rho_marginal` coordinate, so
844    // the outer REML selects the absorber precision like any other
845    // random-effect variance (large λ recovers the null correction; the
846    // residualized columns carry no marginal-span signal by construction).
847    if p1 > 0 {
848        penalties.push(PenaltyMatrix::Blockwise {
849            local: Array2::<f64>::eye(p1),
850            col_range: p_m..total_dim,
851            total_dim,
852        });
853        nullspace_dims.push(0);
854    }
855
856    Ok((penalties, nullspace_dims, Array1::from_vec(log_lambdas)))
857}
858
859/// Widen an optional β warm-start hint to the influence-widened marginal
860/// dimension, zero-filling the absorber coefficients `γ` (#461).
861pub(crate) fn widen_marginal_beta_hint(
862    beta_hint: Option<Array1<f64>>,
863    p_marginal_widened: usize,
864) -> Option<Array1<f64>> {
865    beta_hint.map(|hint| {
866        if hint.len() == p_marginal_widened {
867            hint
868        } else {
869            let mut widened = Array1::<f64>::zeros(p_marginal_widened);
870            let copy = hint.len().min(p_marginal_widened);
871            widened
872                .slice_mut(s![..copy])
873                .assign(&hint.slice(s![..copy]));
874            widened
875        }
876    })
877}
878
879/// Sup-norm of the fitted marginal linear predictor `η = X·β` restricted to a
880/// subset of the marginal design's columns. The mask selects which columns of
881/// `design.design` (length `design.design.ncols()`) contribute; coefficients
882/// beyond `ncols` (the fixed-ridge influence absorber) never enter the marginal
883/// predictor and are excluded by construction. Returns `0.0` for an empty
884/// design. This is the decisive separation quantity: the probit Fisher weight
885/// collapses with `|η|`, not with `‖β‖` (an ill-conditioned non-orthonormal
886/// Duchon/thin-plate basis carries large cancelling coefficients on a smooth,
887/// bounded surface).
888fn marginal_fitted_eta_sup_norm(design: &TermCollectionDesign, masked_beta: &Array1<f64>) -> f64 {
889    let x = &design.design;
890    let n = x.nrows();
891    if n == 0 || x.ncols() == 0 {
892        return 0.0;
893    }
894    let mut sup = 0.0_f64;
895    for row in 0..n {
896        let eta = x.dot_row_view(row, masked_beta.view());
897        if eta.is_finite() {
898            sup = sup.max(eta.abs());
899        }
900    }
901    sup
902}
903
904/// Build a copy of the marginal block β truncated to `design.design.ncols()`
905/// (drops any fixed-ridge absorber tail) so it can drive `X·β`.
906fn marginal_design_beta(
907    design: &TermCollectionDesign,
908    block_beta: ArrayView1<'_, f64>,
909) -> Array1<f64> {
910    let ncols = design.design.ncols();
911    let mut masked = Array1::<f64>::zeros(ncols);
912    let copy = ncols.min(block_beta.len());
913    masked
914        .slice_mut(s![..copy])
915        .assign(&block_beta.slice(s![..copy]));
916    masked
917}
918
919/// Zero every entry of `beta` outside the parametric (penalty-nullspace)
920/// marginal columns — the intercept and the single-penalty linear terms. These
921/// are the directions an unpenalized fit can genuinely separate along (no
922/// smoothness penalty bounds them), so their fitted contribution is tested on
923/// the same η scale.
924fn mask_parametric_columns(
925    design: &TermCollectionDesign,
926    spec: &TermCollectionSpec,
927    full: &Array1<f64>,
928) -> Array1<f64> {
929    let ncols = design.design.ncols();
930    let mut masked = Array1::<f64>::zeros(ncols);
931    if design.intercept_range.len() == 1 {
932        let idx = design.intercept_range.start;
933        if idx < ncols {
934            masked[idx] = full[idx];
935        }
936    }
937    for (linear, (_, range)) in spec.linear_terms.iter().zip(design.linear_ranges.iter()) {
938        if linear.double_penalty {
939            continue;
940        }
941        for col in range.clone() {
942            if col < ncols {
943                masked[col] = full[col];
944            }
945        }
946    }
947    masked
948}
949
950/// Decide whether the converged marginal fit has genuinely separated, using the
951/// FITTED predictor sup-norm `|η|∞` (not raw `|β|∞`). Two arms share the
952/// numerical-degeneracy threshold [`BMS_PROBIT_SEPARATION_ETA_INF`]:
953///   - parametric arm: the penalty-nullspace columns' fitted contribution
954///     (an unpenalized direction can run to infinity);
955///   - full arm: the whole marginal surface's fitted predictor.
956/// The raw `|β|∞` (and its term label) is reported only as diagnostic context;
957/// it never gates the abort. When `|η|∞` is below threshold the converged
958/// penalized fit is numerically trustworthy and this returns `None` — no error,
959/// even if individual coefficients are large.
960pub(crate) fn bernoulli_marginal_slope_runaway_error_from_beta(
961    block_beta: ArrayView1<'_, f64>,
962    design: &TermCollectionDesign,
963    spec: &TermCollectionSpec,
964    inner_converged: bool,
965    eval_label: &str,
966) -> Option<String> {
967    let full_beta = marginal_design_beta(design, block_beta);
968    let parametric_beta = mask_parametric_columns(design, spec, &full_beta);
969
970    let eta_parametric = marginal_fitted_eta_sup_norm(design, &parametric_beta);
971    let eta_full = marginal_fitted_eta_sup_norm(design, &full_beta);
972
973    let (eta_inf, explanation) = if eta_parametric >= BMS_PROBIT_SEPARATION_ETA_INF {
974        (
975            eta_parametric,
976            "an unpenalized parametric marginal direction has no stable finite probit optimum and its fitted predictor has run to the probit underflow scale",
977        )
978    } else if eta_full >= BMS_PROBIT_SEPARATION_ETA_INF {
979        (
980            eta_full,
981            "a marginal direction is trading off against the logslope surface; this is the under-constrained marginal/logslope coupling that appears when the score is correlated with the shared surface covariates",
982        )
983    } else {
984        // |η|∞ is bounded: even if raw coefficients are large (ill-conditioned
985        // non-orthonormal basis with cancellation), the converged penalized
986        // probit fit is numerically trustworthy. Do NOT abort.
987        return None;
988    };
989
990    let inner_status = if inner_converged {
991        "the inner solve reached a KKT certificate at this separation-scale predictor"
992    } else {
993        "the inner solve failed while already carrying a separation-scale predictor"
994    };
995    // Raw |β|∞ context (decisive quantity is |η|∞ above).
996    let beta_abs = full_beta
997        .iter()
998        .copied()
999        .filter(|v| v.is_finite())
1000        .fold(0.0_f64, |acc, v| acc.max(v.abs()));
1001
1002    Some(format!(
1003        "bernoulli marginal-slope probit marginal/logslope runaway detected in block \
1004         'marginal_surface' during {eval_label}: the fitted marginal predictor has \
1005         |η|∞={eta_inf:.3e} (numerical-degeneracy threshold \
1006         {BMS_PROBIT_SEPARATION_ETA_INF:.1}; raw |β|∞={beta_abs:.3e} is reported for \
1007         context only and does not gate this diagnostic). The joint design is \
1008         identifiable; {explanation}. {inner_status}. The robust Jeffreys curvature \
1009         path is already installed for this fit, so this diagnostic means the current \
1010         coupled surface still drives the linear predictor to the probit underflow \
1011         scale rather than a request for an external bias-reduction prior. Reduce or \
1012         reparameterize the coupled marginal/logslope surface, or use a \
1013         lower-dimensional logslope interaction. This is not a \
1014         Matérn/Duchon polynomial-nullspace or cross-block gauge-priority \
1015         failure."
1016    ))
1017}
1018
1019pub(crate) fn bernoulli_marginal_slope_runaway_error(
1020    warm_start: &CustomFamilyWarmStart,
1021    design: &TermCollectionDesign,
1022    spec: &TermCollectionSpec,
1023    inner_converged: bool,
1024    eval_label: &str,
1025) -> Option<String> {
1026    let block_beta = warm_start.block_beta_view(0)?;
1027    bernoulli_marginal_slope_runaway_error_from_beta(
1028        block_beta,
1029        design,
1030        spec,
1031        inner_converged,
1032        eval_label,
1033    )
1034}
1035
1036#[cfg(test)]
1037mod runaway_tests {
1038    use super::*;
1039    use gam_linalg::faer_ndarray::{
1040        FaerArrayView, factorize_symmetricwith_fallback, fast_xt_diag_y,
1041    };
1042    use gam_terms::smooth::{LinearCoefficientGeometry, LinearTermSpec};
1043
1044    // The marginal↔logslope overlap penalty is no longer installed as a pinned
1045    // ridge (subsumed by the now-unconditional exact logslope orthogonalisation in
1046    // `build_reduced_logslope_reparam`). The geometry helper is retained here under
1047    // the test module because the basis-independence/weight-orthogonality unit tests
1048    // below exercise it directly as the canonical overlap-direction reference.
1049    pub(crate) fn marginal_logslope_overlap_penalty(
1050        marginal_design: &DesignMatrix,
1051        logslope_design: &DesignMatrix,
1052        z: &Array1<f64>,
1053        row_metric: &Array1<f64>,
1054        marginal_offset: &Array1<f64>,
1055        logslope_offset: &Array1<f64>,
1056        marginal_baseline: f64,
1057        logslope_baseline: f64,
1058        probit_scale: f64,
1059    ) -> Result<Option<Array2<f64>>, String> {
1060        let marginal =
1061            marginal_design.try_to_dense_arc("marginal_logslope_overlap_penalty::marginal")?;
1062        let logslope =
1063            logslope_design.try_to_dense_arc("marginal_logslope_overlap_penalty::logslope")?;
1064        let n = marginal.nrows();
1065        if logslope.nrows() != n
1066            || z.len() != n
1067            || row_metric.len() != n
1068            || marginal_offset.len() != n
1069            || logslope_offset.len() != n
1070        {
1071            return Err(format!(
1072                "marginal/logslope overlap penalty row mismatch: marginal={}, logslope={}, z={}, row_metric={}, marginal_offset={}, logslope_offset={}",
1073                marginal.nrows(),
1074                logslope.nrows(),
1075                z.len(),
1076                row_metric.len(),
1077                marginal_offset.len(),
1078                logslope_offset.len(),
1079            ));
1080        }
1081        let p_m = marginal.ncols();
1082        let p_g = logslope.ncols();
1083        if p_m == 0 || p_g == 0 {
1084            return Ok(None);
1085        }
1086        if !marginal_baseline.is_finite()
1087            || !logslope_baseline.is_finite()
1088            || !probit_scale.is_finite()
1089            || probit_scale <= 0.0
1090            || z.iter().any(|v| !v.is_finite())
1091            || row_metric.iter().any(|v| !v.is_finite() || *v < 0.0)
1092            || marginal_offset.iter().any(|v| !v.is_finite())
1093            || logslope_offset.iter().any(|v| !v.is_finite())
1094        {
1095            return Err(
1096                "marginal/logslope overlap penalty requires finite pilot geometry and finite non-negative row metric"
1097                    .to_string(),
1098            );
1099        }
1100
1101        let mut marginal_effective = Array2::<f64>::zeros((n, p_m));
1102        let mut effective_logslope = Array2::<f64>::zeros((n, p_g));
1103        for i in 0..n {
1104            let q_i = marginal_offset[i] + marginal_baseline;
1105            let g_i = logslope_offset[i] + logslope_baseline;
1106            let sg = probit_scale * g_i;
1107            let c_i = (1.0 + sg * sg).sqrt();
1108            let logslope_factor =
1109                q_i * probit_scale * probit_scale * g_i / c_i + probit_scale * z[i];
1110            for j in 0..p_m {
1111                marginal_effective[[i, j]] = c_i * marginal[[i, j]];
1112            }
1113            for j in 0..p_g {
1114                effective_logslope[[i, j]] = logslope_factor * logslope[[i, j]];
1115            }
1116        }
1117        if effective_logslope.iter().all(|v| v.abs() <= f64::EPSILON) {
1118            return Ok(None);
1119        }
1120
1121        let mut gram = fast_xt_diag_x(&effective_logslope, row_metric);
1122        let gram_scale = gram.diag().iter().copied().fold(0.0_f64, f64::max);
1123        if !gram_scale.is_finite() || gram_scale <= 0.0 {
1124            return Ok(None);
1125        }
1126        let projection_ridge = (gram_scale * 1.0e-10).max(f64::EPSILON);
1127        for i in 0..p_g {
1128            gram[[i, i]] += projection_ridge;
1129        }
1130        let cross = fast_xt_diag_y(&effective_logslope, row_metric, &marginal_effective);
1131        let gram_view = FaerArrayView::new(&gram);
1132        let factor = factorize_symmetricwith_fallback(gram_view.as_ref(), Side::Lower)
1133            .map_err(|e| format!("marginal/logslope overlap Gram factorization failed: {e}"))?;
1134        let rhsview = FaerArrayView::new(&cross);
1135        let coeffs_mat = factor.solve(rhsview.as_ref());
1136        let coeffs = Array2::from_shape_fn((p_g, p_m), |(i, j)| coeffs_mat[(i, j)]);
1137        let projected_marginal = fast_ab(&effective_logslope, &coeffs);
1138        let mut penalty = fast_xt_diag_y(&marginal_effective, row_metric, &projected_marginal);
1139        penalty = (&penalty + &penalty.t()) * 0.5;
1140        let max_abs = penalty.iter().map(|v| v.abs()).fold(0.0_f64, f64::max);
1141        if !max_abs.is_finite() || max_abs <= 1.0e-12 {
1142            return Ok(None);
1143        }
1144        Ok(Some(penalty))
1145    }
1146
1147    // The raw-vs-effective counterexample. With q=g=0, s=1: c_i=1 (so M_eff=M)
1148    // and f_i=z_i (so G_eff=diag(z)·G). Pick M=[1,1,1]ᵀ and a two-column logslope
1149    // G whose RAW columns are both linearly independent of M (raw orthogonalising
1150    // [M|G] would keep BOTH — the old code returned None, no reduction), but whose
1151    // first EFFECTIVE column diag(z)·G[:,0] equals M_eff exactly. The effective
1152    // audit must therefore drop exactly one direction (r=1), proving it removes
1153    // the joint-Hessian rank-soft direction the raw audit could not see.
1154    #[test]
1155    pub(crate) fn effective_reduction_drops_score_weighted_confound_raw_audit_misses() {
1156        // G col0 = [1,2,3], col1 = [1,2,9]  (row-major rows: [1,1],[2,2],[3,9]).
1157        let m = Array2::<f64>::from_shape_vec((3, 1), vec![1.0, 1.0, 1.0]).unwrap();
1158        let g = Array2::<f64>::from_shape_vec((3, 2), vec![1.0, 1.0, 2.0, 2.0, 3.0, 9.0]).unwrap();
1159        let z = Array1::from_vec(vec![1.0, 0.5, 1.0 / 3.0]);
1160        let w = Array1::<f64>::ones(3);
1161        let zero = Array1::<f64>::zeros(3);
1162
1163        // diag(z)·G[:,0] = [1·1, 0.5·2, (1/3)·3] = [1,1,1] = M_eff (fully aliased);
1164        // diag(z)·G[:,1] = [1·1, 0.5·2, (1/3)·9] = [1,1,3] (NOT in span([1,1,1])).
1165        let reparam = match reduced_logslope_transform_effective(
1166            m.view(),
1167            g.view(),
1168            &z,
1169            &w,
1170            &zero,
1171            &zero,
1172            0.0,
1173            0.0,
1174            1.0,
1175        )
1176        .expect("effective reduction must succeed")
1177        {
1178            ReducedLogslopeOutcome::Reduced(t) => t,
1179            other => panic!(
1180                "effective audit must reduce the score-weighted confound (raw audit would not), got {}",
1181                match other {
1182                    ReducedLogslopeOutcome::FullRank => "FullRank",
1183                    ReducedLogslopeOutcome::FullyConfounded => "FullyConfounded",
1184                    ReducedLogslopeOutcome::Reduced(_) => unreachable!(),
1185                }
1186            ),
1187        };
1188        assert_eq!(
1189            reparam.ncols(),
1190            1,
1191            "exactly one effective-identifiable logslope direction should survive"
1192        );
1193
1194        // The surviving raw direction's EFFECTIVE image diag(z)·G·t must carry the
1195        // non-constant ([1,1,3]) content — i.e. it is the identifiable direction,
1196        // not the [1,1,1] confound. Its row variance must be clearly positive.
1197        let g_eff = {
1198            let mut e = Array2::<f64>::zeros((3, 2));
1199            for i in 0..3 {
1200                for j in 0..2 {
1201                    e[[i, j]] = z[i] * g[[i, j]];
1202                }
1203            }
1204            e
1205        };
1206        let img = g_eff.dot(&reparam.column(0));
1207        let mean = img.iter().sum::<f64>() / 3.0;
1208        let var = img.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / 3.0;
1209        assert!(
1210            var > 1.0e-6,
1211            "kept direction must be the identifiable (non-constant) effective column, var={var}"
1212        );
1213    }
1214
1215    // The single-column fully-confounded case: G=[1,2,3]ᵀ, z=[1,1/2,1/3] gives
1216    // G_eff=[1,1,1]=M_eff, so the entire effective logslope image is in the
1217    // effective marginal span (r==0). The helper must report the distinct
1218    // FullyConfounded outcome — NOT the FullRank keep-the-raw-design signal —
1219    // because the data identify only the sum of the two surfaces and the
1220    // caller must refuse the block.
1221    #[test]
1222    pub(crate) fn effective_reduction_fully_confounded_single_column_is_distinct_outcome() {
1223        let m = Array2::<f64>::from_shape_vec((3, 1), vec![1.0, 1.0, 1.0]).unwrap();
1224        let g = Array2::<f64>::from_shape_vec((3, 1), vec![1.0, 2.0, 3.0]).unwrap();
1225        let z = Array1::from_vec(vec![1.0, 0.5, 1.0 / 3.0]);
1226        let w = Array1::<f64>::ones(3);
1227        let zero = Array1::<f64>::zeros(3);
1228        let outcome = reduced_logslope_transform_effective(
1229            m.view(),
1230            g.view(),
1231            &z,
1232            &w,
1233            &zero,
1234            &zero,
1235            0.0,
1236            0.0,
1237            1.0,
1238        )
1239        .expect("effective reduction must succeed");
1240        assert!(
1241            matches!(outcome, ReducedLogslopeOutcome::FullyConfounded),
1242            "fully effective-confounded logslope must surface the distinct FullyConfounded outcome"
1243        );
1244    }
1245
1246    // No effective confound: both effective logslope columns stay independent of
1247    // M_eff, so nothing is reduced (r==p_g ⇒ None) and healthy fits are untouched.
1248    #[test]
1249    pub(crate) fn effective_reduction_no_confound_returns_none() {
1250        let m = Array2::<f64>::from_shape_vec((3, 1), vec![1.0, 1.0, 1.0]).unwrap();
1251        // diag(z)·col gives non-constant images for both columns under z below.
1252        let g = Array2::<f64>::from_shape_vec((3, 2), vec![1.0, 0.0, 0.0, 1.0, 0.0, 0.0]).unwrap();
1253        let z = Array1::from_vec(vec![1.0, 2.0, 3.0]);
1254        let w = Array1::<f64>::ones(3);
1255        let zero = Array1::<f64>::zeros(3);
1256        let outcome = reduced_logslope_transform_effective(
1257            m.view(),
1258            g.view(),
1259            &z,
1260            &w,
1261            &zero,
1262            &zero,
1263            0.0,
1264            0.0,
1265            1.0,
1266        )
1267        .expect("effective reduction must succeed");
1268        assert!(
1269            matches!(outcome, ReducedLogslopeOutcome::FullRank),
1270            "no effective confound ⇒ FullRank (raw design kept unchanged)"
1271        );
1272    }
1273
1274    #[test]
1275    pub(crate) fn spatial_joint_setup_counts_only_learned_penalties_in_rho() {
1276        let data = Array2::<f64>::zeros((3, 1));
1277        let empty_terms = TermCollectionSpec {
1278            linear_terms: Vec::new(),
1279            random_effect_terms: Vec::new(),
1280            smooth_terms: Vec::new(),
1281        };
1282        let setup = joint_setup(
1283            data.view(),
1284            &empty_terms,
1285            &empty_terms,
1286            2,
1287            3,
1288            Some(2.5),
1289            &[0.4],
1290            &SpatialLengthScaleOptimizationOptions::default(),
1291        );
1292
1293        assert_eq!(
1294            setup.rho_dim(),
1295            6,
1296            "BMS spatial setup rho holds every learned marginal/logslope/auxiliary penalty; the #461 absorber ridge occupies the trailing marginal slot"
1297        );
1298        assert_eq!(
1299            setup.theta0()[1], 2.5,
1300            "absorber ridge seeds the trailing marginal rho coordinate at the ln(n) leakage scale"
1301        );
1302    }
1303
1304    #[test]
1305    pub(crate) fn overlap_penalty_targets_score_weighted_logslope_span() {
1306        let marginal = DesignMatrix::Dense(gam_linalg::matrix::DenseDesignMatrix::from(
1307            Array2::from_shape_vec((4, 1), vec![0.0, 1.0, 2.0, 3.0]).unwrap(),
1308        ));
1309        let logslope = DesignMatrix::Dense(gam_linalg::matrix::DenseDesignMatrix::from(
1310            Array2::from_shape_vec((4, 1), vec![1.0, 1.0, 1.0, 1.0]).unwrap(),
1311        ));
1312        let z = Array1::from_vec(vec![0.0, 1.0, 2.0, 3.0]);
1313        let row_metric = Array1::ones(4);
1314        let offsets = Array1::zeros(4);
1315
1316        let penalty = marginal_logslope_overlap_penalty(
1317            &marginal,
1318            &logslope,
1319            &z,
1320            &row_metric,
1321            &offsets,
1322            &offsets,
1323            0.0,
1324            0.0,
1325            1.0,
1326        )
1327        .expect("overlap penalty should build")
1328        .expect("marginal signal lies in the pilot logslope Jacobian span");
1329
1330        assert_eq!(penalty.dim(), (1, 1));
1331        assert!((penalty[[0, 0]] - 14.0).abs() < 1.0e-6);
1332    }
1333
1334    #[test]
1335    pub(crate) fn overlap_penalty_skips_weight_orthogonal_channels() {
1336        let marginal = DesignMatrix::Dense(gam_linalg::matrix::DenseDesignMatrix::from(
1337            Array2::from_shape_vec((4, 1), vec![-1.0, 1.0, -1.0, 1.0]).unwrap(),
1338        ));
1339        let logslope = DesignMatrix::Dense(gam_linalg::matrix::DenseDesignMatrix::from(
1340            Array2::from_shape_vec((4, 1), vec![1.0, 1.0, 1.0, 1.0]).unwrap(),
1341        ));
1342        let z = Array1::ones(4);
1343        let row_metric = Array1::ones(4);
1344        let offsets = Array1::zeros(4);
1345
1346        let penalty = marginal_logslope_overlap_penalty(
1347            &marginal,
1348            &logslope,
1349            &z,
1350            &row_metric,
1351            &offsets,
1352            &offsets,
1353            0.0,
1354            0.0,
1355            1.0,
1356        )
1357        .expect("overlap penalty should build");
1358
1359        assert!(penalty.is_none());
1360    }
1361
1362    // ── Fitted-η separation guard fixtures ───────────────────────────────
1363    //
1364    // The runaway guard tests the FITTED marginal predictor sup-norm
1365    // `|η|∞ = max_i |X[i,:]·β|`, not raw `|β|∞`. These helpers build minimal
1366    // `TermCollectionDesign` / `TermCollectionSpec` pairs from a dense design so
1367    // the criterion is exercised deterministically with no data files.
1368
1369    fn dense_marginal_design(
1370        x: Array2<f64>,
1371        intercept_range: std::ops::Range<usize>,
1372        linear_ranges: Vec<(String, std::ops::Range<usize>)>,
1373    ) -> TermCollectionDesign {
1374        TermCollectionDesign {
1375            design: DesignMatrix::Dense(gam_linalg::matrix::DenseDesignMatrix::from(x)),
1376            penalties: Vec::new(),
1377            nullspace_dims: Vec::new(),
1378            penaltyinfo: Vec::new(),
1379            dropped_penaltyinfo: Vec::new(),
1380            coefficient_lower_bounds: None,
1381            linear_constraints: None,
1382            intercept_range,
1383            linear_ranges,
1384            random_effect_ranges: Vec::new(),
1385            random_effect_levels: Vec::new(),
1386            smooth: gam_terms::smooth::SmoothDesign {
1387                term_designs: Vec::new(),
1388                penalties: Vec::new(),
1389                nullspace_dims: Vec::new(),
1390                penaltyinfo: Vec::new(),
1391                dropped_penaltyinfo: Vec::new(),
1392                terms: Vec::new(),
1393                coefficient_lower_bounds: None,
1394                linear_constraints: None,
1395            },
1396        }
1397    }
1398
1399    fn linear_term(name: &str, feature_col: usize) -> LinearTermSpec {
1400        LinearTermSpec {
1401            name: name.to_string(),
1402            feature_col,
1403            feature_cols: vec![feature_col],
1404            categorical_levels: vec![],
1405            double_penalty: false,
1406            coefficient_geometry: LinearCoefficientGeometry::default(),
1407            coefficient_min: None,
1408            coefficient_max: None,
1409        }
1410    }
1411
1412    fn empty_spec() -> TermCollectionSpec {
1413        TermCollectionSpec {
1414            linear_terms: Vec::new(),
1415            random_effect_terms: Vec::new(),
1416            smooth_terms: Vec::new(),
1417        }
1418    }
1419
1420    /// Regression lock for the false-positive fix: an ill-conditioned
1421    /// non-orthonormal basis (two identical/collinear columns) with a large
1422    /// cancelling coefficient `β=[60,-60]` yields `Xβ ≡ 0` — a perfectly
1423    /// bounded fitted predictor. The guard MUST NOT fire even though raw
1424    /// `|β|∞=60` is far above the old `40.0` coefficient threshold. This is the
1425    /// exact pathology that aborted valid biobank fits.
1426    #[test]
1427    pub(crate) fn runaway_guard_silent_when_huge_beta_cancels_to_bounded_eta() {
1428        // Two identical columns ⇒ Xβ = (β0+β1)·col; β=[60,-60] ⇒ Xβ ≡ 0.
1429        let x = Array2::<f64>::from_shape_vec((4, 2), vec![1.0; 8]).unwrap();
1430        let design = dense_marginal_design(x, 0..0, Vec::new());
1431        let beta = Array1::from_vec(vec![60.0, -60.0]);
1432
1433        let msg = bernoulli_marginal_slope_runaway_error_from_beta(
1434            beta.view(),
1435            &design,
1436            &empty_spec(),
1437            true,
1438            "regression-fixture",
1439        );
1440        assert!(
1441            msg.is_none(),
1442            "huge cancelling β with bounded fitted η must NOT trip the runaway guard; got {msg:?}"
1443        );
1444    }
1445
1446    /// A genuinely separating full marginal surface: a single column with a
1447    /// large coefficient drives `|η|∞ = 40 ≥ 35`, so the guard fires and names
1448    /// the marginal/logslope coupling explanation.
1449    #[test]
1450    pub(crate) fn runaway_guard_fires_when_fitted_eta_exceeds_threshold() {
1451        let x = Array2::<f64>::from_shape_vec((3, 1), vec![1.0, 1.0, 1.0]).unwrap();
1452        let design = dense_marginal_design(x, 0..0, Vec::new());
1453        let beta = Array1::from_vec(vec![40.0]);
1454
1455        let msg = bernoulli_marginal_slope_runaway_error_from_beta(
1456            beta.view(),
1457            &design,
1458            &empty_spec(),
1459            true,
1460            "separation-fixture",
1461        )
1462        .expect("fitted |η|∞=40 ≥ 35 must trip the runaway guard");
1463
1464        assert!(msg.contains("marginal/logslope runaway"));
1465        assert!(msg.contains("|η|∞"));
1466        assert!(msg.contains("4.000e1"));
1467        assert!(msg.contains("score is correlated with the shared surface covariates"));
1468        assert!(msg.contains("not a Matérn/Duchon polynomial-nullspace"));
1469        assert!(msg.contains("KKT certificate"));
1470    }
1471
1472    /// An unpenalized parametric direction can genuinely separate (no smoothness
1473    /// penalty bounding it). When its fitted contribution reaches the η scale
1474    /// the parametric arm fires first and names the parametric explanation.
1475    #[test]
1476    pub(crate) fn runaway_guard_names_unpenalized_parametric_direction_via_fitted_eta() {
1477        let x = Array2::<f64>::from_shape_vec((3, 1), vec![1.0, 1.0, 1.0]).unwrap();
1478        let design = dense_marginal_design(x, 0..0, vec![("sex".to_string(), 0..1)]);
1479        let mut spec = empty_spec();
1480        spec.linear_terms.push(linear_term("sex", 0));
1481        let beta = Array1::from_vec(vec![41.0]);
1482
1483        let msg = bernoulli_marginal_slope_runaway_error_from_beta(
1484            beta.view(),
1485            &design,
1486            &spec,
1487            true,
1488            "parametric-fixture",
1489        )
1490        .expect("parametric fitted |η|∞=41 ≥ 35 must trip the runaway guard");
1491
1492        assert!(msg.contains("unpenalized parametric marginal direction"));
1493        assert!(msg.contains("|η|∞"));
1494        assert!(msg.contains("robust Jeffreys curvature path is already installed"));
1495        assert!(msg.contains("not a Matérn/Duchon polynomial-nullspace"));
1496    }
1497
1498    /// A non-converged inner solve with a BOUNDED fitted predictor must NOT
1499    /// surface the separation error — the non-convergence is reported through
1500    /// the existing downstream path, not as a runaway.
1501    #[test]
1502    pub(crate) fn runaway_guard_silent_for_nonconverged_but_bounded_eta() {
1503        let x = Array2::<f64>::from_shape_vec((3, 1), vec![1.0, 1.0, 1.0]).unwrap();
1504        let design = dense_marginal_design(x, 0..0, Vec::new());
1505        let beta = Array1::from_vec(vec![5.0]);
1506
1507        let msg = bernoulli_marginal_slope_runaway_error_from_beta(
1508            beta.view(),
1509            &design,
1510            &empty_spec(),
1511            false,
1512            "nonconverged-fixture",
1513        );
1514        assert!(
1515            msg.is_none(),
1516            "bounded fitted η must not raise the separation error even when the inner solve did not converge; got {msg:?}"
1517        );
1518    }
1519
1520    /// A genuinely separating fit that ALSO failed to converge still surfaces
1521    /// the runaway error, and reports the non-converged inner status.
1522    #[test]
1523    pub(crate) fn runaway_guard_fires_for_nonconverged_separating_eta() {
1524        let x = Array2::<f64>::from_shape_vec((3, 1), vec![1.0, 1.0, 1.0]).unwrap();
1525        let design = dense_marginal_design(x, 0..0, Vec::new());
1526        let beta = Array1::from_vec(vec![50.0]);
1527
1528        let msg = bernoulli_marginal_slope_runaway_error_from_beta(
1529            beta.view(),
1530            &design,
1531            &empty_spec(),
1532            false,
1533            "nonconverged-separating-fixture",
1534        )
1535        .expect("separating |η|∞ at non-convergence must still trip the guard");
1536
1537        assert!(msg.contains(
1538            "the inner solve failed while already carrying a separation-scale predictor"
1539        ));
1540    }
1541
1542    /// Regression lock for gam#370: the pre-fit identifiability audit evaluates
1543    /// every block's effective Jacobian at the empty/zero β with
1544    /// `family_scalars: None`. The BMS marginal and logslope blocks own the
1545    /// logslope design + offset, so `g_i = offset_s[i]` (the fitted logslope
1546    /// baseline, generically nonzero) at β = 0 — and the old code hard-errored
1547    /// ("requires BmsFamilyScalars when beta != 0 … got family_scalars: None")
1548    /// because it read `any_nonzero_g` and demanded a caller-supplied scalar it
1549    /// could in fact reconstruct itself. Both blocks must now self-compute the
1550    /// closed-form `c_i = sqrt(1 + (s·g_i)²)` (and the logslope factor) from
1551    /// owned data and return a finite Jacobian, NOT an error. This makes every
1552    /// `logslope_formula` / `linkwiggle(...)` BMS fit reachable through the
1553    /// Python `gamfit.fit` API (the audit no longer aborts before the fit).
1554    #[test]
1555    pub(crate) fn bms_block_jacobians_self_compute_at_audit_empty_beta_nonzero_logslope_baseline() {
1556        use std::sync::Arc;
1557        let n = 4usize;
1558        let marginal =
1559            Arc::new(Array2::<f64>::from_shape_vec((n, 1), vec![1.0, 1.0, 1.0, 1.0]).unwrap());
1560        let logslope =
1561            Arc::new(Array2::<f64>::from_shape_vec((n, 1), vec![1.0, 1.0, 1.0, 1.0]).unwrap());
1562        let offset_m = Array1::<f64>::zeros(n);
1563        // Nonzero logslope baseline absorbed into offset_s — the exact pooled
1564        // probit pilot value that is "essentially never exactly 0".
1565        let g_baseline = 0.3_f64;
1566        let offset_s = Array1::<f64>::from_elem(n, g_baseline);
1567        let z = Arc::new(Array1::from_vec(vec![-0.7, 0.2, 0.9, 1.4]));
1568        let s = 1.0_f64;
1569
1570        // The pre-fit audit linearization state: EMPTY β, no family scalars.
1571        let beta: Vec<f64> = Vec::new();
1572        let state = FamilyLinearizationState {
1573            beta: &beta,
1574            family_scalars: None,
1575            channel_hessian: None,
1576            probit_frailty_scale: s,
1577        };
1578
1579        let marginal_jac = BmsMarginalJacobian::new(
1580            Arc::clone(&marginal),
1581            Arc::clone(&logslope),
1582            offset_m.clone(),
1583            offset_s.clone(),
1584            1,
1585        );
1586        let j_m = marginal_jac
1587            .effective_jacobian_rows(&state, 0..n)
1588            .expect("BMS marginal Jacobian must self-compute at audit empty β (gam#370)");
1589        // ∂η_i/∂β_m = c_i · M[i,:], c_i = sqrt(1 + (s·g_baseline)²), M[i,0]=1.
1590        let c_expected = (1.0 + (s * g_baseline).powi(2)).sqrt();
1591        assert_eq!(j_m.dim(), (n, 1));
1592        for i in 0..n {
1593            assert!(
1594                (j_m[[i, 0]] - c_expected).abs() < 1e-12,
1595                "marginal J[{i}] = {} != closed-form c_i = {c_expected}",
1596                j_m[[i, 0]]
1597            );
1598        }
1599
1600        let logslope_jac = BmsLogslopeJacobian::new(
1601            Arc::clone(&marginal),
1602            Arc::clone(&logslope),
1603            offset_m,
1604            offset_s,
1605            Arc::clone(&z),
1606            1,
1607        );
1608        let j_s = logslope_jac
1609            .effective_jacobian_rows(&state, 0..n)
1610            .expect("BMS logslope Jacobian must self-compute at audit empty β (gam#370)");
1611        // ∂η_i/∂β_s = (q_i·s²·g_i/c_i + s·z_i)·G[i,:]; at empty β, q_i = 0 and
1612        // g_i = g_baseline, so the factor is s²·0·… + s·z_i = s·z_i (G[i,0]=1).
1613        assert_eq!(j_s.dim(), (n, 1));
1614        for i in 0..n {
1615            let expected = s * z[i];
1616            assert!(
1617                (j_s[[i, 0]] - expected).abs() < 1e-12,
1618                "logslope J[{i}] = {} != closed-form factor {expected}",
1619                j_s[[i, 0]]
1620            );
1621            assert!(j_s[[i, 0]].is_finite());
1622        }
1623    }
1624}
1625
1626pub(crate) fn build_marginal_blockspec_bms(
1627    design: &TermCollectionDesign,
1628    baseline: f64,
1629    offset: &Array1<f64>,
1630    rho: Array1<f64>,
1631    beta_hint: Option<Array1<f64>>,
1632    logslope_design: &TermCollectionDesign,
1633    logslope_offset: &Array1<f64>,
1634    logslope_baseline: f64,
1635    p_marginal: usize,
1636    influence_columns: Option<&Array2<f64>>,
1637) -> Result<ParameterBlockSpec, String> {
1638    let offset_m = offset + baseline;
1639    let offset_s = logslope_offset + logslope_baseline;
1640    let raw_marginal_dense = design
1641        .design
1642        .try_to_dense_arc("build_marginal_blockspec_bms::marginal")?;
1643    let marginal_dense =
1644        widen_marginal_dense_with_influence(&raw_marginal_dense, influence_columns)?;
1645    let logslope_dense = logslope_design
1646        .design
1647        .try_to_dense_arc("build_marginal_blockspec_bms::logslope")?;
1648    let callback: Arc<dyn BlockEffectiveJacobian> = Arc::new(BmsMarginalJacobian {
1649        marginal_dense: Arc::clone(&marginal_dense),
1650        logslope_dense,
1651        offset_m: offset_m.clone(),
1652        offset_s,
1653        p_marginal,
1654    });
1655    let (penalties, nullspace_dims, initial_log_lambdas) =
1656        marginal_penalties_with_influence_ridge(design, &rho, influence_columns)?;
1657    Ok(ParameterBlockSpec {
1658        name: "marginal_surface".to_string(),
1659        design: DesignMatrix::Dense(gam_linalg::matrix::DenseDesignMatrix::from(
1660            (*marginal_dense).clone(),
1661        )),
1662        offset: offset_m,
1663        penalties,
1664        nullspace_dims,
1665        initial_log_lambdas,
1666        initial_beta: widen_marginal_beta_hint(beta_hint, p_marginal),
1667        // Canonical-gauge architecture (issue #322): give marginal_surface
1668        // strictly higher priority than logslope_surface so the priority-
1669        // ordered RRQR in `canonicalize_for_identifiability` presents
1670        // marginal columns first and routes any cross-block alias drop into
1671        // logslope.  Equal priorities (the previous default of 100/100)
1672        // produced a same-priority `hard_alias_pair` whenever a
1673        // high-dimensional smooth — e.g. `s(x, type=duchon, centers>=6)`
1674        // in the location block — accidentally spanned the logslope basis
1675        // direction, leaving the joint Hessian with a structural null and
1676        // the spectral Newton solve refusing to step.  The values mirror
1677        // the canonical-gauge entry for survival marginal-slope
1678        // (marginal=150, logslope=120).
1679        gauge_priority: GAUGE_PRIORITY_MARGINAL,
1680        jacobian_callback: Some(callback),
1681        stacked_design: None,
1682        stacked_offset: None,
1683    })
1684}
1685
1686pub(crate) fn build_logslope_blockspec_bms(
1687    design: &TermCollectionDesign,
1688    baseline: f64,
1689    offset: &Array1<f64>,
1690    rho: Array1<f64>,
1691    beta_hint: Option<Array1<f64>>,
1692    marginal_design: &TermCollectionDesign,
1693    marginal_offset: &Array1<f64>,
1694    marginal_baseline: f64,
1695    z: Arc<Array1<f64>>,
1696    p_marginal: usize,
1697    influence_columns: Option<&Array2<f64>>,
1698) -> Result<ParameterBlockSpec, String> {
1699    let offset_s = offset + baseline;
1700    let offset_m = marginal_offset + marginal_baseline;
1701    let raw_marginal_dense = marginal_design
1702        .design
1703        .try_to_dense_arc("build_logslope_blockspec_bms::marginal")?;
1704    // The logslope Jacobian reconstructs q_i = M·β_m + offset_m; with the
1705    // absorbed influence columns folded into the marginal index, the marginal
1706    // reference design and p_marginal MUST be the widened [M | Z̃] / (p_m+p₁)
1707    // so β_m slices to the absorber and q_i carries the Z̃·γ shift (#461).
1708    let marginal_dense =
1709        widen_marginal_dense_with_influence(&raw_marginal_dense, influence_columns)?;
1710    let logslope_dense = design
1711        .design
1712        .try_to_dense_arc("build_logslope_blockspec_bms::logslope")?;
1713    let callback: Arc<dyn BlockEffectiveJacobian> = Arc::new(BmsLogslopeJacobian {
1714        marginal_dense,
1715        logslope_dense: Arc::clone(&logslope_dense),
1716        offset_m,
1717        offset_s: offset_s.clone(),
1718        z,
1719        p_marginal,
1720    });
1721    Ok(ParameterBlockSpec {
1722        name: "logslope_surface".to_string(),
1723        design: DesignMatrix::Dense(gam_linalg::matrix::DenseDesignMatrix::from(
1724            (*logslope_dense).clone(),
1725        )),
1726        offset: offset_s,
1727        penalties: design.penalties_as_penalty_matrix(),
1728        nullspace_dims: design.nullspace_dims.clone(),
1729        initial_log_lambdas: rho,
1730        initial_beta: beta_hint,
1731        // Canonical-gauge architecture (issue #322): logslope is strictly
1732        // lower priority than marginal so the priority-ordered RRQR in
1733        // `canonicalize_for_identifiability` demotes a shared cross-block
1734        // direction here, not in marginal.  Mirrors the survival-mgs
1735        // value (marginal=150, logslope=120).  See the matching comment
1736        // on `build_marginal_blockspec_bms` for the failure mode this
1737        // resolves.
1738        gauge_priority: GAUGE_PRIORITY_LOGSLOPE,
1739        jacobian_callback: Some(callback),
1740        stacked_design: None,
1741        stacked_offset: None,
1742    })
1743}
1744
1745pub(crate) fn build_deviation_aux_blockspec(
1746    name: &str,
1747    prepared: &DeviationPrepared,
1748    rho: Array1<f64>,
1749    beta_hint: Option<Array1<f64>>,
1750) -> Result<ParameterBlockSpec, String> {
1751    let mut block = prepared.block.clone();
1752    block.initial_log_lambdas = Some(rho);
1753    let candidate_beta = beta_hint.or_else(|| Some(Array1::<f64>::zeros(block.design.ncols())));
1754    block.initial_beta = candidate_beta
1755        .map(|beta| {
1756            let zero = Array1::<f64>::zeros(beta.len());
1757            project_monotone_feasible_beta(&prepared.runtime, &zero, &beta, name)
1758        })
1759        .transpose()?;
1760    let mut spec = block.intospec(name)?;
1761    // Deviation auxiliary blocks (score_warp_dev, link_dev, and any
1762    // future flex block routed through this builder) model pure
1763    // shape modifications on top of parametric anchors. They must
1764    // never own a shared affine direction with the parametric
1765    // (time / marginal / logslope) blocks. The canonical-gauge
1766    // selector drops shared directions from blocks with lower
1767    // gauge_priority first; assigning a value below the parametric
1768    // default (GAUGE_PRIORITY_CANDIDATE_FLEX) realises that contract
1769    // automatically.
1770    spec.gauge_priority = match name {
1771        "link_dev" => GAUGE_PRIORITY_LINK_DEV,
1772        // score_warp_dev gets a slightly higher priority than link_dev
1773        // because in mixed-flex configurations (both blocks present)
1774        // link_dev is the residualised one (orthogonalised against the
1775        // parametric anchors PLUS the already-prepared score_warp
1776        // basis at construction time); link_dev should therefore yield
1777        // first when an alias still survives into the joint design.
1778        "score_warp_dev" => GAUGE_PRIORITY_SCORE_WARP_DEV,
1779        _ => GAUGE_PRIORITY_DEVIATION_DEFAULT,
1780    };
1781    Ok(spec)
1782}
1783
1784pub(crate) fn push_deviation_aux_blockspecs(
1785    blocks: &mut Vec<ParameterBlockSpec>,
1786    rho: &Array1<f64>,
1787    cursor: &mut usize,
1788    score_warp_prepared: Option<&DeviationPrepared>,
1789    link_dev_prepared: Option<&DeviationPrepared>,
1790    score_warp_beta_hint: Option<Array1<f64>>,
1791    link_dev_beta_hint: Option<Array1<f64>>,
1792) -> Result<(), String> {
1793    if let Some(prepared) = score_warp_prepared {
1794        let rho_h = rho
1795            .slice(s![*cursor..*cursor + prepared.block.penalties.len()])
1796            .to_owned();
1797        *cursor += prepared.block.penalties.len();
1798        blocks.push(build_deviation_aux_blockspec(
1799            "score_warp_dev",
1800            prepared,
1801            rho_h,
1802            score_warp_beta_hint,
1803        )?);
1804    }
1805    if let Some(prepared) = link_dev_prepared {
1806        let rho_w = rho
1807            .slice(s![*cursor..*cursor + prepared.block.penalties.len()])
1808            .to_owned();
1809        blocks.push(build_deviation_aux_blockspec(
1810            "link_dev",
1811            prepared,
1812            rho_w,
1813            link_dev_beta_hint,
1814        )?);
1815    }
1816    Ok(())
1817}
1818
1819fn inner_fit(
1820    family: &BernoulliMarginalSlopeFamily,
1821    blocks: &[ParameterBlockSpec],
1822    options: &BlockwiseFitOptions,
1823) -> Result<UnifiedFitResult, String> {
1824    let mut options = options.clone();
1825    // BMS carries fixed physical ridge penalties that regularize coefficient
1826    // geometry but are not REML coordinates. The exact hyper-Hessian route can
1827    // stall after that projection; the family has a dedicated exact-gradient
1828    // path with full-data polish, so make it the primary nested smoother.
1829    options.use_outer_hessian = false;
1830    options.outer_tol = options.outer_tol.max(2.0e-5);
1831    fit_custom_family(family, blocks, &options).map_err(|e| e.to_string())
1832}
1833
1834pub fn fit_bernoulli_marginal_slope_terms(
1835    data: ArrayView2<'_, f64>,
1836    spec: BernoulliMarginalSlopeTermSpec,
1837    options: &BlockwiseFitOptions,
1838    kappa_options: &SpatialLengthScaleOptimizationOptions,
1839    policy: &gam_runtime::resource::ResourcePolicy,
1840) -> Result<BernoulliMarginalSlopeFitResult, String> {
1841    let mut spec = spec;
1842    let data_view = data;
1843    validate_spec(data_view, &spec)?;
1844    // Freeze the measure-jet representer length-scale dial on the coupled
1845    // marginal + log-slope surfaces (#1116). A shared mjs basis feeds BOTH
1846    // blocks; a design-moving ℓ on those shared covariates lets the outer
1847    // search reach a sharp ℓ where a marginal smooth direction trades off
1848    // against the log-slope into a separation-scale runaway (|β|→1e3). The auto
1849    // (frozen) ℓ is well-conditioned here — the pre-#1116 behavior this
1850    // restores. ℓ-learning stays on for single-surface (e.g. Gaussian) fits,
1851    // where there is no marginal/log-slope coupling to destabilize.
1852    let mjs_frozen_marginal =
1853        gam_terms::smooth::freeze_measure_jet_length_scale_learning(&mut spec.marginalspec);
1854    let mjs_frozen_logslope =
1855        gam_terms::smooth::freeze_measure_jet_length_scale_learning(&mut spec.logslopespec);
1856    if mjs_frozen_marginal + mjs_frozen_logslope > 0 {
1857        log::info!(
1858            "[BMS spatial] froze measure-jet length-scale learning on {} marginal + {} log-slope \
1859             term(s): the coupled surface keeps ℓ at its conditioned auto value (#1116)",
1860            mjs_frozen_marginal,
1861            mjs_frozen_logslope
1862        );
1863    }
1864    let mut effective_kappa_options = kappa_options.clone();
1865    // Honor explicit `length_scale=X` in the user's formula: when every
1866    // spatial term in BOTH the marginal mean and log-slope blocks carries
1867    // a user-supplied scalar length scale and no per-axis anisotropy is
1868    // requested, there is nothing for the joint-spatial outer optimizer
1869    // to do. Routing through it anyway spends ~80 outer ARC iters stalled
1870    // at the user's chosen ρ (the n-block ARC's first proposed step lands
1871    // at the box corner and never recovers), then falls through to the
1872    // ρ-only "custom family" path which is what we wanted all along.
1873    // Short-circuit straight to the ρ-only path.
1874    let kappa_locked_marginal =
1875        gam_terms::smooth::all_spatial_terms_kappa_fixed(&spec.marginalspec);
1876    let kappa_locked_logslope =
1877        gam_terms::smooth::all_spatial_terms_kappa_fixed(&spec.logslopespec);
1878    if effective_kappa_options.enabled && kappa_locked_marginal && kappa_locked_logslope {
1879        log::info!(
1880            "[BMS spatial] disabling κ/ψ optimization: every spatial term has an \
1881             explicit length_scale and no anisotropy; user-supplied kernel scale is fixed"
1882        );
1883        effective_kappa_options.enabled = false;
1884    }
1885    let flex_spatial_pilot_path = (spec.score_warp.is_some() || spec.link_dev.is_some())
1886        && spec.y.len() >= BMS_FLEX_SPATIAL_OUTER_PILOT_ROW_THRESHOLD
1887        && effective_kappa_options.enabled;
1888    if flex_spatial_pilot_path {
1889        let marginal_terms = spatial_length_scale_term_indices(&spec.marginalspec);
1890        let logslope_terms = spatial_length_scale_term_indices(&spec.logslopespec);
1891        let marginal_updates = apply_spatial_anisotropy_pilot_initializer(
1892            data_view,
1893            &mut spec.marginalspec,
1894            &marginal_terms,
1895            effective_kappa_options.pilot_subsample_threshold,
1896            &effective_kappa_options,
1897        );
1898        let logslope_updates = apply_spatial_anisotropy_pilot_initializer(
1899            data_view,
1900            &mut spec.logslopespec,
1901            &logslope_terms,
1902            effective_kappa_options.pilot_subsample_threshold,
1903            &effective_kappa_options,
1904        );
1905        effective_kappa_options.enabled = false;
1906        log::info!(
1907            "[BMS spatial] n={} flex=true pilot_geometry_updates={} iterative_spatial_outer=false reason=large-flex-spatial-pilot",
1908            spec.y.len(),
1909            marginal_updates + logslope_updates,
1910        );
1911    }
1912    let (z_standardized, z_normalization) = standardize_latent_z_with_policy(
1913        &spec.z,
1914        &spec.weights,
1915        "bernoulli-marginal-slope",
1916        &spec.latent_z_policy,
1917    )?;
1918    spec.z = z_standardized;
1919    let sigma_learnable = matches!(
1920        &spec.frailty,
1921        FrailtySpec::GaussianShift { sigma_fixed: None }
1922    );
1923    let initial_sigma = match &spec.frailty {
1924        FrailtySpec::GaussianShift {
1925            sigma_fixed: Some(s),
1926        } => Some(*s),
1927        FrailtySpec::GaussianShift { sigma_fixed: None } => Some(0.5),
1928        FrailtySpec::None => None,
1929        FrailtySpec::HazardMultiplier { .. } => {
1930            return Err(
1931                "internal: validate_spec should have rejected unsupported marginal-slope frailty"
1932                    .to_string(),
1933            );
1934        }
1935    };
1936    let probit_scale = probit_frailty_scale(initial_sigma);
1937    let (_raw_joint_designs, mut joint_specs) = build_term_collection_designs_and_freeze_joint(
1938        data_view,
1939        &[spec.marginalspec.clone(), spec.logslopespec.clone()],
1940    )
1941    .map_err(|e| e.to_string())?;
1942    let marginalspec_boot = joint_specs.remove(0);
1943    let logslopespec_boot = joint_specs.remove(0);
1944    // Rebuild the probe designs from the frozen `*_boot` specs so the probe's
1945    // penalty topology matches the topology produced by every other build path
1946    // in this optimization. The spatial optimizer's own bootstrap
1947    // (`build_term_collection_designs_and_freeze_joint(data, &[marginalspec_boot,
1948    // logslopespec_boot])` inside `optimize_spatial_length_scale_exact_joint`)
1949    // and every subsequent kappa-driven rebuild feed the basis builder the
1950    // captured `FrozenTransform` identifiability. Applying that captured
1951    // transform to the same kernel can land the structural null-space block on
1952    // the other side of `build_nullspace_shrinkage_penalty`'s spectral
1953    // tolerance, so the raw and frozen builds disagree on whether the trend
1954    // ridge survives as an active penalty candidate. Without this rebuild,
1955    // `marginal_penalty_count` / `logslope_design.penalties.len()` are taken
1956    // from the raw build but every subsequent evaluator measures the frozen
1957    // build, and `evaluate_custom_family_joint_hyper` refuses with a
1958    // "joint hyper rho dimension mismatch". Mirrors the CTN-side fix in
1959    // `fit_transformation_normal`.
1960    let (mut joint_designs, _) = build_term_collection_designs_and_freeze_joint(
1961        data_view,
1962        &[marginalspec_boot.clone(), logslopespec_boot.clone()],
1963    )
1964    .map_err(|e| format!("failed to rebuild frozen probe BMS joint designs: {e}"))?;
1965    let marginal_design = joint_designs.remove(0);
1966    let logslope_design = joint_designs.remove(0);
1967    // #905: the conditional `E[z|C]`/`Var(z|C)` Rao gate conditions on the
1968    // marginal-index span a(C) (= the marginal design columns), which is
1969    // exactly where the `b(C)·m(C)` leakage lives. It is engaged only on the
1970    // raw-z path (no CTN Stage-1 influence absorber); when an absorber is
1971    // active the conditional leakage is already absorbed (#461) and the
1972    // widened-marginal predict seam must not be perturbed by replacing z.
1973    let absorber_active = spec
1974        .score_influence_jacobian
1975        .as_ref()
1976        .is_some_and(|j| j.ncols() > 0);
1977    let conditioning_dense = if absorber_active {
1978        None
1979    } else {
1980        Some(
1981            marginal_design
1982                .design
1983                .try_to_dense_arc("bernoulli marginal-slope conditional latent-z gate")?,
1984        )
1985    };
1986    let (latent_measure, latent_z_calibration) = build_latent_measure_with_geometry(
1987        &spec.z,
1988        &spec.weights,
1989        &spec.latent_z_policy,
1990        conditioning_dense.as_ref().map(|d| d.view()),
1991    )?;
1992    if latent_measure.is_empirical() && sigma_learnable {
1993        return Err("empirical latent-measure marginal-slope calibration requires fixed GaussianShift sigma; learnable sigma derivatives must be fit under the standard-normal latent measure"
1994                    .to_string());
1995    }
1996
1997    let y = Arc::new(spec.y.clone());
1998    let weights = Arc::new(spec.weights.clone());
1999    // Apply rank-INT calibration to training z before any downstream
2000    // consumer (pooled probit baseline, term-collection designs, the
2001    // family's PIRLS loops) sees it. The calibration is persisted on the
2002    // fit result so prediction applies the identical monotone map.
2003    let z = match &latent_z_calibration {
2004        LatentMeasureCalibration::None => Arc::new(spec.z.clone()),
2005        LatentMeasureCalibration::RankInverseNormal(cal) => {
2006            Arc::new(cal.apply_to_training(&spec.z)?)
2007        }
2008        LatentMeasureCalibration::ConditionalLocationScale(cal) => {
2009            // ζ = (z − m(C))/√v(C) on the marginal-index span. The conditioning
2010            // block was built above (raw-z path only), so it is present here.
2011            let a_block = conditioning_dense.as_ref().ok_or_else(|| {
2012                "conditional latent calibration requires the marginal conditioning block"
2013                    .to_string()
2014            })?;
2015            Arc::new(cal.apply(spec.z.view(), a_block.view())?)
2016        }
2017    };
2018    let z_train = z.as_ref();
2019    let pilot_baseline = pooled_probit_baseline(&spec.y, z_train, &spec.weights)?;
2020    let baseline = (
2021        bernoulli_marginal_slope_eta_from_probability(
2022            &spec.base_link,
2023            normal_cdf(pilot_baseline.0),
2024            "bernoulli marginal-slope baseline link inversion",
2025        )?,
2026        pilot_baseline.1 / probit_scale,
2027    );
2028
2029    // Score-warp basis construction is β-independent (identifiability is
2030    // provided by the smoothness-null-space drop on the basis transform,
2031    // not by a data-distribution moment anchor at the rigid-pilot η₀), so
2032    // the standard-normal and empirical latent-measure branches build the
2033    // same block. There is no row-weight pilot to thread into the basis;
2034    // the latent-measure split is enforced upstream via the empirical
2035    // intercept solve in `build_row_exact_context_with_stats`, not in the
2036    // deviation basis.
2037    // Score-warp basis is built first, then immediately reparameterised
2038    // against the parametric span (marginal + logslope columns at the n
2039    // training rows) so its column span is orthogonal to span(X_marginal,
2040    // X_logslope) by construction. This is the first half of the joint-
2041    // design identifiability invariant; the second half (link-deviation
2042    // orthogonalised against parametric + the now-reparameterised score-
2043    // warp) runs inside the link-deviation closure below. Together they
2044    // ensure `[X_marginal | X_logslope | Φ_score_warp · T_sw |
2045    // Φ_link_dev · T_lw]` has full numerical column rank, structurally
2046    // bounding `σ_min(joint H + S) ≥ λ_min(S) > 0` regardless of how β
2047    // drifts the linear predictor distribution during PIRLS.
2048    // Cross-block W-metric pilot. The joint penalised Hessian during PIRLS
2049    // uses the probit-style data Hessian row metric
2050    //
2051    //   W_pirls[i] = spec.weights[i] · φ(η_i)² / (μ_i·(1−μ_i))
2052    //
2053    // which is the canonical IRLS row weight. The cross-block
2054    // orthogonalisation below must use this metric (not uniform
2055    // spec.weights) so that `Aᵀ W C̃ = 0` holds in the same inner product
2056    // the joint Hessian sees — otherwise A and C̃ are merely Euclidean-
2057    // orthogonal, `Aᵀ W_pirls C̃ ≠ 0`, the joint Hessian carries a near-
2058    // null direction along the W-metric alias, and REML can drive the
2059    // flex block's λ small enough that the alias direction's joint
2060    // Hessian eigenvalue collapses. β then runs away along the alias
2061    // (manifest as `rho≈2.0`, constant `step_inf`, growing `beta_inf`
2062    // during PIRLS, and the inner solve hitting `inner_max_cycles`
2063    // without satisfying the KKT residual).
2064    //
2065    // Use the rigid pooled-probit pilot η for score-warp (its basis is
2066    // β-independent in z, so the rigid pilot suffices) and the one-GN-
2067    // stepped pilot η for link-deviation (its basis is evaluated at the
2068    // same eta_pilot used here, so the orthogonalisation metric matches
2069    // the basis evaluation point exactly). Both are β-independent so the
2070    // orthogonalisation remains a one-shot construction-time step.
2071    let rigid_pilot_eta = rigid_pooled_probit_pilot_eta(
2072        &spec.base_link,
2073        z_train,
2074        &spec.marginal_offset,
2075        &spec.logslope_offset,
2076        baseline.0,
2077        baseline.1,
2078        probit_scale,
2079    )?;
2080    let cross_block_pilot_w_score_warp =
2081        pilot_irls_hessian_row_metric_at_eta(&rigid_pilot_eta, &spec.weights);
2082
2083    // Absorbed Stage-1 influence columns (#461, design §3). When the workflow
2084    // chained a CTN Stage-1 into this marginal-slope fit, `spec.score_influence_
2085    // jacobian` carries the out-of-fold `J = ∂z/∂θ₁`; the realized leakage
2086    // directions `Z_infl = diag(s_f·β̂₀)·J` are residualised against the fitted
2087    // marginal+logslope target span and appended to the additive marginal-index
2088    // block as a fixed-ridge absorber, so the joint penalised solve makes the
2089    // (α,β) score orthogonal to the remaining nuisance span without letting the
2090    // absorber compete for identifiable β(x) signal. `None` ⇒ raw z, and the
2091    // free score_warp spline below is the x-free-column fallback. β̂₀(x_i) is
2092    // the rigid-pilot logslope `baseline.1 + logslope_offset[i]`; s_f =
2093    // probit_scale.
2094    let influence_columns = if let Some(jac) = spec
2095        .score_influence_jacobian
2096        .as_ref()
2097        .filter(|j| j.ncols() > 0)
2098    {
2099        let protected_design = DesignMatrix::hstack(vec![
2100            marginal_design.design.clone(),
2101            logslope_design.design.clone(),
2102        ])
2103        .map_err(|e| {
2104            format!(
2105                "bernoulli marginal-slope influence-block protected projection stack failed to concatenate marginal + logslope design: {e}"
2106            )
2107        })?;
2108        let protected_dense_for_proj = protected_design
2109            .try_to_dense_arc("bernoulli marginal-slope influence-block protected projection")?;
2110        let protected_dense = protected_dense_for_proj.as_ref();
2111        if jac.nrows() != protected_dense.nrows() {
2112            return Err(format!(
2113                "influence block: Jacobian has {} rows, protected design has {}",
2114                jac.nrows(),
2115                protected_dense.nrows()
2116            ));
2117        }
2118        // Z̃ = residualize(diag(s_f·β̂₀)·J) against the fitted target span in
2119        // the rigid-pilot W-metric.  For BMS the absorbed columns are installed
2120        // in the same additive predictor as the marginal surface; if we protect
2121        // only M, any component of Z_infl aligned with the logslope design G can
2122        // be assigned to the fixed-ridge absorber by the joint solve, erasing
2123        // genuine β(x) heterogeneity.  Projecting out [M | G] keeps the nuisance
2124        // absorber orthogonal to both parametric target surfaces while still
2125        // absorbing Stage-1 leakage directions outside that identifiable target
2126        // span. β̂₀(x_i) = baseline.1 + logslope_offset[i]; s_f = probit_scale;
2127        // W = the rigid-pilot PIRLS row metric.
2128        let rigid_logslope_at_rows = &spec.logslope_offset + baseline.1;
2129        let residualized = crate::marginal_slope_orthogonal::residualized_influence_block(
2130            jac,
2131            z_train,
2132            &rigid_logslope_at_rows,
2133            probit_scale,
2134            protected_dense.view(),
2135            &cross_block_pilot_w_score_warp,
2136        )?;
2137        Some(residualized)
2138    } else {
2139        None
2140    };
2141    let mut cross_block_warnings: Vec<CrossBlockIdentifiabilityWarning> = Vec::new();
2142    let score_warp_prepared = if let Some(cfg) = spec.score_warp.as_ref() {
2143        use super::deviation_runtime::ParametricAnchorBlock;
2144        let mut prepared = build_score_warp_deviation_block_from_seed(z_train, cfg)?;
2145        // `install_compiled_flex_block_into_runtime` now delegates
2146        // its math body to `identifiability::families::compiler::compile` (commit
2147        // 4e20b8dc8); the prior Phase-4a shadow compile here was a
2148        // duplicate of that internal call and has been removed.
2149        let outcome = install_compiled_flex_block_into_runtime(
2150            &mut prepared,
2151            z_train,
2152            cfg,
2153            &[
2154                (&marginal_design.design, ParametricAnchorBlock::Marginal),
2155                (&logslope_design.design, ParametricAnchorBlock::Logslope),
2156            ],
2157            &[],
2158            &cross_block_pilot_w_score_warp,
2159        )?;
2160        match outcome {
2161            FlexCompileOutcome::Reparameterised => Some(prepared),
2162            FlexCompileOutcome::FullyAliased { reason } => {
2163                // Record via the structured channel. Keep the original
2164                // (non-compiled) design so the unified audit sees score_warp_dev
2165                // and attributes the drop via dropped_columns (gauge_priority=80
2166                // is below marginal=150 / logslope=120, so RRQR correctly
2167                // demotes score_warp_dev when it aliases those blocks).
2168                cross_block_warnings.push(CrossBlockIdentifiabilityWarning {
2169                    candidate_label: "score_warp",
2170                    anchor_summary: "marginal+logslope".to_string(),
2171                    reason,
2172                });
2173                Some(prepared)
2174            }
2175        }
2176    } else {
2177        None
2178    };
2179    // Build the link-deviation block. The basis lives in η-space, and at
2180    // PIRLS time `runtime.design(η_current)` is re-evaluated at the
2181    // current β-dependent η, so the basis is genuinely β-dependent during
2182    // optimisation. The construction-time seed is used only for (a) knot
2183    // placement in η-space and (b) the cross-block identifiability check
2184    // that computes the basis-space transform `T` orthogonalising the
2185    // candidate against the parametric and score-warp anchors at training
2186    // rows.
2187    //
2188    // Using the rigid pooled probit pilot directly (`q0 = a₀·√(…) + s_f·
2189    // b₀·z`) is structurally degenerate: with zero per-row offsets it is
2190    // affine in z, so a degree-3 I-spline of `q0` spans the same column
2191    // space at training rows as a degree-3 I-spline of z, and the cross-
2192    // block check finds the candidate fully aliased by the score-warp
2193    // anchor even though at any non-rigid β the link-deviation carries
2194    // PC/age structure the score-warp cannot represent.
2195    //
2196    // Instead, seed both knot placement and the orthogonalisation pivot at
2197    // a non-rigid pilot η computed via one probit Gauss-Newton step from
2198    // the rigid pilot onto the full marginal design (see
2199    // `pilot_eta_for_link_dev_orthogonalisation`). The pilot is row-varying
2200    // in PCs/age and the resulting `T` drops only directions aliased
2201    // across all β. The score-warp basis at training rows is also threaded
2202    // in as a flex anchor when active so the kept directions are jointly
2203    // orthogonal to parametric ⊕ score-warp.
2204    let link_dev_prepared = if let Some(cfg) = spec.link_dev.as_ref() {
2205        let eta_pilot = pilot_eta_for_link_dev_orthogonalisation(
2206            &spec.base_link,
2207            &spec.y,
2208            z_train,
2209            &spec.weights,
2210            &marginal_design.design,
2211            &spec.marginal_offset,
2212            &spec.logslope_offset,
2213            baseline.0,
2214            baseline.1,
2215            probit_scale,
2216        )?;
2217        let link_dev_seed = padded_deviation_seed(&eta_pilot, 1.0, 0.5);
2218        let mut prepared = build_link_deviation_block_from_knots_design_seed_and_weights(
2219            &link_dev_seed,
2220            &eta_pilot,
2221            cfg,
2222        )?;
2223        // Cross-block identifiability for the link-deviation basis. The
2224        // anchor union covers BOTH possible aliasing channels:
2225        //
2226        //  - Parametric: location and logslope designs evaluated at the n
2227        //    training rows. Columns of `Φ_link_dev(q0)` that reproduce
2228        //    parametric features become null-direction targets in the
2229        //    joint penalised Hessian since `S_link_dev` has no mass on
2230        //    them.
2231        //
2232        //  - Score-warp (when active): the now-reparameterised score-warp
2233        //    basis, also evaluated at training rows. Both flex bases are
2234        //    cubic I-spline cubic combinations of an η-pilot scalar, and
2235        //    even with each block's own smoothness-null-space drop their
2236        //    column spans can still overlap inside the orthogonal
2237        //    complement of `{1, η_pilot}`.
2238        //
2239        // After the orthogonalisation, `[X_marginal | X_logslope |
2240        // Φ_score_warp · T_sw | Φ_link_dev · T_lw]` has full numerical
2241        // column rank at training rows, so `σ_min(joint H+S) ≥ λ_min(S)
2242        // > 0` for every β. This is the standard GAM `gam.side`
2243        // convention generalised to multi-anchor unions (mgcv applies it
2244        // sequentially across smooths sharing a covariate).
2245        // When `install_compiled_flex_block_into_runtime`
2246        // reparameterised the score-warp runtime against the parametric
2247        // anchor union (marginal + logslope), it installed an
2248        // `anchor_residual` and cached the training-row parametric
2249        // anchor matrix on the runtime. `runtime.design()` on a
2250        // residualised runtime returns the *raw* basis evaluation,
2251        // which `assert`s the caller hasn't conflated with the
2252        // reparameterised basis — we want the reparameterised one
2253        // here, so go through `design_at_training_with_residual` so
2254        // the cached anchor rows are folded in. For score-warp
2255        // configurations where reparameterisation was a no-op (no
2256        // residual installed) the same call falls back to the raw
2257        // `design()` path, so the residual-vs-no-residual branches
2258        // converge on the right matrix.
2259        let score_warp_anchor_design = score_warp_prepared
2260            .as_ref()
2261            .map(|sw| sw.runtime.design_at_training_with_residual(z_train))
2262            .transpose()?;
2263        use super::deviation_runtime::ParametricAnchorBlock;
2264        let parametric_anchors: [(&DesignMatrix, ParametricAnchorBlock); 2] = [
2265            (&marginal_design.design, ParametricAnchorBlock::Marginal),
2266            (&logslope_design.design, ParametricAnchorBlock::Logslope),
2267        ];
2268        let flex_anchor_slot: Option<&Array2<f64>> = score_warp_anchor_design.as_ref();
2269        let flex_anchors: Vec<&Array2<f64>> = flex_anchor_slot.into_iter().collect();
2270        // W-metric for link-deviation orthogonalisation: same IRLS-style
2271        // probit Hessian row weight as the score-warp path, but evaluated at
2272        // `eta_pilot` (the one-GN-stepped pilot at which the link-dev basis
2273        // itself is anchored).
2274        let cross_block_pilot_w_link_dev =
2275            pilot_irls_hessian_row_metric_at_eta(&eta_pilot, &spec.weights);
2276        let outcome = install_compiled_flex_block_into_runtime(
2277            &mut prepared,
2278            &eta_pilot,
2279            cfg,
2280            &parametric_anchors,
2281            &flex_anchors,
2282            &cross_block_pilot_w_link_dev,
2283        )?;
2284        match outcome {
2285            FlexCompileOutcome::Reparameterised => Some(prepared),
2286            FlexCompileOutcome::FullyAliased { reason } => {
2287                // Record via the structured channel. Keep the original
2288                // (non-compiled) design so the unified audit sees link_dev
2289                // and attributes the drop via dropped_columns (gauge_priority=60
2290                // is below all parametric blocks so RRQR correctly demotes
2291                // link_dev when it aliases marginal / logslope / score_warp).
2292                cross_block_warnings.push(CrossBlockIdentifiabilityWarning {
2293                    candidate_label: "link_deviation",
2294                    anchor_summary: "marginal+logslope+score_warp".to_string(),
2295                    reason,
2296                });
2297                Some(prepared)
2298            }
2299        }
2300    } else {
2301        None
2302    };
2303    let extra_rho0 = {
2304        let mut out = Vec::new();
2305        if let Some(ref prepared) = score_warp_prepared {
2306            out.extend(std::iter::repeat_n(0.0, prepared.block.penalties.len()));
2307        }
2308        if let Some(ref prepared) = link_dev_prepared {
2309            out.extend(std::iter::repeat_n(0.0, prepared.block.penalties.len()));
2310        }
2311        out
2312    };
2313    // Reduced-basis orthogonalisation of the logslope design through the BMS
2314    // family's OWN internal `logslope_design` geometry (robust cure for the
2315    // marginal↔logslope structural confound). Robustness is unconditional, so we
2316    // always reparameterize the logslope coordinate space to a full-rank reduced
2317    // basis `T` whose effective weighted columns are W-orthogonal to the marginal
2318    // span at the rigid pilot — removing the rank-soft confounded direction the
2319    // former pinned overlap ridge merely penalised. The transform is
2320    // β/ρ-independent (pilot geometry only), so it is a one-shot construction-
2321    // time map applied to every per-iteration logslope design inside
2322    // `build_blocks` / `make_family`, and inverted at fit-result assembly so the
2323    // reported logslope β is in the original basis. `None` ⇒ nothing to reduce
2324    // (no rank-soft confounded direction) ⇒ raw design used everywhere.
2325    let logslope_reduced_reparam: Option<ReducedLogslopeReparam> = build_reduced_logslope_reparam(
2326        &marginal_design,
2327        &logslope_design,
2328        z.as_ref(),
2329        &cross_block_pilot_w_score_warp,
2330        &spec.marginal_offset,
2331        &spec.logslope_offset,
2332        baseline.0,
2333        baseline.1,
2334        probit_scale,
2335    )?;
2336    // Apply the reduced reparam to a logslope `TermCollectionDesign`, or return
2337    // the raw design clone when the reparam is absent (flag off / nothing to
2338    // reduce). Used by both `build_blocks` and `make_family` so the family's
2339    // internal design, the block design, β width, jacobian, penalty, and the
2340    // `validate_exact_block_state_shapes` check all agree at the reduced width.
2341    let reduce_logslope_design =
2342        |logslope_design: &TermCollectionDesign| -> Result<TermCollectionDesign, String> {
2343            match logslope_reduced_reparam.as_ref() {
2344                Some(reparam) => reparameterize_logslope_design_reduced(logslope_design, reparam),
2345                None => Ok(logslope_design.clone()),
2346            }
2347        };
2348
2349    // With the #461 influence absorber active, the marginal block carries one
2350    // extra REML-learned ρ coordinate (the absorber ridge precision), seeded
2351    // at the ln(n) leakage scale and clamped into the outer ρ box.
2352    let absorber_slots = usize::from(influence_columns.is_some());
2353    let absorber_rho0 = influence_columns
2354        .as_ref()
2355        .map(|_| influence_absorber_log_lambda(spec.z.len()).clamp(-12.0, 12.0));
2356    let marginal_penalty_count = marginal_design.penalties.len() + absorber_slots;
2357    let setup = joint_setup(
2358        data_view,
2359        &marginalspec_boot,
2360        &logslopespec_boot,
2361        marginal_penalty_count,
2362        logslope_design.penalties.len(),
2363        absorber_rho0,
2364        &extra_rho0,
2365        &effective_kappa_options,
2366    );
2367    let setup = if sigma_learnable {
2368        setup.with_auxiliary(
2369            Array1::from_vec(vec![initial_sigma.expect("learnable sigma seed").ln()]),
2370            Array1::from_vec(vec![0.01_f64.ln()]),
2371            Array1::from_vec(vec![5.0_f64.ln()]),
2372        )
2373    } else {
2374        setup
2375    };
2376    let final_sigma_cell = std::cell::Cell::new(initial_sigma);
2377    let exact_warm_start = RefCell::new(None::<CustomFamilyWarmStart>);
2378    let runaway_error = RefCell::new(None::<String>);
2379    // Outer ρ-cache β-seed staging slot. On a cache hit the spatial-joint
2380    // optimizer invokes `seed_inner_beta_fn` before the first eval at the
2381    // restored ρ: per-block column widths aren't known until the first
2382    // `build_blocks(rho, …)` runs, so we stash the flat β here and the eval
2383    // closures promote it into `exact_warm_start` (the slot the inner
2384    // PIRLS / Newton solve actually consumes) on their first invocation.
2385    let pending_beta_seed = RefCell::new(None::<Array1<f64>>);
2386    let hints = RefCell::new(ThetaHints::default());
2387    let score_warp_runtime = score_warp_prepared.as_ref().map(|p| p.runtime.clone());
2388    let link_dev_runtime = link_dev_prepared.as_ref().map(|p| p.runtime.clone());
2389
2390    let build_blocks = |rho: &Array1<f64>,
2391                        marginal_design: &TermCollectionDesign,
2392                        logslope_design: &TermCollectionDesign|
2393     -> Result<Vec<ParameterBlockSpec>, String> {
2394        let hints = hints.borrow();
2395        let mut cursor = 0usize;
2396        // Reduced-basis orthogonalisation: replace the per-iteration logslope
2397        // design with its full-rank reduced reparameterization `G·T` (flag ON);
2398        // a no-op clone when off. The reduced design carries the SAME number of
2399        // penalties (each S → Tᵀ S T), so the `rho_logslope` slice width below
2400        // is unchanged. Every consumer (marginal jacobian's c_i, logslope
2401        // blockspec design/β/penalty/jacobian) now agrees at the reduced width.
2402        let logslope_design_reduced = reduce_logslope_design(logslope_design)?;
2403        let logslope_design = &logslope_design_reduced;
2404        // The marginal slice carries the genuine smooth penalties plus, when
2405        // the #461 influence absorber is active, one TRAILING coordinate for
2406        // the absorber ridge — its precision is REML-learned like every other
2407        // penalty (seeded at the ln(n) leakage scale by `joint_setup`).
2408        let marginal_rho_len = marginal_design.penalties.len() + absorber_slots;
2409        let rho_marginal = rho.slice(s![cursor..cursor + marginal_rho_len]).to_owned();
2410        cursor += marginal_rho_len;
2411        let rho_logslope = rho
2412            .slice(s![cursor..cursor + logslope_design.penalties.len()])
2413            .to_owned();
2414        cursor += logslope_design.penalties.len();
2415        let p_m = marginal_design.design.ncols()
2416            + influence_columns.as_ref().map(|z| z.ncols()).unwrap_or(0);
2417        let mut blocks = vec![
2418            build_marginal_blockspec_bms(
2419                marginal_design,
2420                baseline.0,
2421                &spec.marginal_offset,
2422                rho_marginal,
2423                hints.marginal_beta.clone(),
2424                logslope_design,
2425                &spec.logslope_offset,
2426                baseline.1,
2427                p_m,
2428                influence_columns.as_ref(),
2429            )?,
2430            build_logslope_blockspec_bms(
2431                logslope_design,
2432                baseline.1,
2433                &spec.logslope_offset,
2434                rho_logslope,
2435                hints.logslope_beta.clone(),
2436                marginal_design,
2437                &spec.marginal_offset,
2438                baseline.0,
2439                Arc::clone(&z),
2440                p_m,
2441                influence_columns.as_ref(),
2442            )?,
2443        ];
2444        push_deviation_aux_blockspecs(
2445            &mut blocks,
2446            rho,
2447            &mut cursor,
2448            score_warp_prepared.as_ref(),
2449            link_dev_prepared.as_ref(),
2450            hints.score_warp_beta.clone(),
2451            hints.link_dev_beta.clone(),
2452        )?;
2453        Ok(blocks)
2454    };
2455
2456    let intercept_warm_starts = new_intercept_warm_start_cache(y.len());
2457    let cell_moment_lru = new_cell_moment_lru_cache(policy);
2458    let cell_moment_cache_stats = new_cell_moment_cache_stats();
2459    let make_family = |marginal_design: &TermCollectionDesign,
2460                       logslope_design: &TermCollectionDesign,
2461                       sigma: Option<f64>|
2462     -> BernoulliMarginalSlopeFamily {
2463        // The kernel reads the marginal index from a matched (self.marginal_
2464        // design, β_m) pair. When the Stage-1 influence absorber is active the
2465        // marginal β is widened to [β_m; γ], so the family's marginal design
2466        // MUST be the widened [M | Z̃] for every per-row projection to slice
2467        // correctly (#461). With no absorber it is the raw design unchanged.
2468        let kernel_marginal_design = match influence_columns.as_ref() {
2469            Some(z_infl) => {
2470                let raw = marginal_design
2471                    .design
2472                    .try_to_dense_arc("make_family::widened-marginal")
2473                    .expect("dense marginal design for influence widening");
2474                let widened = widen_marginal_dense_with_influence(&raw, Some(z_infl))
2475                    .expect("widen marginal design with influence columns");
2476                DesignMatrix::Dense(gam_linalg::matrix::DenseDesignMatrix::from(
2477                    (*widened).clone(),
2478                ))
2479            }
2480            None => marginal_design.design.clone(),
2481        };
2482        // The family's row kernel reconstructs η_logslope = G·β_s and the
2483        // logslope Jacobian factor_i·G_i from this matched (logslope_design,
2484        // β_s) pair, so it MUST be the SAME reduced design `G·T` the block specs
2485        // fit against — otherwise β_s (reduced width) and the family design
2486        // (full width) desync. A no-op clone when the reparam is absent.
2487        let kernel_logslope_design = reduce_logslope_design(logslope_design)
2488            .expect("reduce logslope design for family construction")
2489            .design;
2490        BernoulliMarginalSlopeFamily {
2491            y: Arc::clone(&y),
2492            weights: Arc::clone(&weights),
2493            z: Arc::clone(&z),
2494            latent_measure: latent_measure.clone(),
2495            gaussian_frailty_sd: sigma,
2496            base_link: spec.base_link.clone(),
2497            marginal_design: kernel_marginal_design,
2498            logslope_design: kernel_logslope_design,
2499            score_warp: score_warp_runtime.clone(),
2500            link_dev: link_dev_runtime.clone(),
2501            policy: policy.clone(),
2502            cell_moment_lru: Arc::clone(&cell_moment_lru),
2503            cell_moment_cache_stats: Arc::clone(&cell_moment_cache_stats),
2504            intercept_warm_starts: Some(Arc::clone(&intercept_warm_starts)),
2505            auto_subsample_phase_counter: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
2506            auto_subsample_last_rho: Arc::new(Mutex::new(None)),
2507        }
2508    };
2509
2510    let marginal_terms = spatial_length_scale_term_indices(&marginalspec_boot);
2511    let logslope_terms = spatial_length_scale_term_indices(&logslopespec_boot);
2512    let marginal_has_spatial = !marginal_terms.is_empty();
2513    let logslope_has_spatial = !logslope_terms.is_empty();
2514    let analytic_joint_derivatives_available =
2515        marginal_has_spatial || logslope_has_spatial || setup.log_kappa_dim() == 0;
2516    if setup.log_kappa_dim() > 0 && !analytic_joint_derivatives_available {
2517        return Err("exact bernoulli marginal-slope spatial optimization requires analytic joint psi derivatives"
2518                    .to_string());
2519    }
2520    let initial_rho = setup.theta0().slice(s![..setup.rho_dim()]).to_owned();
2521    let initial_blocks = build_blocks(&initial_rho, &marginal_design, &logslope_design)?;
2522    let initial_family = make_family(&marginal_design, &logslope_design, initial_sigma);
2523    let (joint_gradient, joint_hessian) =
2524        custom_family_outer_derivatives(&initial_family, &initial_blocks, options);
2525    let analytic_joint_gradient_available = analytic_joint_derivatives_available
2526        && matches!(joint_gradient, gam_problem::Derivative::Analytic);
2527    // Keep the analytic outer Hessian advertised at large scale. The
2528    // row-tensor terms below are represented through block-local
2529    // `HyperOperator`s and cached exact-Hessian workspaces, so ARC/trust-region
2530    // can consume exact HVPs without falling back to BFGS merely because the
2531    // realized problem is large.
2532    let analytic_joint_hessian_available =
2533        analytic_joint_derivatives_available && joint_hessian.is_analytic();
2534    let kappa_options_ref: &SpatialLengthScaleOptimizationOptions = &effective_kappa_options;
2535    let sigma_from_theta = |theta: &Array1<f64>| -> Option<f64> {
2536        if sigma_learnable {
2537            Some(theta[setup.rho_dim() + setup.log_kappa_dim()].exp())
2538        } else {
2539            initial_sigma
2540        }
2541    };
2542    let derivative_block_cache = RefCell::new(
2543        None::<(
2544            Array1<f64>,
2545            Arc<Vec<Vec<crate::custom_family::CustomFamilyBlockPsiDerivative>>>,
2546        )>,
2547    );
2548    let theta_matches = |left: &Array1<f64>, right: &Array1<f64>| -> bool {
2549        left.len() == right.len()
2550            && left
2551                .iter()
2552                .zip(right.iter())
2553                .all(|(lhs, rhs)| (*lhs - *rhs).abs() <= 1e-12 * (1.0 + lhs.abs().max(rhs.abs())))
2554    };
2555    let get_derivative_blocks = |theta: &Array1<f64>,
2556                                 specs: &[TermCollectionSpec],
2557                                 designs: &[TermCollectionDesign]|
2558     -> Result<
2559        Arc<Vec<Vec<crate::custom_family::CustomFamilyBlockPsiDerivative>>>,
2560        String,
2561    > {
2562        if let Some((cached_theta, cached_blocks)) = derivative_block_cache.borrow().as_ref()
2563            && theta_matches(cached_theta, theta)
2564        {
2565            return Ok(Arc::clone(cached_blocks));
2566        }
2567
2568        let built = |specs: &[TermCollectionSpec],
2569                     designs: &[TermCollectionDesign]|
2570         -> Result<
2571            Vec<Vec<crate::custom_family::CustomFamilyBlockPsiDerivative>>,
2572            String,
2573        > {
2574            let marginal_psi_derivs = if marginal_has_spatial {
2575                build_block_spatial_psi_derivatives(data_view, &specs[0], &designs[0])?.ok_or_else(
2576                    || {
2577                        "bernoulli marginal-slope: marginal block has spatial terms \
2578                         but spatial psi derivatives are unavailable"
2579                            .to_string()
2580                    },
2581                )?
2582            } else {
2583                Vec::new()
2584            };
2585            let logslope_psi_derivs = if logslope_has_spatial {
2586                build_block_spatial_psi_derivatives(data_view, &specs[1], &designs[1])?.ok_or_else(
2587                    || {
2588                        "bernoulli marginal-slope: logslope block has spatial terms \
2589                         but spatial psi derivatives are unavailable"
2590                            .to_string()
2591                    },
2592                )?
2593            } else {
2594                Vec::new()
2595            };
2596            let mut derivative_blocks = vec![marginal_psi_derivs, logslope_psi_derivs];
2597            if score_warp_runtime.is_some() {
2598                derivative_blocks.push(Vec::new());
2599            }
2600            if link_dev_runtime.is_some() {
2601                derivative_blocks.push(Vec::new());
2602            }
2603            if sigma_learnable {
2604                derivative_blocks
2605                    .last_mut()
2606                    .expect("bernoulli derivative block list is non-empty")
2607                    .push(crate::custom_family::CustomFamilyBlockPsiDerivative::new(
2608                        None,
2609                        Array2::zeros((0, 0)),
2610                        Array2::zeros((0, 0)),
2611                        None,
2612                        None,
2613                        None,
2614                        None,
2615                    ));
2616            }
2617            Ok(derivative_blocks)
2618        }(specs, designs)?;
2619        let built = Arc::new(built);
2620        derivative_block_cache.replace(Some((theta.clone(), Arc::clone(&built))));
2621        Ok(built)
2622    };
2623
2624    // Bernoulli marginal-slope is a multi-block family with β-dependent
2625    // joint Hessian: EFS/HybridEFS fixed-point structural invariant fails,
2626    // so we disable fixed-point at plan time rather than burning cycles on
2627    // a stalled first attempt that silently falls back.
2628    let outer_policy = {
2629        let psi_dim = setup.theta0().len() - setup.rho_dim();
2630        initial_family.outer_derivative_policy(&initial_blocks, psi_dim, options)
2631    };
2632    let exact_spatial_outer_tol = kappa_options_ref.rel_tol.max(EXACT_SPATIAL_OUTER_TOL_FLOOR);
2633    let solved = optimize_spatial_length_scale_exact_joint(
2634        data_view,
2635        &[marginalspec_boot.clone(), logslopespec_boot.clone()],
2636        &[marginal_terms.clone(), logslope_terms.clone()],
2637        kappa_options_ref,
2638        &setup,
2639        gam_solve::seeding::SeedRiskProfile::GeneralizedLinear,
2640        analytic_joint_gradient_available,
2641        analytic_joint_hessian_available,
2642        true,
2643        None,
2644        outer_policy,
2645        |theta, specs: &[TermCollectionSpec], designs: &[TermCollectionDesign]| {
2646            if let Some(err) = runaway_error.borrow().as_ref().cloned() {
2647                return Err(err);
2648            }
2649            assert_eq!(
2650                specs.len(),
2651                designs.len(),
2652                "spatial joint optimizer must supply one spec per design",
2653            );
2654            let rho = theta.slice(s![..setup.rho_dim()]).to_owned();
2655            let blocks = build_blocks(&rho, &designs[0], &designs[1])?;
2656            let sigma = sigma_from_theta(theta);
2657            final_sigma_cell.set(sigma);
2658            let family = make_family(&designs[0], &designs[1], sigma);
2659            let fit = inner_fit(&family, &blocks, options)?;
2660            if let Some(block) = fit.block_states.first()
2661                && let Some(err) = bernoulli_marginal_slope_runaway_error_from_beta(
2662                    block.beta.view(),
2663                    &designs[0],
2664                    &specs[0],
2665                    true,
2666                    "final fit",
2667                )
2668            {
2669                runaway_error.replace(Some(err.clone()));
2670                return Err(err);
2671            }
2672            let mut hints_mut = hints.borrow_mut();
2673            let mut bidx = 0usize;
2674            if let Some(block) = fit.block_states.get(bidx) {
2675                hints_mut.marginal_beta = Some(block.beta.clone());
2676            }
2677            bidx += 1;
2678            if let Some(block) = fit.block_states.get(bidx) {
2679                hints_mut.logslope_beta = Some(block.beta.clone());
2680            }
2681            bidx += 1;
2682            if score_warp_prepared.is_some() {
2683                if let Some(block) = fit.block_states.get(bidx) {
2684                    hints_mut.score_warp_beta = Some(block.beta.clone());
2685                }
2686                bidx += 1;
2687            }
2688            if link_dev_prepared.is_some()
2689                && let Some(block) = fit.block_states.get(bidx)
2690            {
2691                hints_mut.link_dev_beta = Some(block.beta.clone());
2692            }
2693            Ok(fit)
2694        },
2695        |theta,
2696         specs: &[TermCollectionSpec],
2697         designs: &[TermCollectionDesign],
2698         eval_mode,
2699         row_set: &crate::row_kernel::RowSet| {
2700            if let Some(err) = runaway_error.borrow().as_ref().cloned() {
2701                return Err(err);
2702            }
2703            use gam_problem::EvalMode;
2704            // One-shot row-measure waypoint. This closure runs on EVERY outer
2705            // objective evaluation (value/gradient/Hessian probes, line-search
2706            // cost-only probes, EFS evals), so an unconditional per-eval line
2707            // floods the biobank fit log with thousands of near-identical
2708            // entries. The bridge already emits a timed `[STAGE] outer eval`
2709            // marker per eval; this one records the row-measure exactly once.
2710            static BMS_OUTER_EVAL_ROWSET_LOGGED: std::sync::Once = std::sync::Once::new();
2711            BMS_OUTER_EVAL_ROWSET_LOGGED.call_once(|| {
2712                let row_set_rows = match row_set {
2713                    crate::row_kernel::RowSet::All => spec.y.len(),
2714                    crate::row_kernel::RowSet::Subsample { rows, .. } => rows.len(),
2715                };
2716                log::debug!(
2717                    "[BMS exact outer eval] mode={eval_mode:?} row_set_rows={row_set_rows}"
2718                );
2719            });
2720            let rho = theta.slice(s![..setup.rho_dim()]).to_owned();
2721            let blocks = build_blocks(&rho, &designs[0], &designs[1])?;
2722            // Promote a staged β seed (deposited by the outer ρ-cache hit
2723            // before any eval ran) into the family warm-start slot now that
2724            // we know the per-block widths from the freshly built blocks.
2725            if let Some(beta_seed) = pending_beta_seed.borrow_mut().take() {
2726                let widths: Vec<usize> = blocks.iter().map(|b| b.design.ncols()).collect();
2727                match CustomFamilyWarmStart::from_cached_beta(&widths, &beta_seed) {
2728                    Ok(ws) => {
2729                        exact_warm_start.replace(Some(ws));
2730                    }
2731                    Err(e) => {
2732                        log::warn!(
2733                            "[BMS] outer ρ-cache β-warm-start rejected: {e}; falling back to cold β"
2734                        );
2735                    }
2736                }
2737            }
2738            let sigma = sigma_from_theta(theta);
2739            final_sigma_cell.set(sigma);
2740            let family = make_family(&designs[0], &designs[1], sigma);
2741            let derivative_blocks = get_derivative_blocks(theta, specs, designs)?;
2742            // Downgrade to ValueAndGradient when the caller asks for a
2743            // Hessian we can't provide; preserve ValueOnly probes for
2744            // line-search cost-only evaluation.
2745            let effective_mode = match eval_mode {
2746                EvalMode::ValueGradientHessian if !analytic_joint_hessian_available => {
2747                    EvalMode::ValueAndGradient
2748                }
2749                other => other,
2750            };
2751            let mut eval_options =
2752                joint_hyper_options_for_outer_tolerance(options, exact_spatial_outer_tol);
2753            if let crate::row_kernel::RowSet::Subsample { rows, n_full } = row_set {
2754                let subsample = crate::outer_subsample::OuterScoreSubsample::from_weighted_rows(
2755                    rows.as_ref().clone(),
2756                    *n_full,
2757                    0,
2758                );
2759                eval_options.outer_score_subsample = Some(Arc::new(subsample));
2760                eval_options.auto_outer_subsample = false;
2761            }
2762            let eval = evaluate_custom_family_joint_hyper_shared(
2763                &family,
2764                &blocks,
2765                &eval_options,
2766                &rho,
2767                derivative_blocks,
2768                exact_warm_start.borrow().as_ref(),
2769                effective_mode,
2770            )?;
2771            if let Some(err) = bernoulli_marginal_slope_runaway_error(
2772                &eval.warm_start,
2773                &designs[0],
2774                &specs[0],
2775                eval.inner_converged,
2776                "exact outer evaluation",
2777            ) {
2778                runaway_error.replace(Some(err.clone()));
2779                return Err(err);
2780            }
2781            exact_warm_start.replace(Some(eval.warm_start.clone()));
2782            if !eval.inner_converged {
2783                return Err(
2784                    "exact bernoulli marginal-slope inner solve did not converge".to_string(),
2785                );
2786            }
2787            if matches!(eval_mode, EvalMode::ValueGradientHessian)
2788                && analytic_joint_hessian_available
2789                && !eval.outer_hessian.is_analytic()
2790            {
2791                return Err("exact bernoulli marginal-slope joint [rho, psi] objective did not return an outer Hessian"
2792                            .to_string());
2793            }
2794            Ok((eval.objective, eval.gradient, eval.outer_hessian))
2795        },
2796        |theta, specs: &[TermCollectionSpec], designs: &[TermCollectionDesign]| {
2797            if let Some(err) = runaway_error.borrow().as_ref().cloned() {
2798                return Err(err);
2799            }
2800            let rho = theta.slice(s![..setup.rho_dim()]).to_owned();
2801            let blocks = build_blocks(&rho, &designs[0], &designs[1])?;
2802            if let Some(beta_seed) = pending_beta_seed.borrow_mut().take() {
2803                let widths: Vec<usize> = blocks.iter().map(|b| b.design.ncols()).collect();
2804                match CustomFamilyWarmStart::from_cached_beta(&widths, &beta_seed) {
2805                    Ok(ws) => {
2806                        exact_warm_start.replace(Some(ws));
2807                    }
2808                    Err(e) => {
2809                        log::warn!(
2810                            "[BMS] outer ρ-cache β-warm-start rejected (efs): {e}; falling back to cold β"
2811                        );
2812                    }
2813                }
2814            }
2815            let sigma = sigma_from_theta(theta);
2816            final_sigma_cell.set(sigma);
2817            let family = make_family(&designs[0], &designs[1], sigma);
2818            let derivative_blocks = get_derivative_blocks(theta, specs, designs)?;
2819            let eval = evaluate_custom_family_joint_hyper_efs_shared(
2820                &family,
2821                &blocks,
2822                &joint_hyper_options_for_outer_tolerance(options, exact_spatial_outer_tol),
2823                &rho,
2824                derivative_blocks,
2825                exact_warm_start.borrow().as_ref(),
2826            )?;
2827            if let Some(err) = bernoulli_marginal_slope_runaway_error(
2828                &eval.warm_start,
2829                &designs[0],
2830                &specs[0],
2831                eval.inner_converged,
2832                "EFS outer evaluation",
2833            ) {
2834                runaway_error.replace(Some(err.clone()));
2835                return Err(err);
2836            }
2837            exact_warm_start.replace(Some(eval.warm_start.clone()));
2838            if !eval.inner_converged {
2839                return Err(
2840                    "exact bernoulli marginal-slope EFS inner solve did not converge".to_string(),
2841                );
2842            }
2843            Ok(eval.efs_eval)
2844        },
2845        crate::marginal_slope_shared::make_beta_seed_validator(&pending_beta_seed),
2846    )?;
2847
2848    let mut resolved_specs = solved.resolved_specs;
2849    let mut designs = solved.designs;
2850    // Reduced-basis round-trip (robust cure). When the logslope design was
2851    // orthogonalised to a reduced basis `G·T`, the fitted logslope coefficient
2852    // `β'` lives in the reduced coordinates (width `r`). The returned
2853    // `logslope_design` / `logslopespec_resolved` are the ORIGINAL full-width
2854    // basis (prediction rebuilds full `G` from the resolved spec), so map the
2855    // reported logslope coefficients back to the original basis `β_logslope =
2856    // T·β'` (predictor-identical: `G·(T·β') = (G·T)·β'`). The marginal block,
2857    // aux blocks, and the internal reduced-width flat β/geometry are untouched;
2858    // only the per-block reported logslope coefficients (blocks[1] and
2859    // block_states[1]) — which prediction/reporting consume against the full
2860    // design — are lifted to full width.
2861    let mut solved_fit = solved.fit;
2862    if let Some(reparam) = logslope_reduced_reparam.as_ref() {
2863        let r = reparam.reduced_cols();
2864        if let Some(block) = solved_fit.blocks.get_mut(1)
2865            && block.beta.len() == r
2866        {
2867            block.beta = reparam.recover_original_logslope_beta(&block.beta)?;
2868        }
2869        if let Some(state) = solved_fit.block_states.get_mut(1)
2870            && state.beta.len() == r
2871        {
2872            state.beta = reparam.recover_original_logslope_beta(&state.beta)?;
2873        }
2874    }
2875    // #905 GENERATED-REGRESSOR (Murphy–Topel) SEAM. When the conditional
2876    // location-scale gate fired, the slope fit above treated the calibrated
2877    // score `ζ = (z − m̂(C))/√v̂(C)` as KNOWN, so `solved_fit.beta_covariance()`
2878    // is the naive second-stage covariance `V_β^naive = H_β⁻¹` that ignores the
2879    // first-stage estimation error in `θ₁ = (mean_coeffs, var_coeffs)`. The
2880    // honest two-stage covariance is
2881    //   `V_β = V_β^naive + (H_β⁻¹ G) V₁ (H_β⁻¹ G)ᵀ`,  `G = ∂(score_β)/∂θ₁`.
2882    // The closed-form first-stage covariance `V₁` and the per-row chain-rule
2883    // sensitivity `∂ζ_i/∂θ₁` are computed and stored on the calibration at fit
2884    // time (see `LatentZConditionalCalibration::{theta1_covariance,
2885    // zeta_theta1_jacobian_row, generated_regressor_term}`), so the correction
2886    // is consumable wherever the slope information `G` (the per-row
2887    // `∂score_β/∂ζ_i` of the marginal/logslope blocks) is available.
2888    //
2889    // ASSEMBLY READY, ONE ENGINE QUANTITY OUTSTANDING. The full correction is
2890    // assembled by `LatentZConditionalCalibration::generated_regressor_correction`
2891    // (mod.rs): given the per-row reduced-frame slope-score sensitivity to the
2892    // calibrated score `s_i = ∂score_β,i/∂ζ_i` (an `n × p_β` matrix), it
2893    //   1. builds `J_zeta` row-by-row via `zeta_theta1_jacobian_row` (exact-zero
2894    //      on floored rows, so `G`'s support is the gate-fired rows),
2895    //   2. accumulates `G = Σ_i s_i ⊗ (∂ζ_i/∂θ₁)` (`p_β × dim θ₁`),
2896    //   3. forms `Vb·G = solved_fit.beta_covariance()·G` (the naive reduced-frame
2897    //      covariance IS `H_β⁻¹`, so `H_β⁻¹ G = Vb·G`), and
2898    //   4. returns `(Vb·G)·V₁·(Vb·G)ᵀ` (PSD ⇒ corrected slope SE strictly ≥
2899    //      naive whenever the gate fires).
2900    // So `V₁`, `∂ζ/∂θ₁`, the `Vb` frame, and the whole congruence are all
2901    // available HERE — the only quantity the seam still lacks is `s_i`.
2902    //
2903    // `s_i = ∂²ℓ_i/∂β∂ζ_i = J_iᵀ·(∂²ℓ_i/∂η_i∂ζ_i)` is the mixed `(β, ζ)` second
2904    // derivative of the row kernel contracted through the slope Jacobian `J_i`.
2905    // When the calibrated residual ζ passes the standard-normal adequacy gate,
2906    // `build_latent_measure_with_geometry` pairs `ConditionalLocationScale`
2907    // with `LatentMeasureKind::StandardNormal` and the per-row kernel is the
2908    // closed-form `rigid_standard_normal` tower
2909    // `η = q·c(g) + g·(s·ζ)`. The mixed 2-vector `∂²ℓ_i/∂(q,g)∂ζ_i` is read off the
2910    // SAME `Tower4` the value/grad/Hessian path uses (#932 row-jet machinery) by
2911    // seeding `ζ` as a third jet axis
2912    // (`rigid_standard_normal_mixed_z_sensitivity`); contracting it through the
2913    // marginal+logslope design rows (the `J_iᵀ` the row kernel exposes via
2914    // `jacobian_transpose_action`) yields `s_i` in the SAME reduced frame as
2915    // `covariance_conditional` (`rigid_standard_normal_score_zeta_sensitivity`).
2916    let (latent_z_rank_int_calibration, latent_z_conditional_calibration) =
2917        match latent_z_calibration {
2918            LatentMeasureCalibration::None => (None, None),
2919            LatentMeasureCalibration::RankInverseNormal(cal) => (Some(cal), None),
2920            LatentMeasureCalibration::ConditionalLocationScale(cal) => (None, Some(cal)),
2921        };
2922    // #905/#1028: apply the Murphy–Topel generated-regressor correction now that
2923    // `s_i` is available. `covariance_conditional` (Vb) and `covariance_corrected`
2924    // (Vp) are in the reduced logslope frame (`p_m + r`), exactly the frame
2925    // `s_i`'s reduced-logslope contraction lives in, so add the PSD term
2926    // `(Vb·G)·V₁·(Vb·G)ᵀ` to each. Applied only for the canonical (non-flex)
2927    // standard-normal kernel: the rigid tower carries no score_warp/link_dev
2928    // z-dependence, so when aux deviation blocks widen β beyond `p_m + r` the
2929    // correction's deviation columns are not yet derived and the term is skipped
2930    // (the conditional gate's intended kernel has no such blocks). Likewise
2931    // skipped when the calibrated residual failed the standard-normal adequacy
2932    // gate and the fit ran under the empirical latent measure: the `s_i`
2933    // sensitivity below is read off the rigid standard-normal tower, which is
2934    // not the kernel that produced `Vb` in that case.
2935    if let Some(cal) = latent_z_conditional_calibration.as_ref()
2936        && matches!(latent_measure, LatentMeasureKind::StandardNormal)
2937        && let Some(vb) = solved_fit.covariance_conditional.clone()
2938    {
2939        let p_beta = vb.nrows();
2940        let marginal_dense = marginal_design
2941            .design
2942            .try_to_dense_arc("bms generated-regressor marginal design")?;
2943        let logslope_reduced = reduce_logslope_design(&logslope_design)?;
2944        let logslope_reduced_dense = logslope_reduced
2945            .design
2946            .try_to_dense_arc("bms generated-regressor reduced logslope design")?;
2947        let p_m = marginal_dense.ncols();
2948        let r = logslope_reduced_dense.ncols();
2949        if p_beta != vb.ncols() {
2950            return Err(format!(
2951                "bms generated-regressor: covariance_conditional must be square, got {}×{}",
2952                vb.nrows(),
2953                vb.ncols()
2954            ));
2955        }
2956        // Skip when aux deviation (score_warp / link_dev) blocks are present:
2957        // β is wider than the marginal+reduced-logslope frame the rigid kernel's
2958        // z-channel covers. Equality ⇒ the canonical non-flex gate kernel.
2959        if p_beta == p_m + r {
2960            let marginal_eta = &solved_fit.block_states[0].eta;
2961            let slope_eta = &solved_fit.block_states[1].eta;
2962            let probit_scale = probit_frailty_scale(final_sigma_cell.get());
2963            let s = rigid_standard_normal_score_zeta_sensitivity(
2964                &spec.base_link,
2965                marginal_eta,
2966                slope_eta,
2967                z.as_ref(),
2968                y.as_ref(),
2969                weights.as_ref(),
2970                probit_scale,
2971                marginal_dense.view(),
2972                logslope_reduced_dense.view(),
2973                p_beta,
2974            )?;
2975            // `generated_regressor_correction` re-derives `∂ζ_i/∂θ₁` via
2976            // `zeta_theta1_jacobian_row(z_i, a_row)`, which expects the RAW
2977            // normalized latent score `z_i` (it recomputes `ζ_i = (z_i − m)/√v`
2978            // internally), and conditions on the marginal-index span
2979            // `a(C_i)` = the RAW marginal design rows (the basis the gate was fit
2980            // on). Feed `spec.z` (the standardized raw score, NOT the calibrated
2981            // ζ the kernel consumed) and the raw marginal dense design.
2982            let correction = cal.generated_regressor_correction(
2983                s.view(),
2984                spec.z.view(),
2985                marginal_dense.view(),
2986                vb.view(),
2987            )?;
2988            if let Some(cov) = solved_fit.covariance_conditional.as_mut() {
2989                *cov = &*cov + &correction;
2990            }
2991            if let Some(cov) = solved_fit.covariance_corrected.as_mut() {
2992                *cov = &*cov + &correction;
2993            }
2994            log::info!(
2995                "[BMS latent-z] Murphy–Topel generated-regressor SE correction applied: \
2996                 p_beta={p_beta} theta1_dim={} max_diag_inflation={:.3e}",
2997                cal.theta1_dim(),
2998                (0..p_beta)
2999                    .map(|i| correction[[i, i]])
3000                    .fold(0.0_f64, f64::max),
3001            );
3002        } else {
3003            log::info!(
3004                "[BMS latent-z] Murphy–Topel generated-regressor SE correction skipped: \
3005                 aux deviation blocks present (p_beta={p_beta} > marginal({p_m})+logslope({r})); \
3006                 rigid-kernel z-channel does not yet cover score_warp/link_dev deviations"
3007            );
3008        }
3009    }
3010    // #461: PREDICT SEAM — when the Stage-1 influence absorber is active
3011    // (spec.score_influence_jacobian.is_some()), `fit.block_states[0].beta` is
3012    // the WIDENED marginal coefficient `[β_m; γ]` (length p_m + p₁), but
3013    // `marginal_design` below is the RAW term-collection design (p_m columns):
3014    // the absorbed influence columns Z̃_infl are a TRAINING-only leakage
3015    // absorber and do NOT exist at predict rows (no Stage-1 fold there). The
3016    // orthogonalized β̂_m is a property of the training fit, so prediction must
3017    // use ONLY the first p_m entries of block_states[0].beta against this raw
3018    // marginal_design and DROP the trailing γ. The model-payload / predict
3019    // builder (src/main.rs run_fit_bernoulli_marginal_slope → inference) owns
3020    // that truncation; it must record p_m (= marginal_design.design.ncols())
3021    // and slice the persisted marginal β to it. Survival mirrors this seam.
3022    Ok(BernoulliMarginalSlopeFitResult {
3023        fit: solved_fit,
3024        marginalspec_resolved: resolved_specs.remove(0),
3025        logslopespec_resolved: resolved_specs.remove(0),
3026        marginal_design: designs.remove(0),
3027        logslope_design: designs.remove(0),
3028        baseline_marginal: baseline.0,
3029        baseline_logslope: baseline.1,
3030        z_normalization,
3031        latent_measure,
3032        score_warp_runtime,
3033        link_dev_runtime,
3034        gaussian_frailty_sd: final_sigma_cell.get(),
3035        cross_block_warnings,
3036        latent_z_rank_int_calibration,
3037        latent_z_conditional_calibration,
3038    })
3039}