Skip to main content

borg/select/
policy.rs

1//! The learned policy's core: a Bayesian model of what each route of a graded apply is worth, fitted
2//! from the outcome log, and the decision it drives at one check. Pure: no file, no clock, no
3//! environment (an engineer's budget comes in as an argument).
4//!
5//! **The value model.** One logistic model of the judge's verdict "the lesson changed the work and the
6//! change avoids its consequence" (`asked_then_changed`), per graded apply j and route a: ask (Q),
7//! free (F) or not now (D, measured by the placebo arm, select.rs `PLACEBO_SLOTS`):
8//! - η_j = β₀ + β₂[g=2] + β₃[g=3] + β_rank·ln(1+rank) + β_stop[stop] + β_three[a 3 in the check]
9//!   + β_three_stop[a 3 in a stop's check] + β_pool·ln(tokens/12k) + u_session + w_lesson + γ_judge;
10//! - P(changed | a, m) = σ(η_j + δ_a + κ_a·ln m_a + interactions), δ_F = 0 (the reference), m_a the
11//!   number of applies the check routes to a (dilution: more questions, or more free context, make
12//!   each one less likely to change the work), κ_D = 0, interactions δ_Q×stop, δ_Q×[g=3], δ_D×(g−2).
13//!
14//! The fixed rule asks exactly when a check has a 3, so in its history a route term and the cell of
15//! checks it is asked in are one column. Each route term therefore has its twin among the effects that
16//! do not depend on the route (δ_Q: β_three; δ_Q×stop: β_three_stop; δ_Q×[g=3]: β₃): what the fixed
17//! rule's cells differ by goes to the twin, and a route term learns only from checks whose routes
18//! varied within a cell, never from the fixed rule's history alone.
19//!
20//! Fitted by penalised Newton (MAP) over the fixed effects and the session, lesson and judge effects
21//! together (the largest family eliminated exactly by its Schur complement), with the Laplace
22//! covariance; empirical Bayes (EM, type-II maximum likelihood) for the spread of each family and
23//! automatic relevance (ARD) for the terms without a dated prior (the rank slope, the pool slope and
24//! the interactions), so a weak feature gets weight only when the data support it. A term with a dated
25//! prior (ask and not now against free, `ASK_PRIOR`, `NOT_PRIOR`; the dilution slopes,
26//! `DILUTION_PRIOR`) keeps it: EM would shrink its sd wherever the data cannot tell the term from the
27//! others (under the fixed rule how many are asked or handed over is set by the check's size, never
28//! chosen), which is the data saying nothing, not the effect being small. Dilution and pool slopes are
29//! ≤ 0 (an active set). Priors in `coefs`. No importance weights for the routes: the randomisation
30//! depends only on logged covariates, so the design is ignorable. The judge's missingness is modelled
31//! (`judged`) and enters as truncated inverse-probability weights. Labels fade with age in sessions,
32//! 2^(−age/H), H chosen from `HALF_LIVES` by prequential likelihood over whole sessions (`half_life`).
33//! The fit runs at `borg learn` (select/summary.rs `refit`, main.rs `learn_store`, which a session's
34//! end starts detached), never in a hook. `fit_pruned` is P2's pre-registered pruned model, for
35//! evaluation only.
36//!
37//! **The decision** (`choose`, policy v2: docs/evidence.md, Rules v2). The value of route a for apply
38//! j is τ_j(a, m) = π_a·[P(changed | a, m) − P(changed | D)], with the learned delivery rate π (a stop's
39//! free lesson arrives only if a next prompt comes, a live question only if it reaches the drone; a
40//! stop's question always does, it blocks) (`Rates`). Not now is worth 0, at the stop and during the
41//! turn alike: a lesson left for later earns its value at the check that delivers it, and crediting it
42//! here too would count that delivery twice in the gate's ledger. A check takes one of three routings:
43//! - **On evidence** (`evident`): the routes maximising Σ_j τ_j (`solve`, exact) under the posterior
44//!   mean (`theta_mean`: the coefficients' and every level's mean, no draw), played only when they
45//!   beat the fixed rule at the `DELTA` quantile over the `DRAWS` joint draws (`gate_seed`, the ledger's
46//!   draws), a lesson the session already had never handed over free (its delivery would drop it).
47//!   Without evidence nothing passes the quantile, so the prior alone never leaves the fixed rule: the
48//!   effects the fixed rule's history cannot identify (how much each question dilutes the others, what
49//!   a lesson not delivered still changes) cannot decide from their priors. No Thompson play.
50//! - **The randomised question-count test**, on a live check (never the stop) whose evidence keeps the
51//!   fixed rule: of the fixed rule's k delivered non-3 lessons that may go free (`tested`), the first s
52//!   in its order are asked and the rest handed over, s uniform in 0..=k drawn from the check's seed
53//!   (`draw_count`). Nothing is withheld and every 3 is asked as the fixed rule asks it, so recall is
54//!   the fixed rule's: on a check with a 3 the hand-overs replace questions, and the free delivery
55//!   carries them past its character budget as the questions would have been carried (hook.rs
56//!   `INSTEAD`). The fixed rule is s = 0 without a 3 and s = k with one (`EXPERIMENT_CONTROL`).
57//!   It measures what the fixed rule's history never varies: how many questions to ask.
58//! - **The fixed rule** otherwise.
59//!
60//! The conservative gate (in `choose`) keeps the fixed rule unless the deviation leaves the replayed
61//! value of the policy's checks, at the `DELTA` quantile over `DRAWS` joint draws, at most α × the
62//! fixed rule's own replayed value below the fixed rule (select/summary.rs `Gate`), α the engineer's
63//! tolerance (`ALPHA` unless the collective sets `risk`, select.rs `risk_of`; 0 turns the test off):
64//! cold start is exactly the fixed rule, and the test is rationed by quality, not by an ε. A stop's
65//! grade 3 is always asked (`forced`). Propensities are exact: 0 or 1 on evidence and under the fixed
66//! rule, and under the test each unit's share of the k + 1 values of s that ask it or hand it over (a
67//! value the gate refuses counting as the fixed rule's routes). Spend is not an objective: only the
68//! pool's size has a price, and only under a budget an engineer set for the collective (`price`);
69//! without one the price is 0.
70//!
71//! **The monitor** (`monitor`) estimates, per session, the policy's value against the fixed rule
72//! (doubly robust, cross-fitted by session, truncated self-normalised weights) and keeps a time-uniform
73//! confidence sequence on it (`upper_bound`); when its bound shows harm beyond `ALPHA` of the fixed
74//! rule's value, the store reverts to the fixed rule for good (select/summary.rs `REVERTED`).
75
76use std::collections::{BTreeMap, HashMap};
77
78use serde::{Deserialize, Serialize};
79
80use super::summary::{Apply, Check as Logged, Gate, Label, Summary};
81use super::{ARMS, Route, Unit};
82use crate::conscience::{self, Challenge};
83use crate::memory::Rng;
84
85/// The share of the fixed rule's replayed quality (mistakes avoided) the learned policy may risk below
86/// it while it learns, at the gate (`choose`, unless the collective sets `risk`, select.rs `risk_of`)
87/// and in the monitor (`monitor`), and the share the gate's ledger accrues (`ledger_add_without`).
88/// Method: a bound on quality, not on cost; the engineer's tolerance for learning, stated once. Kept by
89/// dated decision (2026-10-31), with the allowance scaling with the fixed rule's modelled value: about one
90/// deviation in 9 to 10 checks in both main stores.
91pub const ALPHA: f64 = 0.10;
92/// The gate's and the evidence rule's quantile, and the monitor's error probability. Method: the
93/// conventional 95% confidence.
94pub const DELTA: f64 = 0.05;
95/// Joint posterior draws behind the gate's and the evidence rule's quantile: conscience.rs `P_DRAWS`
96/// (method, its standard error ≤ 0.022).
97pub const DRAWS: usize = conscience::P_DRAWS;
98/// Applies a check may have for the learned decision; a larger check takes the fixed rule (source
99/// `size`). Guard: bounds the exact solver's time per check (O(n³ log n), on the posterior mean's
100/// table) and the valuing of the evidence rule's and the test's routes (O(n) per draw, `DRAWS` draws,
101/// k + 2 routings); its hit rate is the share of `size` checks.
102pub const SOLVE_MAX: usize = 16;
103
104/// Prior sd of every identified effect (intercept, grades, channel, a 3 in the check, a 3 at the
105/// stop): N(0, 2.5²). Method: the weakly informative default for logistic coefficients (Gelman et al.
106/// 2008); also the ceiling of every learned spread.
107pub const PRIOR_SD: f64 = 2.5;
108/// Ask against free, N(0, 0.35²). Learned, dated prior: the review→fix evaluation of 2026-10 (asked
109/// +6.3, handed over +7.3 points against the plain agent) puts them within a few points; wide.
110pub const ASK_PRIOR: (f64, f64) = (0.0, 0.35);
111/// Not now against free, N(−0.3, 0.25²). Learned, dated prior: the same evaluation, a lesson not
112/// delivered changes less than one handed over. Fixed by dated decision (2026-10-31, docs/evidence.md):
113/// 8 placebos drawn, 1 judged, the fitted effect is this prior; withholding is not learned until 100
114/// judged placebos exist.
115pub const NOT_PRIOR: (f64, f64) = (-0.3, 0.25);
116/// Dilution slope per ln(m) of asks or free lessons, N(0, 0.1²) truncated ≤ 0 (half-normal, its mode
117/// at 0). Learned, dated prior: the 2026-10-22 estimate (0.04 [0, 0.12] less per extra question on the
118/// log-odds scale) has an interval that includes 0, so no dilution is assumed; its width sets the scale.
119pub const DILUTION_PRIOR: (f64, f64) = (0.0, 0.1);
120/// Starting sd of an ARD term, every term without a dated prior (rank, interactions, pool). Method: EM
121/// moves it.
122pub const ARD_START: f64 = 1.0;
123/// Starting spread of the session, lesson and judge effects. Method: EM moves it.
124pub const LEVEL_START: f64 = 0.5;
125/// Floor of every learned spread. Method: EM's update can never leave 0, and 0.01 on the log-odds
126/// scale is no effect.
127pub const SD_FLOOR: f64 = 0.01;
128/// Half-lives of a label's weight, in sessions, the forgetting is chosen from (None: none). Method: a
129/// doubling grid; a tie goes to the longer.
130pub const HALF_LIVES: [Option<u32>; 5] = [None, Some(64), Some(32), Some(16), Some(8)];
131/// Sessions a fit reads at most, the newest. Guard: bounds the fit's dense block (one effect per
132/// session) and its time; the labels it leaves out are counted (`Fit::dropped`).
133pub const FIT_SESSIONS: usize = 256;
134/// The largest inverse-probability weight of a judged label. Guard: a route the judge rarely reaches
135/// would otherwise let a handful of its labels outweigh the rest.
136pub const MAX_IPW: f64 = 10.0;
137/// The least chance a placebo that happened is weighed at (`monitor`, select/replay.rs P5). Method: a
138/// logged ψ of 0 for a drawn placebo is rounding (outcome.rs `round_p`), so it is read as 1/1000 at
139/// least: such a label weighs at most a thousand sure ones.
140pub const PSI_FLOOR: f64 = 1e-3;
141/// The pool budgets the policy chooses among: whole.rs `TOKENS` × 2^(i/2). Method: a √2 grid around
142/// the baseline.
143pub const POOL_STEPS: [i32; 5] = [-2, -1, 0, 1, 2];
144/// Latency observations needed before the pool may grow past the baseline. Method: with 20, the
145/// empirical 95% quantile has an observation above it.
146pub const LATENCY_MIN: usize = 20;
147/// The share of a budget a call must have read to count as latency observed at that budget
148/// (`PoolFit::latency_reach`, `pool_feasible`). Guard, dated 2026-10-31: a pool grows only to a budget
149/// its latency was measured at, never on a slope extrapolated past the calls (a team store's fit was
150/// flat, b = 0, and would have let a 16,971-token pool in on 12,000-token calls alone). At 0.9 a pool
151/// filled to its budget counts: it stops within a lesson of it (about 90 tokens there), and 193 of
152/// that store's 203 calls at the 12,000 baseline read 10,800 or more.
153pub const LATENCY_NEAR: f64 = 0.9;
154
155/// The labelled applies with leverage (the taken route's difference between the policy and the fixed
156/// rule is not 0) a route needs before the monitor uses its weighted residual (`monitor`); below it the
157/// direct-method term (the cross-fitted outcome model) carries the route alone. Guard, dated
158/// 2026-10-31: weights are normalised per route, so a route's only label carries the whole route (a
159/// team store's not-now route: 1 judged placebo at 42× the mean weight, ESS 9 of 127); at 5 one label
160/// is at most about a fifth of its route's residual. Labels without leverage do not count: they move
161/// no residual, so 5 of them would leave the next label with leverage carrying the route alone. Below it a route's residual is noise one verdict
162/// decides, so dropping it loses no evidence a confidence sequence could use.
163pub const ROUTE_LABELS_MIN: usize = 5;
164
165/// Newton's convergence: the largest step below this. Method.
166const TOL: f64 = 1e-8;
167/// Newton steps per fit at most. Guard: a fit that does not converge stops here (`Model::converged`).
168const MAX_NEWTON: usize = 50;
169/// Step halvings per Newton step at most. Guard: a step that cannot improve the objective (at the
170/// optimum, to float precision) ends the fit instead of halving forever.
171const MAX_HALVINGS: usize = 30;
172/// EM rounds of the spreads per fit at most. Guard: EM's slow crawl toward a spread of 0 stops here.
173const MAX_EB: usize = 50;
174/// EM's convergence: the largest relative change of a spread below this. Method.
175const EB_TOL: f64 = 1e-4;
176/// Sessions the prequential choice of the half-life predicts at most, the newest. Guard: one fit per
177/// session and half-life.
178const PREQ_SESSIONS: usize = 16;
179/// The sessions at which the monitor's confidence sequence is tightest: the pre-registered online
180/// readout's 30 sessions. Method: it sets the normal mixture's ρ, not the error rate.
181const CS_SESSIONS: f64 = 30.0;
182/// Sessions before the monitor may trip. Method: the sequence plugs in the increments' variance,
183/// which needs a few sessions to mean anything.
184const CS_MIN: usize = 10;
185/// Bisection steps of the budget's price. Method: enough halvings for f64 precision.
186const PRICE_STEPS: usize = 60;
187
188// The value model's coefficients (module doc). Protocol: their places in `Model::beta`.
189const B0: usize = 0;
190const G2: usize = 1;
191const G3: usize = 2;
192const RANK: usize = 3;
193const STOP: usize = 4;
194const THREE: usize = 5;
195const ASK: usize = 6;
196const NOT: usize = 7;
197const ASK_M: usize = 8;
198const FREE_M: usize = 9;
199const ASK_STOP: usize = 10;
200const ASK_G3: usize = 11;
201const NOT_G: usize = 12;
202const POOL: usize = 13;
203const THREE_STOP: usize = 14;
204/// The value model's coefficients. Protocol: the layout of `Model::beta` (a cached model of another
205/// layout is not read, `Model::current`).
206pub const P: usize = 15;
207/// Their names, for `borg debug select` and the monitoring, in `Model::beta`'s order.
208pub const NAMES: [&str; P] = [
209    "intercept",
210    "grade2",
211    "grade3",
212    "rank",
213    "stop",
214    "three",
215    "ask",
216    "not",
217    "ask_dilution",
218    "free_dilution",
219    "ask_stop",
220    "ask_grade3",
221    "not_grade",
222    "pool",
223    "three_stop",
224];
225/// The random-effect families, in `Model`'s order. Protocol.
226const SESSION: usize = 0;
227const LESSON: usize = 1;
228const JUDGE: usize = 2;
229const FAMILIES: usize = 3;
230
231/// A coefficient's prior: N(mean, sd²), its sd learned (ARD) or fixed, bounded above by 0 or not.
232#[derive(Debug, Clone, Copy)]
233struct Coef {
234    mean: f64,
235    sd: f64,
236    ard: bool,
237    nonpos: bool,
238}
239
240/// The value model's priors (module doc, constants above): a dated prior keeps its sd, ARD learns the
241/// sd of the terms without one.
242fn coefs() -> [Coef; P] {
243    let fixed = |(mean, sd): (f64, f64), nonpos| Coef { mean, sd, ard: false, nonpos };
244    let ard = |nonpos| Coef { mean: 0.0, sd: ARD_START, ard: true, nonpos };
245    let mut c = [fixed((0.0, PRIOR_SD), false); P];
246    c[RANK] = ard(false);
247    c[ASK] = fixed(ASK_PRIOR, false);
248    c[NOT] = fixed(NOT_PRIOR, false);
249    c[ASK_M] = fixed(DILUTION_PRIOR, true);
250    c[FREE_M] = fixed(DILUTION_PRIOR, true);
251    for i in [ASK_STOP, ASK_G3, NOT_G] {
252        c[i] = ard(false);
253    }
254    c[POOL] = ard(true);
255    c
256}
257
258/// The terms P2's pruned model keeps (`fit_pruned`): grade (the intercept and both grades), route (ask
259/// and not now against free) and dilution. Method: the pre-registered prune (tasks/todo.md, P2).
260const PRUNED_KEEPS: [usize; 7] = [B0, G2, G3, ASK, NOT, ASK_M, FREE_M];
261
262/// The priors of P2's pruned model: `coefs` for the terms it keeps, every other held at N(0,
263/// `SD_FLOOR`²) without ARD, which could bring it back: out of the model.
264fn pruned() -> [Coef; P] {
265    let mut c = coefs();
266    for (k, x) in c.iter_mut().enumerate() {
267        if !PRUNED_KEEPS.contains(&k) {
268            *x = Coef { mean: 0.0, sd: SD_FLOOR, ard: false, nonpos: false };
269        }
270    }
271    c
272}
273
274/// What the value model knows of a graded apply, its route aside.
275#[derive(Debug, Clone, Copy, PartialEq)]
276pub struct Feat {
277    pub grade: u8,
278    pub rank: usize,
279    /// The check is the stop's (else live).
280    pub stop: bool,
281    /// The check has a 3.
282    pub three: bool,
283    /// ln(pool tokens / whole.rs `TOKENS`), 0 when unknown.
284    pub pool: f64,
285}
286
287impl Feat {
288    /// The features of `units` at a check on `stop` with a pool of `tokens` (0 unknown).
289    pub fn of(units: &[Unit], stop: bool, tokens: u32) -> Vec<Feat> {
290        let three = units.iter().any(|u| u.grade == 3);
291        let pool = pool_x(tokens);
292        units.iter().map(|u| Feat { grade: u.grade, rank: u.rank, stop, three, pool }).collect()
293    }
294}
295
296/// ln(tokens / whole.rs `TOKENS`), 0 for an unknown pool (a record from before pool sizes).
297fn pool_x(tokens: u32) -> f64 {
298    if tokens == 0 { 0.0 } else { (f64::from(tokens) / crate::whole::TOKENS as f64).ln() }
299}
300
301/// The value model's row for apply `f` on `route` among `m` of its route.
302fn design(f: &Feat, route: Route, m: usize) -> [f64; P] {
303    let mut x = [0.0; P];
304    let g = f.grade;
305    x[B0] = 1.0;
306    x[G2] = f64::from(u8::from(g == 2));
307    x[G3] = f64::from(u8::from(g == 3));
308    x[RANK] = (1.0 + f.rank as f64).ln();
309    x[STOP] = f64::from(u8::from(f.stop));
310    x[THREE] = f64::from(u8::from(f.three));
311    x[THREE_STOP] = f64::from(u8::from(f.stop && f.three));
312    x[POOL] = f.pool;
313    let ln_m = (m.max(1) as f64).ln();
314    match route {
315        Route::Ask => {
316            x[ASK] = 1.0;
317            x[ASK_M] = ln_m;
318            x[ASK_STOP] = x[STOP];
319            x[ASK_G3] = x[G3];
320        }
321        Route::Free => x[FREE_M] = ln_m,
322        Route::Placebo | Route::Not => {
323            x[NOT] = 1.0;
324            x[NOT_G] = f64::from(g) - 2.0;
325        }
326    }
327    x
328}
329
330fn dot<const K: usize>(a: &[f64; K], b: &[f64; K]) -> f64 {
331    a.iter().zip(b).map(|(x, y)| x * y).sum()
332}
333
334fn sigmoid(x: f64) -> f64 {
335    if x >= 0.0 {
336        1.0 / (1.0 + (-x).exp())
337    } else {
338        let e = x.exp();
339        e / (1.0 + e)
340    }
341}
342
343/// ln(1 + eˣ), without overflow.
344fn log1pexp(x: f64) -> f64 {
345    if x > 0.0 { x + (-x).exp().ln_1p() } else { x.exp().ln_1p() }
346}
347
348/// The lower Cholesky factor of the symmetric positive definite `a` (n×n, row-major), in place; false
349/// when it is not positive definite.
350fn cholesky(a: &mut [f64], n: usize) -> bool {
351    for j in 0..n {
352        let d = a[j * n + j] - (0..j).map(|k| a[j * n + k] * a[j * n + k]).sum::<f64>();
353        if d.is_nan() || d <= 0.0 || !d.is_finite() {
354            return false;
355        }
356        let d = d.sqrt();
357        a[j * n + j] = d;
358        for i in j + 1..n {
359            let s = a[i * n + j] - (0..j).map(|k| a[i * n + k] * a[j * n + k]).sum::<f64>();
360            a[i * n + j] = s / d;
361        }
362        for i in 0..j {
363            a[i * n + j] = 0.0;
364        }
365    }
366    true
367}
368
369/// Solves L Lᵀ x = b in place, `l` from `cholesky`.
370fn chol_solve(l: &[f64], n: usize, b: &mut [f64]) {
371    for i in 0..n {
372        let s = b[i] - (0..i).map(|k| l[i * n + k] * b[k]).sum::<f64>();
373        b[i] = s / l[i * n + i];
374    }
375    for i in (0..n).rev() {
376        let s = b[i] - (i + 1..n).map(|k| l[k * n + i] * b[k]).sum::<f64>();
377        b[i] = s / l[i * n + i];
378    }
379}
380
381/// The inverse of L Lᵀ (n×n, row-major).
382fn chol_inverse(l: &[f64], n: usize) -> Vec<f64> {
383    let mut inv = vec![0.0; n * n];
384    let mut e = vec![0.0; n];
385    for j in 0..n {
386        e.iter_mut().for_each(|x| *x = 0.0);
387        e[j] = 1.0;
388        chol_solve(l, n, &mut e);
389        for (i, x) in e.iter().enumerate() {
390            inv[i * n + j] = *x;
391        }
392    }
393    inv
394}
395
396/// A standard normal draw (Box-Muller, one of the pair): O(1).
397fn normal(rng: &mut Rng) -> f64 {
398    let (u, v) = (rng.unit(), rng.unit());
399    (-2.0 * u.ln()).sqrt() * (std::f64::consts::TAU * v).cos()
400}
401
402/// A Gamma(shape, 1) draw (Marsaglia & Tsang 2000; shape < 1 by the boost U^(1/shape)): O(1) expected.
403fn gamma(shape: f64, rng: &mut Rng) -> f64 {
404    if shape < 1.0 {
405        return gamma(shape + 1.0, rng) * rng.unit().powf(1.0 / shape);
406    }
407    let d = shape - 1.0 / 3.0;
408    let c = 1.0 / (9.0 * d).sqrt();
409    // Guard: each round accepts with probability over 0.95, so 64 rounds never all reject in practice;
410    // the mode-like d stands in if they do.
411    for _ in 0..64 {
412        let z = normal(rng);
413        let v = (1.0 + c * z).powi(3);
414        if v <= 0.0 {
415            continue;
416        }
417        if rng.unit().ln() < 0.5 * z * z + d - d * v + d * v.ln() {
418            return d * v;
419        }
420    }
421    d
422}
423
424/// A Beta(a, b) draw from two Gamma draws.
425fn beta_draw(a: f64, b: f64, rng: &mut Rng) -> f64 {
426    let (x, y) = (gamma(a, rng), gamma(b, rng));
427    if x + y > 0.0 { x / (x + y) } else { a / (a + b) }
428}
429
430/// A stable 64-bit hash of `parts` (blake3, separated), for seeds.
431fn hash(parts: &[&[u8]]) -> u64 {
432    let mut h = blake3::Hasher::new();
433    h.update(b"borg-select-policy-v1\0");
434    for p in parts {
435        h.update(p);
436        h.update(b"\0");
437    }
438    let mut first = [0u8; 8];
439    first.copy_from_slice(&h.finalize().as_bytes()[..8]);
440    u64::from_le_bytes(first)
441}
442
443/// A seed for draw `i` of the stream `seed` (SplitMix64 of both).
444fn mix(seed: u64, i: u64) -> u64 {
445    Rng::new(seed ^ i.wrapping_add(1).wrapping_mul(0x9e37_79b9_7f4a_7c15)).next_u64()
446}
447
448/// One observation of a logistic model: features, label, weight, and its level in each family.
449#[derive(Debug, Clone)]
450struct Obs<const K: usize, const F: usize> {
451    x: [f64; K],
452    y: f64,
453    w: f64,
454    lv: [Option<usize>; F],
455}
456
457/// A fitted logistic model: the MAP and its Laplace covariance.
458#[derive(Debug, Clone)]
459struct Est<const K: usize, const F: usize> {
460    beta: [f64; K],
461    u: [Vec<f64>; F],
462    /// The prior sds the fit used (ARD's learned for theirs) and the families' spreads.
463    sd: [f64; K],
464    spread: [f64; F],
465    /// The marginal covariance of `beta`, and each level's marginal variance.
466    cov: [[f64; K]; K],
467    var_u: [Vec<f64>; F],
468    converged: bool,
469}
470
471impl<const K: usize, const F: usize> Est<K, F> {
472    fn eta(&self, o: &Obs<K, F>) -> f64 {
473        dot(&self.beta, &o.x) + (0..F).filter_map(|f| o.lv[f].map(|l| self.u[f][l])).sum::<f64>()
474    }
475}
476
477/// The MAP of the penalised logistic model over `obs` (`levels[f]` levels in family f), by Newton
478/// steps over every parameter at once: the family with the most levels is eliminated exactly (its
479/// levels are independent given the rest), the rest solved densely. Deterministic. None when the
480/// system is singular (cannot happen with proper priors; a guard).
481fn map<const K: usize, const F: usize>(
482    obs: &[Obs<K, F>],
483    levels: [usize; F],
484    spec: &[Coef; K],
485    sd: &[f64; K],
486    spread: &[f64; F],
487    warm: Option<&Est<K, F>>,
488) -> Option<Est<K, F>> {
489    let elim = (0..F).filter(|&f| levels[f] > 0).max_by_key(|&f| (levels[f], std::cmp::Reverse(f)));
490    let mut off = [0usize; F];
491    let mut dim = K;
492    for f in 0..F {
493        if Some(f) != elim {
494            off[f] = dim;
495            dim += levels[f];
496        }
497    }
498    let members: Vec<Vec<usize>> = match elim {
499        Some(e) => {
500            let mut m = vec![Vec::new(); levels[e]];
501            for (i, o) in obs.iter().enumerate() {
502                if let Some(l) = o.lv[e] {
503                    m[l].push(i);
504                }
505            }
506            m
507        }
508        None => Vec::new(),
509    };
510    let mut beta: [f64; K] = std::array::from_fn(|k| warm.map_or(spec[k].mean, |w| w.beta[k]));
511    for k in 0..K {
512        if spec[k].nonpos {
513            beta[k] = beta[k].min(0.0);
514        }
515    }
516    let mut u: [Vec<f64>; F] = std::array::from_fn(|f| match warm {
517        Some(w) if w.u[f].len() == levels[f] => w.u[f].clone(),
518        _ => vec![0.0; levels[f]],
519    });
520    let prec: [f64; K] = std::array::from_fn(|k| 1.0 / (sd[k] * sd[k]));
521    let uprec: [f64; F] = std::array::from_fn(|f| 1.0 / (spread[f] * spread[f]));
522    let objective = |beta: &[f64; K], u: &[Vec<f64>; F]| -> f64 {
523        let mut ll = 0.0;
524        for o in obs {
525            let eta = dot(beta, &o.x) + (0..F).filter_map(|f| o.lv[f].map(|l| u[f][l])).sum::<f64>();
526            ll += o.w * (o.y * eta - log1pexp(eta));
527        }
528        let pb: f64 = (0..K).map(|k| (beta[k] - spec[k].mean).powi(2) * prec[k]).sum();
529        let pu: f64 = (0..F).map(|f| u[f].iter().map(|x| x * x).sum::<f64>() * uprec[f]).sum();
530        ll - 0.5 * (pb + pu)
531    };
532    let mut converged = false;
533    let mut s = vec![0.0; dim * dim];
534    let mut d_e: Vec<f64> = Vec::new();
535    let mut b_e: Vec<Vec<(usize, f64)>> = Vec::new();
536    let mut current = objective(&beta, &u);
537    for _ in 0..MAX_NEWTON {
538        // The precision (negative Hessian) and gradient at the current point.
539        let mut g = vec![0.0; dim];
540        s.iter_mut().for_each(|x| *x = 0.0);
541        let mut r = vec![0.0; obs.len()];
542        let mut wt = vec![0.0; obs.len()];
543        let mut dense: Vec<(usize, f64)> = Vec::with_capacity(K + F);
544        for (i, o) in obs.iter().enumerate() {
545            let eta = dot(&beta, &o.x) + (0..F).filter_map(|f| o.lv[f].map(|l| u[f][l])).sum::<f64>();
546            let mu = sigmoid(eta);
547            r[i] = o.w * (o.y - mu);
548            wt[i] = o.w * mu * (1.0 - mu);
549            dense.clear();
550            dense.extend((0..K).filter(|&k| o.x[k] != 0.0).map(|k| (k, o.x[k])));
551            dense.extend((0..F).filter(|&f| Some(f) != elim).filter_map(|f| o.lv[f].map(|l| (off[f] + l, 1.0))));
552            for &(a, xa) in &dense {
553                g[a] += r[i] * xa;
554                for &(b, xb) in &dense {
555                    s[a * dim + b] += wt[i] * xa * xb;
556                }
557            }
558        }
559        for k in 0..K {
560            g[k] -= (beta[k] - spec[k].mean) * prec[k];
561            s[k * dim + k] += prec[k];
562        }
563        for f in (0..F).filter(|&f| Some(f) != elim) {
564            for l in 0..levels[f] {
565                g[off[f] + l] -= u[f][l] * uprec[f];
566                s[(off[f] + l) * dim + off[f] + l] += uprec[f];
567            }
568        }
569        // The eliminated family: its own precision, gradient and coupling to the dense block.
570        let mut g_e: Vec<f64> = Vec::new();
571        d_e.clear();
572        b_e.clear();
573        if let Some(e) = elim {
574            for (l, rows) in members.iter().enumerate() {
575                let mut d = uprec[e];
576                let mut gl = -u[e][l] * uprec[e];
577                let mut b: Vec<(usize, f64)> = Vec::new();
578                for &i in rows {
579                    d += wt[i];
580                    gl += r[i];
581                    let o = &obs[i];
582                    for k in 0..K {
583                        add_sparse(&mut b, k, wt[i] * o.x[k]);
584                    }
585                    for f in (0..F).filter(|&f| f != e) {
586                        if let Some(lv) = o.lv[f] {
587                            add_sparse(&mut b, off[f] + lv, wt[i]);
588                        }
589                    }
590                }
591                for &(a, va) in &b {
592                    for &(c, vc) in &b {
593                        s[a * dim + c] -= va * vc / d;
594                    }
595                    g[a] -= va * gl / d;
596                }
597                d_e.push(d);
598                g_e.push(gl);
599                b_e.push(b);
600            }
601        }
602        // The step: a Newton step on the reduced system, with the bounded coefficients at 0 held there
603        // while the gradient pushes them up (an active set).
604        let mut held: Vec<usize> = (0..K).filter(|&k| spec[k].nonpos && beta[k] >= 0.0 && g[k] > 0.0).collect();
605        let step = loop {
606            let mut delta = vec![0.0; dim];
607            for &k in &held {
608                delta[k] = -beta[k];
609            }
610            let free: Vec<usize> = (0..dim).filter(|i| !held.contains(i)).collect();
611            let n = free.len();
612            let mut a = vec![0.0; n * n];
613            let mut rhs = vec![0.0; n];
614            for (fi, &i) in free.iter().enumerate() {
615                rhs[fi] = g[i] - held.iter().map(|&h| s[i * dim + h] * delta[h]).sum::<f64>();
616                for (fj, &j) in free.iter().enumerate() {
617                    a[fi * n + fj] = s[i * dim + j];
618                }
619            }
620            if !cholesky(&mut a, n) {
621                return None;
622            }
623            chol_solve(&a, n, &mut rhs);
624            for (fi, &i) in free.iter().enumerate() {
625                delta[i] = rhs[fi];
626            }
627            let out: Vec<usize> = (0..K).filter(|&k| spec[k].nonpos && !held.contains(&k) && beta[k] + delta[k] > 0.0).collect();
628            if out.is_empty() {
629                break delta;
630            }
631            held.extend(out);
632        };
633        let delta_e: Vec<f64> = (0..d_e.len()).map(|l| (g_e[l] - b_e[l].iter().map(|&(a, v)| v * step[a]).sum::<f64>()) / d_e[l]).collect();
634        let largest = step.iter().chain(&delta_e).fold(0.0f64, |m, x| m.max(x.abs()));
635        // Halve the step until the objective does not fall.
636        let mut t = 1.0;
637        let mut accepted = false;
638        for _ in 0..=MAX_HALVINGS {
639            let nb: [f64; K] = std::array::from_fn(|k| {
640                let x = beta[k] + t * step[k];
641                if spec[k].nonpos { x.min(0.0) } else { x }
642            });
643            let mut nu = u.clone();
644            for f in 0..F {
645                for l in 0..levels[f] {
646                    nu[f][l] += t * if Some(f) == elim { delta_e[l] } else { step[off[f] + l] };
647                }
648            }
649            let next = objective(&nb, &nu);
650            // Not below the current objective beyond float noise (relative 1e-12).
651            if next >= current - 1e-12 * current.abs().max(1.0) {
652                (beta, u, current) = (nb, nu, next);
653                accepted = true;
654                break;
655            }
656            t *= 0.5;
657        }
658        if !accepted || largest * t < TOL {
659            converged = accepted || largest < TOL;
660            break;
661        }
662    }
663    // The Laplace covariance: the inverse of the reduced precision, and each eliminated level's.
664    if !cholesky(&mut s, dim) {
665        return None;
666    }
667    let inv = chol_inverse(&s, dim);
668    let cov: [[f64; K]; K] = std::array::from_fn(|a| std::array::from_fn(|b| inv[a * dim + b]));
669    let var_u: [Vec<f64>; F] = std::array::from_fn(|f| {
670        if Some(f) == elim {
671            (0..levels[f])
672                .map(|l| {
673                    let b = &b_e[l];
674                    let q: f64 = b.iter().map(|&(a, va)| b.iter().map(|&(c, vc)| va * inv[a * dim + c] * vc).sum::<f64>()).sum();
675                    1.0 / d_e[l] + q / (d_e[l] * d_e[l])
676                })
677                .collect()
678        } else {
679            (0..levels[f]).map(|l| inv[(off[f] + l) * dim + off[f] + l]).collect()
680        }
681    });
682    Some(Est { beta, u, sd: *sd, spread: *spread, cov, var_u, converged })
683}
684
685/// Adds `v` at `i` of a short sparse vector.
686fn add_sparse(b: &mut Vec<(usize, f64)>, i: usize, v: f64) {
687    if v == 0.0 {
688        return;
689    }
690    match b.iter_mut().find(|(j, _)| *j == i) {
691        Some(e) => e.1 += v,
692        None => b.push((i, v)),
693    }
694}
695
696/// `map` with its spreads and ARD sds learned by EM (type-II maximum likelihood): each family's spread
697/// is the root mean of its levels' u² + var, each ARD coefficient's sd √((β − mean)² + var), within
698/// [`SD_FLOOR`, `PRIOR_SD`].
699fn eb<const K: usize, const F: usize>(obs: &[Obs<K, F>], levels: [usize; F], spec: &[Coef; K], warm: Option<&Est<K, F>>) -> Option<Est<K, F>> {
700    let mut sd: [f64; K] = std::array::from_fn(|k| warm.filter(|_| spec[k].ard).map_or(spec[k].sd, |w| w.sd[k]));
701    let mut spread: [f64; F] = std::array::from_fn(|f| warm.map_or(LEVEL_START, |w| w.spread[f]));
702    let mut est = map(obs, levels, spec, &sd, &spread, warm)?;
703    for _ in 0..MAX_EB {
704        let nsd: [f64; K] = std::array::from_fn(|k| match spec[k].ard {
705            true => ((est.beta[k] - spec[k].mean).powi(2) + est.cov[k][k]).sqrt().clamp(SD_FLOOR, PRIOR_SD),
706            false => sd[k],
707        });
708        let nspread: [f64; F] = std::array::from_fn(|f| match levels[f] {
709            0 => spread[f],
710            n => (est.u[f].iter().zip(&est.var_u[f]).map(|(x, v)| x * x + v).sum::<f64>() / n as f64).sqrt().clamp(SD_FLOOR, PRIOR_SD),
711        });
712        let moved = sd.iter().zip(&nsd).chain(spread.iter().zip(&nspread)).any(|(a, b)| (a - b).abs() > EB_TOL * a.abs().max(SD_FLOOR));
713        (sd, spread) = (nsd, nspread);
714        est = map(obs, levels, spec, &sd, &spread, Some(&est))?;
715        if !moved {
716            break;
717        }
718    }
719    Some(est)
720}
721
722/// The learned delivery rates a route's value uses (module doc), posterior means of Beta(1, 1) with
723/// the fit's forgetting.
724#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
725pub struct Rates {
726    /// A stop's free lesson was delivered (a next prompt came).
727    pub free_stop: f64,
728    /// A live check's free lesson was delivered.
729    pub free_live: f64,
730    /// A lesson a live check left for later was delivered later in the session: shown, not used (not
731    /// now is worth 0, `Valuer::value`; the later delivery earns its value at its own check).
732    pub later: f64,
733    /// A live question was still waiting at the stop and asked there in a block: shown, not used.
734    pub wait: f64,
735    /// A live question of a check with a 3, of a lesson its session lacked, reached the drone, during
736    /// the turn or waiting for the stop and asked in its block (select/summary.rs `ASK_LIVE`): such an
737    /// ask's rate in its value (`Valuer::ask`; a stop's is 1, it blocks; one of a live check without a
738    /// 3 no stop asks, so it arrives as a hand-over does, at `free_live`). 1 until one is tallied
739    /// (baseline: the fixed rule takes every question as delivered, as a stop's is).
740    pub ask_live: f64,
741}
742
743/// The pool's learned state at the fit (`pool_tokens`).
744#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
745pub struct PoolFit {
746    /// Per log2 bin of fill position, the yield's Beta posterior (shown lessons applied), monotone
747    /// non-increasing in position (pool adjacent violators over the bins).
748    #[serde(default, skip_serializing_if = "Vec::is_empty")]
749    pub yields: Vec<(f64, f64)>,
750    /// Pool tokens per shown lesson.
751    #[serde(default, skip_serializing_if = "is_default")]
752    pub per_lesson: f64,
753    /// The model call's duration in ms against its pool tokens: a + b·tokens, plus the residuals'
754    /// 95% quantile, from `latency_n` calls.
755    #[serde(default, skip_serializing_if = "is_default")]
756    pub latency: (f64, f64, f64),
757    #[serde(default, skip_serializing_if = "is_default")]
758    pub latency_n: u32,
759    /// The largest pool tokens `LATENCY_MIN` of those calls read at least (the `LATENCY_MIN`-th
760    /// largest; 0 with fewer calls): a budget above the baseline is feasible only up to this over
761    /// `LATENCY_NEAR`, where the latency fit is read among calls, not extrapolated.
762    #[serde(default, skip_serializing_if = "is_default")]
763    pub latency_reach: u32,
764    /// The model's mean η of a labelled apply, its pool slope and its "not now" effect (mean, sd):
765    /// what a lesson more in the pool is worth.
766    #[serde(default, skip_serializing_if = "is_default")]
767    pub eta: f64,
768    #[serde(default, skip_serializing_if = "is_default")]
769    pub slope: (f64, f64),
770    #[serde(default, skip_serializing_if = "is_default")]
771    pub not: (f64, f64),
772}
773
774/// The fitted value model (module doc): its MAP and draws' ingredients.
775#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
776pub struct Model {
777    /// The coefficients (`NAMES`) and the lower Cholesky factor of their marginal covariance (P×P,
778    /// row-major).
779    pub beta: Vec<f64>,
780    pub chol: Vec<f64>,
781    /// The prior sd of each coefficient the fit ended with (ARD's learned).
782    pub sd: Vec<f64>,
783    /// The spread of the session, lesson and judge effects.
784    pub spread: [f64; FAMILIES],
785    /// Each level's effect, (mean, marginal sd).
786    pub sessions: BTreeMap<String, (f64, f64)>,
787    pub lessons: BTreeMap<String, (f64, f64)>,
788    pub judges: BTreeMap<String, (f64, f64)>,
789    /// The judge of the newest labelled check: the one that will judge the next.
790    #[serde(default, skip_serializing_if = "String::is_empty")]
791    pub judge: String,
792    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
793    pub converged: bool,
794}
795
796impl Model {
797    /// Whether the model has this build's layout (`P` coefficients). A cache written by a build with
798    /// another layout holds one that is not: its Cholesky rows would be read at the wrong places, so
799    /// decisions and the ledger take it for no model (the fixed rule) until the next fit.
800    #[must_use]
801    pub fn current(&self) -> bool {
802        self.beta.len() == P && self.chol.len() == P * P && self.sd.len() == P
803    }
804}
805
806/// What a decision draws from, fitted at `borg learn` (select/summary.rs `refit`), never in a hook. The
807/// default is the prior: no data, every decision the fixed rule's.
808#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
809pub struct Fit {
810    /// The outcomes it was fitted on (select/summary.rs `Summary::key`: byte offset and hash), logged
811    /// with each check (`Log::fit`) so a replay finds the same fit. Empty for the prior.
812    #[serde(default, skip_serializing_if = "String::is_empty")]
813    pub key: String,
814    /// The value model; None without a label.
815    #[serde(default, skip_serializing_if = "Option::is_none")]
816    pub model: Option<Model>,
817    /// The forgetting's half-life in sessions (None: none).
818    #[serde(default, skip_serializing_if = "Option::is_none")]
819    pub half_life: Option<u32>,
820    #[serde(default, skip_serializing_if = "is_default")]
821    pub rates: Rates,
822    #[serde(default, skip_serializing_if = "is_default")]
823    pub pool: PoolFit,
824    /// The engineer's budget (pool tokens per session) in force at the fit, and its price per token
825    /// (`price`); 0 without a budget.
826    #[serde(default, skip_serializing_if = "Option::is_none")]
827    pub budget: Option<f64>,
828    #[serde(default, skip_serializing_if = "is_default")]
829    pub lambda: f64,
830    /// Whether ask's or not-now's effect changes sign when an unclear verdict counts as "no change"
831    /// instead of missing: the label pipeline's unclear share decides the sign, so read with care.
832    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
833    pub sensitive: bool,
834    /// Labels the model read, and labels `FIT_SESSIONS` left out.
835    #[serde(default, skip_serializing_if = "is_default")]
836    pub labels: u32,
837    #[serde(default, skip_serializing_if = "is_default")]
838    pub dropped: u32,
839}
840
841fn is_default<T: Default + PartialEq>(v: &T) -> bool {
842    *v == T::default()
843}
844
845/// The age weight of a label `age` sessions old under half-life `h`.
846pub(super) fn decay(age: u32, h: Option<u32>) -> f64 {
847    h.map_or(1.0, |h| 0.5f64.powf(f64::from(age) / f64::from(h)))
848}
849
850/// The labelled applies of a summary as the value model's rows, with what the missingness model and
851/// the monitor need beside them.
852struct Data {
853    obs: Vec<Obs<P, FAMILIES>>,
854    /// Per row: its session's tick, its weight before forgetting, and whether its verdict was unclear
855    /// (in the rows only for the unclear-is-no-change variant).
856    tick: Vec<u32>,
857    base_w: Vec<f64>,
858    unclear: Vec<bool>,
859    levels: [usize; FAMILIES],
860    names: [Vec<String>; FAMILIES],
861    /// Per apply of the summary: its levels, its judged probability.
862    lv_of: HashMap<usize, [Option<usize>; FAMILIES]>,
863    judged_p: HashMap<usize, f64>,
864    dropped: u32,
865}
866
867/// The index of a level among the labelled ones, added when new: `names[f]`, `index[f]` by family.
868fn level_of(names: &mut [Vec<String>; FAMILIES], index: &mut [HashMap<String, usize>; FAMILIES], tagged: &(usize, String)) -> usize {
869    let (f, name) = tagged;
870    *index[*f].entry(name.clone()).or_insert_with(|| {
871        names[*f].push(name.clone());
872        names[*f].len() - 1
873    })
874}
875
876/// The route a labelled apply counts as in the model: ask, free, or not now (a placebo); None for an
877/// apply never delivered or never judged.
878fn model_route(a: &Apply) -> Option<Route> {
879    match a.route {
880        Route::Ask | Route::Free if a.delivered != super::summary::Delivered::Dropped => Some(a.route),
881        Route::Placebo => Some(Route::Not),
882        _ => None,
883    }
884}
885
886/// The applies of a logged check of `s` (none for a range the summary does not hold).
887fn applies_of<'a>(s: &'a Summary, c: &Logged) -> &'a [Apply] {
888    s.applies.get(c.first as usize..c.first as usize + usize::from(c.n)).unwrap_or(&[])
889}
890
891/// The lessons a logged check of `s` could not hand over free (select/summary.rs `Apply::nofree`, its
892/// record's `nofree`): the `had` its decision read, so a replay values it against the same fixed rule.
893fn logged_had(s: &Summary, c: &Logged) -> Vec<String> {
894    applies_of(s, c).iter().filter(|a| a.nofree).filter_map(|a| s.lessons.get(a.lesson as usize).cloned()).collect()
895}
896
897/// The units, features and routes of a logged check of `s`.
898fn check_view<'a>(s: &'a Summary, c: &Logged) -> (Vec<Unit<'a>>, Vec<Feat>, Vec<Route>) {
899    let applies = applies_of(s, c);
900    let units: Vec<Unit> =
901        applies.iter().map(|a| Unit { lesson: s.lessons.get(a.lesson as usize).map_or("", String::as_str), grade: a.grade, rank: a.rank as usize }).collect();
902    let feats = Feat::of(&units, c.stop, c.tokens);
903    let routes = applies.iter().map(|a| if a.route == Route::Placebo { Route::Not } else { a.route }).collect();
904    (units, feats, routes)
905}
906
907impl Data {
908    /// The rows of `s` (the newest `FIT_SESSIONS` sessions), unclear verdicts included as no change
909    /// when `zero`, else left out.
910    fn of(s: &Summary, zero: bool) -> Data {
911        let now = s.sessions.len() as u32;
912        let from = now.saturating_sub(FIT_SESSIONS as u32);
913        let mut names: [Vec<String>; FAMILIES] = Default::default();
914        let mut index: [HashMap<String, usize>; FAMILIES] = Default::default();
915        let judged_p = judged(s);
916        let mut d = Data {
917            obs: Vec::new(),
918            tick: Vec::new(),
919            base_w: Vec::new(),
920            unclear: Vec::new(),
921            levels: [0; FAMILIES],
922            names: Default::default(),
923            lv_of: HashMap::new(),
924            judged_p: HashMap::new(),
925            dropped: 0,
926        };
927        let names_of = |c: &Logged, a: &Apply| -> [Option<(usize, String)>; FAMILIES] {
928            [
929                Some((SESSION, s.sessions.get(c.tick as usize).map_or("", |x| x.id.as_str()).to_string())),
930                s.lessons.get(a.lesson as usize).map(|n| (LESSON, n.clone())),
931                a.judge.and_then(|j| s.judges.get(j as usize).cloned()).map(|n| (JUDGE, n)),
932            ]
933        };
934        for c in &s.checks {
935            let (_, feats, _) = check_view(s, c);
936            let (m_q, m_f) = (usize::from(c.m_q), usize::from(c.m_f));
937            for (j, f) in feats.iter().enumerate() {
938                let i = c.first as usize + j;
939                let a = &s.applies[i];
940                let Some(route) = model_route(a) else { continue };
941                let y = match a.label {
942                    Label::Changed => 1.0,
943                    // The point never came up: nothing in the work changed on it, whatever the route.
944                    Label::Ignored | Label::NotArisen => 0.0,
945                    // A change that left the consequence is read as an unclear verdict.
946                    Label::Unclear | Label::Remains if zero => 0.0,
947                    Label::Unclear | Label::Remains | Label::Open | Label::Censored => continue,
948                };
949                if c.tick < from {
950                    d.dropped += 1;
951                    continue;
952                }
953                let m = match route {
954                    Route::Ask => m_q,
955                    Route::Free => m_f,
956                    _ => 1,
957                };
958                let p = judged_p.get(&i).copied().unwrap_or(1.0);
959                let w = 1.0 / p.max(1.0 / MAX_IPW);
960                let lv = names_of(c, a).map(|n| n.map(|n| level_of(&mut names, &mut index, &n)));
961                d.obs.push(Obs { x: design(f, route, m), y, w, lv });
962                d.tick.push(c.tick);
963                d.base_w.push(w);
964                d.unclear.push(a.label.pending());
965            }
966        }
967        // Every apply's levels among the labelled ones (the monitor's predictions): an unseen one has none.
968        for c in &s.checks {
969            for i in c.first as usize..(c.first as usize + c.n as usize).min(s.applies.len()) {
970                let n = names_of(c, &s.applies[i]);
971                d.lv_of.insert(i, std::array::from_fn(|f| n[f].as_ref().and_then(|(_, n)| index[f].get(n).copied())));
972            }
973        }
974        d.levels = std::array::from_fn(|f| names[f].len());
975        d.names = names;
976        d.judged_p = judged_p;
977        d
978    }
979
980    /// The rows without their session, lesson and judge levels (P2's pruned model, `fit_pruned`).
981    fn without_levels(mut self) -> Data {
982        for o in &mut self.obs {
983            o.lv = [None; FAMILIES];
984        }
985        for lv in self.lv_of.values_mut() {
986            *lv = [None; FAMILIES];
987        }
988        self.levels = [0; FAMILIES];
989        self.names = Default::default();
990        self
991    }
992
993    /// The rows weighted by forgetting at `now` under `h`.
994    fn weighted(&self, now: u32, h: Option<u32>) -> Vec<Obs<P, FAMILIES>> {
995        self.obs.iter().zip(&self.tick).zip(&self.base_w).map(|((o, t), w)| Obs { w: w * decay(now.saturating_sub(*t), h), ..o.clone() }).collect()
996    }
997}
998
999/// Per delivered apply of `s` with a closed fate (judged, unclear or censored), the probability that
1000/// the judge gave it a verdict: a logistic fit on its route, channel, the session's applies waiting
1001/// for a verdict at its check, and whether its check was the session's last. Unclear (and a remaining
1002/// consequence, `Label::pending`) counts as not judged; not arisen as judged (`Label::verdict`).
1003pub(crate) fn judged(s: &Summary) -> HashMap<usize, f64> {
1004    // Derived: the fit's features (intercept, asked, free, stop, log pending, last check).
1005    const K: usize = 6;
1006    let mut last: HashMap<u32, usize> = HashMap::new();
1007    for (i, c) in s.checks.iter().enumerate() {
1008        last.insert(c.tick, i);
1009    }
1010    let mut rows: Vec<(usize, Obs<K, 0>)> = Vec::new();
1011    for (ci, c) in s.checks.iter().enumerate() {
1012        for i in c.first as usize..(c.first as usize + c.n as usize).min(s.applies.len()) {
1013            let a = &s.applies[i];
1014            if model_route(a).is_none() || a.label == Label::Open {
1015                continue;
1016            }
1017            let y = f64::from(u8::from(a.label.verdict()));
1018            let x = [
1019                1.0,
1020                f64::from(u8::from(a.route == Route::Ask)),
1021                f64::from(u8::from(a.route == Route::Free)),
1022                f64::from(u8::from(c.stop)),
1023                (1.0 + f64::from(a.pending)).ln(),
1024                f64::from(u8::from(last.get(&c.tick) == Some(&ci))),
1025            ];
1026            rows.push((i, Obs { x, y, w: 1.0, lv: [] }));
1027        }
1028    }
1029    if rows.is_empty() {
1030        return HashMap::new();
1031    }
1032    let spec = [Coef { mean: 0.0, sd: PRIOR_SD, ard: false, nonpos: false }; K];
1033    let obs: Vec<Obs<K, 0>> = rows.iter().map(|(_, o)| o.clone()).collect();
1034    let Some(est) = map(&obs, [], &spec, &[PRIOR_SD; K], &[], None) else { return HashMap::new() };
1035    rows.iter().map(|(i, o)| (*i, sigmoid(est.eta(o)))).collect()
1036}
1037
1038/// The log-likelihood of `obs` under `est`, each row at weight `w`.
1039fn loglik(est: &Est<P, FAMILIES>, obs: &[Obs<P, FAMILIES>]) -> f64 {
1040    obs.iter()
1041        .map(|o| {
1042            // Clamped so a certain miss costs a large finite loss, not −∞.
1043            let p = sigmoid(est.eta(o)).clamp(1e-12, 1.0 - 1e-12);
1044            o.w * (o.y * p.ln() + (1.0 - o.y) * (1.0 - p).ln())
1045        })
1046        .sum()
1047}
1048
1049/// The forgetting's half-life (`HALF_LIVES`) with the highest prequential log-likelihood: each of the
1050/// newest `PREQ_SESSIONS` labelled sessions predicted by a fit on the sessions before it, aged from it;
1051/// the spreads stay at `base`'s. A tie goes to the longer half-life.
1052fn half_life(d: &Data, base: &Est<P, FAMILIES>, spec: &[Coef; P]) -> Option<u32> {
1053    let mut ticks: Vec<u32> = d.tick.clone();
1054    ticks.sort_unstable();
1055    ticks.dedup();
1056    let eval: Vec<u32> = ticks.iter().skip(1).rev().take(PREQ_SESSIONS).rev().copied().collect();
1057    if eval.is_empty() {
1058        return None;
1059    }
1060    let mut best: (f64, Option<u32>) = (f64::NEG_INFINITY, None);
1061    for h in HALF_LIVES {
1062        let mut score = 0.0;
1063        let mut warm: Option<Est<P, FAMILIES>> = None;
1064        for &t in &eval {
1065            let train: Vec<Obs<P, FAMILIES>> = d
1066                .obs
1067                .iter()
1068                .zip(&d.tick)
1069                .zip(&d.base_w)
1070                .filter(|((_, tk), _)| **tk < t)
1071                .map(|((o, tk), w)| Obs { w: w * decay(t - tk, h), ..o.clone() })
1072                .collect();
1073            let test: Vec<Obs<P, FAMILIES>> = d.obs.iter().zip(&d.tick).filter(|(_, tk)| **tk == t).map(|(o, _)| o.clone()).collect();
1074            let Some(est) = map(&train, d.levels, spec, &base.sd, &base.spread, warm.as_ref()) else { continue };
1075            score += loglik(&est, &test);
1076            warm = Some(est);
1077        }
1078        // A tie (within float noise, relative 1e-9) keeps the longer half-life found first.
1079        if score > best.0 + 1e-9 * best.0.abs().max(1.0) || best.0 == f64::NEG_INFINITY {
1080            best = (score, h);
1081        }
1082    }
1083    best.1
1084}
1085
1086/// The value model of `est` with the level names of `d`; None unless every number is finite (a JSON
1087/// cache cannot hold another, select/summary.rs `save`).
1088fn model_of(est: &Est<P, FAMILIES>, d: &Data, judge: String) -> Option<Model> {
1089    let mut chol: Vec<f64> = est.cov.iter().flatten().copied().collect();
1090    let finite = est.beta.iter().chain(&est.sd).chain(&est.spread).chain(est.u.iter().flatten()).chain(est.var_u.iter().flatten()).all(|x| x.is_finite());
1091    if !finite || !cholesky(&mut chol, P) {
1092        return None;
1093    }
1094    let levels = |f: usize| -> BTreeMap<String, (f64, f64)> {
1095        d.names[f].iter().enumerate().map(|(l, n)| (n.clone(), (est.u[f][l], est.var_u[f][l].max(0.0).sqrt()))).collect()
1096    };
1097    Some(Model {
1098        beta: est.beta.to_vec(),
1099        chol,
1100        sd: est.sd.to_vec(),
1101        spread: est.spread,
1102        sessions: levels(SESSION),
1103        lessons: levels(LESSON),
1104        judges: levels(JUDGE),
1105        judge,
1106        converged: est.converged,
1107    })
1108}
1109
1110/// The fit of `s` (module doc): the value model, the forgetting, the delivery rates, the pool's state
1111/// and, under an engineer's `budget` (pool tokens per session), its price. The prior without labels.
1112#[must_use]
1113pub fn fit(s: &Summary, budget: Option<f64>) -> Fit {
1114    fit_with(s, budget, &coefs(), true)
1115}
1116
1117/// `borg debug select` P2's pre-registered pruned model (tasks/todo.md, P2: "prune the model to
1118/// grade, route and dilution and rerun once"): `fit` of `s` with the value model cut to the terms of
1119/// `PRUNED_KEEPS`, every other coefficient held at N(0, `SD_FLOOR`²) and no session, lesson or judge
1120/// effects (their spreads 0, so a prediction adds none), its half-life chosen as `fit` chooses it.
1121/// Evaluation only: never what a hook decides with.
1122#[must_use]
1123pub fn fit_pruned(s: &Summary, budget: Option<f64>) -> Fit {
1124    fit_with(s, budget, &pruned(), false)
1125}
1126
1127/// `fit` under the priors `spec`, with the session, lesson and judge effects when `levels`.
1128fn fit_with(s: &Summary, budget: Option<f64>, spec: &[Coef; P], levels: bool) -> Fit {
1129    let data = |zero: bool| if levels { Data::of(s, zero) } else { Data::of(s, zero).without_levels() };
1130    let d = data(false);
1131    let now = s.sessions.len() as u32;
1132    let mut fit = Fit { key: s.key(), labels: d.obs.len() as u32, dropped: d.dropped, budget: budget.filter(|b| *b > 0.0), ..Fit::default() };
1133    let base = if d.obs.is_empty() { None } else { eb(&d.obs, d.levels, spec, None) };
1134    if let Some(base) = &base {
1135        fit.half_life = half_life(&d, base, spec);
1136        let est = eb(&d.weighted(now, fit.half_life), d.levels, spec, Some(base));
1137        let judge = s.checks.iter().rev().flat_map(|c| applies_of(s, c)).find_map(|a| a.judge);
1138        let judge = judge.filter(|_| levels).and_then(|j| s.judges.get(j as usize)).cloned().unwrap_or_default();
1139        if let Some(est) = est {
1140            let z = data(true);
1141            if z.unclear.iter().any(|u| *u)
1142                && let Some(alt) = eb(&z.weighted(now, fit.half_life), z.levels, spec, None)
1143            {
1144                fit.sensitive = [ASK, NOT].iter().any(|&k| est.beta[k].signum() != alt.beta[k].signum());
1145            }
1146            let eta = d.obs.iter().map(|o| est.eta(o)).sum::<f64>() / d.obs.len() as f64;
1147            fit.pool.eta = eta;
1148            fit.pool.slope = (est.beta[POOL], est.cov[POOL][POOL].max(0.0).sqrt());
1149            fit.pool.not = (est.beta[NOT], est.cov[NOT][NOT].max(0.0).sqrt());
1150            // Without families no level has an effect: the fit's spreads are EM's untouched start.
1151            fit.model = model_of(&est, &d, judge).map(|m| if levels { m } else { Model { spread: [0.0; FAMILIES], ..m } });
1152        }
1153    }
1154    fit.rates = rates(s, fit.half_life);
1155    pool_state(s, &mut fit.pool);
1156    if let Some(b) = fit.budget {
1157        fit.lambda = price(s, &fit, b);
1158    }
1159    fit
1160}
1161
1162/// The n = 0 prior as a fit, for `borg debug select` P4's "ungated policy under the n = 0 prior": the
1163/// value model's MAP over no labels (every coefficient at its prior mean with its prior covariance,
1164/// every family at its starting spread) and the delivery rates' Beta(1, 1) means. Never what a hook
1165/// decides with: `fit` without a label has no model, so cold start is the fixed rule.
1166#[must_use]
1167pub fn prior() -> Fit {
1168    prior_with(&coefs(), true)
1169}
1170
1171/// The n = 0 prior of P2's pruned model (`fit_pruned`), for its rerun's units with no label before
1172/// their check: `prior` under the pruned model's priors (`pruned`) and, as `fit_pruned`, no session,
1173/// lesson or judge effects (spreads 0). Evaluation only.
1174#[must_use]
1175pub fn prior_pruned() -> Fit {
1176    prior_with(&pruned(), false)
1177}
1178
1179/// The value model's MAP over no labels under the priors `spec`, each family at its starting spread
1180/// when `levels`, else at 0 (`fit_with`), and the delivery rates' Beta(1, 1) means.
1181fn prior_with(spec: &[Coef; P], levels: bool) -> Fit {
1182    let s = Summary::default();
1183    let d = Data::of(&s, false);
1184    let sd: [f64; P] = std::array::from_fn(|k| spec[k].sd);
1185    let model = map(&d.obs, d.levels, spec, &sd, &[LEVEL_START; FAMILIES], None)
1186        .and_then(|est| model_of(&est, &d, String::new()))
1187        .map(|m| if levels { m } else { Model { spread: [0.0; FAMILIES], ..m } });
1188    Fit { model, rates: rates(&s, None), ..Fit::default() }
1189}
1190
1191/// π/8, the probit approximation's scale: E[σ(η)] ≈ σ(μ / √(1 + π σ² / 8)) for η ~ N(μ, σ²) (MacKay
1192/// 1992). Method.
1193const PROBIT: f64 = std::f64::consts::PI / 8.0;
1194
1195/// The model's chance that an apply with features `f`, routed `route` among `m` of its route, changes
1196/// the work (`borg debug select` P2's prediction): σ(η) averaged over η's Laplace posterior by the
1197/// probit approximation (`PROBIT`), η's variance from the coefficients' covariance and the session's,
1198/// lesson's and next judge's effects (an unseen level at 0 with its family's spread). None without a
1199/// model of this build's layout.
1200#[must_use]
1201pub fn predict(fit: &Fit, f: &Feat, route: Route, m: usize, session: &str, lesson: &str) -> Option<f64> {
1202    let model = fit.model.as_ref().filter(|m| m.current())?;
1203    let x = design(f, route, m);
1204    // (Lᵀx)_k over the lower factor's rows i ≥ k: xᵀΣx = |Lᵀx|².
1205    let lx = (0..P).map(|k| (k..P).map(|i| model.chol[i * P + k] * x[i]).sum::<f64>());
1206    let mut var: f64 = lx.map(|v| v * v).sum();
1207    let mut mean: f64 = model.beta.iter().zip(&x).map(|(b, x)| b * x).sum();
1208    for (map, name, spread) in [
1209        (&model.sessions, session, model.spread[SESSION]),
1210        (&model.lessons, lesson, model.spread[LESSON]),
1211        (&model.judges, model.judge.as_str(), model.spread[JUDGE]),
1212    ] {
1213        let (mu, sd) = map.get(name).copied().unwrap_or((0.0, spread));
1214        mean += mu;
1215        var += sd * sd;
1216    }
1217    Some(sigmoid(mean / (1.0 + PROBIT * var).sqrt()))
1218}
1219
1220/// The delivery rates of `s` under half-life `h`: Beta(1, 1) on every session's tallies, the compacted
1221/// ones included (select/summary.rs `Summary::tallies`); a live question's certain until one is tallied.
1222fn rates(s: &Summary, h: Option<u32>) -> Rates {
1223    let mean = |(k, miss): (f64, f64)| (1.0 + k) / (2.0 + k + miss);
1224    let [free_stop, free_live, later, wait, ask] = s.tallies(h);
1225    // Baseline before data (`Rates::ask_live`).
1226    let ask_live = if ask.0 + ask.1 > 0.0 { mean(ask) } else { 1.0 };
1227    Rates { free_stop: mean(free_stop), free_live: mean(free_live), later: mean(later), wait: mean(wait), ask_live }
1228}
1229
1230/// The pool's learned state from `s` into `pool`: the yields (PAVA over the bins), tokens per lesson,
1231/// and the latency model (least squares plus the residuals' 95% quantile).
1232fn pool_state(s: &Summary, pool: &mut PoolFit) {
1233    // Up to the first bin no lesson was shown in: past it (a gap between a tail sample's sparse places,
1234    // select/summary.rs `tail_of`) a bin's yield would be its prior alone, and a pool reaching there
1235    // would count as known (`pool_feasible`). A pool's own bins have no gap.
1236    let bins: Vec<(f64, f64)> = s.pool.bins.iter().take_while(|(n, _)| *n > 0).map(|&(n, k)| (1.0 + k as f64, 1.0 + n.saturating_sub(k) as f64)).collect();
1237    pool.yields = pava(&bins);
1238    pool.per_lesson = if s.pool.shown > 0 { s.pool.tokens as f64 / s.pool.shown as f64 } else { 0.0 };
1239    let obs = &s.pool.latency;
1240    pool.latency_n = obs.len() as u32;
1241    let mut read: Vec<u32> = obs.iter().map(|o| o.0).collect();
1242    read.sort_unstable_by(|a, b| b.cmp(a));
1243    pool.latency_reach = read.get(LATENCY_MIN - 1).copied().unwrap_or(0);
1244    if obs.len() >= 2 {
1245        let n = obs.len() as f64;
1246        let mx = obs.iter().map(|o| f64::from(o.0)).sum::<f64>() / n;
1247        let my = obs.iter().map(|o| f64::from(o.1)).sum::<f64>() / n;
1248        let sxx: f64 = obs.iter().map(|o| (f64::from(o.0) - mx).powi(2)).sum();
1249        let sxy: f64 = obs.iter().map(|o| (f64::from(o.0) - mx) * (f64::from(o.1) - my)).sum();
1250        let b = if sxx > 0.0 { (sxy / sxx).max(0.0) } else { 0.0 };
1251        let a = my - b * mx;
1252        let mut res: Vec<f64> = obs.iter().map(|o| f64::from(o.1) - a - b * f64::from(o.0)).collect();
1253        res.sort_by(f64::total_cmp);
1254        let q = res[((1.0 - DELTA) * (res.len() - 1) as f64).ceil() as usize];
1255        pool.latency = (a, b, q.max(0.0));
1256    }
1257}
1258
1259/// Pool adjacent violators: Beta posteriors per bin, merged so their means never rise with position;
1260/// each bin of a merged block carries the block's summed parameters.
1261fn pava(bins: &[(f64, f64)]) -> Vec<(f64, f64)> {
1262    let mut blocks: Vec<(f64, f64, usize)> = Vec::new();
1263    for &(a, b) in bins {
1264        blocks.push((a, b, 1));
1265        while blocks.len() >= 2 {
1266            let (x, y) = (blocks[blocks.len() - 2], blocks[blocks.len() - 1]);
1267            if x.0 / (x.0 + x.1) >= y.0 / (y.0 + y.1) {
1268                break;
1269            }
1270            blocks.pop();
1271            if let Some(last) = blocks.last_mut() {
1272                *last = (x.0 + y.0, x.1 + y.1, x.2 + y.2);
1273            }
1274        }
1275    }
1276    blocks.iter().flat_map(|&(a, b, n)| std::iter::repeat_n((a, b), n)).collect()
1277}
1278
1279/// A joint draw of the model for one check: the coefficients, and each unit's η without its route
1280/// (its session, lesson and judge effects included).
1281#[derive(Debug, Clone)]
1282struct Theta {
1283    b: [f64; P],
1284    base: Vec<f64>,
1285}
1286
1287/// The seed of each level of a check, by family and name, so draw k of one session or lesson is the
1288/// same at every check (the gate's ledger re-values past checks with the same draws).
1289struct Levels<'a> {
1290    name: &'a str,
1291    session: u64,
1292    judge: u64,
1293    lessons: Vec<u64>,
1294}
1295
1296impl<'a> Levels<'a> {
1297    fn of(session: &'a str, judge: &str, units: &[Unit]) -> Levels<'a> {
1298        Levels {
1299            name: session,
1300            session: hash(&[b"session", session.as_bytes()]),
1301            judge: hash(&[b"judge", judge.as_bytes()]),
1302            lessons: units.iter().map(|u| hash(&[b"lesson", u.lesson.as_bytes()])).collect(),
1303        }
1304    }
1305}
1306
1307/// Draw `seed` of `m`'s coefficients: β̂ + L z, coordinate by coordinate, each bounded slope drawn
1308/// from its normal given the coordinates before it truncated at 0 (`below_zero`: the same z mapped by
1309/// its inverse CDF, never a clamp, which would put half the mass of a slope whose mode is 0 on 0 itself)
1310/// and the later coordinates conditioned on the value it took. Under the n = 0 prior (the slopes
1311/// independent of the rest) each is exactly its prior, `DILUTION_PRIOR`'s half-normal; with data it is
1312/// the sequential (GHK) approximation of the truncated joint posterior.
1313fn draw_beta(m: &Model, seed: u64) -> [f64; P] {
1314    let mut rng = Rng::new(seed);
1315    let mut z: [f64; P] = std::array::from_fn(|_| normal(&mut rng));
1316    let spec = coefs();
1317    let l = |i: usize, k: usize| m.chol.get(i * P + k).copied().unwrap_or(0.0);
1318    let mut x = [0.0; P];
1319    for i in 0..P {
1320        let given = m.beta.get(i).copied().unwrap_or(0.0) + (0..i).map(|k| l(i, k) * z[k]).sum::<f64>();
1321        x[i] = given + l(i, i) * z[i];
1322        if spec[i].nonpos {
1323            x[i] = below_zero(given, l(i, i), z[i]);
1324            // The z that gives the truncated value: what the later coordinates are conditioned on.
1325            if l(i, i) > 0.0 {
1326                z[i] = (x[i] - given) / l(i, i);
1327            }
1328        }
1329    }
1330    x
1331}
1332
1333/// The draw of N(`mean`, `sd`²) truncated to ≤ 0 at the standard normal draw `z`: Φ⁻¹ of Φ(z) scaled
1334/// into the mass below 0, in logs so a bound far below the mean neither underflows nor leaves the
1335/// half-line. Monotone in z; `mean` held ≤ 0 when `sd` is 0.
1336fn below_zero(mean: f64, sd: f64, z: f64) -> f64 {
1337    if sd <= 0.0 || !sd.is_finite() {
1338        return mean.min(0.0);
1339    }
1340    let bound = -mean / sd;
1341    // The draw's lower tail Φ(z)·Φ(bound) and its upper 1 − that, each without cancellation.
1342    let ln_lower = ln_phi(z) + ln_phi(bound);
1343    let upper = phi(-z) + phi(z) * phi(-bound);
1344    (mean + sd * probit(ln_lower, upper)).min(0.0)
1345}
1346
1347/// The standard normal CDF Φ(x): O(1), relative error below 1.2e-7 (`erfc`).
1348fn phi(x: f64) -> f64 {
1349    0.5 * erfc(-x / std::f64::consts::SQRT_2)
1350}
1351
1352/// ln Φ(x), finite far into the lower tail (`erfcx`, the factor exp(−x²/2) taken out).
1353fn ln_phi(x: f64) -> f64 {
1354    if x < 0.0 { 0.5f64.ln() - 0.5 * x * x + erfcx(-x / std::f64::consts::SQRT_2).ln() } else { (-0.5 * erfc(x / std::f64::consts::SQRT_2)).ln_1p() }
1355}
1356
1357/// erfc(x) (`erfcx` for x ≥ 0, reflected below).
1358fn erfc(x: f64) -> f64 {
1359    let a = x.abs();
1360    let tail = (-a * a).exp() * erfcx(a);
1361    if x >= 0.0 { tail } else { 2.0 - tail }
1362}
1363
1364/// exp(x²)·erfc(x) for x ≥ 0: the Chebyshev fit of Numerical Recipes' `erfcc` (Press et al. 2007,
1365/// §6.2), its relative error below 1.2e-7 everywhere. Method: the coefficients are the fit's.
1366fn erfcx(x: f64) -> f64 {
1367    const C: [f64; 10] =
1368        [-1.265_512_23, 1.000_023_68, 0.374_091_96, 0.096_784_18, -0.186_288_06, 0.278_868_07, -1.135_203_98, 1.488_515_87, -0.822_152_23, 0.170_872_77];
1369    let t = 1.0 / (1.0 + 0.5 * x);
1370    t * C.iter().rev().fold(0.0, |acc, c| acc * t + c).exp()
1371}
1372
1373/// Φ⁻¹ of the probability whose lower tail is exp(`ln_lower`) and upper tail `upper` (both given, so
1374/// neither tail loses its digits): Acklam's rational approximation, relative error below 1.15e-9.
1375/// Method: the coefficients and the tails' breakpoint (0.02425) are Acklam's.
1376fn probit(ln_lower: f64, upper: f64) -> f64 {
1377    const A: [f64; 6] =
1378        [-3.969_683_028_665_376e1, 2.209_460_984_245_205e2, -2.759_285_104_469_687e2, 1.383_577_518_672_69e2, -3.066_479_806_614_716e1, 2.506_628_277_459_239];
1379    const B: [f64; 5] = [-5.447_609_879_822_406e1, 1.615_858_368_580_409e2, -1.556_989_798_598_866e2, 6.680_131_188_771_972e1, -1.328_068_155_288_572e1];
1380    const C: [f64; 6] =
1381        [-7.784_894_002_430_293e-3, -3.223_964_580_411_365e-1, -2.400_758_277_161_838, -2.549_732_539_343_734, 4.374_664_141_464_968, 2.938_163_982_698_783];
1382    const D: [f64; 4] = [7.784_695_709_041_462e-3, 3.224_671_290_700_398e-1, 2.445_134_137_142_996, 3.754_408_661_907_416];
1383    const LOW: f64 = 0.02425;
1384    let poly = |c: &[f64], x: f64| c.iter().fold(0.0, |acc, k| acc * x + k);
1385    // The tail from its log: q = √(−2 ln p).
1386    let tail = |ln_p: f64| {
1387        let q = (-2.0 * ln_p).sqrt();
1388        poly(&C, q) / (poly(&D, q) * q + 1.0)
1389    };
1390    let lower = ln_lower.exp();
1391    if lower < LOW {
1392        tail(ln_lower)
1393    } else if upper < LOW {
1394        -tail(upper.ln())
1395    } else {
1396        let q = lower - 0.5;
1397        let r = q * q;
1398        poly(&A, r) * q / (poly(&B, r) * r + 1.0)
1399    }
1400}
1401
1402/// Draw `seed` of `m` for a check, its coefficients `b` (`draw_beta` of the same seed): each level
1403/// from its marginal (an unseen level from its family's spread), seeded by the draw and the level.
1404/// The levels are drawn apart from β: wider than the joint posterior where a level and the intercept
1405/// trade off, so the gate errs cautious.
1406fn theta_with(m: &Model, b: [f64; P], feats: &[Feat], units: &[Unit], lv: &Levels, seed: u64) -> Theta {
1407    theta_by(m, b, feats, units, lv, |(mean, sd), h| mean + sd * normal(&mut Rng::new(mix(seed, h))))
1408}
1409
1410/// `m` for a check at its posterior centre (`choose`'s evidence rule): the coefficients at β̂, the
1411/// Laplace posterior's mean, which for a bounded slope is its mode (held ≤ 0; at the n = 0 prior 0,
1412/// not the half-normal's mean −0.08: dilution is not assumed, docs/evidence.md Rules v2), and each
1413/// level at its mean (an unseen one at 0). Not a draw: the draws (`draw_beta`) carry the truncated
1414/// spread the quantile is taken over.
1415fn theta_mean(m: &Model, feats: &[Feat], units: &[Unit], lv: &Levels) -> Theta {
1416    let spec = coefs();
1417    let b = std::array::from_fn(|i| {
1418        let x = m.beta.get(i).copied().unwrap_or(0.0);
1419        if spec[i].nonpos { x.min(0.0) } else { x }
1420    });
1421    theta_by(m, b, feats, units, lv, |(mean, _), _| mean)
1422}
1423
1424/// `m` for a check under the coefficients `b`, each level's effect from `level` (its posterior mean
1425/// and sd, an unseen level's (0, its family's spread), and its seed in `lv`).
1426fn theta_by(m: &Model, b: [f64; P], feats: &[Feat], units: &[Unit], lv: &Levels, level: impl Fn((f64, f64), u64) -> f64) -> Theta {
1427    let effect = |map: &BTreeMap<String, (f64, f64)>, name: &str, spread: f64, h: u64| level(map.get(name).copied().unwrap_or((0.0, spread)), h);
1428    let shared = effect(&m.sessions, lv.name, m.spread[SESSION], lv.session) + effect(&m.judges, &m.judge, m.spread[JUDGE], lv.judge);
1429    let base = feats
1430        .iter()
1431        .zip(units)
1432        .zip(&lv.lessons)
1433        .map(|((f, u), h)| dot(&b, &design(f, Route::Free, 1)) + shared + effect(&m.lessons, u.lesson, m.spread[LESSON], *h))
1434        .collect();
1435    Theta { b, base }
1436}
1437
1438/// Draw `seed` of `m` for a check (`draw_beta`, `theta_with`).
1439fn theta(m: &Model, feats: &[Feat], units: &[Unit], lv: &Levels, seed: u64) -> Theta {
1440    theta_with(m, draw_beta(m, seed), feats, units, lv, seed)
1441}
1442
1443/// The value of each route of each unit under one draw (module doc: τ).
1444struct Valuer<'a> {
1445    t: &'a Theta,
1446    feats: &'a [Feat],
1447    rates: &'a Rates,
1448}
1449
1450impl Valuer<'_> {
1451    fn n(&self) -> usize {
1452        self.feats.len()
1453    }
1454
1455    fn stop(&self) -> bool {
1456        self.feats.first().is_some_and(|f| f.stop)
1457    }
1458
1459    /// P(changed) of unit j not delivered.
1460    fn p_not(&self, j: usize) -> f64 {
1461        let b = &self.t.b;
1462        sigmoid(self.t.base[j] + b[NOT] + b[NOT_G] * (f64::from(self.feats[j].grade) - 2.0))
1463    }
1464
1465    fn ask(&self, j: usize, m: usize) -> f64 {
1466        let (b, f) = (&self.t.b, &self.feats[j]);
1467        let eta = self.t.base[j]
1468            + b[ASK]
1469            + b[ASK_M] * (m.max(1) as f64).ln()
1470            + b[ASK_STOP] * f64::from(u8::from(f.stop))
1471            + b[ASK_G3] * f64::from(u8::from(f.grade == 3));
1472        // A stop's question blocks, so it arrives; a live one of a check with a 3 only if it reaches the
1473        // drone, during the turn or waiting for the stop, which asks it; one of a check without a 3 no
1474        // stop asks (hook.rs `live_check`): like a hand-over it arrives only at a tool call or the next
1475        // prompt, at the free rate.
1476        let rate = match (self.stop(), f.three) {
1477            (true, _) => 1.0,
1478            (false, true) => self.rates.ask_live,
1479            (false, false) => self.rates.free_live,
1480        };
1481        rate * (sigmoid(eta) - self.p_not(j))
1482    }
1483
1484    fn free(&self, j: usize, m: usize) -> f64 {
1485        let rate = if self.stop() { self.rates.free_stop } else { self.rates.free_live };
1486        rate * (sigmoid(self.t.base[j] + self.t.b[FREE_M] * (m.max(1) as f64).ln()) - self.p_not(j))
1487    }
1488
1489    /// The check's value under `routes` (aligned with the units). Not now (a placebo too) is worth 0,
1490    /// at the stop and during the turn (the comparison is against not delivering): a lesson left for
1491    /// later earns its value at the check that delivers it, whose ledger entry credits it; credited
1492    /// here as well, the later rate × a hand-over's lift, it would count twice, at a rate no draw
1493    /// varies.
1494    fn value(&self, routes: &[Route]) -> f64 {
1495        let m_q = routes.iter().filter(|r| **r == Route::Ask).count();
1496        let m_f = routes.iter().filter(|r| **r == Route::Free).count();
1497        routes
1498            .iter()
1499            .enumerate()
1500            .map(|(j, r)| match r {
1501                Route::Ask => self.ask(j, m_q),
1502                Route::Free => self.free(j, m_f),
1503                Route::Placebo | Route::Not => 0.0,
1504            })
1505            .sum()
1506    }
1507}
1508
1509/// A stop's grade 3 is always asked: never routed away from a question without a pre-registered
1510/// randomised test of its own.
1511fn forced(f: &Feat) -> bool {
1512    f.stop && f.grade == 3
1513}
1514
1515/// One draw's value of every unit on every route and size (`Valuer`), computed once: the solver and
1516/// the gate read sums of it, never a sigmoid again.
1517struct Table {
1518    n: usize,
1519    /// `ask[m·n + j]`, `free[m·n + j]` for m in 0..=n (0 unused); not now is worth 0 (`Valuer::value`).
1520    /// Whether j is forced, and whether it may not go free (a lesson the session already had,
1521    /// `nofree_of`).
1522    ask: Vec<f64>,
1523    free: Vec<f64>,
1524    forced: Vec<bool>,
1525    nofree: Vec<bool>,
1526}
1527
1528impl Table {
1529    /// The table of `v`, the units marked in `nofree` (aligned, or shorter: the rest may go free) kept
1530    /// from the free route.
1531    fn of(v: &Valuer, nofree: &[bool]) -> Table {
1532        let n = v.n();
1533        let mut ask = vec![0.0; (n + 1) * n];
1534        let mut free = vec![0.0; (n + 1) * n];
1535        for m in 1..=n {
1536            for j in 0..n {
1537                ask[m * n + j] = v.ask(j, m);
1538                free[m * n + j] = v.free(j, m);
1539            }
1540        }
1541        Table { n, ask, free, forced: v.feats.iter().map(forced).collect(), nofree: (0..n).map(|j| nofree.get(j).copied().unwrap_or(false)).collect() }
1542    }
1543
1544    /// The check's value under `routes` (`Valuer::value`), read from the table: the tests' check that
1545    /// the solver's entries value as the model does.
1546    #[cfg(test)]
1547    fn value(&self, routes: &[Route]) -> f64 {
1548        let m_q = routes.iter().filter(|r| **r == Route::Ask).count();
1549        let m_f = routes.iter().filter(|r| **r == Route::Free).count();
1550        let n = self.n;
1551        routes
1552            .iter()
1553            .enumerate()
1554            .map(|(j, r)| match r {
1555                Route::Ask => self.ask[m_q * n + j],
1556                Route::Free => self.free[m_f * n + j],
1557                Route::Placebo | Route::Not => 0.0,
1558            })
1559            .sum()
1560    }
1561}
1562
1563/// An f64 ordered by `total_cmp`, for a heap.
1564#[derive(Debug, Clone, Copy, PartialEq)]
1565struct Total(f64);
1566
1567impl Eq for Total {}
1568
1569impl PartialOrd for Total {
1570    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
1571        Some(self.cmp(other))
1572    }
1573}
1574
1575impl Ord for Total {
1576    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
1577        self.0.total_cmp(&other.0)
1578    }
1579}
1580
1581/// Into `out`: the sum of the `k` largest of the first s values, for every s (NEG_INFINITY while
1582/// s < k). O(n log k).
1583fn top_sums(values: impl Iterator<Item = f64>, k: usize, out: &mut Vec<f64>, heap: &mut std::collections::BinaryHeap<std::cmp::Reverse<Total>>) {
1584    out.clear();
1585    heap.clear();
1586    out.push(if k == 0 { 0.0 } else { f64::NEG_INFINITY });
1587    let mut sum = 0.0;
1588    for x in values {
1589        if k > 0 {
1590            if heap.len() < k {
1591                heap.push(std::cmp::Reverse(Total(x)));
1592                sum += x;
1593            } else if let Some(min) = heap.peek().map(|r| r.0.0)
1594                && x > min
1595            {
1596                heap.pop();
1597                heap.push(std::cmp::Reverse(Total(x)));
1598                sum += x - min;
1599            }
1600        }
1601        out.push(if heap.len() < k { f64::NEG_INFINITY } else { sum });
1602    }
1603}
1604
1605/// The routes maximising the check's value (`Table::value`) over every routing with at most `rail`
1606/// asks (more only for the forced ones) and `cap` free lessons, the forced units asked and the units
1607/// that may not go free (`Table::nofree`) never free. Exact: for fixed sizes (m_Q, m_F) an optimum
1608/// asks before it hands over in the order of ask's gain over free's (an exchange argument; a unit that
1609/// may not go free has an infinite key, so it leads, and the split never passes it to the free side),
1610/// so per size pair one sort and one sweep over the split. O(n³ log n). Deterministic: ties keep the
1611/// first found (fewer asks, fewer free, earlier split).
1612fn solve(t: &Table, rail: usize, cap: usize) -> Vec<Route> {
1613    let n = t.n;
1614    let nf_forced = t.forced.iter().filter(|x| **x).count();
1615    let open: Vec<usize> = (0..n).filter(|&j| !t.forced[j]).collect();
1616    // The open units that may not go free: first in every order below, so every split leaves them on
1617    // the ask-or-not side.
1618    let held = open.iter().filter(|&&j| t.nofree[j]).count();
1619    let q_max = rail.max(nf_forced).min(n);
1620    let f_max = cap.min(open.len() - held);
1621    // Gains against not now, which is worth 0 (`Valuer::value`), so a route's value; size 0 gains nothing.
1622    let ask = |m: usize, j: usize| if m == 0 { 0.0 } else { t.ask[m * n + j] };
1623    let free = |m: usize, j: usize| if m == 0 { 0.0 } else { t.free[m * n + j] };
1624    let mut order = open.clone();
1625    let mut keys = vec![0.0; n];
1626    let (mut pre, mut suf) = (Vec::with_capacity(n + 1), Vec::with_capacity(n + 1));
1627    let mut heap = std::collections::BinaryHeap::with_capacity(n + 1);
1628    let sort = |order: &mut Vec<usize>, keys: &mut Vec<f64>, mq: usize, mf: usize| {
1629        for &j in &open {
1630            keys[j] = if t.nofree[j] { f64::INFINITY } else { ask(mq, j) - free(mf, j) };
1631        }
1632        order.clear();
1633        order.extend_from_slice(&open);
1634        order.sort_by(|&a, &b| keys[b].total_cmp(&keys[a]).then(a.cmp(&b)));
1635    };
1636    let mut best: Option<(f64, usize, usize, usize)> = None;
1637    for mq in nf_forced..=q_max {
1638        let k = mq - nf_forced;
1639        if k > open.len() {
1640            break;
1641        }
1642        let fixed: f64 = (0..n).filter(|&j| t.forced[j]).map(|j| ask(mq, j)).sum();
1643        for mf in 0..=f_max.min(open.len() - k) {
1644            sort(&mut order, &mut keys, mq, mf);
1645            top_sums(order.iter().map(|&j| ask(mq, j)), k, &mut pre, &mut heap);
1646            top_sums(order.iter().rev().map(|&j| free(mf, j)), mf, &mut suf, &mut heap);
1647            for split in k.max(held)..=open.len() - mf {
1648                let total = fixed + pre[split] + suf[open.len() - split];
1649                if best.is_none_or(|b| total > b.0) {
1650                    best = Some((total, mq, mf, split));
1651                }
1652            }
1653        }
1654    }
1655    let mut routes = vec![Route::Not; n];
1656    for j in (0..n).filter(|&j| t.forced[j]) {
1657        routes[j] = Route::Ask;
1658    }
1659    let Some((_, mq, mf, split)) = best else { return routes };
1660    sort(&mut order, &mut keys, mq, mf);
1661    let pick = |within: &[usize], gain: &dyn Fn(usize) -> f64, k: usize| -> Vec<usize> {
1662        let mut c = within.to_vec();
1663        c.sort_by(|&a, &b| gain(b).total_cmp(&gain(a)).then(a.cmp(&b)));
1664        c.truncate(k);
1665        c
1666    };
1667    for j in pick(&order[..split], &|j| ask(mq, j), mq - nf_forced) {
1668        routes[j] = Route::Ask;
1669    }
1670    for j in pick(&order[split..], &|j| free(mf, j), mf) {
1671        routes[j] = Route::Free;
1672    }
1673    routes
1674}
1675
1676/// The fixed rule's routes for a session that already had `had` (conscience.rs `graded_without`
1677/// without a cap), by position: a lesson the model named twice keeps each copy's route.
1678#[must_use]
1679pub fn fixed_routes(units: &[Unit], had: &[String]) -> Vec<Route> {
1680    let ls: Vec<Challenge> = units.iter().map(|u| Challenge { id: u.lesson.to_string(), ..Default::default() }).collect();
1681    let applied: Vec<(&Challenge, u8)> = ls.iter().zip(units).map(|(c, u)| (c, u.grade)).collect();
1682    let (ask, free) = conscience::graded_without(&applied, None, had);
1683    let holds = |v: &[&Challenge], c: &Challenge| v.iter().any(|x| std::ptr::eq(*x, c));
1684    ls.iter()
1685        .map(|c| match (holds(&ask, c), holds(&free, c)) {
1686            (true, _) => Route::Ask,
1687            (_, true) => Route::Free,
1688            _ => Route::Not,
1689        })
1690        .collect()
1691}
1692
1693/// Per unit, whether its lesson is one the session already had (`had`): it may not go free.
1694fn nofree_of(units: &[Unit], had: &[String]) -> Vec<bool> {
1695    units.iter().map(|u| had.iter().any(|h| h == u.lesson)).collect()
1696}
1697
1698/// The check a decision is made for, as the model sees it.
1699#[derive(Debug, Clone, Copy)]
1700pub struct Check<'a> {
1701    pub session: &'a str,
1702    pub stop: bool,
1703    /// The check's pool tokens (0 unknown: the baseline's).
1704    pub tokens: u32,
1705}
1706
1707/// `Decision::source` values. Protocol: logged as the graded record's `source` (outcome.rs), which the
1708/// summary fold, `borg debug select`, `borg top` and the web's Selection view read back.
1709/// `FIXED`: the fixed rule because the policy cannot decide yet (cold start, an empty gate, no model).
1710pub const FIXED: &str = "fixed";
1711/// `SIZE`: the fixed rule past `SOLVE_MAX` applies.
1712pub const SIZE: &str = "size";
1713/// `GATE`: the gate kept the fixed rule, its allowance too short for the deviation's risk (the
1714/// evidence rule's, or the randomised test's).
1715pub const GATE: &str = "gate";
1716/// `EVIDENCE`: the evidence rule's routes (`evident`): the routes best under the posterior mean where
1717/// they beat the fixed rule at the `DELTA` quantile over the `DRAWS` joint draws, else, when the
1718/// randomised test does not run (the stop, no lesson to test, α 0), the fixed rule's.
1719pub const EVIDENCE: &str = "evidence";
1720/// `EXPERIMENT`: a check of the randomised question-count test whose draw s routes differently from
1721/// the fixed rule (`Decision::xk`, `xs`).
1722pub const EXPERIMENT: &str = "experiment";
1723/// `EXPERIMENT_CONTROL`: a check of the test whose draw s is the fixed rule's own count (s = 0
1724/// without a 3, s = k with one), so it routes as the fixed rule: the test's control arm.
1725pub const EXPERIMENT_CONTROL: &str = "experiment_control";
1726
1727/// A check's decision: a route per unit, each unit's chance of being asked (`p`) and handed over free
1728/// (`pf`), what set the routes (`source`: `FIXED`, `SIZE`, `GATE`, `EVIDENCE`, `EXPERIMENT`,
1729/// `EXPERIMENT_CONTROL`), the quality the gate may still risk
1730/// after the ledger's past (`Gate`), at its `DELTA` quantile, and how much of it this decision takes
1731/// (`risk`: how far its routes lower that quantile, 0 for the fixed rule's). The gate admits a
1732/// deviation exactly when `risk` ≤ `gate`, which `borg debug select` P3 checks. A check the randomised
1733/// question-count test considered (sources `EXPERIMENT`, `EXPERIMENT_CONTROL`, and `GATE` when the
1734/// gate refused its draw) carries `xk`, the fixed rule's delivered non-3 lessons that may go free, and
1735/// `xs`, the drawn number of them to ask (on `GATE` the draw the gate refused: the routes are the fixed
1736/// rule's); both None on every other check (outcome.rs `xk`, `xs`).
1737#[derive(Debug, Clone, PartialEq)]
1738pub struct Decision {
1739    pub routes: Vec<Route>,
1740    pub p: Vec<f64>,
1741    pub pf: Vec<f64>,
1742    pub source: &'static str,
1743    pub gate: f64,
1744    pub risk: f64,
1745    pub xk: Option<u32>,
1746    pub xs: Option<u32>,
1747}
1748
1749/// The `DELTA` quantile of `v` (the ⌈δ·n⌉-th smallest: the lower side, cautious).
1750fn lower_quantile(v: &mut [f64]) -> f64 {
1751    if v.is_empty() {
1752        return 0.0;
1753    }
1754    v.sort_by(f64::total_cmp);
1755    v[((DELTA * v.len() as f64).ceil() as usize).clamp(1, v.len()) - 1]
1756}
1757
1758/// The quality `gate` may still risk below the fixed rule at `ALPHA`: its allowance plus the ledger's
1759/// `DELTA` quantile, not held at 0 (`remaining_at` is), so a test can see an overspend as a negative.
1760#[cfg(test)]
1761#[must_use]
1762pub(crate) fn remaining(gate: &Gate) -> f64 {
1763    gate.allowance + lower_quantile(&mut gate.gain.clone())
1764}
1765
1766/// `gate`'s allowance at the risk share `alpha` (select.rs `risk_of`): `choose`'s, for the evidence
1767/// rule's deviations and the randomised test's alike.
1768fn allowance_at(gate: &Gate, alpha: f64) -> f64 {
1769    // Derived: the ledger accrues `ALPHA` × the fixed rule's value per check (`add_with`), so its
1770    // allowance scaled by alpha / `ALPHA` is exactly alpha's; 0 stays 0 whatever the ledger holds.
1771    if alpha > 0.0 { gate.allowance * (alpha / ALPHA) } else { 0.0 }
1772}
1773
1774/// What `gate` may still risk below the fixed rule at the risk share `alpha`, never below 0: the gate
1775/// in force (`Decision::gate`), which the monitoring shows.
1776#[must_use]
1777pub fn remaining_at(gate: &Gate, alpha: f64) -> f64 {
1778    let (allowance, ledger) = gate_parts(gate, alpha);
1779    (allowance + ledger).max(0.0)
1780}
1781
1782/// The two parts `remaining_at` adds: `gate`'s allowance at the risk share `alpha`, and its ledger's
1783/// `DELTA` quantile (what the policy's deviations did against the fixed rule, ≤ 0 once they cost).
1784/// The monitoring tells a cold start (no allowance yet) from a spent gate (an allowance the ledger's
1785/// quantile used up) by them.
1786#[must_use]
1787pub fn gate_parts(gate: &Gate, alpha: f64) -> (f64, f64) {
1788    (allowance_at(gate, alpha), lower_quantile(&mut gate.gain.clone()))
1789}
1790
1791/// The seed of the gate's draw `k` under `fit`: shared by every check, so the ledger and a decision
1792/// re-value with the same joint draws.
1793fn gate_seed(fit: &Fit, k: usize) -> u64 {
1794    mix(hash(&[b"gate", fit.key.as_bytes()]), k as u64)
1795}
1796
1797/// A check's joint draws of the model (`gate_seed`: the ledger's, so a decision and its ledger entry
1798/// re-value with the same draws) and the fixed rule's value under each.
1799struct Draws<'a> {
1800    thetas: Vec<Theta>,
1801    feats: Vec<Feat>,
1802    rates: &'a Rates,
1803    base: Vec<f64>,
1804}
1805
1806impl<'a> Draws<'a> {
1807    fn of(model: &Model, fit: &'a Fit, units: &[Unit], check: &Check, lv: &Levels, base: &[Route]) -> Draws<'a> {
1808        let feats = Feat::of(units, check.stop, check.tokens);
1809        let thetas: Vec<Theta> = (0..DRAWS).map(|k| theta(model, &feats, units, lv, gate_seed(fit, k))).collect();
1810        let mut d = Draws { thetas, feats, rates: &fit.rates, base: Vec::new() };
1811        d.base = (0..DRAWS).map(|k| d.value(k, base)).collect();
1812        d
1813    }
1814
1815    /// Draw `k`'s value of `routes` (`Valuer::value`).
1816    fn value(&self, k: usize, routes: &[Route]) -> f64 {
1817        Valuer { t: &self.thetas[k], feats: &self.feats, rates: self.rates }.value(routes)
1818    }
1819
1820    /// Per draw, the value of `routes` minus the fixed rule's.
1821    fn gains(&self, routes: &[Route]) -> Vec<f64> {
1822        self.base.iter().enumerate().map(|(k, b)| self.value(k, routes) - b).collect()
1823    }
1824}
1825
1826/// The evidence rule (module doc): the routes best under the posterior mean (`theta_mean`, `solve`),
1827/// when they are not the fixed rule's `base` and gain on it at the `DELTA` quantile over the joint
1828/// draws `d`; else None (the fixed rule). The units in `nofree` never go free.
1829fn evident(model: &Model, d: &Draws, units: &[Unit], lv: &Levels, base: &[Route], nofree: &[bool]) -> Option<Vec<Route>> {
1830    let t = theta_mean(model, &d.feats, units, lv);
1831    let best = solve(&Table::of(&Valuer { t: &t, feats: &d.feats, rates: d.rates }, nofree), crate::attention::RAIL, conscience::CAP);
1832    (best != base && lower_quantile(&mut d.gains(&best)) > 0.0).then_some(best)
1833}
1834
1835/// The randomised question-count test's lessons (module doc), by position: the applies the fixed rule
1836/// delivers (`base`: asks or hands over) that are not a 3 and whose lesson the session never had
1837/// (`had`: such a lesson may not go free, so it keeps the fixed rule's route), in the fixed rule's order
1838/// (the higher grade first, then the model's: select.rs `ordered`). Their number is the test's k.
1839pub(crate) fn tested(units: &[Unit], base: &[Route], had: &[String]) -> Vec<usize> {
1840    let mut order: Vec<usize> =
1841        (0..units.len()).filter(|&j| units[j].grade != 3 && matches!(base[j], Route::Ask | Route::Free) && !had.iter().any(|h| h == units[j].lesson)).collect();
1842    order.sort_by_key(|&j| std::cmp::Reverse(units[j].grade));
1843    order
1844}
1845
1846/// The test's routes for the count `s`: `base` with the first `s` of `order` (`tested`) asked and the
1847/// rest of it handed over.
1848fn test_routes(base: &[Route], order: &[usize], s: usize) -> Vec<Route> {
1849    let mut routes = base.to_vec();
1850    for (i, &j) in order.iter().enumerate() {
1851        routes[j] = if i < s { Route::Ask } else { Route::Free };
1852    }
1853    routes
1854}
1855
1856/// The test's count at the check whose seed is `seed`: s uniform in 0..=k, on the test's own stream
1857/// of the seed (apart from the placebo's, select.rs `draw_placebo`). The modulo's bias is below
1858/// (k + 1)/2⁶⁴.
1859fn draw_count(seed: u64, k: usize) -> usize {
1860    (hash(&[b"question-count", &seed.to_le_bytes()]) % (k as u64 + 1)) as usize
1861}
1862
1863/// The routes of `units` at `check` for a session that already had the lessons `had` (module doc: the
1864/// decision), none of those handed over free (its `pf` 0) and the fixed rule they are gated against
1865/// the same (`fixed_routes` with `had`). Without a model, with an empty gate or past `SOLVE_MAX`
1866/// applies, exactly the fixed rule, its choice as the propensities. The gate's bound holds for
1867/// decisions made one after another, each against a `gate` with every earlier decision folded in
1868/// (`ledger_add_without`, with the same `had`): two checks deciding against the same `gate` could each
1869/// take all it may still risk, so a caller whose checks run at once decides and records each under one
1870/// lock.
1871///
1872/// `alpha` is the share of the fixed rule's value the engineer tolerates risking for learning (select.rs
1873/// `risk_of`, `ALPHA` unless the collective sets `risk`): the gate's allowance in this decision is the
1874/// ledger's (accrued at `ALPHA`) scaled to it, for the evidence rule's deviations and the test's alike.
1875/// The randomised question-count test runs on a live check (`check.stop` false) whose evidence keeps
1876/// the fixed rule (an evidence deviation the gate refuses is not tested either), only while `alpha` is
1877/// above 0, its count drawn from `seed`.
1878#[must_use]
1879pub fn choose(units: &[Unit], check: &Check, fit: &Fit, gate: &Gate, alpha: f64, seed: u64, had: &[String]) -> Decision {
1880    let base = fixed_routes(units, had);
1881    let fixed = |source: &'static str| Decision {
1882        p: share(&[&base], Route::Ask),
1883        pf: share(&[&base], Route::Free),
1884        routes: base.clone(),
1885        source,
1886        gate: 0.0,
1887        risk: 0.0,
1888        xk: None,
1889        xs: None,
1890    };
1891    let Some(model) = fit.model.as_ref().filter(|m| m.current()) else { return fixed(FIXED) };
1892    if gate.allowance <= 0.0 || gate.gain.len() != DRAWS || units.is_empty() {
1893        return fixed(FIXED);
1894    }
1895    if units.len() > SOLVE_MAX {
1896        return fixed(SIZE);
1897    }
1898    let lv = Levels::of(check.session, &model.judge, units);
1899    let d = Draws::of(model, fit, units, check, &lv, &base);
1900    let allowance = allowance_at(gate, alpha);
1901    let held = lower_quantile(&mut gate.gain.clone());
1902    let remaining = remaining_at(gate, alpha);
1903    // What `routes` take of the remaining budget, None when the gate refuses them: admitted iff
1904    // allowance + q(gain + their gain) ≥ 0, that is iff `risk` = q(gain) − q(gain + their gain) ≤
1905    // allowance + q(gain).
1906    let admit = |routes: &[Route]| -> Option<f64> {
1907        if routes == base {
1908            return Some(0.0);
1909        }
1910        let mut after: Vec<f64> = d.gains(routes).iter().zip(&gate.gain).map(|(x, g)| g + x).collect();
1911        let q = lower_quantile(&mut after);
1912        (q >= -allowance).then_some((held - q).max(0.0))
1913    };
1914    if let Some(best) = evident(model, &d, units, &lv, &base, &nofree_of(units, had)) {
1915        return match admit(&best) {
1916            Some(risk) => Decision {
1917                p: share(&[&best], Route::Ask),
1918                pf: share(&[&best], Route::Free),
1919                routes: best,
1920                source: EVIDENCE,
1921                gate: remaining,
1922                risk,
1923                xk: None,
1924                xs: None,
1925            },
1926            None => Decision { gate: remaining, ..fixed(GATE) },
1927        };
1928    }
1929    let order = tested(units, &base, had);
1930    if check.stop || alpha <= 0.0 || order.is_empty() {
1931        return Decision { gate: remaining, ..fixed(EVIDENCE) };
1932    }
1933    // Every count's routes as played (a count the gate refuses plays the fixed rule's), so each unit's
1934    // propensity is its exact share over the k + 1 equally likely counts.
1935    let k = order.len();
1936    let arms: Vec<(Vec<Route>, Option<f64>)> = (0..=k)
1937        .map(|s| {
1938            let routes = test_routes(&base, &order, s);
1939            let risk = admit(&routes);
1940            (if risk.is_some() { routes } else { base.clone() }, risk)
1941        })
1942        .collect();
1943    let played: Vec<&Vec<Route>> = arms.iter().map(|(r, _)| r).collect();
1944    let s = draw_count(seed, k);
1945    let (routes, risk) = &arms[s];
1946    let source = match risk {
1947        None => GATE,
1948        Some(_) if *routes == base => EXPERIMENT_CONTROL,
1949        Some(_) => EXPERIMENT,
1950    };
1951    let count = |x: usize| Some(u32::try_from(x).unwrap_or(u32::MAX));
1952    Decision {
1953        p: share(&played, Route::Ask),
1954        pf: share(&played, Route::Free),
1955        routes: routes.clone(),
1956        source,
1957        gate: remaining,
1958        risk: risk.unwrap_or(0.0),
1959        xk: count(k),
1960        xs: count(s),
1961    }
1962}
1963
1964/// The decision rule without the randomised question-count test, for a session that already had `had`
1965/// (none of those handed over free, gated against `fixed_routes` with the same `had`): `borg debug
1966/// select` P4a (under the n = 0 prior it must be the fixed rule on every check) and P4b (recall under
1967/// the store's posterior). The evidence rule (`evident`): the routes best under the posterior mean,
1968/// played only when they beat the fixed rule at the `DELTA` quantile over the `DRAWS` joint draws, else
1969/// the fixed rule; `choose`'s routes with α 0 under a gate that admits them. Deterministic: it draws
1970/// nothing of its own (its joint draws are the gate's, `gate_seed`), so it takes no seed. The fixed
1971/// rule whatever the evidence: no model, no applies, past `SOLVE_MAX`.
1972#[must_use]
1973pub fn decide_on_evidence(units: &[Unit], check: &Check, fit: &Fit, had: &[String]) -> Vec<Route> {
1974    let base = fixed_routes(units, had);
1975    let Some(model) = fit.model.as_ref().filter(|m| m.current()) else { return base };
1976    if units.is_empty() || units.len() > SOLVE_MAX {
1977        return base;
1978    }
1979    let lv = Levels::of(check.session, &model.judge, units);
1980    let d = Draws::of(model, fit, units, check, &lv, &base);
1981    evident(model, &d, units, &lv, &base, &nofree_of(units, had)).unwrap_or(base)
1982}
1983
1984/// Per unit, the share of the equally likely routings `draws` that give it `route`, rounded (outcome.rs
1985/// `round_p`): one routing's 0 or 1, the test's k + 1 counts' exact shares.
1986fn share(draws: &[&Vec<Route>], route: Route) -> Vec<f64> {
1987    let n = draws.first().map_or(0, |d| d.len());
1988    (0..n).map(|j| crate::outcome::round_p(draws.iter().filter(|d| d[j] == route).count() as f64 / draws.len() as f64)).collect()
1989}
1990
1991/// `gate` with one more check of the learned policy, decided for a session that already had `had`
1992/// (the graded record's `nofree`): per joint draw k, the value of the routes it took (`routes`) minus
1993/// the fixed rule's with the same `had` (the rule `choose` gated it against), and `ALPHA` × the fixed
1994/// rule's value at its draws' mean (≥ 0; `choose` scales it to the collective's α). The prior fit adds
1995/// nothing: the ledger opens with a model.
1996pub fn ledger_add_without(fit: &Fit, gate: &mut Gate, check: &Check, units: &[Unit], routes: &[Route], had: &[String]) {
1997    let Some(model) = fit.model.as_ref().filter(|m| m.current()) else { return };
1998    let betas: Vec<[f64; P]> = (0..DRAWS).map(|k| draw_beta(model, gate_seed(fit, k))).collect();
1999    add_with(fit, &betas, gate, check, units, routes, had);
2000}
2001
2002/// `ledger_add_without` with the gate's coefficient draws (`draw_beta` of `fit`'s model per
2003/// `gate_seed`) drawn once.
2004fn add_with(fit: &Fit, betas: &[[f64; P]], gate: &mut Gate, check: &Check, units: &[Unit], routes: &[Route], had: &[String]) {
2005    let Some(model) = fit.model.as_ref().filter(|m| m.current()) else { return };
2006    if units.is_empty() || units.len() != routes.len() {
2007        return;
2008    }
2009    if gate.gain.len() != DRAWS {
2010        gate.gain = vec![0.0; DRAWS];
2011    }
2012    let base = fixed_routes(units, had);
2013    // A placebo is not delivered: as the policy decided, not now.
2014    let routes: Vec<Route> = routes.iter().map(|r| if *r == Route::Placebo { Route::Not } else { *r }).collect();
2015    let feats = Feat::of(units, check.stop, check.tokens);
2016    let lv = Levels::of(check.session, &model.judge, units);
2017    let mut mean = 0.0;
2018    for (k, (g, b)) in gate.gain.iter_mut().zip(betas).enumerate() {
2019        let t = theta_with(model, *b, &feats, units, &lv, gate_seed(fit, k));
2020        let v = Valuer { t: &t, feats: &feats, rates: &fit.rates };
2021        let fixed = v.value(&base);
2022        *g += v.value(&routes) - fixed;
2023        mean += fixed / DRAWS as f64;
2024    }
2025    gate.allowance += ALPHA * mean.max(0.0);
2026    gate.checks += 1;
2027    if routes != base {
2028        gate.deviated += 1;
2029    }
2030}
2031
2032/// The gate's ledger over every learned check of `s` under `s.fit` (at `refit`), each as the fold adds
2033/// it (select/summary.rs, `ledger_add_without` with the record's `nofree`, `logged_had`).
2034#[must_use]
2035pub fn ledger(s: &Summary) -> Gate {
2036    let mut gate = Gate::default();
2037    let Some(model) = s.fit.model.as_ref().filter(|m| m.current()) else { return gate };
2038    let betas: Vec<[f64; P]> = (0..DRAWS).map(|k| draw_beta(model, gate_seed(&s.fit, k))).collect();
2039    for c in s.checks.iter().filter(|c| c.learned) {
2040        let (units, _, routes) = check_view(s, c);
2041        let session = s.sessions.get(c.tick as usize).map_or("", |x| x.id.as_str());
2042        add_with(&s.fit, &betas, &mut gate, &Check { session, stop: c.stop, tokens: c.tokens }, &units, &routes, &logged_had(s, c));
2043    }
2044    gate
2045}
2046
2047/// The monitor's reading of the learned policy against the fixed rule (module doc).
2048#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
2049pub struct Monitor {
2050    /// The store went back to the fixed rule (sticky: select/summary.rs `REVERTED`).
2051    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
2052    pub reverted: bool,
2053    /// Sessions and applies of the learned policy it read.
2054    #[serde(default, skip_serializing_if = "is_default")]
2055    pub sessions: u32,
2056    #[serde(default, skip_serializing_if = "is_default")]
2057    pub units: u32,
2058    /// Per apply, the mean of (policy − fixed rule) + α × the fixed rule's value, and the confidence
2059    /// sequence's upper bound on it (None before `CS_MIN` sessions): below 0, the policy costs more
2060    /// than α of the fixed rule's quality.
2061    #[serde(default, skip_serializing_if = "is_default")]
2062    pub mean: f64,
2063    #[serde(default, skip_serializing_if = "Option::is_none")]
2064    pub ucb: Option<f64>,
2065    /// How far its weights can be trusted (borg top `Evaluation`): the labelled applies weighed, the
2066    /// effective number of the weights the estimate used (truncated, normalised per route: (Σw)² /
2067    /// Σw²), the largest of them against their mean, and the applies whose weight the √N cap cut; each
2068    /// over the applies whose weight can move the estimate: a residual in use (`ROUTE_LABELS_MIN`) on a
2069    /// taken route where the policy and the fixed rule differ (a placebo both rules leave undelivered
2070    /// has none, however large its weight).
2071    #[serde(default, skip_serializing_if = "is_default")]
2072    pub labelled: u32,
2073    #[serde(default, skip_serializing_if = "is_default")]
2074    pub ess: f64,
2075    #[serde(default, skip_serializing_if = "is_default")]
2076    pub max_weight: f64,
2077    #[serde(default, skip_serializing_if = "is_default")]
2078    pub truncated: u32,
2079}
2080
2081/// The monitor of `s` (module doc): per session, the doubly robust difference between the policy
2082/// that ran (its logged propensities) and the fixed rule, each apply's outcome model fitted without
2083/// its session's half (cross-fitting by the parity of the session's tick), the inverse-probability
2084/// weights truncated at √N × their mean and normalised per route, a route's weighted residual in use
2085/// from `ROUTE_LABELS_MIN` labelled applies on (the direct-method term alone before); plus α × the
2086/// fixed rule's value;
2087/// per apply, a session's mean an increment, in session order, under a one-sided time-uniform
2088/// confidence sequence at `DELTA` (`upper_bound`). Trips when its upper bound falls below 0.
2089#[must_use]
2090pub fn monitor(s: &Summary) -> Monitor {
2091    let spec = coefs();
2092    let d = Data::of(s, false);
2093    let Some(model) = &s.fit.model else { return Monitor::default() };
2094    let sd: [f64; P] = std::array::from_fn(|k| model.sd.get(k).copied().unwrap_or(spec[k].sd));
2095    let spread = model.spread;
2096    let folds: Vec<Option<Est<P, FAMILIES>>> = (0..2u32)
2097        .map(|half| {
2098            let train: Vec<Obs<P, FAMILIES>> =
2099                d.weighted(s.sessions.len() as u32, s.fit.half_life).into_iter().zip(&d.tick).filter(|(_, t)| *t % 2 != half).map(|(o, _)| o).collect();
2100            map(&train, d.levels, &spec, &sd, &spread, None)
2101        })
2102        .collect();
2103    // Per learned apply: the session, the per-route difference terms before the weights.
2104    struct Term {
2105        tick: u32,
2106        diff: [f64; ARMS],
2107        p_hat: [f64; ARMS],
2108        taken: usize,
2109        y: Option<f64>,
2110        w: f64,
2111        vb: f64,
2112    }
2113    let mut terms: Vec<Term> = Vec::new();
2114    for c in s.checks.iter().filter(|c| c.learned) {
2115        let Some(est) = &folds[(c.tick % 2) as usize] else { continue };
2116        let (units, feats, routes) = check_view(s, c);
2117        // The fixed rule for the lessons the session had, as the decision was gated against it.
2118        let base = fixed_routes(&units, &logged_had(s, c));
2119        let (m_q, m_f) = (usize::from(c.m_q).max(1), usize::from(c.m_f).max(1));
2120        for (j, f) in feats.iter().enumerate() {
2121            let i = c.first as usize + j;
2122            let a = &s.applies[i];
2123            let lv = d.lv_of.get(&i).copied().unwrap_or([None; FAMILIES]);
2124            // The held-out session's own effect is not in its fold's fit.
2125            let eta = |route: Route, m: usize| -> f64 {
2126                dot(&est.beta, &design(f, route, m))
2127                    + lv[1].map_or(0.0, |l| est.u[LESSON].get(l).copied().unwrap_or(0.0))
2128                    + lv[2].map_or(0.0, |l| est.u[JUDGE].get(l).copied().unwrap_or(0.0))
2129            };
2130            let p_hat = [sigmoid(eta(Route::Ask, m_q)), sigmoid(eta(Route::Free, m_f)), sigmoid(eta(Route::Not, 1))];
2131            let mu = [a.p, a.pf, (1.0 - a.p - a.pf).max(0.0)];
2132            let (taken, fixed) = (routes[j].arm(), base[j].arm());
2133            let diff: [f64; ARMS] = std::array::from_fn(|x| mu[x] - f64::from(u8::from(x == fixed)));
2134            let y = match a.label {
2135                Label::Changed => Some(1.0),
2136                Label::Ignored | Label::NotArisen => Some(0.0),
2137                Label::Unclear | Label::Remains | Label::Open | Label::Censored => None,
2138            };
2139            // Floors: a logged ψ or μ of 0 for a route that happened is rounding (outcome.rs `round_p`),
2140            // so the least the log can say (ψ at 1/1000, μ at one draw of `DRAWS`).
2141            let psi = if a.route == Route::Placebo { a.psi.max(PSI_FLOOR) } else { 1.0 };
2142            let judged_p = d.judged_p.get(&i).copied().unwrap_or(1.0).max(1.0 / MAX_IPW);
2143            let w = if y.is_some() { 1.0 / (mu[taken].max(1.0 / DRAWS as f64) * judged_p * psi) } else { 0.0 };
2144            let vb = p_hat[fixed] - p_hat[2];
2145            terms.push(Term { tick: c.tick, diff, p_hat, taken, y, w, vb });
2146        }
2147    }
2148    let labelled: Vec<f64> = terms.iter().filter(|t| t.y.is_some()).map(|t| t.w).collect();
2149    if terms.is_empty() || labelled.is_empty() {
2150        return Monitor::default();
2151    }
2152    let cap = (labelled.len() as f64).sqrt() * labelled.iter().sum::<f64>() / labelled.len() as f64;
2153    let mut norm = [0.0f64; ARMS];
2154    for t in &terms {
2155        norm[t.taken] += t.w.min(cap);
2156    }
2157    let count = terms.len() as f64;
2158    let norm = norm.map(|x| if x > 0.0 { x / count } else { 1.0 });
2159    // A route's residual only from `ROUTE_LABELS_MIN` labels with leverage on: below, its direct-method
2160    // term alone. A label whose difference is 0 adds nothing to the residual, only weight to the
2161    // route's normaliser, so it opens no route.
2162    let mut routed = [0usize; ARMS];
2163    for t in terms.iter().filter(|t| t.y.is_some() && t.diff[t.taken] != 0.0) {
2164        routed[t.taken] += 1;
2165    }
2166    let residual = routed.map(|n| n >= ROUTE_LABELS_MIN);
2167    let mut per: BTreeMap<u32, (f64, usize)> = BTreeMap::new();
2168    for t in &terms {
2169        let w = t.w.min(cap) / norm[t.taken];
2170        let r = |a: usize| if a == t.taken && residual[a] { t.y.map_or(0.0, |y| w * (y - t.p_hat[a])) } else { 0.0 };
2171        let dr: f64 = (0..ARMS).map(|a| t.diff[a] * (t.p_hat[a] + r(a))).sum();
2172        let e = per.entry(t.tick).or_insert((0.0, 0));
2173        e.0 += dr + ALPHA * t.vb;
2174        e.1 += 1;
2175    }
2176    let z: Vec<f64> = per.values().map(|(x, n)| x / *n as f64).collect();
2177    let mean = z.iter().sum::<f64>() / z.len() as f64;
2178    let ucb = Some(upper_bound(&z)).filter(|u| u.is_finite());
2179    // The weights' health, over the labelled applies' weights as the estimate used them (each > 0), of
2180    // the applies whose weighted residual enters it: a residual in use, times a difference that is not
2181    // 0 (a placebo neither rule delivers moves nothing, its weight however large).
2182    let moves = |t: &&Term| t.y.is_some() && residual[t.taken] && t.diff[t.taken] != 0.0;
2183    let used: Vec<f64> = terms.iter().filter(moves).map(|t| t.w.min(cap) / norm[t.taken]).collect();
2184    let (sum, sq) = used.iter().fold((0.0, 0.0), |(s, q), w| (s + w, q + w * w));
2185    let ess = if sq > 0.0 { sum * sum / sq } else { 0.0 };
2186    let max_weight = if sum > 0.0 { used.iter().copied().fold(0.0, f64::max) * used.len() as f64 / sum } else { 0.0 };
2187    Monitor {
2188        reverted: ucb.is_some_and(|u| u < 0.0),
2189        sessions: z.len() as u32,
2190        units: terms.len() as u32,
2191        mean,
2192        ucb,
2193        labelled: used.len() as u32,
2194        ess,
2195        max_weight,
2196        truncated: terms.iter().filter(moves).filter(|t| t.w > cap).count() as u32,
2197    }
2198}
2199
2200/// The time-uniform upper bound on the running mean of `x` at `DELTA`, intersected over time from
2201/// `CS_MIN` on: the normal-mixture boundary on the sum, √((v + ρ)(ln(1 + v/ρ) + 2 ln(1/δ))) with
2202/// v = t·σ̂² (Howard et al. 2021; asymptotically valid with the variance plugged in, Waudby-Smith et al.
2203/// 2024), ρ tightest at `CS_SESSIONS`; the two-sided boundary read on one side, so cautious. Valid at
2204/// every time at once, so reading it after every session costs no error. +∞ before `CS_MIN`. An
2205/// empirical-Bernstein sequence would be valid without asymptotics but needs a range bound, and the
2206/// truncated weights' is far wider than the increments' spread: it could never trip on a few dozen
2207/// sessions.
2208fn upper_bound(x: &[f64]) -> f64 {
2209    let log = (1.0 / DELTA).ln();
2210    let shape = 2.0 * log + (1.0 + 2.0 * log).ln();
2211    let (mut sum, mut sum_sq) = (0.0, 0.0);
2212    let mut best = f64::INFINITY;
2213    for (i, &xi) in x.iter().enumerate() {
2214        let t = (i + 1) as f64;
2215        sum += xi;
2216        sum_sq += xi * xi;
2217        if i + 1 < CS_MIN.max(2) {
2218            continue;
2219        }
2220        let mean = sum / t;
2221        let var = ((sum_sq - t * mean * mean) / (t - 1.0)).max(f64::MIN_POSITIVE);
2222        let (v, rho) = (t * var, var * CS_SESSIONS / shape);
2223        best = best.min(mean + ((v + rho) * ((1.0 + v / rho).ln() + 2.0 * log)).sqrt() / t);
2224    }
2225    best
2226}
2227
2228/// The seed of a session's pool draw (`pool_tokens`).
2229#[must_use]
2230pub fn session_seed(session: &str) -> u64 {
2231    hash(&[b"pool", session.as_bytes()])
2232}
2233
2234/// The pool budgets (`POOL_STEPS`) in tokens.
2235#[must_use]
2236pub fn pool_grid() -> Vec<usize> {
2237    POOL_STEPS.iter().map(|&i| (crate::whole::TOKENS as f64 * 2f64.powf(f64::from(i) / 2.0)).round() as usize).collect()
2238}
2239
2240/// The quality a pool of `tokens` buys per check under one draw (`seed`), its price aside: the
2241/// expected applies of its fill positions times what an apply is worth there (the grader's dilution
2242/// included).
2243fn pool_value(pool: &PoolFit, tokens: usize, seed: u64) -> f64 {
2244    let mut rng = Rng::new(seed);
2245    let shown = tokens as f64 / pool.per_lesson.max(1.0);
2246    let mut applies = 0.0;
2247    for (b, &(a, bb)) in pool.yields.iter().enumerate() {
2248        let (lo, hi) = ((1u64 << b) - 1, (1u64 << (b + 1)) - 1);
2249        let inside = (shown.min(hi as f64) - lo as f64).max(0.0);
2250        applies += inside * if inside > 0.0 { beta_draw(a, bb, &mut rng) } else { 0.0 };
2251    }
2252    let slope = (pool.slope.0 + pool.slope.1 * normal(&mut rng)).min(0.0);
2253    let not = pool.not.0 + pool.not.1 * normal(&mut rng);
2254    let eta = pool.eta + slope * (tokens as f64 / crate::whole::TOKENS as f64).ln();
2255    applies * (sigmoid(eta) - sigmoid(eta + not)).max(0.0)
2256}
2257
2258/// Whether a pool of `tokens` may be chosen at all: never above the baseline without a known latency
2259/// limit (`limit_ms`) its 95% latency fits in, latency observed at that budget (`LATENCY_NEAR` of it,
2260/// `PoolFit::latency_reach`: the fit read among its calls, never extrapolated) and a yield for every
2261/// position it adds; below it, a yield for every position it drops, or a price to pay.
2262fn pool_feasible(pool: &PoolFit, tokens: usize, limit_ms: Option<u64>, lambda: f64) -> bool {
2263    let baseline = crate::whole::TOKENS;
2264    let bins_to = |t: usize| -> usize {
2265        let shown = (t as f64 / pool.per_lesson.max(1.0)).ceil() as u64;
2266        (u64::BITS - shown.leading_zeros()) as usize
2267    };
2268    let known = pool.per_lesson > 0.0 && pool.yields.len() >= bins_to(tokens.max(baseline));
2269    if tokens > baseline {
2270        let (a, b, q) = pool.latency;
2271        let fits = limit_ms.is_some_and(|l| a + b * tokens as f64 + q <= l as f64);
2272        let observed = f64::from(pool.latency_reach) >= LATENCY_NEAR * tokens as f64;
2273        return known && fits && observed && pool.latency_n as usize >= LATENCY_MIN;
2274    }
2275    tokens == baseline || known || lambda > 0.0
2276}
2277
2278/// The pool's draws under a fit: per budget of `pool_grid`, its value under each of the `DRAWS`
2279/// shared draws (the gate's evidence) and under a session's own draw (its play).
2280struct PoolDraws {
2281    grid: Vec<usize>,
2282    shared: Vec<Vec<f64>>,
2283}
2284
2285impl PoolDraws {
2286    fn of(pool: &PoolFit) -> PoolDraws {
2287        let grid = pool_grid();
2288        let shared = grid.iter().map(|&t| (0..DRAWS).map(|k| pool_value(pool, t, mix(hash(&[b"pool-gate"]), k as u64))).collect()).collect();
2289        PoolDraws { grid, shared }
2290    }
2291
2292    /// The budget a session plays (`play`: its own draw's value per budget) at price `lambda`: of the
2293    /// feasible budgets, those whose gain over the baseline, price included, is ≥ 0 at the `DELTA`
2294    /// quantile of the shared draws (the baseline always; a larger budget only on a gain > 0 there,
2295    /// never on draws that tie with the baseline), the one its draw values most.
2296    fn choose(&self, play: &[f64], feasible: &[bool], lambda: f64) -> usize {
2297        let baseline = crate::whole::TOKENS;
2298        let Some(b) = self.grid.iter().position(|&t| t == baseline) else { return baseline };
2299        let admits = |i: usize| -> bool {
2300            let cost = lambda * (self.grid[i] as f64 - baseline as f64);
2301            let mut gain: Vec<f64> = self.shared[i].iter().zip(&self.shared[b]).map(|(x, y)| x - y - cost).collect();
2302            let q = lower_quantile(&mut gain);
2303            i == b || if self.grid[i] > baseline { q > 0.0 } else { q >= 0.0 }
2304        };
2305        (0..self.grid.len())
2306            .filter(|&i| feasible[i] && admits(i))
2307            .map(|i| (play[i] - lambda * self.grid[i] as f64, self.grid[i]))
2308            .fold(None, |best: Option<(f64, usize)>, x| if best.is_none_or(|b| x.0 > b.0) { Some(x) } else { best })
2309            .map_or(baseline, |(_, t)| t)
2310    }
2311
2312    /// A session's own draw of each budget's value (`seed`: `session_seed`).
2313    fn play(&self, pool: &PoolFit, seed: u64) -> Vec<f64> {
2314        self.grid.iter().map(|&t| pool_value(pool, t, seed)).collect()
2315    }
2316}
2317
2318/// The pool budget for a session (`seed`) under `fit`: the baseline (whole.rs `TOKENS`) unless the
2319/// learned policy is in force (`active`); else, of the feasible budgets of `pool_grid` whose gain over
2320/// the baseline, the budget's price included, is ≥ 0 at the `DELTA` quantile (> 0 for a larger one,
2321/// `PoolDraws::choose`; the gate's caution: an
2322/// unidentified dilution never moves the pool), the one the session's Thompson draw values most. One
2323/// draw per session keeps a session's pool, and its prompt prefix, stable.
2324#[must_use]
2325pub fn pool_tokens(fit: &Fit, active: bool, limit_ms: Option<u64>, seed: u64) -> usize {
2326    let baseline = crate::whole::TOKENS;
2327    if !active || fit.pool.yields.is_empty() && fit.lambda == 0.0 {
2328        return baseline;
2329    }
2330    let draws = PoolDraws::of(&fit.pool);
2331    let feasible: Vec<bool> = draws.grid.iter().map(|&t| pool_feasible(&fit.pool, t, limit_ms, fit.lambda)).collect();
2332    draws.choose(&draws.play(&fit.pool, seed), &feasible, fit.lambda)
2333}
2334
2335/// The budget's price per pool token: the smallest λ ≥ 0 under which the pools `pool_tokens` chooses
2336/// for the newest `FIT_SESSIONS` sessions of `s` (each with its own draw, every check at its
2337/// session's pool) spend at most `budget` tokens per session on average, by bisection (a higher price
2338/// never grows a pool); deterministic. The pools are replayed under the loosest latency limit, where
2339/// every budget the latency evidence covers may be chosen: a hook's limit (live.rs `call_limit`) only
2340/// takes the largest budgets out of the choice, and a choice among fewer, smaller budgets never takes
2341/// a larger pool, so what the hooks spend under any limit stays within the spend replayed here. A
2342/// budget no pool meets gets the price at which every session takes the smallest pool.
2343#[must_use]
2344pub fn price(s: &Summary, fit: &Fit, budget: f64) -> f64 {
2345    let sessions: Vec<(&str, u32)> = s.sessions.iter().rev().take(FIT_SESSIONS).filter(|x| x.checks > 0).map(|x| (x.id.as_str(), x.checks)).collect();
2346    if sessions.is_empty() || budget <= 0.0 {
2347        return 0.0;
2348    }
2349    let draws = PoolDraws::of(&fit.pool);
2350    let plays: Vec<Vec<f64>> = sessions.iter().map(|(id, _)| draws.play(&fit.pool, session_seed(id))).collect();
2351    let spend = |lambda: f64| -> f64 {
2352        // The loosest limit: none binds (u64::MAX ms).
2353        let feasible: Vec<bool> = draws.grid.iter().map(|&t| pool_feasible(&fit.pool, t, Some(u64::MAX), lambda)).collect();
2354        sessions.iter().zip(&plays).map(|((_, n), play)| f64::from(*n) * draws.choose(play, &feasible, lambda) as f64).sum::<f64>() / sessions.len() as f64
2355    };
2356    if spend(0.0) <= budget {
2357        return 0.0;
2358    }
2359    // The price at which even the most valuable apply is not worth one token more: every pool shrinks.
2360    let mut hi = 1.0 / crate::whole::TOKENS as f64;
2361    for _ in 0..PRICE_STEPS {
2362        if spend(hi) <= budget {
2363            break;
2364        }
2365        hi *= 2.0;
2366    }
2367    let mut lo = 0.0;
2368    for _ in 0..PRICE_STEPS {
2369        let mid = 0.5 * (lo + hi);
2370        if spend(mid) <= budget { hi = mid } else { lo = mid }
2371    }
2372    hi
2373}
2374
2375#[cfg(test)]
2376mod tests {
2377    use super::*;
2378    use crate::outcome::{self, Outcome};
2379    use crate::select::summary::{self, Summary};
2380
2381    fn unit(lesson: &str, grade: u8, rank: usize) -> Unit<'_> {
2382        Unit { lesson, grade, rank }
2383    }
2384
2385    /// Every grade sequence over {1, 2, 3} of up to `n` applies.
2386    fn tables(n: usize) -> Vec<Vec<u8>> {
2387        let mut out = vec![Vec::new()];
2388        for len in 1..=n {
2389            out.extend((0..3usize.pow(len as u32)).map(|mut x| {
2390                (0..len)
2391                    .map(|_| {
2392                        let g = (x % 3) as u8 + 1;
2393                        x /= 3;
2394                        g
2395                    })
2396                    .collect()
2397            }));
2398        }
2399        out
2400    }
2401
2402    /// A planted world: the judge's P(changed) for an apply on a route among m, and a lift of the stop's
2403    /// checks with a 3 on the log-odds scale, planted apart from the model's terms.
2404    #[derive(Clone, Copy)]
2405    struct Truth {
2406        b: [f64; P],
2407        lift: f64,
2408    }
2409
2410    impl Truth {
2411        fn p(&self, f: &Feat, route: Route, m: usize) -> f64 {
2412            sigmoid(dot(&self.b, &design(f, route, m)) + if f.stop && f.three { self.lift } else { 0.0 })
2413        }
2414    }
2415
2416    /// A simulated outcome log: per session, checks of random grades routed by `route` (given the
2417    /// grades, the routes and their logged p, pf), delivered, judged from `truth` (a placebo too), and
2418    /// settled at the session's end.
2419    struct Sim {
2420        rng: Rng,
2421        lines: Vec<Outcome>,
2422        ms: i64,
2423    }
2424
2425    type Router<'a> = dyn FnMut(&[u8], bool, &mut Rng) -> (Vec<Route>, Vec<f64>, Vec<f64>, &'static str) + 'a;
2426
2427    impl Sim {
2428        fn new(seed: u64) -> Sim {
2429            Sim { rng: Rng::new(seed), lines: Vec::new(), ms: 0 }
2430        }
2431
2432        fn session(&mut self, session: &str, checks: usize, lessons: usize, truth: &Truth, route: &mut Router) {
2433            for c in 0..checks {
2434                let n = 1 + (self.rng.next_u64() % 4) as usize;
2435                let stop = c % 4 == 3;
2436                let grades: Vec<u8> = (0..n).map(|_| 1 + (self.rng.next_u64() % 3) as u8).collect();
2437                let ids: Vec<String> = (0..n).map(|_| format!("L{}", self.rng.next_u64() % lessons as u64)).collect();
2438                self.check(session, stop, &grades, &ids, truth, route);
2439            }
2440            self.ms += 1;
2441            let asked: Vec<String> =
2442                self.lines.iter().filter(|o| o.session == session && o.kind == outcome::DELIVERY).flat_map(|o| o.lessons.clone()).collect();
2443            if let Some(l) = asked.first() {
2444                self.lines.push(Outcome {
2445                    kind: outcome::NOT_CORRECTED.into(),
2446                    session: session.into(),
2447                    lessons: vec![l.clone()],
2448                    ms: self.ms,
2449                    reason: outcome::UNJUDGED_NONE.into(),
2450                    ..Default::default()
2451                });
2452            }
2453        }
2454
2455        fn check(&mut self, session: &str, stop: bool, grades: &[u8], ids: &[String], truth: &Truth, route: &mut Router) {
2456            self.ms += 1;
2457            let check = crate::select::check_id(session, if stop { "stop" } else { "live" }, self.ms, 1);
2458            let (routes, p, pf, policy) = route(grades, stop, &mut self.rng);
2459            let pick = |r: Route| ids.iter().zip(&routes).filter(|(_, x)| **x == r).map(|(l, _)| l.clone()).collect::<Vec<_>>();
2460            self.lines.push(Outcome {
2461                kind: outcome::GRADED.into(),
2462                session: session.into(),
2463                lessons: ids.to_vec(),
2464                ms: self.ms,
2465                channel: if stop { "stop" } else { "live" }.into(),
2466                grades: grades.to_vec(),
2467                ranks: (0..ids.len() as u16).collect(),
2468                applied: ids.len() as u16,
2469                chosen: pick(Route::Ask),
2470                free: pick(Route::Free),
2471                placebo: pick(Route::Placebo),
2472                psi: 1.0,
2473                p,
2474                pf,
2475                check: check.clone(),
2476                policy: policy.into(),
2477                ..Default::default()
2478            });
2479            let three = grades.contains(&3);
2480            let m = |r: Route| routes.iter().filter(|x| **x == r).count();
2481            for (j, (l, r)) in ids.iter().zip(&routes).enumerate() {
2482                if *r == Route::Not {
2483                    continue;
2484                }
2485                self.ms += 1;
2486                let delivered = match r {
2487                    Route::Ask => outcome::ROUTE_ASKED,
2488                    Route::Free => outcome::ROUTE_FREE,
2489                    _ => outcome::ROUTE_PLACEBO,
2490                };
2491                self.lines.push(Outcome {
2492                    kind: outcome::DELIVERY.into(),
2493                    session: session.into(),
2494                    lessons: vec![l.clone()],
2495                    ms: self.ms,
2496                    check: check.clone(),
2497                    route: delivered.into(),
2498                    ..Default::default()
2499                });
2500                let f = Feat { grade: grades[j], rank: j, stop, three, pool: 0.0 };
2501                let as_route = if *r == Route::Placebo { Route::Not } else { *r };
2502                let y = self.rng.unit() < truth.p(&f, as_route, m(*r).max(1));
2503                let channel = match r {
2504                    Route::Ask => {
2505                        if stop {
2506                            "stop"
2507                        } else {
2508                            "live"
2509                        }
2510                    }
2511                    Route::Free => "queued",
2512                    _ => outcome::PLACEBO,
2513                };
2514                self.lines.push(Outcome {
2515                    kind: if y { outcome::CHANGED } else { outcome::IGNORED }.into(),
2516                    session: session.into(),
2517                    lessons: vec![l.clone()],
2518                    ms: self.ms,
2519                    channel: channel.into(),
2520                    check: check.clone(),
2521                    judge: 2,
2522                    ..Default::default()
2523                });
2524            }
2525        }
2526
2527        fn text(&self) -> String {
2528            self.lines.iter().map(|o| format!("{}\n", serde_json::to_string(o).unwrap())).collect()
2529        }
2530
2531        fn summary(&self) -> Summary {
2532            summary::fold(&self.text(), Summary::default())
2533        }
2534    }
2535
2536    /// Each apply's route drawn uniformly over ask, free and placebo, the stop's 3s asked.
2537    fn uniform(grades: &[u8], stop: bool, rng: &mut Rng) -> (Vec<Route>, Vec<f64>, Vec<f64>, &'static str) {
2538        let routes: Vec<Route> = grades
2539            .iter()
2540            .map(|g| if stop && *g == 3 { Route::Ask } else { [Route::Ask, Route::Free, Route::Placebo][(rng.next_u64() % 3) as usize] })
2541            .collect();
2542        let p = grades.iter().map(|g| if stop && *g == 3 { 1.0 } else { 0.3333 }).collect();
2543        let pf = grades.iter().map(|g| if stop && *g == 3 { 0.0 } else { 0.3333 }).collect();
2544        (routes, p, pf, "fixed")
2545    }
2546
2547    /// The fixed rule's routes and propensities.
2548    fn fixed_rule(grades: &[u8], _: bool, _: &mut Rng) -> (Vec<Route>, Vec<f64>, Vec<f64>, &'static str) {
2549        let ids: Vec<String> = (0..grades.len()).map(|i| format!("x{i}")).collect();
2550        let units: Vec<Unit> = ids.iter().zip(grades).enumerate().map(|(r, (l, g))| unit(l, *g, r)).collect();
2551        let routes = fixed_routes(&units, &[]);
2552        let p = routes.iter().map(|r| f64::from(u8::from(*r == Route::Ask))).collect();
2553        let pf = routes.iter().map(|r| f64::from(u8::from(*r == Route::Free))).collect();
2554        (routes, p, pf, "fixed")
2555    }
2556
2557    fn truth() -> Truth {
2558        let mut b = [0.0; P];
2559        b[B0] = -1.0;
2560        b[G3] = 1.2;
2561        b[ASK] = 0.6;
2562        b[NOT] = -0.8;
2563        Truth { b, lift: 0.0 }
2564    }
2565
2566    fn planted(sessions: usize, checks: usize, seed: u64) -> Summary {
2567        let mut sim = Sim::new(seed);
2568        for i in 0..sessions {
2569            sim.session(&format!("s{i}"), checks, 30, &truth(), &mut uniform);
2570        }
2571        sim.summary()
2572    }
2573
2574    #[test]
2575    fn the_fit_recovers_a_planted_world() {
2576        let s = planted(24, 40, 1);
2577        let fit = fit(&s, None);
2578        let m = fit.model.as_ref().expect("a model");
2579        assert!(m.converged, "{m:?}");
2580        assert!(fit.labels > 600, "{}", fit.labels);
2581        let cov = |k: usize| (0..=k).map(|j| m.chol[k * P + j].powi(2)).sum::<f64>().sqrt();
2582        for k in [B0, G3, ASK, NOT] {
2583            let (got, want, sd) = (m.beta[k], truth().b[k], cov(k));
2584            assert!((got - want).abs() < 3.0 * sd + 0.15, "{}: {got:.3} vs {want} (sd {sd:.3})", NAMES[k]);
2585        }
2586        assert!(m.beta[ASK] > 0.0 && m.beta[NOT] < 0.0, "{:?}", m.beta);
2587        // Rank has no effect in this world: relevance shrinks its slope's prior.
2588        assert!(m.sd[RANK] < ARD_START, "{}", m.sd[RANK]);
2589        assert!(m.lessons.len() <= 30 && m.sessions.len() == 24);
2590        assert!(m.beta.iter().chain(&m.chol).all(|x| x.is_finite()));
2591    }
2592
2593    /// The fixed rule's history (every 3 asked with its block, every check without one handed over)
2594    /// in a world without dilution: the labels say nothing about it, the dilution slopes keep their
2595    /// dated prior's sd, while EM still moves the terms without one.
2596    #[test]
2597    fn a_dated_prior_keeps_its_sd_where_the_labels_say_nothing() {
2598        let mut sim = Sim::new(12);
2599        for i in 0..16 {
2600            sim.session(&format!("s{i}"), 16, 12, &truth(), &mut fixed_rule);
2601        }
2602        let f = fit(&sim.summary(), None);
2603        let m = f.model.as_ref().expect("a model");
2604        for k in [ASK_M, FREE_M] {
2605            assert_eq!(m.sd[k], DILUTION_PRIOR.1, "{}: {:?}", NAMES[k], m.sd);
2606        }
2607        assert_eq!((m.sd[ASK], m.sd[NOT]), (ASK_PRIOR.1, NOT_PRIOR.1));
2608        assert!([RANK, ASK_STOP, ASK_G3, NOT_G, POOL].iter().any(|&k| m.sd[k] != ARD_START), "EM ran on the rest: {:?}", m.sd);
2609    }
2610
2611    /// The pruned model's n = 0 prior, what P2's rerun predicts a unit with no label before its check by:
2612    /// the kept terms at their prior, every other at 0 with the floor's sd, and no level's spread (an
2613    /// unseen session or lesson adds no variance), unlike the full model's prior.
2614    #[test]
2615    fn the_pruned_prior_is_the_pruned_models_before_any_label() {
2616        let (full, pruned) = (prior(), prior_pruned());
2617        let (fm, pm) = (full.model.as_ref().expect("a prior"), pruned.model.as_ref().expect("a pruned prior"));
2618        let spec = coefs();
2619        for (k, name) in NAMES.iter().enumerate() {
2620            let want = if PRUNED_KEEPS.contains(&k) { (spec[k].mean, spec[k].sd) } else { (0.0, SD_FLOOR) };
2621            assert!((pm.beta[k] - want.0).abs() < 1e-9 && pm.sd[k] == want.1, "{name}: {} sd {}", pm.beta[k], pm.sd[k]);
2622        }
2623        assert_eq!((pm.spread, fm.spread), ([0.0; FAMILIES], [LEVEL_START; FAMILIES]));
2624        let f = Feat { grade: 2, rank: 3, stop: true, three: false, pool: 0.5 };
2625        // Not now, whose prior mean is off 0 (`NOT_PRIOR`): at a mean of 0 every variance predicts ½.
2626        let at = |fit: &Fit| predict(fit, &f, Route::Not, 1, "unseen", "L99").expect("a prediction");
2627        assert_ne!(at(&pruned), at(&full), "the full prior's rank, pool and level variance are not the pruned model's");
2628        assert_eq!(pruned.rates, full.rates);
2629    }
2630
2631    /// P2's pruned model: grade, route and dilution learned, every other term held at 0 with the
2632    /// floor's sd, no session, lesson or judge effect (a prediction is the same for any of them), the
2633    /// half-life chosen as the full fit's is. The full fit of the same world learns the rank slope and
2634    /// the stop's effect the prune leaves out.
2635    #[test]
2636    fn the_pruned_model_keeps_grade_route_and_dilution_alone() {
2637        let mut t = truth();
2638        t.b[RANK] = -0.6;
2639        t.b[STOP] = 0.8;
2640        let mut sim = Sim::new(4);
2641        for i in 0..20 {
2642            sim.session(&format!("s{i}"), 30, 20, &t, &mut uniform);
2643        }
2644        let s = sim.summary();
2645        let (full, pruned) = (fit(&s, None), fit_pruned(&s, None));
2646        let (fm, pm) = (full.model.as_ref().expect("a full model"), pruned.model.as_ref().expect("a pruned model"));
2647        assert!(fm.beta[RANK] < -0.2 && fm.beta[STOP] > 0.2 && !fm.sessions.is_empty(), "the scenario: {:?}", fm.beta);
2648        assert!(pm.current() && pm.converged && pruned.labels == full.labels && pruned.key == full.key);
2649        for (k, name) in NAMES.iter().enumerate() {
2650            if PRUNED_KEEPS.contains(&k) {
2651                assert!(pm.sd[k] > SD_FLOOR, "{name} is kept");
2652            } else {
2653                assert_eq!(pm.sd[k], SD_FLOOR, "{name}");
2654                assert!(pm.beta[k].abs() < 3.0 * SD_FLOOR, "{name}: {}", pm.beta[k]);
2655            }
2656        }
2657        assert!(pm.beta[ASK] > 0.0 && pm.beta[NOT] < 0.0, "{:?}", pm.beta);
2658        assert!(pm.sessions.is_empty() && pm.lessons.is_empty() && pm.judges.is_empty() && pm.judge.is_empty());
2659        assert_eq!(pm.spread, [0.0; FAMILIES]);
2660        assert!(HALF_LIVES.contains(&pruned.half_life));
2661        let f = Feat { grade: 2, rank: 3, stop: true, three: false, pool: 0.0 };
2662        let at = |session: &str, lesson: &str| predict(&pruned, &f, Route::Free, 2, session, lesson);
2663        assert_eq!(at("s0", "L1"), at("unseen", "L99"), "no level effect");
2664        assert_ne!(predict(&full, &f, Route::Free, 2, "s0", "L1"), predict(&full, &f, Route::Free, 2, "unseen", "L99"), "the full model's levels");
2665    }
2666
2667    /// The same model two ways: four session effects as a random-effect family (eliminated by its
2668    /// Schur complement), and as four fixed coefficients with the family's prior. Their MAP and
2669    /// covariance agree.
2670    #[test]
2671    fn eliminating_a_family_equals_solving_it_densely() {
2672        let mut rng = Rng::new(9);
2673        let rows: Vec<([f64; 3], usize, f64)> = (0..400)
2674            .map(|i| {
2675                let x = [1.0, rng.unit() * 2.0 - 1.0, f64::from(u8::from(rng.unit() < 0.4))];
2676                let l = i % 4;
2677                let eta = -0.3 + 0.8 * x[1] - 0.5 * x[2] + [0.6, -0.4, 0.1, 0.0][l];
2678                (x, l, f64::from(u8::from(rng.unit() < sigmoid(eta))))
2679            })
2680            .collect();
2681        let spread = 0.7;
2682        let spec3 = [Coef { mean: 0.0, sd: 2.5, ard: false, nonpos: false }; 3];
2683        let obs: Vec<Obs<3, 1>> = rows.iter().map(|(x, l, y)| Obs { x: *x, y: *y, w: 1.0 + f64::from(*l as u8) * 0.1, lv: [Some(*l)] }).collect();
2684        let a = map(&obs, [4], &spec3, &[2.5; 3], &[spread], None).unwrap();
2685        let mut spec7 = [Coef { mean: 0.0, sd: spread, ard: false, nonpos: false }; 7];
2686        spec7[..3].copy_from_slice(&spec3);
2687        let sd7: [f64; 7] = std::array::from_fn(|k| spec7[k].sd);
2688        let dense: Vec<Obs<7, 0>> = rows
2689            .iter()
2690            .map(|(x, l, y)| {
2691                let mut z = [0.0; 7];
2692                z[..3].copy_from_slice(x);
2693                z[3 + l] = 1.0;
2694                Obs { x: z, y: *y, w: 1.0 + f64::from(*l as u8) * 0.1, lv: [] }
2695            })
2696            .collect();
2697        let b = map(&dense, [], &spec7, &sd7, &[], None).unwrap();
2698        assert!(a.converged && b.converged);
2699        for k in 0..3 {
2700            assert!((a.beta[k] - b.beta[k]).abs() < 1e-6, "{k}: {} {}", a.beta[k], b.beta[k]);
2701            for j in 0..3 {
2702                assert!((a.cov[k][j] - b.cov[k][j]).abs() < 1e-6, "cov {k} {j}");
2703            }
2704        }
2705        for l in 0..4 {
2706            assert!((a.u[0][l] - b.beta[3 + l]).abs() < 1e-6, "level {l}");
2707            assert!((a.var_u[0][l] - b.cov[3 + l][3 + l]).abs() < 1e-6, "var {l}: {} {}", a.var_u[0][l], b.cov[3 + l][3 + l]);
2708        }
2709    }
2710
2711    #[test]
2712    fn a_bounded_slope_stops_at_zero_and_a_negative_one_is_learned() {
2713        let mut rng = Rng::new(3);
2714        let obs: Vec<Obs<3, 0>> = (0..600)
2715            .map(|_| {
2716                let x = [1.0, rng.unit() * 3.0, rng.unit() * 3.0];
2717                let eta = -0.5 + 0.9 * x[1] - 0.7 * x[2];
2718                Obs { x, y: f64::from(u8::from(rng.unit() < sigmoid(eta))), w: 1.0, lv: [] }
2719            })
2720            .collect();
2721        let bounded = Coef { mean: 0.0, sd: 2.5, ard: false, nonpos: true };
2722        let spec = [Coef { nonpos: false, ..bounded }, bounded, bounded];
2723        let e = map(&obs, [], &spec, &[2.5; 3], &[], None).unwrap();
2724        assert_eq!(e.beta[1], 0.0, "a positive effect under a ≤ 0 bound sits at the bound");
2725        assert!(e.beta[2] < -0.3, "{:?}", e.beta);
2726    }
2727
2728    /// Every feasible routing's value, the best; a unit marked in `nofree` never free.
2729    fn brute(v: &Valuer, nofree: &[bool], rail: usize, cap: usize) -> f64 {
2730        let n = v.n();
2731        let mut best = f64::NEG_INFINITY;
2732        for code in 0..3usize.pow(n as u32) {
2733            let mut x = code;
2734            let routes: Vec<Route> = (0..n)
2735                .map(|_| {
2736                    let r = [Route::Ask, Route::Free, Route::Not][x % 3];
2737                    x /= 3;
2738                    r
2739                })
2740                .collect();
2741            let (m_q, m_f) = (routes.iter().filter(|r| **r == Route::Ask).count(), routes.iter().filter(|r| **r == Route::Free).count());
2742            let forced_ok = v.feats.iter().zip(&routes).all(|(f, r)| !forced(f) || *r == Route::Ask);
2743            let free_ok = nofree.iter().zip(&routes).all(|(x, r)| !x || *r != Route::Free);
2744            let f = v.feats.iter().filter(|f| forced(f)).count();
2745            if forced_ok && free_ok && m_q <= rail.max(f) && m_f <= cap {
2746                best = best.max(v.value(&routes));
2747            }
2748        }
2749        best
2750    }
2751
2752    #[test]
2753    fn the_solver_equals_brute_force() {
2754        let mut rng = Rng::new(11);
2755        for case in 0..400 {
2756            let n = case % 8;
2757            let stop = case % 3 == 0;
2758            let feats: Vec<Feat> = (0..n).map(|r| Feat { grade: 1 + (rng.next_u64() % 3) as u8, rank: r, stop, three: false, pool: 0.0 }).collect();
2759            let mut b = [0.0; P];
2760            for x in &mut b {
2761                *x = 2.0 * normal(&mut rng);
2762            }
2763            b[ASK_M] = -rng.unit() * 2.0;
2764            b[FREE_M] = -rng.unit() * 2.0;
2765            let t = Theta { b, base: (0..n).map(|_| normal(&mut rng)).collect() };
2766            let rates = Rates { free_stop: rng.unit(), free_live: rng.unit(), later: rng.unit(), wait: 0.0, ask_live: 1.0 };
2767            let v = Valuer { t: &t, feats: &feats, rates: &rates };
2768            // Every other case: units that may not go free (lessons the session had), forced ones too.
2769            let nofree: Vec<bool> = (0..n).map(|_| case % 2 == 1 && rng.unit() < 0.4).collect();
2770            let table = Table::of(&v, &nofree);
2771            for (rail, cap) in [(20, 10), (2, 1), (1, 3), (0, 0)] {
2772                let got = solve(&table, rail, cap);
2773                let want = brute(&v, &nofree, rail, cap);
2774                assert!((v.value(&got) - want).abs() < 1e-12, "case {case} rail {rail} cap {cap}: {} vs {want} {got:?}", v.value(&got));
2775                assert!((table.value(&got) - v.value(&got)).abs() < 1e-12, "the table values as the model does");
2776                assert!(feats.iter().zip(&got).all(|(f, r)| !forced(f) || *r == Route::Ask));
2777                assert!(nofree.iter().zip(&got).all(|(x, r)| !x || *r != Route::Free), "case {case}: {nofree:?} {got:?}");
2778            }
2779        }
2780    }
2781
2782    #[test]
2783    fn the_value_of_a_route_is_the_models_lift() {
2784        let f = Feat { grade: 3, rank: 2, stop: false, three: true, pool: 0.3 };
2785        let mut b = [0.0; P];
2786        for (i, x) in b.iter_mut().enumerate() {
2787            *x = 0.1 * i as f64 - 0.6;
2788        }
2789        let base = dot(&b, &design(&f, Route::Free, 1)) + 0.25;
2790        let t = Theta { b, base: vec![base] };
2791        let rates = Rates { free_stop: 0.5, free_live: 0.8, later: 0.4, wait: 0.0, ask_live: 0.6 };
2792        let v = Valuer { t: &t, feats: std::slice::from_ref(&f), rates: &rates };
2793        let p = |r: Route, m: usize| sigmoid(dot(&b, &design(&f, r, m)) + 0.25);
2794        // During the turn a question arrives at the learned rate a live one reached the drone.
2795        assert!((v.ask(0, 3) - 0.6 * (p(Route::Ask, 3) - p(Route::Not, 1))).abs() < 1e-12);
2796        assert!((v.free(0, 2) - 0.8 * (p(Route::Free, 2) - p(Route::Not, 1))).abs() < 1e-12);
2797        // Not now counts nothing during the turn, whatever the later rate: the check that delivers it
2798        // later credits its value, and its ledger entry with it.
2799        for r in [Route::Not, Route::Placebo] {
2800            assert_eq!(v.value(&[r]), 0.0, "during the turn a lesson left for later counts nothing here: {r:?}");
2801        }
2802        let stop = Feat { stop: true, ..f };
2803        let t = Theta { b, base: vec![dot(&b, &design(&stop, Route::Free, 1)) + 0.25] };
2804        let v = Valuer { t: &t, feats: std::slice::from_ref(&stop), rates: &rates };
2805        let p = |r: Route, m: usize| sigmoid(dot(&b, &design(&stop, r, m)) + 0.25);
2806        assert!((v.ask(0, 3) - (p(Route::Ask, 3) - p(Route::Not, 1))).abs() < 1e-12, "a stop's question blocks: it arrives");
2807        assert!((v.free(0, 2) - 0.5 * (p(Route::Free, 2) - p(Route::Not, 1))).abs() < 1e-12);
2808        for r in [Route::Not, Route::Placebo] {
2809            assert_eq!(v.value(&[r]), 0.0, "at the stop a lesson not delivered counts nothing: {r:?}");
2810        }
2811    }
2812
2813    #[test]
2814    fn a_live_question_without_a_3_arrives_as_a_hand_over_does() {
2815        let mut b = [0.0; P];
2816        for (i, x) in b.iter_mut().enumerate() {
2817            *x = 0.1 * i as f64 - 0.6;
2818        }
2819        let t = Theta { b, base: vec![0.25] };
2820        let rates = Rates { free_stop: 0.5, free_live: 0.3, later: 0.4, wait: 0.0, ask_live: 0.9 };
2821        let ask = |three: bool| {
2822            let f = Feat { grade: 2, rank: 0, stop: false, three, pool: 0.0 };
2823            Valuer { t: &t, feats: std::slice::from_ref(&f), rates: &rates }.ask(0, 1)
2824        };
2825        // The lift of asking a 2, which the check's 3 does not change.
2826        let lift = sigmoid(0.25 + b[ASK]) - sigmoid(0.25 + b[NOT]);
2827        assert!(lift.abs() > 0.01);
2828        // On a check with a 3 the question waits for the stop, which asks it.
2829        assert!((ask(true) - 0.9 * lift).abs() < 1e-12);
2830        // Without one no stop asks it (hook.rs `live_check`): a tool call or the next prompt brings it,
2831        // as it brings a hand-over.
2832        assert!((ask(false) - 0.3 * lift).abs() < 1e-12);
2833    }
2834
2835    /// A gate that may risk plenty: the learned policy decides.
2836    fn open_gate() -> Gate {
2837        Gate { gain: vec![0.0; DRAWS], allowance: 5.0, ..Gate::default() }
2838    }
2839
2840    #[test]
2841    fn cold_start_is_the_fixed_rule() {
2842        let fit_model = fit(&planted(6, 20, 2), None);
2843        assert!(fit_model.model.is_some());
2844        let wrong_len = Gate { gain: vec![0.0; 3], allowance: 1.0, ..Gate::default() };
2845        let ids: Vec<String> = (0..14).map(|i| format!("L{i}")).collect();
2846        let mut grades = tables(5);
2847        grades.extend([vec![3; 12], [vec![1; 11], vec![2; 3]].concat()]);
2848        for g in &grades {
2849            let units: Vec<Unit> = ids.iter().zip(g).enumerate().map(|(r, (l, g))| unit(l, *g, r)).collect();
2850            let want = fixed_routes(&units, &[]);
2851            for (fit, gate) in [(&Fit::default(), &open_gate()), (&fit_model, &Gate::default()), (&fit_model, &wrong_len)] {
2852                for stop in [true, false] {
2853                    let d = choose(&units, &Check { session: "s", stop, tokens: 0 }, fit, gate, ALPHA, 7, &[]);
2854                    assert_eq!(d.routes, want, "{g:?}");
2855                    assert_eq!(d.p, want.iter().map(|r| f64::from(u8::from(*r == Route::Ask))).collect::<Vec<_>>());
2856                    assert_eq!(d.pf, want.iter().map(|r| f64::from(u8::from(*r == Route::Free))).collect::<Vec<_>>());
2857                    assert_eq!((d.source, d.gate), ("fixed", 0.0));
2858                }
2859            }
2860        }
2861    }
2862
2863    #[test]
2864    fn n_zero_and_n_one() {
2865        let empty = fit(&Summary::default(), None);
2866        assert!(empty.model.is_none() && empty.labels == 0);
2867        let mut sim = Sim::new(5);
2868        let mut one = |_: &[u8], _: bool, _: &mut Rng| (vec![Route::Ask], vec![1.0], vec![0.0], "fixed");
2869        sim.check("s", false, &[2], &["A".to_string()], &truth(), &mut one);
2870        let f = fit(&sim.summary(), None);
2871        let m = f.model.as_ref().expect("one label is a model");
2872        assert_eq!(f.labels, 1);
2873        assert!(m.beta.iter().chain(&m.chol).all(|x| x.is_finite()), "{m:?}");
2874        let gate = open_gate();
2875        assert!(choose(&[], &Check { session: "s", stop: true, tokens: 0 }, &f, &gate, ALPHA, 1, &[]).routes.is_empty());
2876        for g in 1..=3 {
2877            let d = choose(&[unit("A", g, 0)], &Check { session: "s", stop: true, tokens: 0 }, &f, &gate, ALPHA, 1, &[]);
2878            assert_eq!(d.routes.len(), 1);
2879            assert!((d.p[0] + d.pf[0]) <= 1.0 + 1e-9);
2880        }
2881    }
2882
2883    /// A decision is a function of its inputs; the seed moves only the randomised test's count, so at
2884    /// the stop, where the test never runs, no seed changes it.
2885    #[test]
2886    fn decisions_are_deterministic_and_only_the_test_varies() {
2887        let f = fit(&planted(8, 20, 3), None);
2888        let gate = open_gate();
2889        let units = [unit("L1", 2, 0), unit("L2", 1, 1), unit("L3", 3, 2)];
2890        let check = Check { session: "new", stop: false, tokens: 0 };
2891        let a = choose(&units, &check, &f, &gate, ALPHA, 42, &[]);
2892        assert_eq!(a, choose(&units, &check, &f, &gate, ALPHA, 42, &[]));
2893        let plays: std::collections::HashSet<Vec<Route>> = (0..60).map(|s| choose(&units, &check, &f, &gate, ALPHA, s, &[]).routes).collect();
2894        assert!(plays.len() > 1, "the test's count varies with the check: {plays:?}");
2895        let stop = Check { stop: true, ..check };
2896        let at_stop: std::collections::HashSet<Vec<Route>> = (0..60).map(|s| choose(&units, &stop, &f, &gate, ALPHA, s, &[]).routes).collect();
2897        assert_eq!(at_stop.len(), 1, "no Thompson play: {at_stop:?}");
2898    }
2899
2900    #[test]
2901    fn propensities_match_the_frequency_of_the_play() {
2902        let f = fit(&planted(6, 15, 4), None);
2903        let gate = open_gate();
2904        let units = [unit("L1", 2, 0), unit("L2", 1, 1), unit("L3", 1, 2)];
2905        let check = Check { session: "new", stop: false, tokens: 0 };
2906        let n = 300;
2907        let (mut asked, mut free) = ([0.0; 3], [0.0; 3]);
2908        let (mut p, mut pf) = ([0.0; 3], [0.0; 3]);
2909        for seed in 0..n {
2910            let d = choose(&units, &check, &f, &gate, ALPHA, seed, &[]);
2911            for j in 0..3 {
2912                asked[j] += f64::from(u8::from(d.routes[j] == Route::Ask)) / n as f64;
2913                free[j] += f64::from(u8::from(d.routes[j] == Route::Free)) / n as f64;
2914                p[j] += d.p[j] / n as f64;
2915                pf[j] += d.pf[j] / n as f64;
2916            }
2917        }
2918        for j in 0..3 {
2919            for (freq, prop) in [(asked[j], p[j]), (free[j], pf[j])] {
2920                let se = (prop * (1.0 - prop) / n as f64).sqrt();
2921                assert!((freq - prop).abs() <= 4.0 * se + 0.01, "unit {j}: played {freq:.3}, propensity {prop:.3}");
2922            }
2923        }
2924        assert!(asked.iter().chain(&free).any(|x| *x > 0.05 && *x < 0.95), "the play varies: {asked:?} {free:?}");
2925    }
2926
2927    /// A model that thinks handing over beats asking by a wide, uncertain margin.
2928    fn free_beats_ask() -> Fit {
2929        let mut sim = Sim::new(8);
2930        let mut t = truth();
2931        t.b[ASK] = -3.0;
2932        for i in 0..10 {
2933            sim.session(&format!("s{i}"), 12, 10, &t, &mut uniform);
2934        }
2935        fit(&sim.summary(), None)
2936    }
2937
2938    /// Guard: a stop's grade 3 is asked whatever the model says. The same 3 during the turn goes free,
2939    /// so the guard, not the model, keeps it asked.
2940    #[test]
2941    fn a_stop_grade_three_is_never_routed_away_from_asking() {
2942        let f = free_beats_ask();
2943        let gate = open_gate();
2944        let units = [unit("L1", 3, 0), unit("L2", 1, 1)];
2945        let live = choose(&units, &Check { session: "n", stop: false, tokens: 0 }, &f, &gate, ALPHA, 1, &[]);
2946        assert_eq!(live.routes[0], Route::Free, "during the turn the model hands it over: {live:?}");
2947        for seed in 0..20 {
2948            let d = choose(&units, &Check { session: "n", stop: true, tokens: 0 }, &f, &gate, ALPHA, seed, &[]);
2949            assert_eq!((d.routes[0], d.p[0], d.pf[0]), (Route::Ask, 1.0, 0.0), "{d:?}");
2950        }
2951    }
2952
2953    /// A lesson the session already had is never handed over free, at cold start (the fixed rule
2954    /// `graded_without`) or by the learned play, its `pf` 0, though the same model hands it over
2955    /// without `had`. Asking it stays open.
2956    #[test]
2957    fn a_lesson_the_session_had_never_goes_free() {
2958        let f = free_beats_ask();
2959        let gate = open_gate();
2960        let units = [unit("L1", 2, 0), unit("L2", 1, 1), unit("L3", 1, 2)];
2961        let had = ["L2".to_string()];
2962        let check = Check { session: "n", stop: false, tokens: 0 };
2963        assert_eq!(fixed_routes(&units, &had), [Route::Free, Route::Not, Route::Free]);
2964        let cold = choose(&units, &check, &Fit::default(), &gate, ALPHA, 1, &had);
2965        assert_eq!((cold.routes, cold.pf[1], cold.source), (fixed_routes(&units, &had), 0.0, "fixed"));
2966        let mut freed = 0;
2967        for seed in 0..20 {
2968            freed += usize::from(choose(&units, &check, &f, &gate, ALPHA, seed, &[]).routes[1] == Route::Free);
2969            let d = choose(&units, &check, &f, &gate, ALPHA, seed, &had);
2970            assert!(d.routes[1] != Route::Free && d.pf[1] == 0.0, "{d:?}");
2971        }
2972        assert!(freed > 0, "the scenario: without `had` the model hands L2 over");
2973        // A stop's 3 the session had is still asked.
2974        let block = [unit("L2", 3, 0), unit("L1", 1, 1)];
2975        let d = choose(&block, &Check { stop: true, ..check }, &f, &gate, ALPHA, 3, &had);
2976        assert_eq!((d.routes[0], d.p[0]), (Route::Ask, 1.0));
2977    }
2978
2979    /// Guard: a check with more applies than `SOLVE_MAX` takes the fixed rule (source `size`). The same
2980    /// model and gate deviate at `SOLVE_MAX` applies, so the guard, not the model, keeps the fixed rule.
2981    #[test]
2982    fn a_check_past_the_solvers_size_takes_the_fixed_rule() {
2983        let f = free_beats_ask();
2984        let gate = open_gate();
2985        let ids: Vec<String> = (0..=SOLVE_MAX).map(|i| format!("L{i}")).collect();
2986        // A 3 and 2s: the fixed rule asks them all.
2987        let units: Vec<Unit> = ids.iter().enumerate().map(|(r, l)| unit(l, if r == 0 { 3 } else { 2 }, r)).collect();
2988        let check = Check { session: "n", stop: false, tokens: 0 };
2989        let at = choose(&units[..SOLVE_MAX], &check, &f, &gate, ALPHA, 1, &[]);
2990        assert_eq!(at.source, EVIDENCE, "{at:?}");
2991        assert_ne!(at.routes, fixed_routes(&units[..SOLVE_MAX], &[]), "at the size the model hands them over: {at:?}");
2992        let past = choose(&units, &check, &f, &gate, ALPHA, 1, &[]);
2993        let base = fixed_routes(&units, &[]);
2994        assert_eq!((&past.routes, past.source, past.risk), (&base, "size", 0.0));
2995        assert_eq!(past.p, base.iter().map(|r| f64::from(u8::from(*r == Route::Ask))).collect::<Vec<_>>(), "its choice is its propensity");
2996    }
2997
2998    /// A history where every 3 was asked (the fixed rule): the model never saw a 3 handed over, and a
2999    /// stop's 3 stays asked.
3000    #[test]
3001    fn a_confounded_history_keeps_the_stop_three_asked() {
3002        let mut sim = Sim::new(12);
3003        for i in 0..12 {
3004            sim.session(&format!("s{i}"), 16, 12, &truth(), &mut fixed_rule);
3005        }
3006        let s = sim.summary();
3007        assert!(s.applies.iter().all(|a| a.grade != 3 || a.route == Route::Ask || a.route == Route::Not), "never free");
3008        let f = fit(&s, None);
3009        let gate = open_gate();
3010        for seed in 0..10 {
3011            let d = choose(&[unit("L1", 3, 0), unit("L2", 2, 1)], &Check { session: "n", stop: true, tokens: 0 }, &f, &gate, ALPHA, seed, &[]);
3012            assert_eq!((d.routes[0], d.p[0]), (Route::Ask, 1.0));
3013        }
3014    }
3015
3016    /// The fixed rule's history logged as the learned policy's cold start (its gate opens on it), in a
3017    /// world with no route effect and the stop's checks with a 3 lifted by `lift`.
3018    fn three_stop_world(lift: f64) -> Summary {
3019        let mut t = truth();
3020        t.b[ASK] = 0.0;
3021        t.b[NOT] = 0.0;
3022        t.lift = lift;
3023        let mut cold = |grades: &[u8], stop: bool, rng: &mut Rng| {
3024            let (routes, p, pf, _) = fixed_rule(grades, stop, rng);
3025            (routes, p, pf, "learned")
3026        };
3027        let mut sim = Sim::new(1);
3028        for i in 0..40 {
3029            sim.session(&format!("s{i}"), 20, 12, &t, &mut cold);
3030        }
3031        summary::with_fit(sim.summary(), None)
3032    }
3033
3034    /// The fixed rule asks exactly when a check has a 3, so a lift of the stop's checks with a 3 and
3035    /// asking at the stop are one cell of its history. The lift goes to its non-route twin
3036    /// (`three_stop`), not to asking at the stop: a stop without a 3 is asked as often as in the same
3037    /// history without the lift (on evidence alone, so not at all), never by a learned certainty.
3038    #[test]
3039    fn a_lift_of_the_stops_with_a_three_is_not_taken_for_asking() {
3040        let (lifted, plain) = (three_stop_world(1.5), three_stop_world(0.0));
3041        let units = [unit("A", 2, 0), unit("B", 1, 1)];
3042        assert_eq!(fixed_routes(&units, &[]), [Route::Free; 2], "the fixed rule hands both over");
3043        let asked = |s: &Summary| -> f64 {
3044            assert!(remaining(&s.gate) > 0.0, "the gate opened on the history: {:?}", s.gate.allowance);
3045            let seeds = 20u32;
3046            (0..seeds)
3047                .map(|seed| {
3048                    let d = choose(&units, &Check { session: "new", stop: true, tokens: 0 }, &s.fit, &s.gate, ALPHA, u64::from(seed), &[]);
3049                    assert_ne!(d.source, "fixed", "{d:?}");
3050                    d.p[0]
3051                })
3052                .sum::<f64>()
3053                / f64::from(seeds)
3054        };
3055        let (with_lift, without) = (asked(&lifted), asked(&plain));
3056        let m = lifted.fit.model.as_ref().expect("a model");
3057        let sd = |k: usize| (0..=k).map(|j| m.chol[k * P + j].powi(2)).sum::<f64>().sqrt();
3058        let (ask_stop, twin) = ((m.beta[ASK_STOP], sd(ASK_STOP)), (m.beta[THREE_STOP], sd(THREE_STOP)));
3059        let seen = format!("asked {with_lift:.3} with the lift, {without:.3} without; ask_stop {ask_stop:.3?}, three_stop {twin:.3?}");
3060        assert!(with_lift < 0.9, "a stop without a 3 is not blocked by the lift: {seen}");
3061        assert!((with_lift - without).abs() < 0.15, "{seen}");
3062        assert!(ask_stop.0.abs() < 2.0 * ask_stop.1, "asking at the stop is not identified: {seen}");
3063        assert!(twin.0 > 0.75, "the lift is the twin's: {seen}");
3064    }
3065
3066    /// The gate's invariant over a run of checks: the replayed value of what the policy did, at the
3067    /// `DELTA` quantile, never falls more than α × the fixed rule's replayed value below the fixed
3068    /// rule. The same run ungated (every draw of the test admitted) breaks it, so the gate, not the
3069    /// scenario, holds it.
3070    #[test]
3071    fn the_gate_never_risks_more_than_its_alpha_share() {
3072        // A wide posterior whose mean says asking is a little worse than handing over: no evidence for
3073        // a deviation, and most of the test's asks lose under the posterior.
3074        let spec = coefs();
3075        let mut beta: Vec<f64> = spec.iter().map(|c| c.mean).collect();
3076        beta[ASK] = -0.4;
3077        beta[B0] = -0.5;
3078        let mut chol = vec![0.0; P * P];
3079        for k in 0..P {
3080            chol[k * P + k] = if k == ASK { 1.0 } else { 0.3 };
3081        }
3082        let model = Model { beta, chol, sd: spec.iter().map(|c| c.sd).collect(), spread: [0.3; FAMILIES], ..Model::default() };
3083        let rates = Rates { free_stop: 1.0, free_live: 1.0, later: 0.5, wait: 0.0, ask_live: 1.0 };
3084        let f = Fit { key: "test".into(), model: Some(model), rates, ..Fit::default() };
3085        let ids: Vec<String> = (0..10).map(|i| format!("L{i}")).collect();
3086        let mut refused = 0;
3087        let mut run = |gated: bool, rng: &mut Rng| -> (bool, usize) {
3088            let mut gate = Gate::default();
3089            let mut broke = false;
3090            let mut deviated = 0;
3091            for c in 0..200 {
3092                let n = 1 + (rng.next_u64() % 3) as usize;
3093                let units: Vec<Unit> = (0..n).map(|r| unit(&ids[(rng.next_u64() % 10) as usize], 1 + (rng.next_u64() % 3) as u8, r)).collect();
3094                let session = format!("t{}", c / 10);
3095                let check = Check { session: &session, stop: c % 5 == 0, tokens: 0 };
3096                let routes = if c < 10 {
3097                    fixed_routes(&units, &[])
3098                } else if gated {
3099                    let d = choose(&units, &check, &f, &gate, ALPHA, c as u64, &[]);
3100                    // A deviation is admitted exactly when its risk fits what the gate may still risk; a
3101                    // refused one keeps the fixed rule and says so.
3102                    match d.source {
3103                        GATE => {
3104                            assert_eq!((&d.routes, d.risk), (&fixed_routes(&units, &[]), 0.0), "{d:?}");
3105                            refused += 1;
3106                        }
3107                        _ if d.routes != fixed_routes(&units, &[]) => {
3108                            assert_eq!(d.source, EXPERIMENT, "{d:?}");
3109                            assert!(d.risk <= d.gate + 1e-12, "{d:?}");
3110                        }
3111                        _ => {}
3112                    }
3113                    d.routes
3114                } else {
3115                    let open = Gate { allowance: f64::INFINITY, ..gate.clone() };
3116                    choose(&units, &check, &f, &open, ALPHA, c as u64, &[]).routes
3117                };
3118                deviated += usize::from(routes != fixed_routes(&units, &[]));
3119                ledger_add_without(&f, &mut gate, &check, &units, &routes, &[]);
3120                broke |= lower_quantile(&mut gate.gain.clone()) < -gate.allowance - 1e-9;
3121            }
3122            (broke, deviated)
3123        };
3124        let (broke, deviated) = run(true, &mut Rng::new(77));
3125        assert!(!broke && deviated > 0, "gated: broke {broke}, deviated {deviated}");
3126        let (broke, _) = run(false, &mut Rng::new(77));
3127        assert!(broke, "ungated, the same run overspends: the scenario needs the gate");
3128        assert!(refused > 0, "the gate refused deviations, logged as `gate`");
3129    }
3130
3131    #[test]
3132    fn no_price_without_a_budget_and_spend_within_one() {
3133        let mut s = planted(10, 12, 6);
3134        // Pool evidence: every check showed 40 lessons for 12k tokens and applied the first few.
3135        s.pool.bins = (0..6).map(|b| (400 * (1u64 << b), 200 / (b as u64 + 1))).collect();
3136        s.pool.shown = 40 * 120;
3137        s.pool.tokens = 12_000 * 120;
3138        let free = fit(&s, None);
3139        assert_eq!((free.lambda, free.budget), (0.0, None), "no budget, no price");
3140        let checks = s.sessions.iter().map(|x| f64::from(x.checks)).sum::<f64>() / s.sessions.len() as f64;
3141        let spend = |f: &Fit| {
3142            s.sessions.iter().map(|x| f64::from(x.checks) * pool_tokens(f, true, None, session_seed(&x.id)) as f64).sum::<f64>() / s.sessions.len() as f64
3143        };
3144        assert!(spend(&free) >= checks * crate::whole::TOKENS as f64 - 1e-6, "unpriced, the pool keeps the baseline");
3145        let budget = checks * 9_000.0;
3146        let priced = fit(&s, Some(budget));
3147        assert!(priced.lambda > 0.0, "a budget below today's spend prices tokens");
3148        assert!(spend(&priced) <= budget + 1e-6, "{} > {budget}", spend(&priced));
3149        let roomy = fit(&s, Some(checks * 1e6));
3150        assert_eq!(roomy.lambda, 0.0, "a budget the baseline meets costs nothing");
3151    }
3152
3153    /// The hooks choose pools under their harness's limit (live.rs `call_limit`), where a pool with
3154    /// latency evidence may grow past the baseline. The budget's price holds what they spend within the
3155    /// budget under every limit: no limit, one only the middle growth fits under, room for all.
3156    #[test]
3157    fn a_budget_holds_where_pools_may_grow() {
3158        let mut s = Summary::default();
3159        for i in 0..10 {
3160            s.sessions.push(summary::Session { id: format!("s{i}"), checks: 10, ..summary::Session::default() });
3161        }
3162        // Yields known past the largest budget, latency evidence enough, no dilution: unpriced, every
3163        // pool grows as far as the limit lets it. The 95% latency at 16,971 tokens is 3,197 ms, at
3164        // 24,000 3,900 ms.
3165        let pool = PoolFit {
3166            yields: vec![(50.0, 10.0); 8],
3167            per_lesson: 300.0,
3168            latency: (1000.0, 0.1, 500.0),
3169            latency_n: LATENCY_MIN as u32,
3170            latency_reach: 24_000,
3171            not: (-1.0, 0.1),
3172            ..PoolFit::default()
3173        };
3174        let spend = |f: &Fit, limit: Option<u64>| {
3175            s.sessions.iter().map(|x| f64::from(x.checks) * pool_tokens(f, true, limit, session_seed(&x.id)) as f64).sum::<f64>() / s.sessions.len() as f64
3176        };
3177        let baseline = 10.0 * crate::whole::TOKENS as f64;
3178        let unpriced = Fit { pool: pool.clone(), ..Fit::default() };
3179        assert!(spend(&unpriced, Some(60_000)) > 1.5 * baseline, "the scenario: unpriced, the pools grow");
3180        for budget in [baseline, 1.2 * baseline, 0.9 * baseline] {
3181            let mut f = Fit { pool: pool.clone(), budget: Some(budget), ..Fit::default() };
3182            f.lambda = price(&s, &f, budget);
3183            assert!(f.lambda > 0.0, "budget {budget}: growth is priced");
3184            for limit in [None, Some(3_500), Some(60_000)] {
3185                assert!(spend(&f, limit) <= budget + 1e-6, "budget {budget}, limit {limit:?}: spent {} (λ {:e})", spend(&f, limit), f.lambda);
3186            }
3187        }
3188    }
3189
3190    #[test]
3191    fn the_pool_stays_at_the_baseline_without_evidence_or_a_limit() {
3192        let f = Fit::default();
3193        assert_eq!(pool_tokens(&f, true, Some(60_000), 1), crate::whole::TOKENS);
3194        assert_eq!(pool_tokens(&f, false, Some(60_000), 1), crate::whole::TOKENS);
3195        let mut s = planted(3, 6, 7);
3196        s.pool.bins = (0..6).map(|b| (100 * (1u64 << b), 90)).collect();
3197        s.pool.shown = 40 * 18;
3198        s.pool.tokens = 12_000 * 18;
3199        let f = fit(&s, None);
3200        // High yields everywhere, but no latency evidence: never past the baseline.
3201        assert!(pool_tokens(&f, true, Some(60_000), 1) <= crate::whole::TOKENS);
3202        assert_eq!(pool_grid(), [6000, 8485, 12000, 16971, 24000]);
3203    }
3204
3205    /// A larger pool needs a gain > 0 at the `DELTA` quantile: draws that tie with the baseline (no
3206    /// yield past it to tell them apart) never move it, whatever a session's own draw prefers. A
3207    /// smaller one still may on a tie (it costs nothing it was not already pricing).
3208    #[test]
3209    fn a_larger_pool_is_admitted_only_on_a_positive_gain() {
3210        let grid = pool_grid();
3211        let b = grid.iter().position(|&t| t == crate::whole::TOKENS).unwrap();
3212        let tied = PoolDraws { grid: grid.clone(), shared: vec![vec![1.0; DRAWS]; grid.len()] };
3213        let mut play = vec![0.0; grid.len()];
3214        play[grid.len() - 1] = 5.0;
3215        // The baseline and the larger budgets (a smaller one would win the tie of plays at 0).
3216        let feasible: Vec<bool> = (0..grid.len()).map(|i| i >= b).collect();
3217        assert_eq!(tied.choose(&play, &feasible, 0.0), crate::whole::TOKENS, "a tie at 0 keeps the baseline");
3218        let mut ahead = tied.shared.clone();
3219        ahead[grid.len() - 1] = vec![1.5; DRAWS];
3220        let ahead = PoolDraws { grid: grid.clone(), shared: ahead };
3221        assert_eq!(ahead.choose(&play, &feasible, 0.0), grid[grid.len() - 1], "a gain > 0 at every draw admits it");
3222        let mut smaller = vec![0.0; grid.len()];
3223        smaller[0] = 5.0;
3224        assert_eq!(tied.choose(&smaller, &[true; 5], 0.0), grid[0], "a smaller pool on a tie, as before");
3225    }
3226
3227    /// A pool grows only to a budget its latency was measured at: a flat fit over calls at the
3228    /// baseline (a team store on 2026-10-31: b = 0, 203 calls, none above 12,000 tokens) admits no
3229    /// larger budget however roomy the limit, and calls that read `LATENCY_NEAR` of a budget admit it.
3230    #[test]
3231    fn a_pool_grows_only_where_its_latency_was_observed() {
3232        let mut s = Summary::default();
3233        // Pairs of calls at the same size, one 16 s and one 19 s: no slope at all.
3234        s.pool.latency = (0..204u32).map(|i| (if i / 2 < 5 { 9_500 } else { 11_000 + i / 2 }, 16_000 + 3_000 * (i % 2))).collect();
3235        // Yields known past the largest budget, as the bins would give them (`pool_state` reads them).
3236        s.pool.bins = vec![(400, 300); 9];
3237        (s.pool.shown, s.pool.tokens) = (100, 9_100);
3238        let mut pool = PoolFit::default();
3239        pool_state(&s, &mut pool);
3240        assert!(pool.yields.len() == 9 && pool.per_lesson == 91.0, "{pool:?}");
3241        assert_eq!((pool.latency.1, pool.latency_n), (0.0, 204), "the scenario: a flat fit, enough calls");
3242        assert!(pool.latency_reach >= 11_000 && pool.latency_reach < 12_000, "{}", pool.latency_reach);
3243        let roomy = Some(u64::MAX);
3244        assert!(pool_feasible(&pool, crate::whole::TOKENS, roomy, 0.0));
3245        for t in pool_grid().into_iter().filter(|&t| t > crate::whole::TOKENS) {
3246            assert!(!pool_feasible(&pool, t, roomy, 0.0), "{t}: no call read near it");
3247        }
3248        // Twenty calls that read 15,300 tokens or more: 16,971 is within reach, 24,000 is not.
3249        s.pool.latency.extend((0..LATENCY_MIN as u32).map(|i| (15_300 + i, 20_000)));
3250        pool_state(&s, &mut pool);
3251        assert_eq!(pool.latency_reach, 15_300);
3252        assert!(pool_feasible(&pool, 16_971, roomy, 0.0) && !pool_feasible(&pool, 24_000, roomy, 0.0));
3253        // The same evidence without the reach (a fit from before it): no growth.
3254        assert!(!pool_feasible(&PoolFit { latency_reach: 0, ..pool }, 16_971, roomy, 0.0));
3255    }
3256
3257    /// A tail sample's sparse places can leave a bin no lesson was shown in before bins that have some:
3258    /// the yields stop at it, so its prior alone never counts as a yield and no pool past it is known.
3259    #[test]
3260    fn the_yields_stop_at_a_bin_no_lesson_was_shown_in() {
3261        let mut s = Summary::default();
3262        s.pool.bins = vec![(40, 20), (80, 30), (0, 0), (3, 1)];
3263        let mut pool = PoolFit::default();
3264        pool_state(&s, &mut pool);
3265        assert_eq!(pool.yields, pava(&[(21.0, 21.0), (31.0, 51.0)]), "the gap ends them");
3266        s.pool.bins[2] = (5, 1);
3267        pool_state(&s, &mut pool);
3268        assert_eq!(pool.yields.len(), 4, "filled, the tail's bin past it counts");
3269    }
3270
3271    #[test]
3272    fn pava_keeps_the_yields_from_rising() {
3273        let y = pava(&[(5.0, 5.0), (8.0, 2.0), (1.0, 9.0), (2.0, 8.0)]);
3274        let means: Vec<f64> = y.iter().map(|(a, b)| a / (a + b)).collect();
3275        assert!(means.windows(2).all(|w| w[0] >= w[1] - 1e-12), "{means:?}");
3276        assert_eq!(y[0], y[1], "the rising pair merged");
3277        assert_eq!(y[0], (13.0, 7.0));
3278    }
3279
3280    #[test]
3281    fn the_samplers_have_their_moments() {
3282        let mut rng = Rng::new(1);
3283        let n = 20_000;
3284        let z: Vec<f64> = (0..n).map(|_| normal(&mut rng)).collect();
3285        let mean = z.iter().sum::<f64>() / n as f64;
3286        let var = z.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / n as f64;
3287        assert!(mean.abs() < 0.03 && (var - 1.0).abs() < 0.05, "{mean} {var}");
3288        for shape in [0.4, 1.0, 3.5] {
3289            let g = (0..n).map(|_| gamma(shape, &mut rng)).sum::<f64>() / n as f64;
3290            assert!((g - shape).abs() < 0.05 * shape.max(1.0), "{shape}: {g}");
3291        }
3292        let b = (0..n).map(|_| beta_draw(2.0, 6.0, &mut rng)).sum::<f64>() / n as f64;
3293        assert!((b - 0.25).abs() < 0.01, "{b}");
3294    }
3295
3296    /// The confidence sequence: rarely below the true mean at any time, and it closes in on it.
3297    #[test]
3298    fn the_upper_bound_covers_the_mean_at_every_time() {
3299        let mut rng = Rng::new(21);
3300        let mut missed = 0;
3301        for _ in 0..400 {
3302            let x: Vec<f64> = (0..200).map(|_| normal(&mut rng) * 0.4 - 0.1).collect();
3303            missed += usize::from(upper_bound(&x) < -0.1);
3304        }
3305        assert!(missed <= 400 * 7 / 100, "{missed} of 400 below the mean at some time (δ = 5%)");
3306        assert_eq!(upper_bound(&[-5.0; CS_MIN - 1]), f64::INFINITY, "too few sessions to trip");
3307        let x: Vec<f64> = (0..60).map(|_| normal(&mut rng) * 0.4 - 0.3).collect();
3308        assert!(upper_bound(&x) < 0.0, "60 sessions of a clear harm trip it: {}", upper_bound(&x));
3309    }
3310
3311    /// Sixty sessions of a learned policy that hands over half of what the fixed rule asks: under a
3312    /// truth where asking changes far more than handing over (`free_helps` false) the monitor trips;
3313    /// where both routes are as good it does not.
3314    fn monitored(free_helps: bool) -> Summary {
3315        summary::with_fit(monitored_sim(free_helps).0.summary(), None)
3316    }
3317
3318    /// `monitored`'s log before the fit, and its truth.
3319    fn monitored_sim(free_helps: bool) -> (Sim, Truth) {
3320        let mut t = truth();
3321        t.b[ASK] = 1.5;
3322        if free_helps {
3323            t.b[ASK] = 0.0;
3324        }
3325        let mut sim = Sim::new(31);
3326        let mut half = |grades: &[u8], _: bool, rng: &mut Rng| -> (Vec<Route>, Vec<f64>, Vec<f64>, &'static str) {
3327            let routes = grades.iter().map(|_| if rng.unit() < 0.5 { Route::Ask } else { Route::Free }).collect();
3328            (routes, vec![0.5; grades.len()], vec![0.5; grades.len()], "learned")
3329        };
3330        // Every check has a 3 (the fixed rule asks all), live.
3331        let mut sim_session = |sim: &mut Sim, name: &str| {
3332            for _ in 0..6 {
3333                let grades = vec![3, 2];
3334                let ids = vec![format!("L{}", sim.rng.next_u64() % 8), format!("L{}", sim.rng.next_u64() % 8)];
3335                sim.check(name, false, &grades, &ids, &t, &mut half);
3336            }
3337        };
3338        for i in 0..60 {
3339            sim_session(&mut sim, &format!("s{i}"));
3340        }
3341        (sim, t)
3342    }
3343
3344    /// A placebo neither rule delivers (both leave it not now) has no leverage: its weight, however
3345    /// large, multiplies a difference of 0. Nor has a free lesson the policy hands over surely, as the
3346    /// fixed rule does. The monitor's estimate is the 0.7.2 one (pinned within 1e-9), and its weights'
3347    /// health leaves those applies out: before, the placebo, its route's only label, counted at the
3348    /// whole route's weight (a team store's ESS 9 of 127, largest weight 42×).
3349    #[test]
3350    fn a_placebo_neither_rule_delivers_moves_neither_the_estimate_nor_its_health() {
3351        // The monitor of this log under 0.7.2, before its health left zero-leverage applies out.
3352        const MEAN: f64 = -0.155_976_075_091_821;
3353        const UCB: f64 = -0.117_250_989_323_595;
3354        let (mut sim, t) = monitored_sim(false);
3355        let without = summary::with_fit(sim.summary(), None).monitor;
3356        // One check of 12 grade-1 lessons routed as the fixed rule routes them (`CAP` handed over
3357        // surely, the rest not now), the last of the rest drawn as a placebo and judged.
3358        let n = 12;
3359        let mut as_fixed = |grades: &[u8], _: bool, _: &mut Rng| -> (Vec<Route>, Vec<f64>, Vec<f64>, &'static str) {
3360            let routes: Vec<Route> = (0..grades.len())
3361                .map(|j| match j {
3362                    j if j < conscience::CAP => Route::Free,
3363                    j if j + 1 == grades.len() => Route::Placebo,
3364                    _ => Route::Not,
3365                })
3366                .collect();
3367            let pf = routes.iter().map(|r| f64::from(u8::from(*r == Route::Free))).collect();
3368            (routes, vec![0.0; grades.len()], pf, "learned")
3369        };
3370        let ids: Vec<String> = (0..n).map(|i| format!("P{i}")).collect();
3371        sim.check("s59", false, &vec![1; n], &ids, &t, &mut as_fixed);
3372        let s = summary::with_fit(sim.summary(), None);
3373        let judged = |r: Route| s.applies.iter().filter(|a| a.route == r && matches!(a.label, summary::Label::Changed | summary::Label::Ignored)).count();
3374        assert_eq!(judged(Route::Placebo), 1, "the scenario: the placebo is judged");
3375        assert_eq!(fixed_routes(&ids.iter().map(|l| unit(l, 1, 0)).collect::<Vec<_>>(), &[]).iter().filter(|r| **r == Route::Free).count(), conscience::CAP);
3376        let m = &s.monitor;
3377        assert!((m.mean - MEAN).abs() < 1e-9, "mean {} vs 0.7.2's {MEAN}", m.mean);
3378        assert!(m.ucb.is_some_and(|u| (u - UCB).abs() < 1e-9), "ucb {:?} vs 0.7.2's {UCB}", m.ucb);
3379        // The health of the applies that move it: the check added none.
3380        assert_eq!((m.labelled, m.truncated), (without.labelled, without.truncated), "{m:?} vs {without:?}");
3381        assert!(m.max_weight < 10.0 && m.ess > 0.5 * f64::from(m.labelled), "{m:?}");
3382    }
3383
3384    /// A placebo on a check where the policy deviated (the fixed rule asks it, the policy left it not
3385    /// now with chance 1/2) has leverage, and as its route's only label its normalised weight is the
3386    /// whole route's: under `ROUTE_LABELS_MIN` its residual stays out, so one verdict moves the
3387    /// estimate only as far as it moves the fit (0.7.2: by 0.37 of a unit).
3388    #[test]
3389    fn one_label_does_not_carry_its_route() {
3390        for changed in [true, false] {
3391            let (mut sim, t) = monitored_sim(true);
3392            let without = summary::with_fit(sim.summary(), None).monitor;
3393            let mut deviated = |grades: &[u8], _: bool, _: &mut Rng| -> (Vec<Route>, Vec<f64>, Vec<f64>, &'static str) {
3394                (vec![Route::Ask, Route::Placebo], vec![1.0, 0.5], vec![0.0; grades.len()], "learned")
3395            };
3396            let truth = Truth { b: if changed { [9.0; P] } else { [-9.0; P] }, ..t };
3397            sim.check("s59", false, &[3, 2], &["Q0".to_string(), "Q1".to_string()], &truth, &mut deviated);
3398            let s = summary::with_fit(sim.summary(), None);
3399            let want = if changed { summary::Label::Changed } else { summary::Label::Ignored };
3400            assert_eq!(s.applies.iter().filter(|a| a.route == Route::Placebo).map(|a| a.label).collect::<Vec<_>>(), [want], "the scenario");
3401            let shift = (s.monitor.mean - without.mean).abs();
3402            assert!(shift < 0.05, "changed {changed}: one placebo moved the mean by {shift} ({} vs {})", s.monitor.mean, without.mean);
3403        }
3404    }
3405
3406    /// `ROUTE_LABELS_MIN` counts labels with leverage: judged placebos neither rule delivers (the
3407    /// expected kind) do not open the not-now route, so the first placebo on a deviated check after
3408    /// them still moves the estimate only as far as it moves the fit.
3409    #[test]
3410    fn labels_without_leverage_do_not_open_a_route() {
3411        let n = 12;
3412        let mut as_fixed = |grades: &[u8], _: bool, _: &mut Rng| -> (Vec<Route>, Vec<f64>, Vec<f64>, &'static str) {
3413            let routes: Vec<Route> = (0..grades.len())
3414                .map(|j| match j {
3415                    j if j < conscience::CAP => Route::Free,
3416                    j if j + 1 == grades.len() => Route::Placebo,
3417                    _ => Route::Not,
3418                })
3419                .collect();
3420            let pf = routes.iter().map(|r| f64::from(u8::from(*r == Route::Free))).collect();
3421            (routes, vec![0.0; grades.len()], pf, "learned")
3422        };
3423        let mut deviated = |grades: &[u8], _: bool, _: &mut Rng| -> (Vec<Route>, Vec<f64>, Vec<f64>, &'static str) {
3424            (vec![Route::Ask, Route::Placebo], vec![1.0, 0.5], vec![0.0; grades.len()], "learned")
3425        };
3426        for changed in [true, false] {
3427            let (mut sim, t) = monitored_sim(true);
3428            for k in 0..ROUTE_LABELS_MIN {
3429                let ids: Vec<String> = (0..n).map(|i| format!("Z{k}-{i}")).collect();
3430                sim.check(&format!("z{k}"), false, &vec![1; n], &ids, &t, &mut as_fixed);
3431            }
3432            let before = summary::with_fit(sim.summary(), None);
3433            let placebos = |s: &Summary| {
3434                s.applies.iter().filter(|a| a.route == Route::Placebo && matches!(a.label, summary::Label::Changed | summary::Label::Ignored)).count()
3435            };
3436            assert_eq!(placebos(&before), ROUTE_LABELS_MIN, "the scenario: every zero-leverage placebo judged");
3437            let truth = Truth { b: if changed { [9.0; P] } else { [-9.0; P] }, ..t };
3438            sim.check("s59", false, &[3, 2], &["Q0".to_string(), "Q1".to_string()], &truth, &mut deviated);
3439            let s = summary::with_fit(sim.summary(), None);
3440            assert_eq!(placebos(&s), ROUTE_LABELS_MIN + 1);
3441            let shift = (s.monitor.mean - before.monitor.mean).abs();
3442            assert!(shift < 0.05, "changed {changed}: one placebo moved the mean by {shift} ({} vs {})", s.monitor.mean, before.monitor.mean);
3443        }
3444    }
3445
3446    #[test]
3447    fn the_monitor_reverts_a_harmful_history_and_keeps_a_benign_one() {
3448        let harmful = monitored(false);
3449        assert!(harmful.monitor.reverted && harmful.monitor.ucb.is_some_and(|u| u < 0.0), "{:?}", harmful.monitor);
3450        assert_eq!(harmful.monitor.sessions, 60);
3451        // Its weights' health (borg top `Evaluation`): labelled applies weighed, an effective number no
3452        // larger, the largest weight at least their mean, no more cut than weighed.
3453        let m = &harmful.monitor;
3454        assert!(m.labelled > 0 && m.labelled <= m.units, "{m:?}");
3455        assert!(m.ess > 0.0 && m.ess <= f64::from(m.labelled) + 1e-9 && m.max_weight >= 1.0 && m.truncated <= m.labelled, "{m:?}");
3456        let benign = monitored(true);
3457        assert!(!benign.monitor.reverted, "{:?}", benign.monitor);
3458        assert!(benign.monitor.mean > harmful.monitor.mean);
3459    }
3460
3461    /// `choose` at cold start is `fixed_routes` (`cold_start_is_the_fixed_rule`); this pins
3462    /// `fixed_routes` itself, by position.
3463    #[test]
3464    fn the_fixed_routes_are_the_fixed_rule_by_position() {
3465        assert!(fixed_routes(&[], &[]).is_empty());
3466        let block = [unit("A", 1, 0), unit("B", 3, 1), unit("C", 2, 2)];
3467        assert_eq!(fixed_routes(&block, &[]), [Route::Ask; 3], "a 3 blocks: every 3, 2 and 1 up to the cap");
3468        let soft = [unit("A", 1, 0), unit("B", 2, 1)];
3469        assert_eq!(fixed_routes(&soft, &[]), [Route::Free; 2], "no 3: handed over free");
3470        let many: Vec<String> = (0..12).map(|i| format!("L{i}")).collect();
3471        let over: Vec<Unit> = many.iter().enumerate().map(|(r, l)| unit(l, 1, r)).collect();
3472        let routes = fixed_routes(&over, &[]);
3473        assert_eq!(routes.iter().filter(|r| **r == Route::Free).count(), conscience::CAP);
3474        assert_eq!(&routes[conscience::CAP..], &[Route::Not; 2], "past the cap: not now");
3475        // The same lesson named twice past the cap: each copy keeps its own route.
3476        let twice: Vec<Unit> = (0..11).map(|r| unit(if r < 9 { many[r].as_str() } else { "Z" }, 1, r)).collect();
3477        assert_eq!(&fixed_routes(&twice, &[])[9..], &[Route::Free, Route::Not]);
3478    }
3479
3480    #[test]
3481    fn a_prior_fit_writes_no_key() {
3482        assert_eq!(serde_json::to_string(&Fit::default()).unwrap(), "{}");
3483        assert_eq!(serde_json::from_str::<Fit>("{}").unwrap(), Fit::default());
3484    }
3485
3486    /// `borg debug select` P4's policy (`decide_on_evidence`) is `choose`'s routes without the test (α
3487    /// 0) under a gate that admits every deviation, whatever `choose`'s seed; without a model it is the
3488    /// fixed rule.
3489    #[test]
3490    fn the_evidence_rule_is_chooses_without_the_test() {
3491        let f = free_beats_ask();
3492        let open = Gate { gain: vec![0.0; DRAWS], allowance: f64::INFINITY, ..Gate::default() };
3493        let ids: Vec<String> = (0..6).map(|i| format!("L{i}")).collect();
3494        let mut left = 0;
3495        for (n, g) in [(3, [2, 1, 1]), (3, [3, 2, 1]), (2, [1, 1, 0])] {
3496            let units: Vec<Unit> = (0..n).map(|r| unit(&ids[r], g[r], r)).collect();
3497            for stop in [false, true] {
3498                let check = Check { session: "new", stop, tokens: 0 };
3499                let routes = decide_on_evidence(&units, &check, &f, &[]);
3500                for seed in 0..5 {
3501                    let d = choose(&units, &check, &f, &open, 0.0, seed, &[]);
3502                    assert_eq!((&routes, d.xk), (&d.routes, None), "{g:?} stop {stop} seed {seed}");
3503                }
3504                left += usize::from(routes != fixed_routes(&units, &[]));
3505                assert_eq!(decide_on_evidence(&units, &check, &Fit::default(), &[]), fixed_routes(&units, &[]), "no model: the fixed rule");
3506            }
3507        }
3508        assert!(left > 0, "the scenario leaves the fixed rule");
3509    }
3510
3511    /// P4a's rule, here on every grade table: under the n = 0 prior the evidence rule is the fixed rule,
3512    /// at the stop and during the turn, for a session that had a lesson or none, and so is `choose`
3513    /// without the test (its source `evidence`, the prior's deviations refused by no gate but by the
3514    /// evidence). A Thompson play of the prior leaves the fixed rule on such tables.
3515    #[test]
3516    fn under_the_prior_the_evidence_rule_is_the_fixed_rule_on_every_grade_table() {
3517        let p = prior();
3518        let open = Gate { gain: vec![0.0; DRAWS], allowance: f64::INFINITY, ..Gate::default() };
3519        let ids: Vec<String> = (0..8).map(|i| format!("L{i}")).collect();
3520        let mut grades = tables(5);
3521        grades.extend([vec![2; 8], vec![1; 8], [vec![3], vec![2; 7]].concat()]);
3522        for g in &grades {
3523            let units: Vec<Unit> = ids.iter().zip(g).enumerate().map(|(r, (l, g))| unit(l, *g, r)).collect();
3524            for had in [Vec::new(), vec!["L1".to_string()]] {
3525                let want = fixed_routes(&units, &had);
3526                for stop in [true, false] {
3527                    let check = Check { session: "s", stop, tokens: 0 };
3528                    assert_eq!(decide_on_evidence(&units, &check, &p, &had), want, "{g:?} stop {stop} had {had:?}");
3529                    let d = choose(&units, &check, &p, &open, 0.0, 7, &had);
3530                    assert_eq!((&d.routes, d.source), (&want, if units.is_empty() { FIXED } else { EVIDENCE }), "{g:?} stop {stop} had {had:?}");
3531                }
3532            }
3533        }
3534    }
3535
3536    /// A fit certain that every question dilutes the others (`ask_dilution` −1, tight): asking the nine
3537    /// a check with a 3 asks loses to asking few and handing over the rest, and the evidence rule
3538    /// deviates, exactly (0/1 propensities, no test). A fit whose mode dilutes but whose posterior,
3539    /// truncated at 0 as every draw is (`draw_beta`), still reaches no dilution at the `DELTA` quantile
3540    /// (`ask_dilution` −0.2, sd 0.5), or a fit without dilution, keeps the fixed rule.
3541    #[test]
3542    fn a_fit_with_evidence_of_dilution_deviates() {
3543        let world = |dilution: f64, sd: f64| {
3544            let mut beta = vec![0.0; P];
3545            beta[ASK] = 0.2;
3546            beta[NOT] = -1.0;
3547            beta[ASK_M] = dilution;
3548            let mut chol = vec![0.0; P * P];
3549            for k in 0..P {
3550                chol[k * P + k] = if k == ASK_M { sd } else { 0.01 };
3551            }
3552            let model = Model { beta, chol, sd: vec![1.0; P], spread: [0.01; FAMILIES], ..Model::default() };
3553            let rates = Rates { free_stop: 1.0, free_live: 1.0, later: 0.5, wait: 0.0, ask_live: 1.0 };
3554            Fit { key: "dilution".into(), model: Some(model), rates, ..Fit::default() }
3555        };
3556        let ids: Vec<String> = (0..9).map(|i| format!("L{i}")).collect();
3557        let units: Vec<Unit> = ids.iter().enumerate().map(|(r, l)| unit(l, if r == 0 { 3 } else { 2 }, r)).collect();
3558        let base = fixed_routes(&units, &[]);
3559        assert_eq!(base, [Route::Ask; 9], "the scenario: the fixed rule asks all nine");
3560        let gate = open_gate();
3561        for stop in [false, true] {
3562            let check = Check { session: "n", stop, tokens: 0 };
3563            let d = choose(&units, &check, &world(-1.0, 0.01), &gate, ALPHA, 1, &[]);
3564            assert_eq!((d.source, d.xk, d.xs), (EVIDENCE, None, None), "{d:?}");
3565            assert_ne!(d.routes, base, "{d:?}");
3566            assert!(d.routes.contains(&Route::Free) && d.routes.contains(&Route::Ask), "asks few, hands over the rest: {d:?}");
3567            assert_eq!(d.p, d.routes.iter().map(|r| f64::from(u8::from(*r == Route::Ask))).collect::<Vec<_>>(), "exact");
3568            assert_eq!(d.pf, d.routes.iter().map(|r| f64::from(u8::from(*r == Route::Free))).collect::<Vec<_>>(), "exact");
3569            // The wide fit's mode would deviate: only the quantile keeps it on the fixed rule.
3570            let wide = world(-0.2, 0.5);
3571            let m = wide.model.as_ref().expect("a model");
3572            let feats = Feat::of(&units, stop, 0);
3573            let t = theta_mean(m, &feats, &units, &Levels::of(check.session, &m.judge, &units));
3574            let at_mode = solve(&Table::of(&Valuer { t: &t, feats: &feats, rates: &wide.rates }, &[false; 9]), crate::attention::RAIL, conscience::CAP);
3575            assert_ne!(at_mode, base, "stop {stop}");
3576            for f in [wide, world(0.0, 0.01)] {
3577                assert_eq!(decide_on_evidence(&units, &check, &f, &[]), base, "stop {stop}");
3578            }
3579        }
3580    }
3581
3582    /// The test's lessons and order for `units` at a live check under the n = 0 prior (no evidence) and
3583    /// a gate that admits every count: `choose` at many seeds.
3584    fn tested_at(units: &[Unit], had: &[String], seeds: u64) -> Vec<Decision> {
3585        let p = prior();
3586        let open = Gate { gain: vec![0.0; DRAWS], allowance: 1e9, ..Gate::default() };
3587        (0..seeds).map(|seed| choose(units, &Check { session: "s", stop: false, tokens: 0 }, &p, &open, ALPHA, seed, had)).collect()
3588    }
3589
3590    /// The randomised test draws s uniformly in 0..=k (each count's frequency over seeds within four
3591    /// standard errors of 1/(k + 1)), asks the first s in the fixed rule's order (2s before 1s, then
3592    /// the model's) and hands over the rest, its propensities each unit's exact share of the k + 1
3593    /// counts, s = 0 (the fixed rule without a 3) the control.
3594    #[test]
3595    fn the_tests_count_is_uniform_and_its_propensities_exact() {
3596        let ids: Vec<String> = (0..5).map(|i| format!("L{i}")).collect();
3597        let units: Vec<Unit> = ids.iter().zip([1, 2, 1, 2, 1]).enumerate().map(|(r, (l, g))| unit(l, g, r)).collect();
3598        let order = [1, 3, 0, 2, 4];
3599        let n = 1200;
3600        let mut counts = [0usize; 6];
3601        for d in tested_at(&units, &[], n) {
3602            let (Some(5), Some(s)) = (d.xk, d.xs) else { panic!("{d:?}") };
3603            let s = s as usize;
3604            counts[s] += 1;
3605            for (i, &j) in order.iter().enumerate() {
3606                assert_eq!(d.routes[j], if i < s { Route::Ask } else { Route::Free }, "{d:?}");
3607                assert_eq!((d.p[j], d.pf[j]), (outcome::round_p((5 - i) as f64 / 6.0), outcome::round_p((i + 1) as f64 / 6.0)), "{d:?}");
3608            }
3609            assert_eq!(d.source, if s == 0 { EXPERIMENT_CONTROL } else { EXPERIMENT }, "{d:?}");
3610        }
3611        let q = 1.0 / 6.0;
3612        let se = (q * (1.0 - q) / n as f64).sqrt();
3613        for (s, c) in counts.iter().enumerate() {
3614            let freq = *c as f64 / n as f64;
3615            assert!((freq - q).abs() <= 4.0 * se, "s = {s}: {freq:.4} against {q:.4} ({counts:?})");
3616        }
3617    }
3618
3619    /// The test never runs at the stop, and never moves a 3: with a 3 during the turn the 3 is asked on
3620    /// every draw (p 1), and the control is s = k, the fixed rule asking everything.
3621    #[test]
3622    fn the_test_never_touches_the_stop_or_a_three() {
3623        let ids: Vec<String> = (0..3).map(|i| format!("L{i}")).collect();
3624        let units: Vec<Unit> = ids.iter().zip([2, 3, 1]).enumerate().map(|(r, (l, g))| unit(l, g, r)).collect();
3625        let base = fixed_routes(&units, &[]);
3626        let p = prior();
3627        let open = Gate { gain: vec![0.0; DRAWS], allowance: 1e9, ..Gate::default() };
3628        for seed in 0..40 {
3629            let d = choose(&units, &Check { session: "s", stop: true, tokens: 0 }, &p, &open, ALPHA, seed, &[]);
3630            assert_eq!((&d.routes, d.source, d.xk, d.xs), (&base, EVIDENCE, None, None), "{d:?}");
3631        }
3632        let mut seen = std::collections::BTreeSet::new();
3633        for d in tested_at(&units, &[], 60) {
3634            assert_eq!((d.routes[1], d.p[1], d.pf[1], d.xk), (Route::Ask, 1.0, 0.0, Some(2)), "{d:?}");
3635            let s = d.xs.unwrap_or(9);
3636            assert_eq!(d.source == EXPERIMENT_CONTROL, s == 2, "{d:?}");
3637            seen.insert(s);
3638        }
3639        assert_eq!(seen.len(), 3, "every count drawn: {seen:?}");
3640    }
3641
3642    /// A lesson the session already had is not among the test's lessons: it keeps the fixed rule's
3643    /// route on every draw (not now without a 3, asked with one), never free.
3644    #[test]
3645    fn the_test_never_hands_over_a_lesson_the_session_had() {
3646        let ids: Vec<String> = (0..4).map(|i| format!("L{i}")).collect();
3647        let had = ["L2".to_string()];
3648        let soft: Vec<Unit> = ids.iter().zip([2, 1, 2, 1]).enumerate().map(|(r, (l, g))| unit(l, g, r)).collect();
3649        let block: Vec<Unit> = ids.iter().zip([2, 3, 2, 1]).enumerate().map(|(r, (l, g))| unit(l, g, r)).collect();
3650        for (units, kept) in [(&soft, Route::Not), (&block, Route::Ask)] {
3651            let mut moved = 0;
3652            for d in tested_at(units, &had, 60) {
3653                assert_eq!((d.routes[2], d.pf[2], d.xk), (kept, 0.0, Some(if kept == Route::Not { 3 } else { 2 })), "{d:?}");
3654                moved += usize::from(d.source == EXPERIMENT);
3655            }
3656            assert!(moved > 0, "the scenario: the test ran");
3657        }
3658    }
3659
3660    /// The gate rations the test: with nothing left to risk, every count that leaves the fixed rule is
3661    /// refused (source `gate`, the fixed rule's routes, k and the refused s logged, nothing taken), so
3662    /// the propensities are the fixed rule's; and α 0 (`risk` 0 in collectives.json) turns it off.
3663    #[test]
3664    fn the_gate_refuses_the_test_when_short_and_risk_zero_turns_it_off() {
3665        let ids: Vec<String> = (0..3).map(|i| format!("L{i}")).collect();
3666        let units: Vec<Unit> = ids.iter().zip([2, 1, 1]).enumerate().map(|(r, (l, g))| unit(l, g, r)).collect();
3667        let base = fixed_routes(&units, &[]);
3668        let exact = |r: Route| base.iter().map(|x| f64::from(u8::from(*x == r))).collect::<Vec<_>>();
3669        let p = prior();
3670        let short = Gate { gain: vec![0.0; DRAWS], allowance: 1e-12, ..Gate::default() };
3671        let check = Check { session: "s", stop: false, tokens: 0 };
3672        let (mut refused, mut control) = (0, 0);
3673        for seed in 0..40 {
3674            let d = choose(&units, &check, &p, &short, ALPHA, seed, &[]);
3675            assert_eq!((&d.routes, &d.p, &d.pf, d.risk, d.xk), (&base, &exact(Route::Ask), &exact(Route::Free), 0.0, Some(3)), "{d:?}");
3676            match d.xs {
3677                Some(0) => control += usize::from(d.source == EXPERIMENT_CONTROL),
3678                _ => refused += usize::from(d.source == GATE),
3679            }
3680            let off = choose(&units, &check, &p, &open_gate(), 0.0, seed, &[]);
3681            assert_eq!((&off.routes, off.source, off.xk, off.xs), (&base, EVIDENCE, None, None), "{off:?}");
3682        }
3683        assert!(refused > 0 && control > 0 && refused + control == 40, "refused {refused}, control {control}");
3684        // The same gate under a larger α (the collective's `risk`) has room: the share scales the
3685        // allowance the ledger accrued at `ALPHA`.
3686        let room = Gate { allowance: 1e9 * ALPHA, ..short };
3687        assert!((0..40).any(|seed| choose(&units, &check, &p, &room, ALPHA, seed, &[]).source == EXPERIMENT));
3688        assert!((0..40).all(|seed| choose(&units, &check, &p, &room, 1e-12, seed, &[]).source != EXPERIMENT), "α scales it down");
3689    }
3690
3691    /// α scales the evidence rule's room too: a ledger that holds no gains, only a loss it already
3692    /// took, admits an evident deviation at `ALPHA` from the allowance alone, and α 0 (`risk` 0 in
3693    /// collectives.json) refuses the same deviation (source `gate`, the fixed rule's routes, nothing
3694    /// taken), though the ledger's allowance is unchanged.
3695    #[test]
3696    fn risk_zero_refuses_an_evidence_deviation_the_allowance_alone_would_cover() {
3697        let f = free_beats_ask();
3698        // A 3 and 2s during the turn: the fixed rule asks them all, the model hands them over.
3699        let ids: Vec<String> = (0..4).map(|i| format!("L{i}")).collect();
3700        let units: Vec<Unit> = ids.iter().enumerate().map(|(r, l)| unit(l, if r == 0 { 3 } else { 2 }, r)).collect();
3701        let base = fixed_routes(&units, &[]);
3702        let check = Check { session: "n", stop: false, tokens: 0 };
3703        // Guard: the loss outweighs any gain the deviation's own value can make (a value is a sum of
3704        // per-apply chances, so it gains less than one per apply), and the allowance covers the loss.
3705        let loss = 2.0 * units.len() as f64;
3706        let gate = Gate { gain: vec![-loss; DRAWS], allowance: 2.0 * loss, ..Gate::default() };
3707        let at = choose(&units, &check, &f, &gate, ALPHA, 1, &[]);
3708        assert_eq!(at.source, EVIDENCE, "the scenario: the allowance admits the deviation at ALPHA: {at:?}");
3709        assert_ne!(at.routes, base, "{at:?}");
3710        let off = choose(&units, &check, &f, &gate, 0.0, 1, &[]);
3711        assert_eq!((&off.routes, off.source, off.risk, off.gate, off.xk), (&base, GATE, 0.0, 0.0, None), "{off:?}");
3712    }
3713
3714    /// Dilution is not assumed: its prior's mode is 0, so under the n = 0 prior's mean the value of a
3715    /// question does not depend on how many are asked with it.
3716    #[test]
3717    fn the_dilution_prior_has_its_mode_at_zero() {
3718        let c = coefs();
3719        for k in [ASK_M, FREE_M] {
3720            assert_eq!((c[k].mean, c[k].sd, c[k].nonpos, c[k].ard), (0.0, 0.1, true, false), "{}", NAMES[k]);
3721        }
3722        let p = prior();
3723        let m = p.model.as_ref().expect("the prior is a model");
3724        let units = [unit("A", 2, 0), unit("B", 2, 1), unit("C", 2, 2)];
3725        let feats = Feat::of(&units, false, 0);
3726        let t = theta_mean(m, &feats, &units, &Levels::of("s", &m.judge, &units));
3727        let v = Valuer { t: &t, feats: &feats, rates: &p.rates };
3728        assert!(v.ask(0, 1) > 0.0 && (v.ask(0, 1) - v.ask(0, 3)).abs() < 1e-12, "{} vs {}", v.ask(0, 1), v.ask(0, 3));
3729        assert!((v.free(0, 1) - v.free(0, 3)).abs() < 1e-12);
3730    }
3731
3732    /// The gate's and the evidence rule's draws of a bounded slope are its prior truncated at 0, not
3733    /// clamped: under the n = 0 prior `DILUTION_PRIOR`'s half-normal, every draw below 0 (no point mass
3734    /// at 0) with the mean −0.1·√(2/π); the unbounded coefficients keep their plain draw β̂ + L z.
3735    #[test]
3736    fn a_bounded_slope_is_drawn_from_its_truncated_prior() {
3737        let p = prior();
3738        let m = p.model.as_ref().expect("the prior is a model");
3739        const N: u64 = 4000;
3740        let draws: Vec<[f64; P]> = (0..N).map(|k| draw_beta(m, gate_seed(&p, k as usize))).collect();
3741        let half = -DILUTION_PRIOR.1 * (2.0 / std::f64::consts::PI).sqrt();
3742        // Its sd 0.1·√(1 − 2/π) ≈ 0.060 over 4000 draws: a standard error of 0.001.
3743        for k in [ASK_M, FREE_M] {
3744            assert!(draws.iter().all(|b| b[k] < 0.0), "{}: a draw at 0", NAMES[k]);
3745            let mean = draws.iter().map(|b| b[k]).sum::<f64>() / N as f64;
3746            assert!((mean - half).abs() < 0.005, "{}: mean {mean} against {half}", NAMES[k]);
3747        }
3748        let ask = draws.iter().map(|b| b[ASK]).sum::<f64>() / N as f64;
3749        assert!((ask - ASK_PRIOR.0).abs() < 0.03, "ask {ask}");
3750        // A bound far above the mean leaves the draw as it was; one far below it, never past 0.
3751        for z in [-2.0, -0.3, 0.0, 1.0, 2.5] {
3752            assert!((below_zero(-1.0, 0.1, z) - (-1.0 + 0.1 * z)).abs() < 1e-6, "z {z}");
3753            let x = below_zero(50.0, 0.1, z);
3754            assert!(x <= 0.0 && x > -0.01, "z {z}: {x}");
3755        }
3756        assert!(below_zero(0.0, 0.1, -1.0) < below_zero(0.0, 0.1, 1.0), "monotone in z");
3757        assert!((phi(1.959_964) - 0.975).abs() < 1e-6 && (probit(0.975f64.ln(), 0.025) - 1.959_964).abs() < 1e-5);
3758    }
3759
3760    /// The n = 0 prior is a model at the priors (means, sds, the families' starting spreads) with
3761    /// Beta(1, 1) delivery rates; `fit` without a label still has none, so cold start stays the fixed rule.
3762    #[test]
3763    fn the_prior_is_a_model_of_the_priors_alone() {
3764        let p = prior();
3765        let m = p.model.as_ref().expect("the prior is a model");
3766        assert!(m.current() && m.converged && p.key.is_empty() && p.labels == 0);
3767        for (k, c) in coefs().iter().enumerate() {
3768            assert_eq!(m.beta[k], if c.nonpos { c.mean.min(0.0) } else { c.mean }, "{}", NAMES[k]);
3769            assert!((m.chol[k * P + k] - c.sd).abs() < 1e-12, "{}", NAMES[k]);
3770        }
3771        assert_eq!(m.spread, [LEVEL_START; FAMILIES]);
3772        assert_eq!(p.rates, Rates { free_stop: 0.5, free_live: 0.5, later: 0.5, wait: 0.5, ask_live: 1.0 });
3773        assert!(fit(&Summary::default(), None).model.is_none());
3774    }
3775
3776    /// A prediction is σ(η) where the model is certain, drawn toward ½ by its uncertainty (the level
3777    /// effects' included), and nothing for a model of another layout.
3778    #[test]
3779    fn a_prediction_is_the_posterior_chance_of_a_change() {
3780        let f = Feat { grade: 3, rank: 1, stop: true, three: true, pool: 0.0 };
3781        let mut beta = vec![0.0; P];
3782        beta[B0] = 0.8;
3783        beta[G3] = 0.4;
3784        beta[ASK] = 0.3;
3785        let lessons = BTreeMap::from([("A".to_string(), (0.5, 0.0))]);
3786        let certain = Model { beta: beta.clone(), chol: vec![0.0; P * P], sd: vec![1.0; P], spread: [0.0; FAMILIES], lessons, ..Model::default() };
3787        let mut fit = Fit { model: Some(certain.clone()), ..Fit::default() };
3788        let eta = dot(&std::array::from_fn(|k| beta[k]), &design(&f, Route::Ask, 2)) + 0.5;
3789        assert!((predict(&fit, &f, Route::Ask, 2, "s", "A").unwrap() - sigmoid(eta)).abs() < 1e-12);
3790        let mut wide = certain.clone();
3791        for k in 0..P {
3792            wide.chol[k * P + k] = 1.0;
3793        }
3794        wide.spread = [0.5; FAMILIES];
3795        fit.model = Some(wide);
3796        let p = predict(&fit, &f, Route::Ask, 2, "s", "unseen").unwrap();
3797        assert!(p > 0.5 && p < sigmoid(eta - 0.5), "{p} against {}", sigmoid(eta - 0.5));
3798        fit.model = Some(Model { beta: vec![0.0; P - 1], ..certain });
3799        assert_eq!(predict(&fit, &f, Route::Ask, 2, "s", "A"), None);
3800    }
3801}