Skip to main content

borg/select/
replay.rs

1//! `borg debug select [--replay] [--rebuild] [--dir DIR | --file FILE] [--json] [--eval RUNS_DIR --qrels
2//! FILE]`: the selection policy's state and its pre-registered checks, replayed from the outcome log (0
3//! tokens). Reports, never applies.
4//!
5//! **The rules.** docs/evidence.md "Lesson selection" (`RULES_AT`): the pre-registered checks P0–P5,
6//! dated `RULES`; a later change is a dated amendment, and `AMENDMENT` names the latest one this file
7//! implements; `RULES_V2` the rules v2, written for policy v2 (it deviates only on evidence and learns
8//! the question count by a randomised test) with the same bars, P4 split into P4a–P4c. Every report
9//! prints all three.
10//!
11//! **Verdicts.** PASS or FAIL against the bar; NOT RUN when there is nothing to run it on (no
12//! evaluation given, or one still incomplete); NOT TESTED when it ran on data that could not have
13//! failed it (no check that applies a lesson, since a check none applied to and a failed call decide
14//! nothing under any policy; no deviation from the fixed rule; an arm that is the fixed rule
15//! everywhere; no label to learn from; every prediction 1/2), never a pass. The command exits 1 when a
16//! decisive check fails or is NOT TESTED (`unmet`): by the rules v2's default rule, P0–P3, P4a and
17//! P4c, and P4b when it fails (NOT TESTED there means it is the fixed rule); P5 only reports.
18//!
19//! **Two passes over the log, in file order** (the order the hook appended it), each folding it into the
20//! selection summary with select/summary.rs `fold`, so every decision sees only the lines before it,
21//! and each deciding a check under the lessons its session already had, as its record logs them
22//! (outcome.rs `nofree`, `had_of`):
23//! - *as logged*: the log folded as it is. At each graded check the replay re-runs the production
24//!   decision (select.rs `graded_under`) on the summary the hook had: the one its record names
25//!   (outcome.rs `seen`, read before the model call), else every line before the record. P0: with the
26//!   gate closed the learned policy decides as the fixed rule (conscience.rs `graded_without`, no cap),
27//!   which is also the logged decision of every check logged under the fixed rule. P1: the logged
28//!   policy, fit key, summary, revert (outcome.rs `source`), session, channel and check id (its seed)
29//!   give the logged decision, its source, the question-count test's k and s (outcome.rs `xk`, `xs`:
30//!   its draw is the check's seed) and propensities within `ope::AGREE`, and folding piece by piece
31//!   equals folding the whole log.
32//! - *cold start*: the same log, the learned policy deciding from the prior on, each graded record
33//!   replaced by the replayed decision before it is folded (`decided`), so the gate's state is the
34//!   policy's own, and the summary refitted where production refits it (`borg learn` when a session
35//!   ends), so the policy has a model to deviate by. P3: no decision risks more than the gate's budget
36//!   (the question-count test's charged risk among them), the first one is the fixed rule's, and with an
37//!   engineer's budget for the collective the policy's pools stay within it; spend and the decisions'
38//!   sources are reported.
39//!
40//! **Labels** (P2, P5, the readout): a judge's verdict (`asked_then_changed`, `asked_ignored`) joined to
41//! the graded check that routed its delivery: by check id, or for older records the session's last
42//! graded check before it that routed the lesson that way (asked for a stop or live verdict, free for a
43//! queued one, placebo for a placebo one). A verdict on an early delivery has no check. A unit is 1 when
44//! its strongest result is the change (`ope::rank`: a later veto or correction in the session outranks
45//! it), 0 otherwise; `asked_not_corrected` is censored, never a 0. What a check could know of a unit is
46//! its value then (`Label::known`): a veto or a stronger verdict after the check is a result from after
47//! it.
48//! - P2 predicts each unit from the labels known before its check (leave-future-out), by the value model
49//!   (select/policy.rs `fit` on exactly those labels at their values then, `predict`; the n = 0 prior's
50//!   before any, `prior`, or the pruned model's `prior_pruned` in the rerun) and by grade alone
51//!   (Beta(1, 1) per grade), and compares their log-loss. After a FAIL, the pre-registered rerun once by
52//!   the model pruned to grade, route and dilution (`fit_pruned`), whose verdict is P2's.
53//! - P5 estimates each policy's change against the fixed rule by doubly robust and inverse propensity
54//!   scoring with the logged propensities (a placebo's times its draw's chance ψ: routed nowhere, a
55//!   unit is judged only when drawn), a Beta(1, 1) per grade and route (leave-future-out) as the
56//!   outcome model; non-decisive.
57//!
58//! **P4** reads an evaluation's graded lines (`#borg-graded` in each run's state files) and the case's
59//! relevant lessons (qrels), and compares the right-lesson recall of the fixed rule with three arms,
60//! each expected over `conscience::P_DRAWS` seeded draws (rules v2):
61//! - P4a: the decision rule without the test (select/policy.rs `decide_on_evidence`) under the n = 0
62//!   prior (`prior`) decides as the fixed rule at every check: 0 differences, else FAIL. It fails if
63//!   any deviation the prior alone drives survives.
64//! - P4b: the same rule under the store's posterior (the whole log fitted as `borg learn` fits it),
65//!   against P4's recall bar; NOT TESTED when it deviates nowhere, which then makes it the fixed rule.
66//! - P4c: the question-count test, ungated (`choose` under the prior with a gate that admits every
67//!   draw), keeps every run's recall at the fixed rule's: it hands over what it does not ask, so it
68//!   withholds nothing. NOT TESTED when no draw leaves the fixed rule (no live check with a lesson that
69//!   may go free).
70//!
71//! **The question-count test's readout** (`test_readout`, rules v2), from the summary's fold of the
72//! log (select/summary.rs `Experiment`, `Check::xk`; never a recount): due after `TEST_CHECKS` checks
73//! that drew a count (played or refused by the gate) or `TEST_SESSIONS` sessions with one, and only
74//! then estimated over the drawn checks the summary still holds (compaction drops the oldest, never
75//! the counts): dilution, the test's top lesson's change rate with m of its questions asked against
76//! asked alone (the same lesson across the uniform draws), and asking a 2 against handing it over (a
77//! Horvitz–Thompson difference by the logged propensities), each verdict weighed by its chance of one,
78//! session-bootstrap 95% intervals.
79//!
80//! **Where it meets the policy core.** Every decision is select.rs `graded_under` with the full `Ctx`
81//! (session, check id, channel, lessons file, summary, logged pool tokens, had, logged tolerance α), the learned policy
82//! named explicitly whatever this process's `policy`; every fold summary.rs `fold`; every pool select.rs
83//! `pool_tokens_under` the learned policy, per check as the hook calls it; the cold start's refits
84//! summary.rs `with_fit`; P0's reference conscience.rs `graded_without`; P2 policy.rs `fit`,
85//! `fit_pruned`, `predict`, `prior`, `prior_pruned`; P3 policy.rs `Decision::risk`; P4 policy.rs
86//! `decide_on_evidence`, `choose`, `prior`, `fit` and its baseline policy.rs `fixed_routes`. Where the
87//! replay still differs from what production ran:
88//! - The refit is `with_fit`, the pure part of the summary.rs `refit` that main.rs `learn_store` calls:
89//!   `refit` loads the cache plus the log's tail (equal to the replay's fold, which P1's fold check
90//!   shows), adds the revert mark beside the store (the replay keeps the revert in memory, sticky as
91//!   `with_fit` keeps it), and writes the cache and the mark, which a replay never does. It runs before
92//!   the first graded record after a session's end, where production runs it in the background after
93//!   the session settles: a hook that decided before `borg learn` finished read the older fit. P1
94//!   replays each record from its logged fit, so only the cold start assumes the refit was in time.
95//! - The had lessons are the record's `nofree`, which is all of `had` a decision reads (the had lessons
96//!   among its applies); a record from before it replays with none, as its hook decided. In the cold
97//!   start they stay the logged history's, not what the replayed policy's own earlier decisions would
98//!   have delivered: only the log's deliveries say that.
99//! - The cold start's labels join by route: where the replayed route differs from the logged one, the
100//!   verdict joins nothing, so its model learns only from the routes the replay took.
101//! - The pools are chosen under the loosest latency limit (`LOOSEST`), as `price` replays them, where
102//!   the hook passes the harness's stop budget: a limit only takes the largest pools out of the
103//!   choice, so P3's pool spend is the most any hook's limit allows.
104//! - P2's fit reads a log rebuilt from the labels (`known`): the graded checks up to the newest result
105//!   then and each label's verdict at its value then, without the delivery records, settles and other
106//!   lines of the real log, so the judge's missingness model sees fewer fates than production's fit at
107//!   that check; no budget (it prices only pools).
108//! - P4 draws its arms at pool tokens 0 (the state files log none), with no had (the state lines log
109//!   no `nofree`, and the hook that ran the evaluation decided without), from a stand-in check id per
110//!   check, each check independent of the run's earlier draws; P4c's gate admits every draw (`OPEN`)
111//!   at the default tolerance (`policy::ALPHA`).
112//! - P1 compares the asked and free lists, propensities and source, not the placebo draw or its chance
113//!   (`psi`): the pre-registered measure.
114
115use std::collections::{BTreeMap, BTreeSet, HashMap};
116use std::path::{Path, PathBuf};
117
118use serde::Serialize;
119
120use super::policy::{self, Fit};
121use super::summary::{self, Summary};
122use super::{Ctx, Policy, Route, Routed, Unit};
123use crate::conscience::{self, Challenge};
124use crate::memory;
125use crate::ope::{self, Estimate};
126use crate::outcome::{self, Outcome};
127use crate::{collective, learn};
128
129/// The pre-registration these checks implement (`RULES_AT`), by the date its rules were written.
130/// Protocol: printed with every report, never changed: a later change is a dated amendment
131/// (`AMENDMENT`).
132pub const RULES: &str = "2026-10-28";
133/// The latest dated amendment of `RULES` this file implements (2026-10-29: P2's prune-and-rerun once;
134/// the bars unchanged). Protocol: printed with every report beside `RULES`.
135pub const AMENDMENT: &str = "2026-10-29";
136/// The rules v2 this file implements, by the date they were written (2026-10-29, after the decisive
137/// rerun: P4a–P4c, P1 and P3 on the question-count test, its readout, the default rule). Protocol:
138/// printed with every report beside `RULES` and `AMENDMENT`.
139pub const RULES_V2: &str = "2026-10-29";
140/// Where the rules and their dated amendments are written: a tracked file of this repository, so a
141/// reader of the report can open them. Protocol: printed with every report.
142pub const RULES_AT: &str = "docs/evidence.md#lesson-selection";
143
144/// P2's bar: the session-bootstrap 95% upper bound of the mean log-loss difference (model − grade
145/// only) may not exceed this. Method: pre-registered.
146pub const CALIBRATION: f64 = 0.005;
147
148/// P4's margin: the policy's right-lesson recall may lie at most this far below the fixed rule's (5
149/// points), point estimate and case-paired bootstrap lower bound. Method: pre-registered.
150pub const RECALL_MARGIN: f64 = 0.05;
151
152/// The online readout is due after this many randomised labelled units (a logged route probability
153/// strictly between 0 and 1) or this many sessions under the learned policy. Method: pre-registered.
154pub const READOUT_UNITS: usize = 300;
155pub const READOUT_SESSIONS: usize = 30;
156
157/// The question-count test's readout (`test_readout`) is due after this many checks that drew a count
158/// (randomised: played or refused) or this many sessions with one. Method: pre-registered (rules v2, 2026-10-29).
159pub const TEST_CHECKS: u64 = 300;
160pub const TEST_SESSIONS: u32 = 30;
161
162/// How far an arm's recall of a run may lie from the fixed rule's and still be equal (P4c). Method:
163/// float slack of summing `conscience::P_DRAWS` draw shares of 1/`P_DRAWS`, far below any one draw's
164/// share.
165const SAME: f64 = 1e-9;
166
167/// The allowance of the gate P4c's test arm decides against: more than any check's charged risk (a
168/// check's value is a sum of per-lesson chances, at most a few units), so every draw is admitted.
169/// Guard: finite, so the gate's arithmetic stays exact.
170const OPEN: f64 = 1e12;
171
172/// A probability a log-loss reads is kept this far from 0 and 1. Guard: a model's 0 or 1 would make
173/// one unit's log-loss infinite and the mean meaningless.
174const CLAMP: f64 = 1e-9;
175
176/// Differences listed per check. Display.
177const SHOW: usize = 5;
178
179/// The routes a label can have been delivered by, as indices: asked, free, not delivered (placebo).
180/// Protocol: select.rs `ARMS` and `Route::arm`, the order of every per-route array below.
181const ASK: usize = Route::Ask.arm();
182const FREE: usize = Route::Free.arm();
183const NOT: usize = Route::Not.arm();
184const ROUTES: usize = super::ARMS;
185const ROUTE_NAMES: [&str; ROUTES] = ["Q", "F", "D"];
186
187/// Grades index their counts directly, 1–3; 0 is unused. Protocol: the model's grades.
188const GRADES: usize = 4;
189
190/// A check's result against its pre-registered bar.
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
192#[serde(rename_all = "snake_case")]
193pub enum Verdict {
194    Pass,
195    Fail,
196    /// Nothing to check it on yet (`why` says what is missing): no evaluation given, or one still
197    /// incomplete. Not decisive: the command passes it.
198    NotRun,
199    /// Run, but on data that could not have failed it: no check that applies a lesson, no deviation
200    /// from the fixed rule, an arm that decides as the fixed rule everywhere, no label learned from,
201    /// every prediction 1/2. Never a pass: a decisive one fails the command (`unmet`).
202    NotTested,
203    /// Reported, not decisive (P5).
204    Reported,
205}
206
207impl Verdict {
208    /// PASS when `ok`, else FAIL; but NOT TESTED instead of a pass when the data could not have failed
209    /// it (`tested` false).
210    fn tested(ok: bool, tested: bool) -> Self {
211        match (ok, tested) {
212            (false, _) => Verdict::Fail,
213            (true, false) => Verdict::NotTested,
214            (true, true) => Verdict::Pass,
215        }
216    }
217
218    fn label(self) -> &'static str {
219        match self {
220            Verdict::Pass => "PASS",
221            Verdict::Fail => "FAIL",
222            Verdict::NotRun => "NOT RUN",
223            Verdict::NotTested => "NOT TESTED",
224            Verdict::Reported => "REPORTED (non-decisive)",
225        }
226    }
227}
228
229// --- The log -------------------------------------------------------------------------------------
230
231/// One line of the outcome log: its text (with its newline) and its record, None when it does not parse.
232struct Line<'t> {
233    text: &'t str,
234    o: Option<Outcome>,
235}
236
237fn lines(text: &str) -> Vec<Line<'_>> {
238    text.split_inclusive('\n').map(|t| Line { text: t, o: serde_json::from_str(t.trim()).ok() }).collect()
239}
240
241/// A graded record's applies, one lesson per apply; None when its grades are not aligned with them.
242fn challenges(o: &Outcome) -> Option<Vec<Challenge>> {
243    (o.grades.len() == o.lessons.len()).then(|| o.lessons.iter().map(|id| Challenge { id: id.clone(), ..Default::default() }).collect())
244}
245
246fn applied<'a>(cs: &'a [Challenge], o: &Outcome) -> Vec<(&'a Challenge, u8)> {
247    cs.iter().zip(o.grades.iter().copied()).collect()
248}
249
250fn ids(v: &[&Challenge]) -> Vec<String> {
251    v.iter().map(|c| c.id.clone()).collect()
252}
253
254fn channel(o: &Outcome) -> &'static str {
255    if o.channel == "live" { "live" } else { "stop" }
256}
257
258/// The lessons a graded record's session already had, as its decision read them (select.rs `Ctx::had`):
259/// its logged `nofree`, sorted, empty for a record from before it (whose hook let every apply go free).
260/// Only the had lessons among a check's applies can change its decision, and `nofree` is exactly those.
261fn had_of(o: &Outcome) -> Vec<String> {
262    let mut had = o.nofree.clone();
263    had.sort_unstable();
264    had.dedup();
265    had
266}
267
268/// The production decision's context for the graded record `o` with its session's `had` (`had_of`).
269fn ctx<'a>(o: &'a Outcome, had: &'a [String], lessons: &'a Path, s: &'a Summary) -> Ctx<'a> {
270    Ctx { session: &o.session, check: &o.check, channel: channel(o), lessons, summary: s, tokens: o.tokens, had, alpha: super::alpha_of(o.alpha) }
271}
272
273/// The policy a graded record can be replayed under: the fixed rule or the learned policy. The
274/// evaluation switches are not: the cap's N is not logged, and the learned cut reads the whole store.
275fn replayable(o: &Outcome) -> Option<Policy> {
276    match outcome::policy_of(o) {
277        "fixed" => Some(Policy::Fixed),
278        "learned" => Some(Policy::Learned),
279        _ => None,
280    }
281}
282
283/// Per apply, 1 when `of` holds its lesson, else 0 (attention.rs `fixed_p`).
284fn holds(lessons: &[String], of: &[String]) -> Vec<f64> {
285    lessons.iter().map(|l| f64::from(u8::from(of.contains(l)))).collect()
286}
287
288/// A graded check of the log: its record, its session's had lessons (`had_of`), its logged decision
289/// and propensities (an older record's free list and pf replayed by `outcome::free_of`), and the fixed
290/// rule's decision on its applies for that session (conscience.rs `graded_without`, no cap).
291#[derive(Debug, Clone)]
292struct Check {
293    o: Outcome,
294    had: Vec<String>,
295    asked: Vec<String>,
296    free: Vec<String>,
297    p: Vec<f64>,
298    pf: Vec<f64>,
299    fixed: (Vec<String>, Vec<String>),
300}
301
302impl Check {
303    fn new(o: Outcome, applied: &[(&Challenge, u8)]) -> Self {
304        let free = outcome::free_of(&o);
305        let p = if o.p.len() == o.lessons.len() { o.p.clone() } else { holds(&o.lessons, &o.chosen) };
306        let pf = if o.pf.len() == o.lessons.len() { o.pf.clone() } else { holds(&o.lessons, &free) };
307        let had = had_of(&o);
308        let (ask, fr) = conscience::graded_without(applied, None, &had);
309        Check { had, asked: o.chosen.clone(), free, p, pf, fixed: (ids(&ask), ids(&fr)), o }
310    }
311
312    fn line(&self) -> String {
313        let check = if self.o.check.is_empty() { "-" } else { self.o.check.as_str() };
314        format!("session {} check {check} ms {}", self.o.session, self.o.ms)
315    }
316}
317
318// --- Where the checks meet the policy core ---------------------------------------------------------
319
320/// `f` on `s` with the gate's budget at 0 (P0), `s` as it was afterwards: the gate's state is swapped
321/// out and back, never cloned with the summary, so a replay stays linear in the log.
322fn gate_closed<T>(s: &mut Summary, f: impl FnOnce(&Summary) -> T) -> T {
323    let gate = std::mem::take(&mut s.gate);
324    let out = f(s);
325    s.gate = gate;
326    out
327}
328
329/// The evaluation's check `c` as the policy sees it: its state file logs no pool tokens (the
330/// baseline's).
331fn eval_check(c: &EvalCheck) -> policy::Check<'_> {
332    policy::Check { session: &c.session, stop: c.channel == "stop", tokens: 0 }
333}
334
335/// The decision rule without the question-count test (P4a, P4b): select/policy.rs
336/// `decide_on_evidence` on `fit` at the evaluation's check `c`, for a session that had none of its
337/// lessons (the state lines log no `nofree`). It draws nothing, so it takes no seed.
338fn evidence(units: &[Unit], c: &EvalCheck, fit: &Fit) -> Vec<Route> {
339    policy::decide_on_evidence(units, &eval_check(c), fit, &[])
340}
341
342/// One draw of the question-count test, ungated (P4c): select/policy.rs `choose` on `fit` (the n = 0
343/// prior, under which the decision rule deviates nowhere when P4a passes) at the evaluation's check
344/// `c`, against a gate that admits every draw (`OPEN`) at the default tolerance (`policy::ALPHA`), for
345/// a session that had none of its lessons.
346fn tested(units: &[Unit], c: &EvalCheck, fit: &Fit, seed: u64) -> Vec<Route> {
347    let gate = summary::Gate { gain: vec![0.0; policy::DRAWS], allowance: OPEN, ..summary::Gate::default() };
348    policy::choose(units, &eval_check(c), fit, &gate, policy::ALPHA, seed, &[]).routes
349}
350
351/// The quality `r` risks below the fixed rule at the gate's 5% quantile (P3): select/policy.rs
352/// `Decision::risk`, which the gate admitted only within its budget; a decision that keeps the fixed
353/// rule risks nothing.
354fn risk(r: &Routed, deviates: bool) -> f64 {
355    if deviates { r.log.risk } else { 0.0 }
356}
357
358/// A unit's prediction, fitted on the labels before it.
359type Predictor<'a> = Box<dyn Fn(&Label) -> f64 + 'a>;
360
361/// The value model P2 predicts by: the one the policy decides with (select/policy.rs `fit`), or, in
362/// the pre-registered rerun after its failure, the model pruned to grade, route and dilution
363/// (`fit_pruned`).
364#[derive(Debug, Clone, Copy, PartialEq, Eq)]
365enum Value {
366    Full,
367    Pruned,
368}
369
370impl Value {
371    fn fit(self, s: &Summary) -> Fit {
372        match self {
373            Value::Full => policy::fit(s, None),
374            Value::Pruned => policy::fit_pruned(s, None),
375        }
376    }
377
378    /// Its n = 0 prior, for a unit with no label before its check.
379    fn prior(self) -> Fit {
380        match self {
381            Value::Full => policy::prior(),
382            Value::Pruned => policy::prior_pruned(),
383        }
384    }
385}
386
387/// The value model `value` fitted on `past` as known before `at` (P2): its fit of the log `past` makes
388/// (`known`), its n = 0 prior's (`Value::prior`) while it has no label, and per unit
389/// `policy::predict`: P(changed ∧ avoids) on its logged route among the check's applies of that route,
390/// its features read from its check's record (`checks[l.check].o`, apply `l.j`) as select/summary.rs
391/// `fold` reads them.
392fn model<'a>(checks: &'a [Check], past: &[&Label], at: i64, value: Value) -> Option<Predictor<'a>> {
393    let fit = Some(value.fit(&known(checks, past, at))).filter(|f| f.model.is_some()).unwrap_or_else(|| value.prior());
394    Some(Box::new(move |l: &Label| {
395        let o = &checks[l.check].o;
396        let routes = routes_of(&checks[l.check]);
397        let units: Vec<Unit> = o
398            .lessons
399            .iter()
400            .zip(&o.grades)
401            .enumerate()
402            .map(|(j, (lesson, grade))| Unit { lesson, grade: *grade, rank: o.ranks.get(j).map_or(j, |r| usize::from(*r)) })
403            .collect();
404        let route = [Route::Ask, Route::Free, Route::Not][l.route];
405        let m = routes.iter().filter(|r| **r == route).count();
406        let feats = policy::Feat::of(&units, o.channel == "stop", o.tokens);
407        policy::predict(&fit, &feats[l.j], route, m, &o.session, &o.lessons[l.j]).unwrap_or(0.5)
408    }))
409}
410
411/// A check's route per apply, as select/summary.rs `fold` reads its record: asked, else free, else
412/// placebo, else not now.
413fn routes_of(c: &Check) -> Vec<Route> {
414    let has = |v: &[String], l: &String| v.contains(l);
415    c.o.lessons
416        .iter()
417        .map(|l| match () {
418            _ if has(&c.asked, l) => Route::Ask,
419            _ if has(&c.free, l) => Route::Free,
420            _ if has(&c.o.placebo, l) => Route::Placebo,
421            _ => Route::Not,
422        })
423        .collect()
424}
425
426/// The summary a fit on exactly `past` as known before `at` reads: every check up to the newest of
427/// their results then and every check of theirs (as logged, in log order, an older one given a check id
428/// of its own), then each label's verdict as known before `at` (`Label::at`) joined to its check by id,
429/// on its route, by its judge. Leave-future-out by construction: no other verdict is in it, and no
430/// result from `at` on.
431fn known(checks: &[Check], past: &[&Label], at: i64) -> Summary {
432    let then: Vec<(&Label, (i64, f64))> = past.iter().filter_map(|l| l.at(at).map(|k| (*l, k))).collect();
433    let Some(until) = then.iter().map(|(_, (ms, _))| *ms).max() else { return Summary::default() };
434    // An id no logged check has (they are `select::CHECK_HEX` hex digits).
435    let id = |i: usize| if checks[i].o.check.is_empty() { format!("replay-{i}") } else { checks[i].o.check.clone() };
436    let theirs: BTreeSet<usize> = then.iter().map(|(l, _)| l.check).collect();
437    let mut log: Vec<Outcome> =
438        checks.iter().enumerate().filter(|(i, c)| c.o.ms <= until || theirs.contains(i)).map(|(i, c)| Outcome { check: id(i), ..c.o.clone() }).collect();
439    for (l, (ms, y)) in then {
440        let o = &checks[l.check].o;
441        log.push(Outcome {
442            kind: if y > 0.5 { outcome::CHANGED } else { outcome::IGNORED }.into(),
443            session: o.session.clone(),
444            lessons: vec![o.lessons[l.j].clone()],
445            ms,
446            channel: match l.route {
447                ASK => channel(o).into(),
448                FREE => "queued".into(),
449                _ => outcome::PLACEBO.into(),
450            },
451            check: id(l.check),
452            judge: l.judge,
453            ..Outcome::default()
454        });
455    }
456    let text: String = log.iter().filter_map(|o| serde_json::to_string(o).ok()).map(|j| j + "\n").collect();
457    summary::fold(&text, Summary::default())
458}
459
460// --- Pass 1: the log as logged (P0, P1) -----------------------------------------------------------
461
462#[derive(Debug, Clone, PartialEq, Serialize)]
463pub struct P0 {
464    pub verdict: Verdict,
465    /// Graded checks decided at gate budget 0.
466    pub checks: usize,
467    /// Of them, the checks that apply no lesson (none applied, or the call failed): every policy asks
468    /// and hands over nothing there, so they are compared but test nothing, and P0 is NOT TESTED when
469    /// they are all it has.
470    pub empty: usize,
471    /// Checks whose decision is not the fixed rule's, or (logged under the fixed rule) not the logged one.
472    pub differ: usize,
473    pub first: Vec<String>,
474}
475
476#[derive(Debug, Clone, PartialEq, Serialize)]
477pub struct P1 {
478    pub verdict: Verdict,
479    /// Checks replayed (fixed rule, learned policy), and those that reproduced their log.
480    pub replayed: usize,
481    pub reproduced: usize,
482    /// Of the replayed checks, those that apply no lesson (P0 `empty`): their decision and propensities
483    /// are empty under any policy, so only the summary and the source their record names are tested
484    /// there, and P1 is NOT TESTED when they are all it replayed.
485    pub empty: usize,
486    /// Replayed checks whose record names the summary its decision read (`Outcome::seen`); the others
487    /// (older records) are replayed on every line before them.
488    pub seen: usize,
489    /// Of the replayed checks, those whose record logs the question-count test (outcome.rs `xk`): their
490    /// draw and its propensities are replayed from the check's seed.
491    pub tests: usize,
492    /// Checks under an evaluation switch (cap, learned cut): counted, not replayed.
493    pub switches: usize,
494    /// The largest |Δ| between a replayed and a logged propensity (p or pf).
495    pub max_delta: f64,
496    /// Folding the log check by check gives the summary that folding it whole gives.
497    pub fold: bool,
498    pub first: Vec<String>,
499}
500
501/// Pass 1's results: the graded checks (in log order), P0, P1 and the store's posterior summary.
502struct AsLogged {
503    checks: Vec<Check>,
504    malformed: usize,
505    p0: P0,
506    p1: P1,
507    posterior: Summary,
508}
509
510/// One fit's summary as the replay folds it on (`fitted`): the fit's offset `at` and what the refit set
511/// there (summary.rs `with_fit`: the fit, the gate's ledger, the monitor), and the summary folded on
512/// to byte `pos`.
513struct Fitted {
514    at: usize,
515    refit: (Fit, summary::Gate, policy::Monitor),
516    s: Summary,
517    pos: usize,
518}
519
520/// The summary a hook decided with under fit `key` when it had read the log up to byte `upto` of
521/// `text`: the refit (summary.rs `with_fit`, the collective's `budget` included) of the log up to the
522/// fit's offset (the key's `at`), then the log from there folded on it as summary.rs `load` does. Kept
523/// per key and folded on as the records come, so each fit's tail is folded about once; a decision that
524/// read less of the log than the last one under the same fit (two checks at once, `Outcome::seen`) is
525/// folded again from the fit's offset. None when no refit of the log there gives that key, or the
526/// decision read less than the fit.
527fn fitted<'a>(cache: &'a mut HashMap<String, Option<Fitted>>, text: &str, upto: usize, key: &str, budget: Option<f64>) -> Option<&'a mut Summary> {
528    let entry = cache.entry(key.to_string()).or_insert_with(|| {
529        let at: usize = key.split('-').next()?.parse().ok()?;
530        if !text.is_char_boundary(at) {
531            return None;
532        }
533        let s = summary::with_fit(summary::fold(&text[..at], Summary::default()), budget);
534        (s.fit.key == key).then(|| Fitted { at, refit: (s.fit.clone(), s.gate.clone(), s.monitor.clone()), s, pos: at })
535    });
536    let f = entry.as_mut().filter(|f| f.at <= upto)?;
537    if upto < f.pos {
538        // A fresh fold with what the refit set is the refit itself (`with_fit` changes nothing else).
539        let mut s = summary::fold(&text[..f.at], Summary::default());
540        (s.fit, s.gate, s.monitor) = f.refit.clone();
541        (f.s, f.pos) = (s, f.at);
542    }
543    if f.pos < upto {
544        f.s = summary::fold(&text[f.pos..upto], std::mem::take(&mut f.s));
545        f.pos = upto;
546    }
547    Some(&mut f.s)
548}
549
550/// The byte of `text` up to which the decision of the graded record at byte `here` read the log: the
551/// summary its record names (`Outcome::seen`, read before the model call, so it can end before
552/// records other checks appended meanwhile), else every line before the record. Err when the named
553/// summary is not a line boundary before the record.
554fn seen_at(o: &Outcome, text: &str, here: usize) -> Result<usize, String> {
555    if o.seen.is_empty() {
556        return Ok(here);
557    }
558    let at = o.seen.split('-').next().and_then(|a| a.parse::<usize>().ok());
559    at.filter(|&a| a <= here && text.is_char_boundary(a) && (a == 0 || text[..a].ends_with('\n')))
560        .ok_or_else(|| format!("its summary {:?} is no line boundary before it", o.seen))
561}
562
563fn as_logged(text: &str, lessons: &Path) -> AsLogged {
564    let mut s = Summary::default();
565    // Per fit key the hook logged, the summary it decided with (`fitted`).
566    let mut fits: HashMap<String, Option<Fitted>> = HashMap::new();
567    let budget = super::budget_of(lessons);
568    let mut at = 0;
569    let mut checks = Vec::new();
570    let mut malformed = 0;
571    let mut p0 = P0 { verdict: Verdict::Pass, checks: 0, empty: 0, differ: 0, first: Vec::new() };
572    let mut p1 =
573        P1 { verdict: Verdict::Pass, replayed: 0, reproduced: 0, empty: 0, seen: 0, tests: 0, switches: 0, max_delta: 0.0, fold: true, first: Vec::new() };
574    let mut start = 0;
575    for line in lines(text) {
576        let here = start;
577        start += line.text.len();
578        let Some(o) = line.o.filter(|o| o.kind == outcome::GRADED) else { continue };
579        let Some(cs) = challenges(&o) else {
580            malformed += 1;
581            continue;
582        };
583        // The summary the hook had: every line before this record.
584        s = summary::fold(&text[at..here], s);
585        at = here;
586        let applied = applied(&cs, &o);
587        let check = Check::new(o, &applied);
588        // P0: at gate budget 0 the learned policy is the fixed rule, and the fixed rule is what was logged.
589        let r = gate_closed(&mut s, |s| super::graded_under(Policy::Learned, &applied, &ctx(&check.o, &check.had, lessons, s)));
590        let mut same = (ids(&r.ask), ids(&r.free)) == check.fixed;
591        if replayable(&check.o) == Some(Policy::Fixed) {
592            same &= (&check.asked, &check.free) == (&check.fixed.0, &check.fixed.1);
593        }
594        p0.checks += 1;
595        p0.empty += usize::from(applied.is_empty());
596        if !same {
597            p0.differ += 1;
598            if p0.first.len() < SHOW {
599                p0.first.push(format!(
600                    "{}: gate 0 asks {:?} free {:?}; logged {:?} free {:?}; fixed rule {:?} free {:?}",
601                    check.line(),
602                    ids(&r.ask),
603                    ids(&r.free),
604                    check.asked,
605                    check.free,
606                    check.fixed.0,
607                    check.fixed.1
608                ));
609            }
610        }
611        // P1: the logged policy from its logged fit, summary and seed.
612        match replayable(&check.o) {
613            None => p1.switches += 1,
614            Some(policy) => {
615                p1.replayed += 1;
616                p1.empty += usize::from(applied.is_empty());
617                p1.seen += usize::from(!check.o.seen.is_empty());
618                p1.tests += usize::from(check.o.xk.is_some());
619                let found = match seen_at(&check.o, text, here) {
620                    Err(e) => Err(e),
621                    // The prior has no model: its decision is the fixed rule whatever else the summary holds.
622                    Ok(_) if check.o.fit.is_empty() => Ok(&mut s),
623                    Ok(upto) => fitted(&mut fits, text, upto, &check.o.fit, budget)
624                        .filter(|f| check.o.seen.is_empty() || f.key() == check.o.seen)
625                        .ok_or_else(|| format!("no summary with fit {:?} and key {:?} before it", check.o.fit, check.o.seen)),
626                };
627                let miss = match found {
628                    Err(e) => Some(format!("{}: {e}", check.line())),
629                    Ok(_) if policy == Policy::Learned && check.o.check.is_empty() => Some(format!("{}: learned without a check id", check.line())),
630                    Ok(at) => {
631                        // The store's revert as the hook read it: its summary ORs in the sticky mark beside
632                        // the store (summary.rs `REVERTED`), which no log line holds; select.rs `learned`
633                        // logs it as its source.
634                        let logged = !check.o.source.is_empty();
635                        let kept = at.monitor.reverted;
636                        if logged {
637                            at.monitor.reverted = check.o.source == super::REVERTED_SOURCE;
638                        }
639                        let r = super::graded_under(policy, &applied, &ctx(&check.o, &check.had, lessons, at));
640                        at.monitor.reverted = kept;
641                        let delta = r.p.iter().zip(&check.p).chain(r.pf.iter().zip(&check.pf)).map(|(a, b)| (a - b).abs()).fold(0.0, f64::max);
642                        p1.max_delta = p1.max_delta.max(delta);
643                        // The test's draw: k and s as logged (None outside the test, and on every record
644                        // from before it).
645                        let drawn = (r.log.xk, r.log.xs) == (check.o.xk, check.o.xs);
646                        let decided = ids(&r.ask) == check.asked && ids(&r.free) == check.free && (!logged || (r.log.source == check.o.source && drawn));
647                        let aligned = r.p.len() == check.p.len() && r.pf.len() == check.pf.len();
648                        let x = |k: Option<u32>, s: Option<u32>| match (k, s) {
649                            (None, None) => String::new(),
650                            (k, s) => format!(" k {} s {}", k.map_or("-".into(), |k| k.to_string()), s.map_or("-".into(), |s| s.to_string())),
651                        };
652                        (!decided || !aligned || delta > ope::AGREE).then(|| {
653                            format!(
654                                "{}: replay asks {:?} free {:?} by {}{} (|Δp| {delta:.4}); logged {:?} free {:?} by {}{}",
655                                check.line(),
656                                ids(&r.ask),
657                                ids(&r.free),
658                                r.log.source,
659                                x(r.log.xk, r.log.xs),
660                                check.asked,
661                                check.free,
662                                if logged { check.o.source.as_str() } else { "-" },
663                                x(check.o.xk, check.o.xs)
664                            )
665                        })
666                    }
667                };
668                match miss {
669                    None => p1.reproduced += 1,
670                    Some(m) if p1.first.len() < SHOW => p1.first.push(m),
671                    Some(_) => {}
672                }
673            }
674        }
675        checks.push(check);
676    }
677    let posterior = summary::fold(&text[at..], s);
678    p1.fold = posterior == summary::fold(text, Summary::default());
679    // Tested only by a check that applies a lesson: on the others every policy decides nothing (`empty`).
680    p0.verdict = Verdict::tested(p0.differ == 0, p0.checks > p0.empty);
681    p1.verdict = Verdict::tested(p1.reproduced == p1.replayed && p1.fold, p1.replayed > p1.empty);
682    AsLogged { checks, malformed, p0, p1, posterior }
683}
684
685// --- Pass 2: cold start (P3, and the policy P5 evaluates) ------------------------------------------
686
687/// What a decision spends, summed over checks: model calls, questions asked, blocks at the stop (an
688/// extra round each), lessons handed over free, the pool's tokens where logged, and the logged calls'
689/// cost in dollars (`usd`, the same for any policy replayed on them: a replay makes no call). Measured,
690/// never priced.
691#[derive(Debug, Clone, Copy, Default, PartialEq, Serialize)]
692pub struct Spend {
693    pub checks: usize,
694    pub questions: usize,
695    pub blocks: usize,
696    pub free: usize,
697    pub tokens: u64,
698    pub usd: f64,
699}
700
701impl Spend {
702    fn add(&mut self, o: &Outcome, asked: usize, free: usize) {
703        self.checks += 1;
704        self.questions += asked;
705        self.blocks += usize::from(channel(o) == "stop" && asked > 0);
706        self.free += free;
707        self.tokens += u64::from(o.tokens);
708        self.usd += o.usd;
709    }
710}
711
712/// One check of the cold-start replay: whether the policy left the fixed rule, the gate's budget at
713/// that check and the quality the decision risked below the fixed rule.
714#[derive(Debug, Clone, PartialEq)]
715struct Step {
716    deviates: bool,
717    gate: f64,
718    risk: f64,
719    at: String,
720}
721
722#[derive(Debug, Clone, PartialEq, Serialize)]
723pub struct P3 {
724    pub verdict: Verdict,
725    /// Why it is not tested: no check, or no decision left the fixed rule, so the gate was never put to
726    /// the test. Empty otherwise.
727    pub why: String,
728    pub checks: usize,
729    pub deviations: usize,
730    /// The first check decided as the fixed rule with a budget of 0.
731    pub cold: bool,
732    /// Checks whose decision risked more than the gate's budget there, or whose budget was negative.
733    pub over: usize,
734    /// The engineer's budget for the collective (select.rs `budget_of`: pool tokens per session), by
735    /// which the policy prices pool tokens; none by default. With one, the replayed pools must stay
736    /// within it (`pool`); spend is reported either way.
737    pub budget: Option<f64>,
738    /// The pool tokens the replayed policy's pools spend per session, as select/policy.rs `price`
739    /// measures what a budget bounds: each check at the pool budget `pool_tokens` chose for it, averaged
740    /// over the sessions with a check.
741    pub pool: f64,
742    /// The refits the replay made, one wherever a session had ended since the last (`cold_start`).
743    pub refits: usize,
744    /// The replayed decisions per source (select/policy.rs `Decision::source`): how many the evidence
745    /// rule, the question-count test (its control arm apart) and the gate's refusals set.
746    pub sources: BTreeMap<String, usize>,
747    pub policy: Spend,
748    pub fixed: Spend,
749    pub first: Vec<String>,
750}
751
752/// P3 over the cold-start steps, and the replayed pools' spend per session (`pool`) against the
753/// engineer's `budget` (the spends are carried through).
754fn conduct(steps: &[Step], policy: Spend, fixed: Spend, budget: Option<f64>, pool: f64) -> P3 {
755    let cold = steps.first().is_none_or(|s| !s.deviates && s.gate == 0.0);
756    let bad: Vec<&Step> = steps.iter().filter(|s| s.gate.is_nan() || s.gate < 0.0 || s.risk > s.gate).collect();
757    let mut first: Vec<String> = bad.iter().take(SHOW).map(|s| format!("{}: risked {} with a budget of {:.4}", s.at, s.risk, s.gate)).collect();
758    let over_budget = budget.filter(|b| pool > *b);
759    if let Some(b) = over_budget {
760        first.push(format!("the policy's pools spend {pool:.0} tokens per session, over the collective's budget of {b}"));
761    }
762    let deviations = steps.iter().filter(|s| s.deviates).count();
763    let verdict = Verdict::tested(cold && bad.is_empty() && over_budget.is_none(), deviations > 0);
764    let why = match (verdict, steps.len()) {
765        (Verdict::NotTested, 0) => "no graded check to replay".to_string(),
766        (Verdict::NotTested, _) => "no decision left the fixed rule, so the gate never had to hold one back".to_string(),
767        _ => String::new(),
768    };
769    P3 { verdict, why, checks: steps.len(), deviations, cold, over: bad.len(), budget, pool, refits: 0, sources: BTreeMap::new(), policy, fixed, first }
770}
771
772/// A check's propensities of asking (`p`) and of handing over free (`pf`), aligned with its applies.
773type Propensities = (Vec<f64>, Vec<f64>);
774
775/// The latency limit the replay's pools are chosen under: the loosest, which no pool's latency
776/// exceeds. Method: as select/policy.rs `price` replays pools, so the spend P3 holds against an
777/// engineer's budget is the most a hook's limit (the harness's stop budget) allows; no limit at all
778/// (None) would instead forbid every pool above the baseline.
779const LOOSEST: Option<u64> = Some(u64::MAX);
780
781/// The pool budget the learned policy chooses for a check of `session` on `s` (select.rs
782/// `pool_tokens_under`, whatever this process's `policy`), under `LOOSEST`.
783fn pool_of(s: &Summary, session: &str) -> usize {
784    super::pool_tokens_under(Policy::Learned, s, LOOSEST, session)
785}
786
787/// The graded record `o` as the decision `r` would have logged it (hook.rs `record_graded`): its
788/// routes, its own propensities (the placebo's `psi` weighs the monitor's estimate, select/policy.rs
789/// `monitor`), policy, fit, source and the question-count test's k and s (select/summary.rs counts
790/// them); its applies, had lessons (`nofree`), pool and tail stay the
791/// logged check's.
792fn decided(o: Outcome, r: &Routed) -> Outcome {
793    let round = |v: &[f64]| v.iter().map(|p| outcome::round_p(*p)).collect();
794    Outcome {
795        chosen: ids(&r.ask),
796        free: ids(&r.free),
797        placebo: ids(&r.placebo),
798        p: round(&r.p),
799        pf: round(&r.pf),
800        psi: r.log.psi,
801        policy: r.log.policy.into(),
802        fit: r.log.fit.clone(),
803        source: r.log.source.into(),
804        xk: r.log.xk,
805        xs: r.log.xs,
806        explore: false,
807        ..o
808    }
809}
810
811/// The cold-start replay: P3, and per graded check (aligned with pass 1's) the learned policy's
812/// propensities. The policy decides as a hook would: with the summary of every line before the check,
813/// fitted where production fits it, at `borg learn` when a session ends (main.rs `learn_store`, after
814/// the session's settle): refitted (summary.rs `with_fit`, the pure part of the `refit` that
815/// `learn_store` calls, under the collective's `budget`) before the first check after a session ended,
816/// the gate's ledger replayed over the policy's own checks; and under the had lessons its record logs
817/// (`had_of`). Each check's pool is the budget the policy chooses there (select.rs `pool_tokens_under`
818/// the learned policy, called per check as the hook calls `pool_tokens`) under the loosest latency
819/// limit (`pool_of`).
820fn cold_start(text: &str, lessons: &Path, budget: Option<f64>) -> (P3, Vec<Propensities>) {
821    let mut s = Summary::default();
822    let mut chunk = String::new();
823    let (mut steps, mut targets) = (Vec::new(), Vec::new());
824    let (mut spent, mut fixed) = (Spend::default(), Spend::default());
825    let (mut ended, mut refits) = (0, 0);
826    // Pool tokens per session; decisions per source.
827    let mut pools: BTreeMap<String, u64> = BTreeMap::new();
828    let mut sources: BTreeMap<String, usize> = BTreeMap::new();
829    for line in lines(text) {
830        let Some((o, cs)) = line.o.filter(|o| o.kind == outcome::GRADED).and_then(|o| challenges(&o).map(|cs| (o, cs))) else {
831            chunk.push_str(line.text);
832            continue;
833        };
834        s = summary::fold(&chunk, s);
835        chunk.clear();
836        // Ended sessions the summary holds; a compaction (summary.rs `MAX_SESSIONS`) drops some, after
837        // which the next end counts from what is left.
838        let now = s.sessions.iter().filter(|x| x.ended).count();
839        ended = ended.min(now);
840        if now > ended {
841            s = summary::with_fit(s, budget);
842            (ended, refits) = (now, refits + 1);
843        }
844        let applied = applied(&cs, &o);
845        let had = had_of(&o);
846        let r = super::graded_under(Policy::Learned, &applied, &ctx(&o, &had, lessons, &s));
847        let (fa, ff) = conscience::graded_without(&applied, None, &had);
848        let deviates = (ids(&r.ask), ids(&r.free)) != (ids(&fa), ids(&ff));
849        spent.add(&o, r.ask.len(), r.free.len());
850        fixed.add(&o, fa.len(), ff.len());
851        let pool = pool_of(&s, &o.session);
852        *pools.entry(o.session.clone()).or_default() += pool as u64;
853        *sources.entry(r.log.source.to_string()).or_default() += 1;
854        steps.push(Step { deviates, gate: r.log.gate, risk: risk(&r, deviates), at: format!("session {} ms {}", o.session, o.ms) });
855        targets.push((r.p.clone(), r.pf.clone()));
856        // The policy's own decision is what the summary folds next.
857        match serde_json::to_string(&decided(o, &r)) {
858            Ok(j) => {
859                chunk.push_str(&j);
860                chunk.push('\n');
861            }
862            Err(_) => chunk.push_str(line.text),
863        }
864    }
865    let pool = if pools.is_empty() { 0.0 } else { pools.values().sum::<u64>() as f64 / pools.len() as f64 };
866    let p3 = P3 { refits, sources, ..conduct(&steps, spent, fixed, budget, pool) };
867    (p3, targets)
868}
869
870// --- Labels (P2, P5, the readout) -----------------------------------------------------------------
871
872/// One judged unit: a graded check's apply with the strongest result of its delivery.
873#[derive(Debug, Clone, PartialEq)]
874struct Label {
875    /// Its check (index into pass 1's checks) and its place among the check's applies.
876    check: usize,
877    j: usize,
878    grade: u8,
879    /// The route that delivered it (`ASK`, `FREE`, `NOT` for a placebo) and each route's logged
880    /// probability of a label (`NOT`'s: routed nowhere and drawn as a placebo).
881    route: usize,
882    mu: [f64; ROUTES],
883    /// 1 changed and avoided, 0 not: from every result of it (the last of `known`).
884    y: f64,
885    session: String,
886    check_ms: i64,
887    /// Its value as the log knew it: from each result's ms on that changed it, the value then, in time
888    /// order, the first at its first verdict. A prediction for a check at t reads the value before t
889    /// (`at`): a veto, correction or stronger verdict after t is a result from after t.
890    known: Vec<(i64, f64)>,
891    /// The judge template version of its first verdict (outcome.rs `judge`).
892    judge: u8,
893}
894
895impl Label {
896    /// Its first result's ms: before it no check could know it.
897    fn first(&self) -> i64 {
898        self.known.first().map_or(i64::MAX, |k| k.0)
899    }
900
901    /// Its value as known before `t`, with the ms of the result that set it; None before its first.
902    fn at(&self, t: i64) -> Option<(i64, f64)> {
903        self.known.iter().take_while(|(ms, _)| *ms < t).last().copied()
904    }
905}
906
907/// A unit's value over its results (each its ms and `ope::rank`), in time order: 1 while its strongest
908/// result so far is the change, 0 otherwise, from its first verdict on; an entry per change.
909fn values(verdicts: &[(i64, u8)], against: &[(i64, u8)]) -> Vec<(i64, f64)> {
910    let Some(start) = verdicts.iter().map(|v| v.0).min() else { return Vec::new() };
911    let mut events: Vec<(i64, u8)> = verdicts.iter().chain(against).copied().collect();
912    events.sort_unstable();
913    let mut out: Vec<(i64, f64)> = Vec::new();
914    let mut strongest = 0;
915    for (i, &(ms, rank)) in events.iter().enumerate() {
916        strongest = strongest.max(rank);
917        // Results at the same ms land together.
918        if ms < start || events.get(i + 1).is_some_and(|e| e.0 == ms) {
919            continue;
920        }
921        let y = f64::from(u8::from(strongest == 1));
922        if out.last().is_none_or(|l| l.1 != y) {
923            out.push((ms, y));
924        }
925    }
926    out
927}
928
929/// The judged units of `checks` from the results in `log`, in check order, and the verdicts that
930/// joined no check.
931fn labels(checks: &[Check], log: &[Outcome]) -> (Vec<Label>, usize) {
932    let by_id: HashMap<&str, usize> = checks.iter().enumerate().filter(|(_, c)| !c.o.check.is_empty()).map(|(i, c)| (c.o.check.as_str(), i)).collect();
933    let mut by_lesson: HashMap<(&str, &str), Vec<usize>> = HashMap::new();
934    for (i, c) in checks.iter().enumerate() {
935        for l in &c.o.lessons {
936            by_lesson.entry((c.o.session.as_str(), l.as_str())).or_default().push(i);
937        }
938    }
939    let routed = |c: &Check, route: usize, l: &str| match route {
940        ASK => c.asked.iter().any(|x| x == l),
941        FREE => c.free.iter().any(|x| x == l),
942        _ => c.o.placebo.iter().any(|x| x == l),
943    };
944    // A unit's verdicts (ms, rank), the route that delivered it, and its first verdict's ms and judge.
945    struct Joined {
946        verdicts: Vec<(i64, u8)>,
947        route: usize,
948        first: (i64, u8),
949    }
950    let mut joined: BTreeMap<(usize, usize), Joined> = BTreeMap::new();
951    let mut unjoined = 0;
952    for r in log.iter().filter(|r| r.kind == outcome::CHANGED || r.kind == outcome::IGNORED) {
953        let route = match r.channel.as_str() {
954            "early" => continue,
955            "queued" => FREE,
956            outcome::PLACEBO => NOT,
957            _ => ASK,
958        };
959        let rank = ope::rank(&r.kind).unwrap_or(0);
960        for l in &r.lessons {
961            let at = match r.check.as_str() {
962                "" => by_lesson
963                    .get(&(r.session.as_str(), l.as_str()))
964                    .and_then(|v| v.iter().rev().find(|&&i| checks[i].o.ms <= r.ms && routed(&checks[i], route, l)))
965                    .copied(),
966                id => by_id.get(id).copied(),
967            };
968            let Some((i, j)) = at.and_then(|i| checks[i].o.lessons.iter().position(|x| x == l).filter(|_| routed(&checks[i], route, l)).map(|j| (i, j))) else {
969                unjoined += 1;
970                continue;
971            };
972            let e = joined.entry((i, j)).or_insert(Joined { verdicts: Vec::new(), route, first: (r.ms, r.judge) });
973            e.verdicts.push((r.ms, rank));
974            if r.ms < e.first.0 {
975                e.first = (r.ms, r.judge);
976            }
977        }
978    }
979    // A veto or correction in the session after the check outranks the change.
980    let mut against: HashMap<(&str, &str), Vec<(i64, u8)>> = HashMap::new();
981    for o in log.iter().filter(|o| o.kind == outcome::VETOED || o.kind == outcome::CORRECTED) {
982        for l in &o.lessons {
983            against.entry((o.session.as_str(), l.as_str())).or_default().push((o.ms, ope::rank(&o.kind).unwrap_or(0)));
984        }
985    }
986    let out = joined
987        .into_iter()
988        .map(|((i, j), Joined { verdicts, route, first: (_, judge) })| {
989            let c = &checks[i];
990            let l = c.o.lessons[j].as_str();
991            let later: Vec<(i64, u8)> = against.get(&(c.o.session.as_str(), l)).into_iter().flatten().filter(|(t, _)| *t >= c.o.ms).copied().collect();
992            let known = values(&verdicts, &later);
993            let (p, pf) = (c.p.get(j).copied().unwrap_or(0.0), c.pf.get(j).copied().unwrap_or(0.0));
994            // Not delivered, a unit is judged only when the placebo draw took it (its chance ψ, `psi`):
995            // that route's probability is both, as select/policy.rs `monitor` weighs it, a placebo that
996            // happened at least at `PSI_FLOOR`.
997            let psi = if route == NOT { c.o.psi.max(policy::PSI_FLOOR) } else { c.o.psi };
998            Label {
999                check: i,
1000                j,
1001                grade: c.o.grades[j],
1002                route,
1003                mu: [p, pf, (1.0 - p - pf).max(0.0) * psi],
1004                y: known.last().map_or(0.0, |k| k.1),
1005                session: c.o.session.clone(),
1006                check_ms: c.o.ms,
1007                known,
1008                judge,
1009            }
1010        })
1011        .collect();
1012    (out, unjoined)
1013}
1014
1015/// Judged and changed counts per grade and route.
1016type Counts = [[(u32, u32); ROUTES]; GRADES];
1017
1018/// Every change of a label's known value (`Label::known`), as (ms, label index, value), in time order.
1019fn changes(labels: &[Label]) -> Vec<(i64, usize, f64)> {
1020    let mut v: Vec<(i64, usize, f64)> = labels.iter().enumerate().flat_map(|(i, l)| l.known.iter().map(move |&(ms, y)| (ms, i, y))).collect();
1021    v.sort_by_key(|c| (c.0, c.1));
1022    v
1023}
1024
1025/// Per label, the counts of the labels whose result came before its check, each at its value then:
1026/// what a decision at that check could have known (leave-future-out).
1027fn past_counts(labels: &[Label]) -> Vec<Counts> {
1028    let changes = changes(labels);
1029    let mut order: Vec<usize> = (0..labels.len()).collect();
1030    order.sort_by_key(|&i| labels[i].check_ms);
1031    let mut counts: Counts = [[(0, 0); ROUTES]; GRADES];
1032    let mut now: Vec<Option<f64>> = vec![None; labels.len()];
1033    let mut out = vec![counts; labels.len()];
1034    let mut next = 0;
1035    for i in order {
1036        while next < changes.len() && changes[next].0 < labels[i].check_ms {
1037            let (_, k, y) = changes[next];
1038            let c = &mut counts[usize::from(labels[k].grade).min(GRADES - 1)][labels[k].route];
1039            if let Some(was) = now[k] {
1040                c.0 -= 1;
1041                c.1 -= u32::from(was > 0.5);
1042            }
1043            c.0 += 1;
1044            c.1 += u32::from(y > 0.5);
1045            now[k] = Some(y);
1046            next += 1;
1047        }
1048        out[i] = counts;
1049    }
1050    out
1051}
1052
1053/// Beta(1, 1)'s posterior mean after `k` of `n`.
1054fn beta(n: u32, k: u32) -> f64 {
1055    (1.0 + f64::from(k)) / (2.0 + f64::from(n))
1056}
1057
1058/// The grade-only Beta-Binomial's prediction of a unit of `grade` (every route pooled).
1059fn by_grade(c: &Counts, grade: u8) -> f64 {
1060    let row = &c[usize::from(grade).min(GRADES - 1)];
1061    beta(row.iter().map(|x| x.0).sum(), row.iter().map(|x| x.1).sum())
1062}
1063
1064fn log_loss(p: f64, y: f64) -> f64 {
1065    let p = p.clamp(CLAMP, 1.0 - CLAMP);
1066    -(y * p.ln() + (1.0 - y) * (1.0 - p).ln())
1067}
1068
1069/// Session index per label, in first-seen order, for the session bootstrap.
1070fn sessions(labels: &[Label]) -> Vec<usize> {
1071    let mut seen: HashMap<&str, usize> = HashMap::new();
1072    labels
1073        .iter()
1074        .map(|l| {
1075            let n = seen.len();
1076            *seen.entry(l.session.as_str()).or_insert(n)
1077        })
1078        .collect()
1079}
1080
1081// --- P2 -------------------------------------------------------------------------------------------
1082
1083/// A prediction this close to 1/2 is a coin's: P2 is NOT TESTED when every prediction of both models
1084/// is one. Method: float slack around an exact 1/2 (Beta(1, 1) at k = n/2, a model's η = 0), far
1085/// below anything a label moves.
1086const COIN: f64 = 1e-9;
1087
1088#[derive(Debug, Clone, PartialEq, Serialize)]
1089pub struct P2 {
1090    pub verdict: Verdict,
1091    pub why: String,
1092    pub labels: usize,
1093    pub sessions: usize,
1094    /// Judged verdicts that joined no graded check (an early delivery's never does).
1095    pub unjoined: usize,
1096    /// Judged units with a label known before their check: those both models predict from data.
1097    pub informed: usize,
1098    /// Mean leave-future-out log-loss, grade only and of the value model.
1099    pub grade_only: f64,
1100    pub model: Option<f64>,
1101    /// The mean difference (model − grade only) with its session-bootstrap 95% interval.
1102    pub diff: Option<Estimate>,
1103    /// The pre-registered rerun after the value model's FAIL, on the same units: the model pruned to
1104    /// grade, route and dilution (select/policy.rs `fit_pruned`); its verdict is P2's. None unless it
1105    /// ran.
1106    pub pruned: Option<Rerun>,
1107}
1108
1109/// One rerun of P2's comparison by another value model.
1110#[derive(Debug, Clone, PartialEq, Serialize)]
1111pub struct Rerun {
1112    pub verdict: Verdict,
1113    pub model: f64,
1114    pub diff: Estimate,
1115}
1116
1117/// A fit of P2's value model `Value` on the labels known before a check at the given ms.
1118type Fitter<'f, 'a> = dyn Fn(Value, &[&Label], i64) -> Option<Predictor<'a>> + 'f;
1119
1120/// Each label's leave-future-out prediction by `value` (`fit` refitted wherever what is known before
1121/// a check changed), or why there is none.
1122fn predictions<'a>(labels: &[Label], value: Value, fit: &Fitter<'_, 'a>) -> Result<Vec<f64>, String> {
1123    let changes = changes(labels);
1124    let mut order: Vec<usize> = (0..labels.len()).collect();
1125    order.sort_by_key(|&i| labels[i].check_ms);
1126    let mut out = vec![0.5; labels.len()];
1127    let (mut known, mut fitted): (usize, Option<(usize, Predictor<'a>)>) = (0, None);
1128    for i in order {
1129        let at = labels[i].check_ms;
1130        while known < changes.len() && changes[known].0 < at {
1131            known += 1;
1132        }
1133        if fitted.as_ref().is_none_or(|(n, _)| *n != known) {
1134            let past: Vec<&Label> = labels.iter().filter(|l| l.first() < at).collect();
1135            let Some(m) = fit(value, &past, at) else { return Err("no value model yet (select/policy.rs)".into()) };
1136            fitted = Some((known, m));
1137        }
1138        if let Some((_, m)) = &fitted {
1139            out[i] = m(&labels[i]);
1140        }
1141    }
1142    Ok(out)
1143}
1144
1145/// The model's predictions `model` against grade only's `grade` on `labels`: the verdict, its mean
1146/// log-loss and the mean difference (session bootstrap over `ss`). NOT TESTED when every prediction of
1147/// both is 1/2 (`COIN`).
1148fn compare(labels: &[Label], grade: &[f64], model: &[f64], ss: &[usize]) -> Rerun {
1149    let ll = |p: &[f64]| -> Vec<f64> { p.iter().zip(labels).map(|(p, l)| log_loss(*p, l.y)).collect() };
1150    let (g, m) = (ll(grade), ll(model));
1151    let units: Vec<(f64, f64, usize)> = m.iter().zip(&g).zip(ss).map(|((m, g), s)| (1.0, m - g, *s)).collect();
1152    let diff = ope::snips(&units, ope::SEED);
1153    let coin = |p: &[f64]| p.iter().all(|p| (p - 0.5).abs() < COIN);
1154    let verdict = Verdict::tested(diff.hi <= CALIBRATION, !(coin(grade) && coin(model)));
1155    Rerun { verdict, model: m.iter().sum::<f64>() / m.len().max(1) as f64, diff }
1156}
1157
1158/// P2 over `labels` with the value model fitted by `fit` on the labels before each unit's check; after
1159/// its FAIL, the pre-registered rerun by the pruned model (`Value::Pruned`), once.
1160fn calibration<'a>(labels: &[Label], unjoined: usize, fit: &Fitter<'_, 'a>) -> P2 {
1161    let past = past_counts(labels);
1162    let ss = sessions(labels);
1163    let grade: Vec<f64> = labels.iter().zip(&past).map(|(l, c)| by_grade(c, l.grade)).collect();
1164    let mean = |v: &[f64]| if v.is_empty() { 0.0 } else { v.iter().sum::<f64>() / v.len() as f64 };
1165    let informed = past.iter().filter(|c| c.iter().flatten().any(|x| x.0 > 0)).count();
1166    let mut p2 = P2 {
1167        verdict: Verdict::NotTested,
1168        why: String::new(),
1169        labels: labels.len(),
1170        sessions: ss.iter().collect::<BTreeSet<_>>().len(),
1171        unjoined,
1172        informed,
1173        grade_only: mean(&grade.iter().zip(labels).map(|(p, l)| log_loss(*p, l.y)).collect::<Vec<_>>()),
1174        model: None,
1175        diff: None,
1176        pruned: None,
1177    };
1178    if labels.is_empty() {
1179        p2.why = "no judged unit joins a graded check".into();
1180        return p2;
1181    }
1182    if informed == 0 {
1183        p2.why = "no judged unit has a label before its check, so neither model learned anything".into();
1184        return p2;
1185    }
1186    let full = match predictions(labels, Value::Full, fit) {
1187        Ok(p) => compare(labels, &grade, &p, &ss),
1188        Err(why) => {
1189            (p2.verdict, p2.why) = (Verdict::NotRun, why);
1190            return p2;
1191        }
1192    };
1193    (p2.verdict, p2.model, p2.diff) = (full.verdict, Some(full.model), Some(full.diff));
1194    if p2.verdict == Verdict::NotTested {
1195        p2.why = "every prediction of both models is 1/2".into();
1196    }
1197    if p2.verdict == Verdict::Fail {
1198        // Pre-registered: prune the model to grade, route and dilution and rerun once; its verdict is P2's.
1199        let pruned = match predictions(labels, Value::Pruned, fit) {
1200            Ok(p) => compare(labels, &grade, &p, &ss),
1201            Err(why) => {
1202                p2.why = format!("the pruned rerun: {why}");
1203                return p2;
1204            }
1205        };
1206        p2.verdict = pruned.verdict;
1207        p2.pruned = Some(pruned);
1208    }
1209    p2
1210}
1211
1212// --- P5 and the readout ---------------------------------------------------------------------------
1213
1214/// One policy's doubly robust change against the fixed rule (per judged unit), its own inverse
1215/// propensity estimate, and how much of its route probability the log covers.
1216#[derive(Debug, Clone, PartialEq, Serialize)]
1217pub struct Row {
1218    pub policy: String,
1219    pub dr: Estimate,
1220    pub ips: Estimate,
1221    pub coverage: f64,
1222}
1223
1224#[derive(Debug, Clone, PartialEq, Serialize)]
1225pub struct P5 {
1226    pub verdict: Verdict,
1227    pub units: usize,
1228    /// Units delivered by a route their check gave probability 0: left out.
1229    pub inconsistent: usize,
1230    /// The learned policy first, then the fixed rule with one grade's route moved.
1231    pub rows: Vec<Row>,
1232}
1233
1234/// Per unit, a policy's probability of each route (`ASK`, `FREE`, `NOT`).
1235type Target<'a> = dyn Fn(&Label) -> [f64; ROUTES] + 'a;
1236
1237/// The fixed rule's route of a unit, as probabilities.
1238fn fixed_route(checks: &[Check], l: &Label) -> [f64; ROUTES] {
1239    let (ask, free) = &checks[l.check].fixed;
1240    let lesson = &checks[l.check].o.lessons[l.j];
1241    match (ask.contains(lesson), free.contains(lesson)) {
1242        (true, _) => [1.0, 0.0, 0.0],
1243        (_, true) => [0.0, 1.0, 0.0],
1244        _ => [0.0, 0.0, 1.0],
1245    }
1246}
1247
1248/// The DR change of `target` against `base` per unit, its IPS value and coverage: with q̂ the
1249/// leave-future-out Beta(1, 1) per grade and route, a unit adds Σ_a (π_a − b_a)·(q̂_a + [a = its
1250/// route]·(y − q̂_a)/μ_a). Session bootstrap, as `ope::snips`.
1251fn doubly_robust(labels: &[Label], past: &[Counts], ss: &[usize], target: &Target, base: &Target, name: &str) -> Row {
1252    let (mut dr, mut ips, mut covered) = (Vec::new(), Vec::new(), 0.0);
1253    for ((l, c), s) in labels.iter().zip(past).zip(ss) {
1254        let mu = l.mu[l.route];
1255        if mu <= 0.0 {
1256            continue;
1257        }
1258        let (t, b) = (target(l), base(l));
1259        let row = &c[usize::from(l.grade).min(GRADES - 1)];
1260        let q: [f64; ROUTES] = std::array::from_fn(|a| beta(row[a].0, row[a].1));
1261        let inc: f64 = (0..ROUTES).map(|a| (t[a] - b[a]) * (q[a] + if a == l.route { (l.y - q[a]) / mu } else { 0.0 })).sum();
1262        dr.push((1.0, inc, *s));
1263        ips.push((t[l.route] / mu, l.y, *s));
1264        covered += (0..ROUTES).filter(|&a| l.mu[a] > 0.0).map(|a| t[a]).sum::<f64>();
1265    }
1266    let n = dr.len().max(1) as f64;
1267    Row { policy: name.into(), dr: ope::snips(&dr, ope::SEED), ips: ope::snips(&ips, ope::SEED), coverage: covered / n }
1268}
1269
1270/// P5: the learned policy (`targets`, the cold-start replay's propensities per check) and the fixed
1271/// rule with one grade's asks handed over free, or its free lessons asked, against the fixed rule.
1272fn off_policy(checks: &[Check], labels: &[Label], targets: &[Propensities]) -> P5 {
1273    let past = past_counts(labels);
1274    let ss = sessions(labels);
1275    let base = |l: &Label| fixed_route(checks, l);
1276    let learned = |l: &Label| {
1277        let (p, pf) = targets.get(l.check).map_or((0.0, 0.0), |(p, pf)| (p.get(l.j).copied().unwrap_or(0.0), pf.get(l.j).copied().unwrap_or(0.0)));
1278        [p, pf, (1.0 - p - pf).max(0.0)]
1279    };
1280    let mut rows = vec![doubly_robust(labels, &past, &ss, &learned, &base, "learned")];
1281    for grade in 1..=3u8 {
1282        for (from, to, name) in [(ASK, FREE, "free"), (FREE, ASK, "asked")] {
1283            let moved = |l: &Label| {
1284                let b = base(l);
1285                match l.grade == grade && b[from] == 1.0 {
1286                    true => {
1287                        let mut m = [0.0; ROUTES];
1288                        m[to] = 1.0;
1289                        m
1290                    }
1291                    false => b,
1292                }
1293            };
1294            if labels.iter().any(|l| moved(l) != base(l)) {
1295                rows.push(doubly_robust(labels, &past, &ss, &moved, &base, &format!("fixed, grade {grade} {name}")));
1296            }
1297        }
1298    }
1299    let units = rows[0].dr.n;
1300    P5 {
1301        verdict: if units == 0 { Verdict::NotTested } else { Verdict::Reported },
1302        units,
1303        inconsistent: labels.iter().filter(|l| l.mu[l.route] <= 0.0).count(),
1304        rows,
1305    }
1306}
1307
1308/// One within-check contrast of two routes at one grade: per check with judged units of that grade on
1309/// both, the difference of their change rates; session bootstrap.
1310#[derive(Debug, Clone, PartialEq, Serialize)]
1311pub struct Contrast {
1312    pub grade: u8,
1313    pub routes: String,
1314    pub est: Estimate,
1315}
1316
1317#[derive(Debug, Clone, PartialEq, Serialize)]
1318pub struct Readout {
1319    pub due: bool,
1320    pub randomised: usize,
1321    pub sessions: usize,
1322    pub contrasts: Vec<Contrast>,
1323    /// The question-count test's own readout (rules v2, `test_readout`).
1324    pub test: TestReadout,
1325}
1326
1327/// The question-count test's readout (module doc), from the summary's fold (select/summary.rs
1328/// `Experiment`, `Check::xk`): its checks that drew a count (randomised), of them the control arm's,
1329/// those the gate refused (the fixed rule played) and the sessions with a drawn one, all-time; once
1330/// due (`TEST_CHECKS`, `TEST_SESSIONS`), and only then, its estimates over the drawn checks the summary
1331/// still holds (`kept`: compaction drops the oldest checks, select/summary.rs `compact`, never the
1332/// counts), refused ones included, each with its session's bootstrap 95% interval (`ope::snips`).
1333/// Each a Horvitz–Thompson mean over every unit that could go either way, so a unit's outcome y·ω
1334/// (`unit_outcome`) counts even when it is 0: a verdict weighed by its inverse chance of one (policy.rs
1335/// `judged`, the monitor's), a lesson never delivered 0 (it changed nothing), one closed without a
1336/// verdict 0 (its route's judged ones stand in for it), one still open out until it closes.
1337/// - `by_asked`, dilution, per m ≥ 2: the test's top lesson (the first of select/policy.rs `tested`,
1338///   asked at every s ≥ 1) asked with m of the test's questions against asked alone, over the drawn
1339///   checks with k ≥ m: Σ (k + 1)·([s = m] − [s = 1])·y·ω / n. s is uniform in 0..=k, so the same
1340///   lesson's two draws differ in the number asked alone (grade mix, the 3s and k do not enter); by the
1341///   drawn s, a count the gate refused played as the fixed rule (intention to treat).
1342/// - `ask_free`, asking a 2 against handing it over: Σ([asked]·y·ω/p − [free]·y·ω/pf)/n over the 2s
1343///   that could go either way (0 < p, pf; the logged propensities are the draw's, a refused count's
1344///   routes the fixed rule's, select/policy.rs `choose`), a difference of change rates.
1345#[derive(Debug, Clone, PartialEq, Serialize)]
1346pub struct TestReadout {
1347    pub due: bool,
1348    pub checks: u64,
1349    pub control: u64,
1350    pub refused: u64,
1351    pub sessions: u32,
1352    /// The drawn checks the summary still holds, which the estimates read.
1353    pub kept: u64,
1354    pub by_asked: Vec<(u16, Estimate)>,
1355    pub ask_free: Option<Estimate>,
1356}
1357
1358/// The outcome of apply `i` of `s` as a Horvitz–Thompson term (`TestReadout`): a verdict's y over its
1359/// chance of one (`judged`, floored at 1/`MAX_IPW` as the monitor floors it), 0 for a lesson never
1360/// delivered (dropped: outside `judged`'s fit, as policy.rs `model_route` leaves it) or closed without
1361/// a verdict, None while open.
1362fn unit_outcome(s: &Summary, judged: &HashMap<usize, f64>, i: usize) -> Option<f64> {
1363    use summary::{Delivered, Label};
1364    let a = s.applies.get(i)?;
1365    let never = a.delivered == Delivered::Dropped;
1366    let y = match a.label {
1367        Label::Changed => 1.0,
1368        Label::Ignored => 0.0,
1369        _ if never => return Some(0.0),
1370        Label::Open => return None,
1371        Label::Unclear | Label::Censored => return Some(0.0),
1372    };
1373    // A lesson never delivered is known to be so: its verdict, if any, stands for itself.
1374    let p = if never { 1.0 } else { judged.get(&i).copied().unwrap_or(1.0).max(1.0 / policy::MAX_IPW) };
1375    Some(y / p)
1376}
1377
1378/// The question-count test's readout of `s` (`TestReadout`): what `borg debug select` reports, and
1379/// what the monitoring can show from the summary it loads.
1380#[must_use]
1381pub fn test_readout(s: &Summary) -> TestReadout {
1382    let e = &s.experiment;
1383    let (checks, refused) = e.totals();
1384    let due = checks >= TEST_CHECKS || e.sessions >= TEST_SESSIONS;
1385    let drawn: Vec<&summary::Check> = s.checks.iter().filter(|c| c.xs.is_some()).collect();
1386    let kept = drawn.len() as u64;
1387    let mut out = TestReadout { due, checks, control: e.control, refused, sessions: e.sessions, kept, by_asked: Vec::new(), ask_free: None };
1388    if !due {
1389        return out;
1390    }
1391    let judged = policy::judged(s);
1392    let mut by: BTreeMap<u16, Vec<(f64, f64, usize)>> = BTreeMap::new();
1393    let mut both: Vec<(f64, f64, usize)> = Vec::new();
1394    for c in drawn {
1395        let session = c.tick as usize;
1396        let first = c.first as usize;
1397        let applies = s.applies.get(first..first + usize::from(c.n)).unwrap_or_default();
1398        for (j, a) in applies.iter().enumerate() {
1399            if a.grade != 2 || a.p <= 0.0 || a.pf <= 0.0 {
1400                continue;
1401            }
1402            let Some(y) = unit_outcome(s, &judged, first + j) else { continue };
1403            let r = match a.route {
1404                Route::Ask => y / a.p,
1405                Route::Free => -y / a.pf,
1406                _ => 0.0,
1407            };
1408            both.push((1.0, r, session));
1409        }
1410        // The test's lessons as its decision ordered them: the fixed rule's for what the session had
1411        // (`nofree`, the `had` the decision read), as select/policy.rs `choose` calls them.
1412        let units: Vec<Unit> = applies
1413            .iter()
1414            .map(|a| Unit { lesson: s.lessons.get(a.lesson as usize).map_or("", String::as_str), grade: a.grade, rank: usize::from(a.rank) })
1415            .collect();
1416        let had: Vec<String> = applies.iter().filter(|a| a.nofree).filter_map(|a| s.lessons.get(a.lesson as usize).cloned()).collect();
1417        let order = policy::tested(&units, &policy::fixed_routes(&units, &had), &had);
1418        let (Some(k), Some(drew), Some(&top)) = (c.xk, c.xs, order.first()) else { continue };
1419        // A check whose applies do not give its logged k is no draw over them.
1420        if order.len() != k as usize {
1421            continue;
1422        }
1423        let Some(y) = unit_outcome(s, &judged, first + top) else { continue };
1424        for m in 2..=k {
1425            let Ok(key) = u16::try_from(m) else { break };
1426            let r = (f64::from(k) + 1.0) * (f64::from(u8::from(drew == m)) - f64::from(u8::from(drew == 1))) * y;
1427            by.entry(key).or_default().push((1.0, r, session));
1428        }
1429    }
1430    out.by_asked = by.into_iter().map(|(m, units)| (m, ope::snips(&units, ope::SEED))).collect();
1431    out.ask_free = Some(ope::snips(&both, ope::SEED));
1432    out
1433}
1434
1435fn readout(checks: &[Check], labels: &[Label], s: &Summary) -> Readout {
1436    let randomised = labels.iter().filter(|l| l.mu[l.route] > 0.0 && l.mu[l.route] < 1.0).count();
1437    let learned: BTreeSet<&str> = checks.iter().filter(|c| outcome::policy_of(&c.o) == "learned").map(|c| c.o.session.as_str()).collect();
1438    let ss = sessions(labels);
1439    // (grade, check) -> per route (units, changed), and the check's session.
1440    type Cell = ([(f64, f64); ROUTES], usize);
1441    let mut cells: BTreeMap<(u8, usize), Cell> = BTreeMap::new();
1442    for (l, s) in labels.iter().zip(&ss) {
1443        let e = cells.entry((l.grade, l.check)).or_insert(([(0.0, 0.0); ROUTES], *s));
1444        e.0[l.route].0 += 1.0;
1445        e.0[l.route].1 += l.y;
1446    }
1447    let mut contrasts = Vec::new();
1448    for grade in 1..=3u8 {
1449        for (a, b) in [(ASK, FREE), (FREE, NOT)] {
1450            let units: Vec<(f64, f64, usize)> = cells
1451                .range((grade, 0)..=(grade, usize::MAX))
1452                .filter(|(_, (r, _))| r[a].0 > 0.0 && r[b].0 > 0.0)
1453                .map(|(_, (r, s))| (1.0, r[a].1 / r[a].0 - r[b].1 / r[b].0, *s))
1454                .collect();
1455            contrasts.push(Contrast { grade, routes: format!("{}−{}", ROUTE_NAMES[a], ROUTE_NAMES[b]), est: ope::snips(&units, ope::SEED) });
1456        }
1457    }
1458    Readout { due: randomised >= READOUT_UNITS || learned.len() >= READOUT_SESSIONS, randomised, sessions: learned.len(), contrasts, test: test_readout(s) }
1459}
1460
1461// --- P4: full-information recall from an evaluation -----------------------------------------------
1462
1463/// One graded check of an evaluation run: its session, channel, applies (lesson, grade) in the
1464/// model's order, and what its model call cost.
1465#[derive(Debug, Clone, PartialEq)]
1466struct EvalCheck {
1467    session: String,
1468    channel: &'static str,
1469    applies: Vec<(String, u8)>,
1470    usd: f64,
1471}
1472
1473#[derive(Debug, Clone, PartialEq)]
1474struct EvalRun {
1475    case: String,
1476    checks: Vec<EvalCheck>,
1477}
1478
1479/// A session's graded checks from its state file `ctx` (`#borg-graded n=<m> <id>:<grade>:<rank>,…`
1480/// after the call's `#borg-predict-cost`) and its cost log `cost`, whose `live usd=` line before a
1481/// check's `graded` line marks a live check. Without an aligned cost log, a check followed by a
1482/// `#borg-live` delivery is live.
1483fn eval_checks(session: &str, ctx: &str, cost: &str) -> Vec<EvalCheck> {
1484    let mut live = Vec::new();
1485    let mut seen = false;
1486    for l in cost.lines() {
1487        seen |= l.starts_with("live usd=");
1488        if l.starts_with("graded applied=") {
1489            live.push(seen);
1490            seen = false;
1491        }
1492    }
1493    let lines: Vec<&str> = ctx.lines().collect();
1494    let graded = lines.iter().filter(|l| l.starts_with("#borg-graded n=")).count();
1495    let mut out = Vec::new();
1496    let mut usd = 0.0;
1497    for (i, l) in lines.iter().enumerate() {
1498        if let Some(c) = l.strip_prefix("#borg-predict-cost ") {
1499            usd = c.trim().parse().unwrap_or(0.0);
1500            continue;
1501        }
1502        let Some(rest) = l.strip_prefix("#borg-graded n=") else { continue };
1503        let applies = rest
1504            .split_once(' ')
1505            .map_or("", |(_, items)| items.trim())
1506            .split(',')
1507            .filter_map(|item| {
1508                let mut parts = item.rsplitn(3, ':');
1509                let (rank, grade, id) = (parts.next()?, parts.next()?, parts.next()?);
1510                rank.parse::<usize>().ok()?;
1511                Some((id.to_string(), grade.parse().ok()?))
1512            })
1513            .collect();
1514        let is_live = match live.len() == graded {
1515            true => live[out.len()],
1516            false => lines[i + 1..]
1517                .iter()
1518                .take_while(|x| !x.starts_with("#borg-graded ") && !x.starts_with("#borg-predict-cost "))
1519                .any(|x| x.starts_with("#borg-live ")),
1520        };
1521        out.push(EvalCheck { session: session.into(), channel: if is_live { "live" } else { "stop" }, applies, usd });
1522        usd = 0.0;
1523    }
1524    out
1525}
1526
1527fn sorted_dir(dir: &Path) -> Vec<PathBuf> {
1528    let mut v: Vec<PathBuf> = std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).collect();
1529    v.sort();
1530    v
1531}
1532
1533/// Every run under `dir`: a directory `<case>-s<seed>` holding `borg-state`, one or two levels down
1534/// (a run set's directory, or a directory of run sets).
1535fn eval_runs(dir: &Path) -> Vec<EvalRun> {
1536    let mut found = Vec::new();
1537    for d in sorted_dir(dir) {
1538        if d.join("borg-state").is_dir() {
1539            found.push(d);
1540        } else {
1541            found.extend(sorted_dir(&d).into_iter().filter(|r| r.join("borg-state").is_dir()));
1542        }
1543    }
1544    found
1545        .into_iter()
1546        .filter_map(|run| {
1547            let name = run.file_name()?.to_string_lossy().into_owned();
1548            let case = name.rsplit_once("-s").map_or(name.as_str(), |(c, _)| c).to_string();
1549            let mut checks = Vec::new();
1550            for f in sorted_dir(&run.join("borg-state")).into_iter().filter(|f| f.extension().is_some_and(|e| e == "ctx")) {
1551                let session = f.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_default();
1552                let ctx = std::fs::read_to_string(&f).unwrap_or_default();
1553                let cost = std::fs::read_to_string(f.with_extension("cost")).unwrap_or_default();
1554                checks.extend(eval_checks(&session, &ctx, &cost));
1555            }
1556            Some(EvalRun { case, checks })
1557        })
1558        .collect()
1559}
1560
1561/// The lessons the qrels grade above 0, per case.
1562fn qrels(path: &Path) -> BTreeMap<String, BTreeSet<String>> {
1563    let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
1564    for v in std::fs::read_to_string(path).unwrap_or_default().lines().filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok()) {
1565        if let (Some(case), Some(id)) = (v["case"].as_str(), v["challenge"].as_str())
1566            && v["grade"].as_f64().unwrap_or(0.0) > 0.0
1567        {
1568            out.entry(case.into()).or_default().insert(id.into());
1569        }
1570    }
1571    out
1572}
1573
1574/// One policy's right-lesson recall (the share of runs in which a check delivers a right lesson,
1575/// expected over its draws), its change against the fixed rule (per case, case-paired bootstrap), per
1576/// check its expected questions, free deliveries and blocks at the stop, the checks at which a draw of
1577/// it routes otherwise than the fixed rule (with none it is the fixed rule, and its comparison tests
1578/// nothing) and the first of them, the runs whose recall equals the fixed rule's (`SAME`), and whether
1579/// it meets P4's recall bar (`RECALL_MARGIN`).
1580#[derive(Debug, Clone, PartialEq, Serialize)]
1581pub struct Arm {
1582    pub recall: f64,
1583    pub delta: Option<Estimate>,
1584    pub questions: f64,
1585    pub free: f64,
1586    pub blocks: f64,
1587    pub deviations: usize,
1588    pub first: Vec<String>,
1589    pub same: usize,
1590    pub pass: bool,
1591}
1592
1593/// One of P4's arms against its own bar (rules v2): P4a identity at n = 0, P4b recall under the
1594/// posterior, P4c the test keeps recall; `why` says what failed or why it tested nothing.
1595#[derive(Debug, Clone, PartialEq, Serialize)]
1596pub struct Part {
1597    pub verdict: Verdict,
1598    pub why: String,
1599    pub arm: Arm,
1600}
1601
1602#[derive(Debug, Clone, PartialEq, Serialize)]
1603pub struct P4 {
1604    pub verdict: Verdict,
1605    pub why: String,
1606    /// Cases with runs, of the cases the qrels name; runs and graded checks read.
1607    pub cases: usize,
1608    pub of: usize,
1609    pub runs: usize,
1610    pub checks: usize,
1611    /// Fewest and most runs (seeds) per case.
1612    pub seeds: (usize, usize),
1613    /// What a check's model call cost, on average: the same call under every policy.
1614    pub usd: f64,
1615    /// Of the checks, those that apply a lesson: P4a tests nothing without one, as every policy
1616    /// decides nothing there.
1617    pub applying: usize,
1618    /// The store's posterior P4b draws from (select/policy.rs `Fit::key`, empty for the prior) and the
1619    /// labels it read.
1620    pub fit: String,
1621    pub labels: u32,
1622    pub baseline: Option<Arm>,
1623    /// P4a, P4b and P4c (module doc); None until the evaluation is complete. `verdict` is theirs by
1624    /// the rules v2's default rule: PASS when P4a and P4c pass and P4b passes or is NOT TESTED, FAIL
1625    /// when one of them fails, NOT TESTED otherwise.
1626    pub p4a: Option<Part>,
1627    pub p4b: Option<Part>,
1628    pub p4c: Option<Part>,
1629}
1630
1631impl P4 {
1632    fn not_run(why: &str) -> Self {
1633        P4 {
1634            verdict: Verdict::NotRun,
1635            why: why.into(),
1636            cases: 0,
1637            of: 0,
1638            runs: 0,
1639            checks: 0,
1640            seeds: (0, 0),
1641            usd: 0.0,
1642            applying: 0,
1643            fit: String::new(),
1644            labels: 0,
1645            baseline: None,
1646            p4a: None,
1647            p4b: None,
1648            p4c: None,
1649        }
1650    }
1651}
1652
1653/// One draw of a policy's routes for a check's units, from a seed.
1654type Draw<'a> = dyn Fn(&[Unit], &EvalCheck, u64) -> Vec<Route> + 'a;
1655
1656/// What `recalls` measures of one policy on an evaluation's runs.
1657struct Recalls {
1658    /// Per run, the chance it delivers a right lesson at some check.
1659    per_run: Vec<f64>,
1660    /// Per check, expected questions, free deliveries and blocks at the stop.
1661    spend: [f64; 3],
1662    /// Checks at which some draw routes otherwise than the fixed rule, and the first `SHOW` of them.
1663    deviations: usize,
1664    first: Vec<String>,
1665}
1666
1667/// The policy `draw` on `runs` (`Recalls`). `draw` None is the fixed rule (select/policy.rs
1668/// `fixed_routes`: by position, P0's conscience.rs `graded_without` with no cap); otherwise `n` draws
1669/// of the policy seeded per check (a stand-in check id from the session and the check's place in it:
1670/// the run logged none), independent across checks. The evaluation's state lines log no `nofree`:
1671/// every check is decided with an empty had, as the hook that ran it decided (module doc).
1672fn recalls(runs: &[EvalRun], right: &BTreeMap<String, BTreeSet<String>>, draw: Option<&Draw>, n_draws: usize, lessons: &Path) -> Recalls {
1673    let none = BTreeSet::new();
1674    let prior = Summary::default();
1675    let (mut per_run, mut spend, mut n, mut deviations, mut first) = (Vec::new(), [0.0; 3], 0.0, 0, Vec::new());
1676    let names = |rs: &[Route]| rs.iter().map(|r| r.name()).collect::<Vec<_>>().join(",");
1677    for run in runs {
1678        let right = right.get(&run.case).unwrap_or(&none);
1679        let mut missed = 1.0;
1680        for (k, c) in run.checks.iter().enumerate() {
1681            let cs: Vec<Challenge> = c.applies.iter().map(|(id, _)| Challenge { id: id.clone(), ..Default::default() }).collect();
1682            let applied: Vec<(&Challenge, u8)> = cs.iter().zip(c.applies.iter().map(|(_, g)| *g)).collect();
1683            let units = super::units(&applied);
1684            let fixed = policy::fixed_routes(&units, &[]);
1685            let draws: Vec<Vec<Route>> = match draw {
1686                None => vec![fixed.clone()],
1687                Some(draw) => {
1688                    let check = super::check_id(&c.session, c.channel, k as i64, 0);
1689                    // Only the seed: the evaluation's state file logs no pool tokens.
1690                    let seed = super::seed(&Ctx {
1691                        session: &c.session,
1692                        check: &check,
1693                        channel: c.channel,
1694                        lessons,
1695                        summary: &prior,
1696                        tokens: 0,
1697                        had: &[],
1698                        alpha: policy::ALPHA,
1699                    });
1700                    let mut rng = memory::Rng::new(seed);
1701                    (0..n_draws.max(1)).map(|_| draw(&units, c, rng.next_u64())).collect()
1702                }
1703            };
1704            if let Some(off) = draws.iter().find(|d| **d != fixed) {
1705                deviations += 1;
1706                if first.len() < SHOW {
1707                    first.push(format!(
1708                        "case {} session {} check {k} ({}): {} against the fixed rule's {}",
1709                        run.case,
1710                        c.session,
1711                        c.channel,
1712                        names(off),
1713                        names(&fixed)
1714                    ));
1715                }
1716            }
1717            let share = 1.0 / draws.len() as f64;
1718            let mut hit = 0.0;
1719            for routes in &draws {
1720                let delivered = |j: usize| matches!(routes.get(j), Some(Route::Ask | Route::Free));
1721                hit += share * f64::from(u8::from((0..cs.len()).any(|j| delivered(j) && right.contains(&cs[j].id))));
1722                let asked = routes.iter().filter(|r| **r == Route::Ask).count();
1723                spend[0] += share * asked as f64;
1724                spend[1] += share * routes.iter().filter(|r| **r == Route::Free).count() as f64;
1725                spend[2] += share * f64::from(u8::from(c.channel == "stop" && asked > 0));
1726            }
1727            missed *= 1.0 - hit;
1728            n += 1.0;
1729        }
1730        per_run.push(1.0 - missed);
1731    }
1732    Recalls { per_run, spend: spend.map(|x| if n > 0.0 { x / n } else { 0.0 }), deviations, first }
1733}
1734
1735/// P4 on the runs under `dir` with the qrels at `qrels_path` (module doc): the decision rule without
1736/// the test under the n = 0 prior (select/policy.rs `prior`, P4a) and under `posterior`, the store's
1737/// fit (`evaluate`, P4b), and the test ungated (P4c).
1738fn recall(dir: &Path, qrels_path: &Path, posterior: &Fit, lessons: &Path) -> P4 {
1739    let right = qrels(qrels_path);
1740    let runs = eval_runs(dir);
1741    if right.is_empty() {
1742        return P4::not_run(&format!("no qrels in {}", qrels_path.display()));
1743    }
1744    if runs.is_empty() {
1745        return P4::not_run(&format!("no runs with graded lines under {}", dir.display()));
1746    }
1747    let prior = policy::prior();
1748    let p4 = against_baseline(
1749        &runs,
1750        &right,
1751        Arms { prior: &|u, c, _| evidence(u, c, &prior), posterior: &|u, c, _| evidence(u, c, posterior), test: &|u, c, s| tested(u, c, &prior, s) },
1752        lessons,
1753    );
1754    P4 { fit: posterior.key.clone(), labels: posterior.labels, ..p4 }
1755}
1756
1757/// P4's three arms (module doc): the decision rule without the test under the n = 0 prior (P4a) and
1758/// under the store's posterior (P4b), each deterministic (one draw per check), and the question-count
1759/// test ungated (P4c), drawn `conscience::P_DRAWS` times per check.
1760struct Arms<'a> {
1761    prior: &'a Draw<'a>,
1762    posterior: &'a Draw<'a>,
1763    test: &'a Draw<'a>,
1764}
1765
1766/// P4's comparison of its three arms (`Arms`) with the fixed rule on `runs`, each against its bar.
1767fn against_baseline(runs: &[EvalRun], right: &BTreeMap<String, BTreeSet<String>>, arms: Arms, lessons: &Path) -> P4 {
1768    let mut per_case: BTreeMap<&str, Vec<usize>> = BTreeMap::new();
1769    for (i, r) in runs.iter().enumerate() {
1770        per_case.entry(r.case.as_str()).or_default().push(i);
1771    }
1772    let checks: Vec<&EvalCheck> = runs.iter().flat_map(|r| &r.checks).collect();
1773    let seeds = per_case.values().map(Vec::len);
1774    let mut p4 = P4 {
1775        verdict: Verdict::NotRun,
1776        why: String::new(),
1777        cases: right.keys().filter(|c| per_case.contains_key(c.as_str())).count(),
1778        of: right.len(),
1779        runs: runs.len(),
1780        checks: checks.len(),
1781        seeds: (seeds.clone().min().unwrap_or(0), seeds.max().unwrap_or(0)),
1782        usd: if checks.is_empty() { 0.0 } else { checks.iter().map(|c| c.usd).sum::<f64>() / checks.len() as f64 },
1783        applying: checks.iter().filter(|c| !c.applies.is_empty()).count(),
1784        fit: String::new(),
1785        labels: 0,
1786        baseline: None,
1787        p4a: None,
1788        p4b: None,
1789        p4c: None,
1790    };
1791    let base = recalls(runs, right, None, 1, lessons);
1792    let case_mean = |v: &[f64], idx: &[usize]| idx.iter().map(|&i| v[i]).sum::<f64>() / idx.len() as f64;
1793    let mean = |v: &[f64]| v.iter().sum::<f64>() / v.len().max(1) as f64;
1794    let arm = |draw: &Draw, n: usize| {
1795        let rec = recalls(runs, right, Some(draw), n, lessons);
1796        let units: Vec<(f64, f64, usize)> =
1797            per_case.values().enumerate().map(|(k, idx)| (1.0, case_mean(&rec.per_run, idx) - case_mean(&base.per_run, idx), k)).collect();
1798        let delta = ope::snips(&units, ope::SEED);
1799        let pass = delta.value.is_some_and(|v| v >= -RECALL_MARGIN) && delta.lo > -RECALL_MARGIN;
1800        let [questions, free, blocks] = rec.spend;
1801        let same = rec.per_run.iter().zip(&base.per_run).filter(|(a, b)| (*a - *b).abs() <= SAME).count();
1802        Arm { recall: mean(&rec.per_run), delta: Some(delta), questions, free, blocks, deviations: rec.deviations, first: rec.first, same, pass }
1803    };
1804    // The decision rule draws nothing of its own (select/policy.rs `decide_on_evidence`): one draw is
1805    // its expectation. The test draws its count from the seed: `conscience::P_DRAWS` of them.
1806    let (prior, post, test) = (arm(arms.prior, 1), arm(arms.posterior, 1), arm(arms.test, conscience::P_DRAWS));
1807    // The pre-registered design is every case at the same seeds: a run still going, or a seed that
1808    // failed, leaves it incomplete.
1809    p4.verdict = match (p4.cases == p4.of, p4.seeds.0 == p4.seeds.1) {
1810        (true, true) => {
1811            let (applying, runs) = (p4.applying, p4.runs);
1812            // P4a: 0 differences from the fixed rule under the n = 0 prior.
1813            let verdict = Verdict::tested(prior.deviations == 0, applying > 0);
1814            let why = match verdict {
1815                Verdict::Fail => format!("{} of {applying} checks that apply a lesson decide otherwise than the fixed rule", prior.deviations),
1816                Verdict::NotTested => "no check applies a lesson".to_string(),
1817                _ => String::new(),
1818            };
1819            let a = Part { verdict, why, arm: prior };
1820            // P4b: P4's recall bar; NOT TESTED where it is the fixed rule.
1821            let (verdict, why) = match (post.deviations, post.pass) {
1822                (0, _) => (Verdict::NotTested, "it decides as the fixed rule at every check, so it is the fixed rule".to_string()),
1823                (_, true) => (Verdict::Pass, String::new()),
1824                (_, false) => (Verdict::Fail, format!("recall Δ {} points misses the bar", post.delta.as_ref().map_or("-".into(), |d| ci(d, 100.0)))),
1825            };
1826            let b = Part { verdict, why, arm: post };
1827            // P4c: every run's recall the fixed rule's, tested only where a draw leaves it.
1828            let verdict = Verdict::tested(test.same == runs, test.deviations > 0);
1829            let why = match verdict {
1830                Verdict::Fail => format!("{} of {runs} runs recall otherwise than the fixed rule", runs - test.same),
1831                Verdict::NotTested => "no draw leaves the fixed rule: no live check has a lesson the test may hand over or ask".to_string(),
1832                _ => String::new(),
1833            };
1834            let c = Part { verdict, why, arm: test };
1835            let unmet: Vec<String> = [("P4a", &a), ("P4b", &b), ("P4c", &c)]
1836                .iter()
1837                .filter(|(n, p)| p.verdict != Verdict::Pass && !(*n == "P4b" && p.verdict == Verdict::NotTested))
1838                .map(|(n, p)| format!("{n} {}", p.verdict.label()))
1839                .collect();
1840            let verdict = match unmet.is_empty() {
1841                true => Verdict::Pass,
1842                false if [&a, &b, &c].iter().any(|p| p.verdict == Verdict::Fail) => Verdict::Fail,
1843                false => Verdict::NotTested,
1844            };
1845            p4.why = unmet.join(", ");
1846            (p4.p4a, p4.p4b, p4.p4c) = (Some(a), Some(b), Some(c));
1847            verdict
1848        }
1849        (false, _) => {
1850            p4.why = format!("runs cover {} of the {} cases the qrels name", p4.cases, p4.of);
1851            Verdict::NotRun
1852        }
1853        (true, false) => {
1854            p4.why = format!("cases have {} to {} runs: the evaluation is incomplete", p4.seeds.0, p4.seeds.1);
1855            Verdict::NotRun
1856        }
1857    };
1858    let [questions, free, blocks] = base.spend;
1859    p4.baseline =
1860        Some(Arm { recall: mean(&base.per_run), delta: None, questions, free, blocks, deviations: 0, first: Vec::new(), same: runs.len(), pass: true });
1861    p4
1862}
1863
1864// --- The report -----------------------------------------------------------------------------------
1865
1866#[derive(Debug, Clone, PartialEq, Serialize)]
1867pub struct Checks {
1868    pub p0: P0,
1869    pub p1: P1,
1870    pub p2: P2,
1871    pub p3: P3,
1872    pub p4: P4,
1873    pub p5: P5,
1874    pub readout: Readout,
1875}
1876
1877#[derive(Debug, Clone, PartialEq, Serialize)]
1878pub struct Report {
1879    pub rules: &'static str,
1880    pub amendment: &'static str,
1881    pub rules_v2: &'static str,
1882    /// The policy this process would decide under (select.rs `policy`). The checks evaluate the
1883    /// learned policy (and P1 each record's logged policy) whatever it is.
1884    pub policy: &'static str,
1885    /// The store's selection summary as a hook would load it (select/summary.rs `load`), or rebuilt.
1886    pub summary: Summary,
1887    pub records: usize,
1888    pub graded: usize,
1889    /// Graded records whose grades are not aligned with their lessons: folded, never replayed.
1890    pub malformed: usize,
1891    /// Graded checks per policy (outcome.rs `policy_of`).
1892    pub policies: BTreeMap<String, usize>,
1893    pub checks: Option<Checks>,
1894}
1895
1896/// What to evaluate: the outcome log's text, the lessons file beside it, the summary to show, whether
1897/// to run the checks, and an evaluation for P4.
1898pub struct Input<'a> {
1899    pub text: &'a str,
1900    pub lessons: &'a Path,
1901    pub summary: Summary,
1902    pub replay: bool,
1903    pub eval: Option<(&'a Path, &'a Path)>,
1904}
1905
1906/// The state and, with `replay`, the checks P0–P5 and the readout.
1907pub fn evaluate(input: Input) -> Report {
1908    let log: Vec<Outcome> = lines(input.text).into_iter().filter_map(|l| l.o).collect();
1909    let mut policies: BTreeMap<String, usize> = BTreeMap::new();
1910    for o in log.iter().filter(|o| o.kind == outcome::GRADED) {
1911        *policies.entry(outcome::policy_of(o).to_string()).or_default() += 1;
1912    }
1913    let mut report = Report {
1914        rules: RULES,
1915        amendment: AMENDMENT,
1916        rules_v2: RULES_V2,
1917        policy: super::policy().name(),
1918        summary: input.summary,
1919        records: log.len(),
1920        graded: policies.values().sum(),
1921        malformed: 0,
1922        policies,
1923        checks: None,
1924    };
1925    if !input.replay {
1926        report.malformed = log.iter().filter(|o| o.kind == outcome::GRADED && challenges(o).is_none()).count();
1927        return report;
1928    }
1929    let pass = as_logged(input.text, input.lessons);
1930    let budget = super::budget_of(input.lessons);
1931    let (p3, targets) = cold_start(input.text, input.lessons, budget);
1932    let (labels, unjoined) = labels(&pass.checks, &log);
1933    // The store's posterior: the whole log fitted as `borg learn` fits it (summary.rs `refit`), never
1934    // the folded summary's own fit, which a fold leaves at whatever it started from.
1935    let p4 = match input.eval {
1936        Some((dir, q)) => recall(dir, q, &policy::fit(&pass.posterior, budget), input.lessons),
1937        None => P4::not_run("pass --eval RUNS_DIR --qrels FILE"),
1938    };
1939    report.malformed = pass.malformed;
1940    report.checks = Some(Checks {
1941        p2: calibration(&labels, unjoined, &|value, past, at| model(&pass.checks, past, at, value)),
1942        p5: off_policy(&pass.checks, &labels, &targets),
1943        readout: readout(&pass.checks, &labels, &pass.posterior),
1944        p0: pass.p0,
1945        p1: pass.p1,
1946        p3,
1947        p4,
1948    });
1949    report
1950}
1951
1952/// A decisive check that failed or tested nothing (`Verdict::NotTested`), by the rules v2's default
1953/// rule: P0–P3, and P4 (`P4::verdict`: P4a and P4c, and P4b failed; P4b NOT TESTED is the fixed rule
1954/// and meets it). The command then exits 1. One not run (P4 without an evaluation) is no verdict
1955/// either way.
1956pub fn unmet(r: &Report) -> bool {
1957    r.checks
1958        .as_ref()
1959        .is_some_and(|c| [c.p0.verdict, c.p1.verdict, c.p2.verdict, c.p3.verdict, c.p4.verdict].iter().any(|v| matches!(v, Verdict::Fail | Verdict::NotTested)))
1960}
1961
1962fn ci(e: &Estimate, scale: f64) -> String {
1963    match e.value {
1964        Some(v) => format!("{:+.3} [{:+.3}, {:+.3}]", v * scale, e.lo * scale, e.hi * scale),
1965        None => "-".into(),
1966    }
1967}
1968
1969fn spend(s: &Spend) -> String {
1970    let tokens = if s.tokens > 0 { format!("{} pool tokens", s.tokens) } else { "pool tokens not logged".into() };
1971    let usd = if s.usd > 0.0 { format!(", ${:.2} logged", s.usd) } else { String::new() };
1972    format!("{} checks, {} questions, {} blocks at the stop, {} free, {tokens}{usd}", s.checks, s.questions, s.blocks, s.free)
1973}
1974
1975fn arm(a: &Arm) -> String {
1976    let delta = a.delta.as_ref().map_or(String::new(), |d| format!(", Δ {} points (case-paired 95% CI)", ci(d, 100.0)));
1977    format!("recall {:.1}%{delta}; per check {:.2} questions, {:.2} free, {:.2} blocks at the stop", 100.0 * a.recall, a.questions, a.free, a.blocks)
1978}
1979
1980/// The report as text: the state, then each check with its verdict against its bar.
1981pub fn render(r: &Report) -> String {
1982    let fit = if r.summary.fit.key.is_empty() { "the prior" } else { r.summary.fit.key.as_str() };
1983    let by: Vec<String> = r.policies.iter().map(|(p, n)| format!("{n} {p}")).collect();
1984    let mut out = format!(
1985        "rules {}, amendment {}, rules v2 {} ({RULES_AT}: pre-registered checks)\npolicy: {}{}; summary v{} at byte {}, fit {fit}\nrecords: {}, graded checks: {} ({}){}\n",
1986        r.rules,
1987        r.amendment,
1988        r.rules_v2,
1989        r.policy,
1990        if r.checks.is_some() { " here, the checks replay the learned policy" } else { "" },
1991        r.summary.sv,
1992        r.summary.at,
1993        r.records,
1994        r.graded,
1995        if by.is_empty() { "none".to_string() } else { by.join(", ") },
1996        if r.malformed > 0 { format!(", {} malformed", r.malformed) } else { String::new() }
1997    );
1998    let Some(c) = &r.checks else {
1999        out.push_str("run with --replay for the pre-registered checks P0–P5\n");
2000        return out;
2001    };
2002    let list = |out: &mut String, first: &[String]| {
2003        for f in first {
2004            out.push_str(&format!("  {f}\n"));
2005        }
2006    };
2007    let empty = |n: usize, tested: &str| if n > 0 { format!("; {n} of them apply no lesson and test {tested}") } else { String::new() };
2008    out.push_str(&format!(
2009        "P0 baseline identity: {}: {} of {} checks at gate budget 0 decide as the fixed rule (conscience::graded_without) (bar: every check){}\n",
2010        c.p0.verdict.label(),
2011        c.p0.checks - c.p0.differ,
2012        c.p0.checks,
2013        empty(c.p0.empty, "nothing")
2014    ));
2015    list(&mut out, &c.p0.first);
2016    out.push_str(&format!(
2017        "P1 determinism: {}: {} of {} replayed checks reproduce their decision and propensities within {} (max |Δ| {:.4}), {} from the summary their record names{}{}; {} under an evaluation switch not replayed; incremental fold {} the whole fold\n",
2018        c.p1.verdict.label(),
2019        c.p1.reproduced,
2020        c.p1.replayed,
2021        ope::AGREE,
2022        c.p1.max_delta,
2023        c.p1.seen,
2024        empty(c.p1.empty, "only the summary and source they name"),
2025        if c.p1.tests > 0 { format!("; {} of them the question-count test's, its draw replayed", c.p1.tests) } else { String::new() },
2026        c.p1.switches,
2027        if c.p1.fold { "=" } else { "≠" }
2028    ));
2029    list(&mut out, &c.p1.first);
2030    let p2 = &c.p2;
2031    let by = if p2.verdict == Verdict::Pass && p2.pruned.is_some() { " by the pruned model" } else { "" };
2032    out.push_str(&format!("P2 calibration: {}{by}", p2.verdict.label()));
2033    if !p2.why.is_empty() {
2034        out.push_str(&format!(": {}", p2.why));
2035    }
2036    match (&p2.model, &p2.diff) {
2037        (Some(m), Some(d)) => out.push_str(&format!(
2038            ": leave-future-out log-loss model {m:.4} vs grade only {:.4}, mean difference {} (bar: upper bound ≤ {CALIBRATION})",
2039            p2.grade_only,
2040            ci(d, 1.0)
2041        )),
2042        _ => out.push_str(&format!("; grade-only leave-future-out log-loss {:.4}", p2.grade_only)),
2043    }
2044    out.push_str(&format!(
2045        " over {} judged units in {} sessions, {} with a label before their check ({} verdicts join no check)\n",
2046        p2.labels, p2.sessions, p2.informed, p2.unjoined
2047    ));
2048    if let Some(r) = &p2.pruned {
2049        out.push_str(&format!(
2050            "  pre-registered rerun, the model pruned to grade, route and dilution: log-loss {:.4} vs grade only {:.4}, mean difference {}: {}{}\n",
2051            r.model,
2052            p2.grade_only,
2053            ci(&r.diff, 1.0),
2054            r.verdict.label(),
2055            match r.verdict {
2056                Verdict::Fail => ": a second miss fails P2",
2057                Verdict::Pass => ": P2 passes on the pruned model",
2058                _ => "",
2059            }
2060        ));
2061    }
2062    let p3 = &c.p3;
2063    out.push_str(&format!(
2064        "P3 gate conduct: {}{}: cold-start replay of {} checks ({} refits, one after each session end), {} deviations from the fixed rule, first check {}, {} over the gate's budget; {}\n",
2065        p3.verdict.label(),
2066        if p3.why.is_empty() { String::new() } else { format!(" ({})", p3.why) },
2067        p3.checks,
2068        p3.refits,
2069        p3.deviations,
2070        if p3.cold { "the fixed rule" } else { "not the fixed rule" },
2071        p3.over,
2072        match p3.budget {
2073            Some(b) => format!(
2074                "the collective's budget of {b} pool tokens per session: the policy's pools spend {:.0} per session, {} it",
2075                p3.pool,
2076                if p3.pool <= b { "within" } else { "over" }
2077            ),
2078            None => format!("no budget set for the collective: spend reported, not gated; the policy's pools spend {:.0} tokens per session", p3.pool),
2079        }
2080    ));
2081    if !p3.sources.is_empty() {
2082        let by: Vec<String> = p3.sources.iter().map(|(s, n)| format!("{n} {s}")).collect();
2083        out.push_str(&format!("  decided by: {}\n", by.join(", ")));
2084    }
2085    out.push_str(&format!("  spend, policy: {}\n  spend, fixed rule: {}\n", spend(&p3.policy), spend(&p3.fixed)));
2086    list(&mut out, &p3.first);
2087    let p4 = &c.p4;
2088    out.push_str(&format!("P4 full-information recall: {}", p4.verdict.label()));
2089    if !p4.why.is_empty() {
2090        out.push_str(&format!(": {}", p4.why));
2091    }
2092    if let Some(b) = &p4.baseline {
2093        out.push_str(&format!(
2094            "\n  {} of {} cases, {} runs ({}–{} per case), {} checks ({} apply a lesson), ${:.4} per check (one model call under every policy)\n  fixed rule: {}",
2095            p4.cases,
2096            p4.of,
2097            p4.runs,
2098            p4.seeds.0,
2099            p4.seeds.1,
2100            p4.checks,
2101            p4.applying,
2102            p4.usd,
2103            arm(b)
2104        ));
2105    }
2106    let part = |out: &mut String, name: &str, bar: &str, p: &Part| {
2107        let why = if p.why.is_empty() { String::new() } else { format!(": {}", p.why) };
2108        out.push_str(&format!(
2109            "\n  {name}: {}{why} (bar: {bar})\n    {}; {} checks drawn off the fixed rule",
2110            p.verdict.label(),
2111            arm(&p.arm),
2112            p.arm.deviations
2113        ));
2114        for f in &p.arm.first {
2115            out.push_str(&format!("\n    {f}"));
2116        }
2117    };
2118    if let (Some(a), Some(b), Some(c)) = (&p4.p4a, &p4.p4b, &p4.p4c) {
2119        part(&mut out, "P4a identity at n = 0, the decision rule without the test under the n = 0 prior", "0 differences from the fixed rule", a);
2120        let bar = format!(
2121            "Δ ≥ −{0} points and lower bound > −{0}; NOT TESTED where it deviates nowhere; a pass on runs seen before is weaker evidence than a first-run pass",
2122            100.0 * RECALL_MARGIN
2123        );
2124        let name =
2125            format!("P4b recall under the store posterior (fit {}, {} labels)", if p4.fit.is_empty() { "the prior" } else { p4.fit.as_str() }, p4.labels);
2126        part(&mut out, &name, &bar, b);
2127        part(
2128            &mut out,
2129            &format!("P4c the test keeps recall, ungated on every live check ({} of {} runs recall as the fixed rule)", c.arm.same, p4.runs),
2130            "every run",
2131            c,
2132        );
2133    }
2134    out.push('\n');
2135    let p5 = &c.p5;
2136    out.push_str(&format!(
2137        "P5 off-policy: {}: {} judged units{}; change against the fixed rule per unit (DR, session 95% CI), the policy's own value (SNIPS), coverage\n",
2138        p5.verdict.label(),
2139        p5.units,
2140        if p5.inconsistent > 0 { format!(" ({} delivered by a route logged at p = 0, left out)", p5.inconsistent) } else { String::new() }
2141    ));
2142    for row in &p5.rows {
2143        out.push_str(&format!(
2144            "  {:<22} DR {:>26}  SNIPS {:>26}  coverage {:>5.1}%  ESS {:.1}\n",
2145            row.policy,
2146            ci(&row.dr, 1.0),
2147            ci(&row.ips, 1.0),
2148            100.0 * row.coverage,
2149            row.ips.ess
2150        ));
2151    }
2152    let ro = &c.readout;
2153    out.push_str(&format!(
2154        "readout: {} ({} of {READOUT_UNITS} randomised labelled units, {} of {READOUT_SESSIONS} sessions under the learned policy); the policy stays on unless the monitor fired\n",
2155        if ro.due { "due" } else { "not due" },
2156        ro.randomised,
2157        ro.sessions
2158    ));
2159    let shown: Vec<&Contrast> = ro.contrasts.iter().filter(|x| x.est.n > 0).collect();
2160    if shown.is_empty() {
2161        out.push_str("  no check has judged units of one grade on two routes yet\n");
2162    }
2163    for x in shown {
2164        out.push_str(&format!("  grade {} {}: {} over {} checks (within-check, session 95% CI)\n", x.grade, x.routes, ci(&x.est, 1.0), x.est.n));
2165    }
2166    let t = &ro.test;
2167    out.push_str(&format!(
2168        "question-count test readout (rules v2): {} ({} of {TEST_CHECKS} checks that drew a count, {} of {TEST_SESSIONS} sessions with one; {} of them the control arm, {} refused by the gate)\n",
2169        if t.due { "due" } else { "not due" },
2170        t.checks,
2171        t.sessions,
2172        t.control,
2173        t.refused
2174    ));
2175    if t.due {
2176        out.push_str(&format!("  estimated over the {} drawn checks the summary still holds (compaction drops the oldest, never the counts)\n", t.kept));
2177    }
2178    for (m, e) in &t.by_asked {
2179        out.push_str(&format!(
2180            "  dilution, {m} asked − 1 asked: the test's top lesson's change rate {} over {} checks with k ≥ {m} (Horvitz–Thompson by the uniform draw, session 95% CI)\n",
2181            ci(e, 1.0),
2182            e.n
2183        ));
2184    }
2185    if let Some(e) = &t.ask_free {
2186        out.push_str(&format!("  grade 2 asked − handed over: {} over {} 2s (Horvitz–Thompson by the logged propensities, session 95% CI)\n", ci(e, 1.0), e.n));
2187    }
2188    out
2189}
2190
2191/// `borg debug select …` (module doc): the store of the collective DIR routes to (the working directory
2192/// by default), or one outcomes file alone. Exits 1 when a decisive check fails or tests nothing
2193/// (`unmet`), 2 on bad usage.
2194/// The hook's budget for selection after its model call, in ms at the 95th percentile. Guard: what
2195/// the shortest harness limit leaves beside the call (omp's 30 s stop with its 18 s call; codex's 10 s
2196/// tool hook), with room to spare; `--bench` exits 1 past it.
2197pub const BENCH_MS: f64 = 50.0;
2198
2199/// Milliseconds of one part of the hook's selection over the log's checks.
2200#[derive(Debug, Clone, Default, Serialize)]
2201pub struct Times {
2202    pub p50: f64,
2203    pub p95: f64,
2204    pub max: f64,
2205}
2206
2207impl Times {
2208    fn of(mut ms: Vec<f64>) -> Times {
2209        ms.sort_by(f64::total_cmp);
2210        let at = |q: f64| ms.get(((q * ms.len() as f64).ceil() as usize).saturating_sub(1)).copied().unwrap_or(0.0);
2211        Times { p50: at(0.5), p95: at(0.95), max: ms.last().copied().unwrap_or(0.0) }
2212    }
2213}
2214
2215/// `borg debug select --bench`: per graded check of the log that applies a lesson, the time the hook
2216/// spends selecting after its model call. `load` is select/summary.rs `refresh` of a cache that holds the
2217/// whole log, as a hook finds it; `decide` is select.rs `graded_under` under the learned policy with the
2218/// log's fit and its gate open (allowance and ledger set), so every path a check can take runs: the
2219/// evidence test over the joint draws, the question-count test's admission. The worst case, not the
2220/// store's state.
2221#[derive(Debug, Clone, Default, Serialize)]
2222pub struct Bench {
2223    pub checks: usize,
2224    pub load: Times,
2225    pub decide: Times,
2226    pub total: Times,
2227    /// Whether the fit had a model: without one the decision is the fixed rule's and costs nothing.
2228    pub model: bool,
2229}
2230
2231impl Bench {
2232    fn line(&self) -> String {
2233        let t = |x: &Times| format!("p50 {:.1} ms, p95 {:.1} ms, max {:.1} ms", x.p50, x.p95, x.max);
2234        let verdict = if self.total.p95 < BENCH_MS { "within" } else { "OVER" };
2235        let model = if self.model { "" } else { " (no model fitted: the fixed rule decides)" };
2236        format!(
2237            "selection cost per check, {} checks{model}\n  load    {}\n  decide  {}\n  total   {}: {verdict} the {BENCH_MS} ms budget\n",
2238            self.checks,
2239            t(&self.load),
2240            t(&self.decide),
2241            t(&self.total)
2242        )
2243    }
2244}
2245
2246/// `Bench` of `text` (the outcome log beside `lessons`): a copy of it with its refitted summary cached,
2247/// in a temp store, so nothing of the store is written.
2248fn bench(text: &str, lessons: &Path) -> Bench {
2249    let store = std::env::temp_dir().join(format!("borg-select-bench-{}", std::process::id()));
2250    let _ = std::fs::remove_dir_all(&store);
2251    if std::fs::create_dir_all(&store).is_err() {
2252        return Bench::default();
2253    }
2254    let at = store.join("lessons.jsonl");
2255    let mut s = summary::with_fit(summary::fold(text, Summary::default()), super::budget_of(lessons));
2256    // The gate open: what a check can risk is never the bound, and the ledger has its draws.
2257    s.gate.allowance = f64::MAX / 4.0;
2258    if s.gate.gain.len() != policy::DRAWS {
2259        s.gate.gain = vec![0.0; policy::DRAWS];
2260    }
2261    let saved = std::fs::write(outcome::path_beside(&at), text).is_ok() && summary::save(&at, &s).is_ok();
2262    let model = s.fit.model.is_some();
2263    let (mut load, mut decide, mut total) = (Vec::new(), Vec::new(), Vec::new());
2264    for o in lines(text).into_iter().filter_map(|l| l.o).filter(|o| o.kind == outcome::GRADED && !o.lessons.is_empty()) {
2265        let Some(cs) = challenges(&o) else { continue };
2266        if !saved {
2267            break;
2268        }
2269        let applied = applied(&cs, &o);
2270        let check = Check::new(o, &applied);
2271        let t0 = std::time::Instant::now();
2272        let s = summary::refresh(&at);
2273        let t1 = std::time::Instant::now();
2274        let r = super::graded_under(Policy::Learned, &applied, &ctx(&check.o, &check.had, &at, &s));
2275        let t2 = std::time::Instant::now();
2276        std::hint::black_box(r);
2277        let ms = |d: std::time::Duration| d.as_secs_f64() * 1000.0;
2278        load.push(ms(t1 - t0));
2279        decide.push(ms(t2 - t1));
2280        total.push(ms(t2 - t0));
2281    }
2282    let _ = std::fs::remove_dir_all(&store);
2283    Bench { checks: total.len(), load: Times::of(load), decide: Times::of(decide), total: Times::of(total), model }
2284}
2285
2286pub fn main(args: &[&str]) -> i32 {
2287    let usage = || {
2288        eprintln!(
2289            "usage: borg debug select [--replay | --bench] [--rebuild] [--dir DIR | --file OUTCOMES.jsonl] [--json] [--eval RUNS_DIR --qrels QRELS.jsonl]"
2290        );
2291        2
2292    };
2293    let (mut replay, mut rebuild, mut json, mut timed) = (false, false, false, false);
2294    let (mut dir, mut file, mut eval, mut qrels_path): (Option<&str>, Option<&str>, Option<&str>, Option<&str>) = (None, None, None, None);
2295    let mut it = args.iter();
2296    while let Some(a) = it.next() {
2297        let slot = match *a {
2298            "--replay" => {
2299                replay = true;
2300                continue;
2301            }
2302            "--rebuild" => {
2303                rebuild = true;
2304                continue;
2305            }
2306            "--json" => {
2307                json = true;
2308                continue;
2309            }
2310            "--bench" => {
2311                timed = true;
2312                continue;
2313            }
2314            "--dir" if file.is_none() => &mut dir,
2315            "--file" if dir.is_none() => &mut file,
2316            "--eval" => &mut eval,
2317            "--qrels" => &mut qrels_path,
2318            _ => return usage(),
2319        };
2320        match (slot.is_none(), it.next()) {
2321            (true, Some(v)) => *slot = Some(v),
2322            _ => return usage(),
2323        }
2324    }
2325    if eval.is_some() != qrels_path.is_some() {
2326        return usage();
2327    }
2328    let (source, lessons): (String, PathBuf) = match file {
2329        Some(f) => (format!("file {f}"), Path::new(f).with_file_name("lessons.jsonl")),
2330        None => {
2331            let cwd = dir.map_or_else(|| std::env::current_dir().unwrap_or_default().display().to_string(), str::to_string);
2332            match collective::load().map(|cfg| collective::route(cfg.as_ref(), &cwd, &learn::home())) {
2333                Ok(collective::Route::Collective { name, home, .. }) => (format!("collective {name} ({})", home.display()), home.join("lessons.jsonl")),
2334                Ok(collective::Route::Off) => {
2335                    println!("off: {cwd} belongs to no collective; no outcomes are kept here");
2336                    return 0;
2337                }
2338                Err(e) => {
2339                    eprintln!("borg debug select: invalid collectives config ({e}); everything is off");
2340                    return 1;
2341                }
2342            }
2343        }
2344    };
2345    let outcomes = file.map_or_else(|| outcome::path_beside(&lessons), PathBuf::from);
2346    let text = std::fs::read_to_string(&outcomes).unwrap_or_default();
2347    if timed {
2348        let b = bench(&text, &lessons);
2349        match json {
2350            true => println!("{}", serde_json::json!({ "source": source, "bench": b })),
2351            false => print!("{source}\n{}", b.line()),
2352        }
2353        return i32::from(b.total.p95 >= BENCH_MS);
2354    }
2355    // A file alone has no store whose cache a hook would load: its summary is the file folded.
2356    let summary = match (file, rebuild) {
2357        (Some(_), _) => summary::fold(&text, Summary::default()),
2358        (None, true) => summary::rebuild(&lessons),
2359        (None, false) => summary::load(&lessons),
2360    };
2361    let report = evaluate(Input {
2362        text: &text,
2363        lessons: &lessons,
2364        summary,
2365        replay: replay || eval.is_some(),
2366        eval: eval.zip(qrels_path).map(|(e, q)| (Path::new(e), Path::new(q))),
2367    });
2368    match json {
2369        true => println!("{}", serde_json::json!({ "source": source, "report": report })),
2370        false => print!("{source}\n{}", render(&report)),
2371    }
2372    i32::from(unmet(&report))
2373}
2374
2375#[cfg(test)]
2376mod tests {
2377    use super::*;
2378
2379    fn graded(session: &str, ms: i64, lessons: &[&str], grades: &[u8]) -> Outcome {
2380        let cs: Vec<Challenge> = lessons.iter().map(|id| Challenge { id: id.to_string(), ..Default::default() }).collect();
2381        let applied: Vec<(&Challenge, u8)> = cs.iter().zip(grades.iter().copied()).collect();
2382        let (ask, _) = conscience::graded_capped(&applied, None);
2383        Outcome {
2384            kind: outcome::GRADED.into(),
2385            session: session.into(),
2386            lessons: lessons.iter().map(|l| l.to_string()).collect(),
2387            ms,
2388            repo: "r".into(),
2389            channel: "live".into(),
2390            grades: grades.to_vec(),
2391            ranks: (0..lessons.len() as u16).collect(),
2392            applied: lessons.len() as u16,
2393            chosen: ids(&ask),
2394            p: holds(&lessons.iter().map(|l| l.to_string()).collect::<Vec<_>>(), &ids(&ask)),
2395            ..Default::default()
2396        }
2397    }
2398
2399    fn result(kind: &str, session: &str, lesson: &str, ms: i64, channel: &str) -> Outcome {
2400        Outcome {
2401            kind: kind.into(),
2402            session: session.into(),
2403            lessons: vec![lesson.into()],
2404            ms,
2405            repo: "r".into(),
2406            channel: channel.into(),
2407            ..Default::default()
2408        }
2409    }
2410
2411    fn text(log: &[Outcome]) -> String {
2412        log.iter().map(|o| format!("{}\n", serde_json::to_string(o).unwrap())).collect()
2413    }
2414
2415    fn checks_of(log: &[Outcome]) -> Vec<Check> {
2416        as_logged(&text(log), Path::new("/nonexistent/lessons.jsonl")).checks
2417    }
2418
2419    #[test]
2420    fn the_bench_reports_nearest_rank_percentiles() {
2421        let t = Times::of((1..=20).rev().map(f64::from).collect());
2422        assert_eq!((t.p50, t.p95, t.max), (10.0, 19.0, 20.0));
2423        assert_eq!((Times::of(Vec::new()).p95, Times::of(vec![4.0]).p95), (0.0, 4.0));
2424    }
2425
2426    #[test]
2427    fn a_fixed_log_reproduces_and_a_changed_decision_fails_p0_and_p1() {
2428        let log = [graded("s", 1, &["A", "B"], &[3, 1]), graded("s", 2, &["C", "D"], &[2, 1]), result(outcome::CHANGED, "s", "A", 3, "live")];
2429        let pass = as_logged(&text(&log), Path::new("/nonexistent/lessons.jsonl"));
2430        assert_eq!((pass.p0.verdict, pass.p0.checks, pass.p0.differ), (Verdict::Pass, 2, 0));
2431        assert_eq!((pass.p1.verdict, pass.p1.replayed, pass.p1.reproduced, pass.p1.max_delta), (Verdict::Pass, 2, 2, 0.0));
2432        assert!(pass.p1.fold);
2433        // The second check logged only one of its free lessons: the fixed rule hands over both.
2434        let mut other = log.clone();
2435        other[1].policy = "fixed".into();
2436        other[1].free = vec!["C".into()];
2437        other[1].pf = vec![1.0, 0.0];
2438        let pass = as_logged(&text(&other), Path::new("/nonexistent/lessons.jsonl"));
2439        assert_eq!((pass.p0.verdict, pass.p0.differ), (Verdict::Fail, 1), "{:?}", pass.p0.first);
2440        assert_eq!((pass.p1.verdict, pass.p1.reproduced), (Verdict::Fail, 1));
2441        assert!(pass.p1.max_delta >= 1.0 && pass.p1.first[0].contains("check - ms 2"), "{:?}", pass.p1);
2442        // Under an evaluation switch: counted, not replayed.
2443        let mut cut = log.clone();
2444        cut[0].policy = "cap".into();
2445        let pass = as_logged(&text(&cut), Path::new("/nonexistent/lessons.jsonl"));
2446        assert_eq!((pass.p1.replayed, pass.p1.switches), (1, 1));
2447    }
2448
2449    /// P0 and P1 are NOT TESTED, never a pass, when no check they replay applies a lesson: every policy
2450    /// decides nothing on a check none applied to or a failed call, so the comparison cannot fail on
2451    /// the policy. One check with an apply tests both; P1 alone is NOT TESTED when every check ran under
2452    /// an evaluation switch.
2453    #[test]
2454    fn p0_and_p1_on_checks_that_decide_nothing_are_not_tested() {
2455        let none = Path::new("/nonexistent/lessons.jsonl");
2456        let pass = as_logged(&text(&[result(outcome::CHANGED, "s", "A", 1, "live")]), none);
2457        assert_eq!((pass.p0.verdict, pass.p0.checks, pass.p1.verdict, pass.p1.replayed), (Verdict::NotTested, 0, Verdict::NotTested, 0));
2458        // A check none applied to, and a failed learned call at the stop.
2459        let failed = Outcome {
2460            failed: true,
2461            policy: "learned".into(),
2462            check: crate::select::check_id("s", "stop", 3, 1),
2463            channel: "stop".into(),
2464            ..graded("s", 3, &[], &[])
2465        };
2466        let mut log = vec![graded("s", 2, &[], &[]), failed, result(outcome::CHANGED, "s", "A", 4, "live")];
2467        let pass = as_logged(&text(&log), none);
2468        assert_eq!((pass.p0.verdict, pass.p0.checks, pass.p0.empty, pass.p0.differ), (Verdict::NotTested, 2, 2, 0), "{:?}", pass.p0);
2469        assert_eq!((pass.p1.verdict, pass.p1.replayed, pass.p1.reproduced, pass.p1.empty), (Verdict::NotTested, 2, 2, 2), "{:?}", pass.p1);
2470        // The command fails on P0 or P1 NOT TESTED alone, the other checks passing.
2471        let mut report = evaluate(Input { text: &text(&log), lessons: none, summary: Summary::default(), replay: true, eval: None });
2472        let c = report.checks.as_mut().unwrap();
2473        assert_eq!((c.p0.verdict, c.p1.verdict), (Verdict::NotTested, Verdict::NotTested));
2474        (c.p1.verdict, c.p2.verdict, c.p3.verdict, c.p4.verdict) = (Verdict::Pass, Verdict::Pass, Verdict::Pass, Verdict::NotRun);
2475        assert!(unmet(&report));
2476        // One check with an apply: both tested, the others still counted and named.
2477        log.push(graded("s", 5, &["A", "B"], &[3, 1]));
2478        let pass = as_logged(&text(&log), none);
2479        assert_eq!((pass.p0.verdict, pass.p0.checks, pass.p0.empty), (Verdict::Pass, 3, 2), "{:?}", pass.p0);
2480        assert_eq!((pass.p1.verdict, pass.p1.replayed, pass.p1.empty), (Verdict::Pass, 3, 2), "{:?}", pass.p1);
2481        let shown = render(&evaluate(Input { text: &text(&log), lessons: none, summary: Summary::default(), replay: true, eval: None }));
2482        assert!(shown.contains("(bar: every check); 2 of them apply no lesson and test nothing\n"), "{shown}");
2483        assert!(shown.contains("their record names; 2 of them apply no lesson and test only the summary and source they name;"), "{shown}");
2484        // Every check under an evaluation switch: P0 decides them, P1 replays none.
2485        let cut = [Outcome { policy: "cap".into(), ..graded("s", 6, &["A"], &[2]) }];
2486        let pass = as_logged(&text(&cut), none);
2487        assert_eq!((pass.p0.verdict, pass.p0.checks), (Verdict::Pass, 1), "{:?}", pass.p0);
2488        assert_eq!((pass.p1.verdict, pass.p1.replayed, pass.p1.switches), (Verdict::NotTested, 0, 1), "{:?}", pass.p1);
2489    }
2490
2491    /// P1 replays a learned decision from the summary its record names (`seen`): the hook read it
2492    /// before its model call, so a record another check appended meanwhile lies before this one but not
2493    /// in it, and that record's entry on the gate's ledger must not count. The revert it logged
2494    /// (`source`) counts too: the sticky mark beside the store is in no log line.
2495    #[test]
2496    fn p1_replays_each_decision_from_the_summary_its_record_names() {
2497        let none = Path::new("/nonexistent/lessons.jsonl");
2498        let mut log = labelled(6, 12, 11);
2499        let fitted = summary::with_fit(summary::fold(&text(&log), Summary::default()), None);
2500        assert!(fitted.fit.model.is_some() && fitted.gate.allowance == 0.0, "a model, and no learned check on its ledger: {:?}", fitted.gate);
2501        // A hook's decision on the summary `s` it read under the collective's tolerance `alpha` (hook.rs
2502        // `decide`), logged as hook.rs `record_graded` logs it.
2503        let decide_at = |o: Outcome, s: &Summary, alpha: f64| {
2504            let cs = challenges(&o).unwrap();
2505            let r = crate::select::graded_under(Policy::Learned, &applied(&cs, &o), &Ctx { alpha, ..ctx(&o, &had_of(&o), none, s) });
2506            let round = |v: &[f64]| v.iter().map(|p| outcome::round_p(*p)).collect();
2507            Outcome {
2508                chosen: ids(&r.ask),
2509                free: ids(&r.free),
2510                placebo: ids(&r.placebo),
2511                p: round(&r.p),
2512                pf: round(&r.pf),
2513                psi: r.log.psi,
2514                policy: r.log.policy.into(),
2515                fit: r.log.fit.clone(),
2516                seen: s.key(),
2517                source: r.log.source.into(),
2518                xk: r.log.xk,
2519                xs: r.log.xs,
2520                alpha: r.log.alpha,
2521                ..o
2522            }
2523        };
2524        let decide = |o: Outcome, s: &Summary| decide_at(o, s, policy::ALPHA);
2525        let check =
2526            |ms: i64, lessons: &[&str], grades: &[u8]| Outcome { check: crate::select::check_id("t", "live", ms, 1), ..graded("t", ms, lessons, grades) };
2527        // x and b read the refit; a reads it after x; then x's, a's and b's records land in that order.
2528        let x = decide(check(100_001, &["L1", "L2", "L3"], &[2, 1, 2]), &fitted);
2529        let after_x = summary::fold(&text(std::slice::from_ref(&x)), fitted.clone());
2530        assert!(after_x.gate.allowance > 0.0, "x's check gives the gate a budget b never read: {:?}", after_x.gate);
2531        let a = decide(check(100_002, &["L4", "L5"], &[1, 2]), &after_x);
2532        let b = decide(check(100_003, &["L6", "L7", "L8"], &[1, 2, 1]), &fitted);
2533        assert_eq!((a.seen != b.seen, b.source.as_str()), (true, "fixed"));
2534        // c reads all three, the store reverted by the mark beside it.
2535        let mut reverted = summary::fold(&text(&[x.clone(), a.clone(), b.clone()]), fitted.clone());
2536        reverted.monitor.reverted = true;
2537        let c = decide(check(100_004, &["L9", "L10"], &[2, 2]), &reverted);
2538        assert_eq!(c.source, crate::select::REVERTED_SOURCE);
2539        log.extend([x, a, b, c]);
2540        let pass = as_logged(&text(&log), none);
2541        assert_eq!((pass.p1.verdict, pass.p1.reproduced, pass.p1.seen), (Verdict::Pass, pass.p1.replayed, 4), "{:?}", pass.p1.first);
2542        // a's hook under a collective's `risk` 0, which the replay's path maps to no collective: the
2543        // record's α decides, not the config's then (c goes: a's other line would change c's summary).
2544        let a_at = log.len() - 3;
2545        assert!(log[a_at].xk.is_some(), "at the default α a is tested: {:?}", log[a_at]);
2546        let mut off = log[..log.len() - 1].to_vec();
2547        off[a_at] = decide_at(check(100_002, &["L4", "L5"], &[1, 2]), &after_x, 0.0);
2548        assert_eq!((off[a_at].alpha, off[a_at].xk), (Some(0.0), None), "{:?}", off[a_at]);
2549        let pass = as_logged(&text(&off), none);
2550        assert_eq!((pass.p1.verdict, pass.p1.reproduced), (Verdict::Pass, pass.p1.replayed), "{:?}", pass.p1.first);
2551        // Without the α on its record, it replays at the default and is not the decision its hook made.
2552        off[a_at].alpha = None;
2553        let pass = as_logged(&text(&off), none);
2554        assert_eq!((pass.p1.verdict, pass.p1.reproduced + 1), (Verdict::Fail, pass.p1.replayed), "{:?}", pass.p1.first);
2555        // The question-count test's draw (k, s) is the check's seed's too: a record logging another s, its
2556        // routes and propensities unchanged, is not the decision its hook made (c goes: a's other line
2557        // would change the summary c's record names).
2558        let mut drawn = log[..log.len() - 1].to_vec();
2559        let a_at = drawn.len() - 2;
2560        drawn[a_at].xs = Some(drawn[a_at].xs.map_or(1, |s| s + 1));
2561        let pass = as_logged(&text(&drawn), none);
2562        assert_eq!((pass.p1.verdict, pass.p1.reproduced + 1), (Verdict::Fail, pass.p1.replayed), "{:?}", pass.p1.first);
2563        assert!(pass.p1.first[0].contains("ms 100002") && pass.p1.first[0].contains(" s "), "{:?}", pass.p1.first);
2564        // Replayed on every line before it instead, b's decision is not the one its hook made (c goes:
2565        // b's shorter line would move the byte c's summary names).
2566        log.pop();
2567        let b_at = log.len() - 1;
2568        log[b_at].seen.clear();
2569        let pass = as_logged(&text(&log), none);
2570        assert_eq!((pass.p1.verdict, pass.p1.reproduced + 1), (Verdict::Fail, pass.p1.replayed), "{:?}", pass.p1.first);
2571        assert!(pass.p1.first[0].contains("ms 100003") && pass.p1.first[0].contains("by fixed"), "{:?}", pass.p1.first);
2572        // A summary the log does not hold at the byte it names is not replayed on another.
2573        log[b_at].seen = format!("{}-00000000", log[b_at].fit.split('-').next().unwrap());
2574        let pass = as_logged(&text(&log), none);
2575        assert!(pass.p1.first.iter().any(|m| m.contains("ms 100003") && m.contains("no summary")), "{:?}", pass.p1.first);
2576    }
2577
2578    #[test]
2579    fn verdicts_join_the_check_that_routed_their_delivery() {
2580        let mut log = vec![
2581            graded("s", 10, &["A", "B"], &[3, 1]), // asks A and B
2582            graded("s", 20, &["A", "C"], &[2, 1]), // hands A and C over free
2583            result(outcome::CHANGED, "s", "A", 25, "live"),
2584            result(outcome::CHANGED, "s", "A", 26, "queued"),
2585            result(outcome::IGNORED, "s", "C", 27, "queued"),
2586            result(outcome::CHANGED, "s", "B", 28, "early"),
2587            result(outcome::NOT_CORRECTED, "s", "B", 29, ""),
2588            result(outcome::CHANGED, "t", "Z", 30, "live"),
2589        ];
2590        let checks = checks_of(&log);
2591        let (ls, unjoined) = labels(&checks, &log);
2592        let got: Vec<(usize, usize, usize, f64)> = ls.iter().map(|l| (l.check, l.j, l.route, l.y)).collect();
2593        assert_eq!(got, [(0, 0, ASK, 1.0), (1, 0, FREE, 1.0), (1, 1, FREE, 0.0)], "early and censored results label nothing");
2594        assert_eq!(unjoined, 1, "Z was graded by no check");
2595        assert_eq!(ls[1].mu, [0.0, 1.0, 0.0]);
2596        // A veto after the check outranks the change; one before it does not.
2597        log.push(result(outcome::VETOED, "s", "A", 21, ""));
2598        let (ls, _) = labels(&checks, &log);
2599        assert_eq!(ls.iter().map(|l| l.y).collect::<Vec<_>>(), [0.0, 0.0, 0.0]);
2600        log.pop();
2601        log.push(result(outcome::VETOED, "s", "A", 5, ""));
2602        assert_eq!(labels(&checks, &log).0[0].y, 1.0);
2603        // A check id joins whatever the times.
2604        let mut a = graded("s", 100, &["Q"], &[3]);
2605        a.check = "abcdef012345".into();
2606        let late = Outcome { check: "abcdef012345".into(), ..result(outcome::CHANGED, "s", "Q", 50, "stop") };
2607        let log = [a, late];
2608        assert_eq!(labels(&checks_of(&log), &log).0.len(), 1);
2609        // The fixed rule's placebo: a leftover judged blindly joins its check as not delivered, at the
2610        // fixed rule's route probabilities; a verdict on the route it did not take joins nothing.
2611        let lessons: Vec<String> = (0..11).map(|i| format!("L{i}")).collect();
2612        let mut f = graded("s", 200, &lessons.iter().map(String::as_str).collect::<Vec<_>>(), &[1; 11]);
2613        (f.check, f.policy, f.placebo, f.psi) = ("0123456789ab".into(), "fixed".into(), vec!["L10".into()], 0.5);
2614        f.free = lessons[..10].to_vec();
2615        f.pf = holds(&f.lessons, &f.free);
2616        let blind = Outcome { check: "0123456789ab".into(), ..result(outcome::CHANGED, "s", "L10", 210, outcome::PLACEBO) };
2617        let wrong = Outcome { check: "0123456789ab".into(), ..result(outcome::CHANGED, "s", "L10", 211, "queued") };
2618        let log = [f, blind, wrong];
2619        let (ls, unjoined) = labels(&checks_of(&log), &log);
2620        assert_eq!((ls.len(), unjoined), (1, 1));
2621        // Its chance of a label is the draw's: routed nowhere (1) and drawn as a placebo (ψ).
2622        assert_eq!((ls[0].j, ls[0].route, ls[0].mu, ls[0].y), (10, NOT, [0.0, 0.0, 0.5], 1.0));
2623    }
2624
2625    /// Each unit is predicted from the results before its check: a result arriving later moves no
2626    /// earlier prediction, one before it does.
2627    #[test]
2628    fn predictions_are_leak_free() {
2629        let unit = |check_ms: i64, result_ms: i64, y: f64| Label {
2630            check: 0,
2631            j: 0,
2632            grade: 1,
2633            route: ASK,
2634            mu: [1.0, 0.0, 0.0],
2635            y,
2636            session: "s".into(),
2637            check_ms,
2638            known: vec![(result_ms, y)],
2639            judge: 2,
2640        };
2641        let early = vec![unit(10, 50, 1.0), unit(20, 60, 1.0)];
2642        let p = |ls: &[Label]| past_counts(ls).iter().zip(ls).map(|(c, l)| by_grade(c, l.grade)).collect::<Vec<_>>();
2643        assert_eq!(p(&early), [0.5, 0.5], "no result before either check");
2644        let mut later = early.clone();
2645        later.push(unit(100, 110, 1.0));
2646        assert_eq!(&p(&later)[..2], &[0.5, 0.5], "the future moves nothing");
2647        assert_eq!(p(&later)[2], beta(2, 2), "both results came before it");
2648        let mut before = early.clone();
2649        before.push(unit(1, 5, 1.0));
2650        assert_eq!(&p(&before)[..2], &[beta(1, 1), beta(1, 1)], "a result before both checks moves both");
2651    }
2652
2653    fn world(n: usize, free_better: bool) -> Vec<Label> {
2654        // Grade-1 units, randomised: asked or free with probability 1/2, in 2-unit checks per session.
2655        (0..n)
2656            .map(|i| {
2657                let route = if i % 2 == 0 { ASK } else { FREE };
2658                let changed = if route == FREE { i % 10 != 1 } else { i % 10 == 0 };
2659                let y = f64::from(u8::from(changed == free_better));
2660                Label {
2661                    check: i / 2,
2662                    j: i % 2,
2663                    grade: 1,
2664                    route,
2665                    mu: [0.5, 0.5, 0.0],
2666                    y,
2667                    session: format!("s{}", i / 4),
2668                    check_ms: 10 * (i as i64 / 2),
2669                    known: vec![(10 * (i as i64 / 2) + 5, y)],
2670                    judge: 2,
2671                }
2672            })
2673            .collect()
2674    }
2675
2676    /// A predictor that ignores what it was fitted on.
2677    fn fixed_p<'a>(f: impl Fn(&Label) -> f64 + 'a) -> Option<Predictor<'a>> {
2678        Some(Box::new(f))
2679    }
2680
2681    /// Knowing the route, in the world where free changes and asked does not.
2682    fn by_route(l: &Label) -> f64 {
2683        if l.route == FREE { 0.85 } else { 0.15 }
2684    }
2685
2686    /// The route backwards.
2687    fn backwards(l: &Label) -> f64 {
2688        1.0 - by_route(l)
2689    }
2690
2691    #[test]
2692    fn calibration_passes_a_model_no_worse_than_grade_only_and_fails_a_worse_one() {
2693        let ls = world(80, true);
2694        let none = calibration(&ls, 0, &|_, _, _| None);
2695        assert_eq!((none.verdict, none.labels, none.sessions), (Verdict::NotRun, 80, 20));
2696        assert!(none.why.contains("no value model") && none.grade_only > 0.0);
2697        // The grade-only model itself: difference 0. Every check of this world has one change and one
2698        // not, so grade only says 1/2 throughout, and so does its copy: not tested.
2699        let grade_only = |_, past: &[&Label], at| {
2700            let mut c: Counts = [[(0, 0); ROUTES]; GRADES];
2701            for (l, (_, y)) in past.iter().filter_map(|l| l.at(at).map(|k| (l, k))) {
2702                c[usize::from(l.grade)][l.route].0 += 1;
2703                c[usize::from(l.grade)][l.route].1 += u32::from(y > 0.5);
2704            }
2705            fixed_p(move |l: &Label| by_grade(&c, l.grade))
2706        };
2707        assert_eq!(calibration(&ls, 0, &grade_only).verdict, Verdict::NotTested);
2708        // Two changes in three: grade only learns, and its copy is no worse.
2709        let tilted: Vec<Label> = ls
2710            .iter()
2711            .enumerate()
2712            .map(|(i, l)| {
2713                let y = f64::from(u8::from(i % 3 != 0));
2714                Label { y, known: vec![(l.known[0].0, y)], ..l.clone() }
2715            })
2716            .collect();
2717        let same = calibration(&tilted, 0, &grade_only);
2718        assert_eq!(same.verdict, Verdict::Pass, "{same:?}");
2719        assert!(same.diff.as_ref().is_some_and(|d| d.value == Some(0.0)) && same.pruned.is_none(), "a pass is not rerun");
2720        let route = calibration(&ls, 0, &|_, _, _| fixed_p(by_route));
2721        assert_eq!(route.verdict, Verdict::Pass);
2722        assert!(route.diff.as_ref().is_some_and(|d| d.hi < 0.0), "{route:?}");
2723        // The route backwards is worse, and P2 says so; the pruned rerun misses again.
2724        let wrong = calibration(&ls, 0, &|_, _, _| fixed_p(backwards));
2725        assert_eq!(wrong.verdict, Verdict::Fail, "{wrong:?}");
2726        assert!(wrong.pruned.as_ref().is_some_and(|r| r.verdict == Verdict::Fail), "a second miss fails P2: {wrong:?}");
2727    }
2728
2729    /// P2's pre-registered rerun: after the value model's FAIL, the pruned model is fitted and compared
2730    /// once, and its verdict is P2's; the value model's numbers stay reported beside it.
2731    #[test]
2732    fn a_failed_calibration_reruns_once_with_the_pruned_model() {
2733        let ls = world(80, true);
2734        let asked = std::cell::RefCell::new(Vec::new());
2735        let p2 = calibration(&ls, 0, &|value, _, _| {
2736            asked.borrow_mut().push(value);
2737            if value == Value::Full { fixed_p(backwards) } else { fixed_p(by_route) }
2738        });
2739        assert_eq!((p2.verdict, p2.pruned.as_ref().map(|r| r.verdict)), (Verdict::Pass, Some(Verdict::Pass)), "{p2:?}");
2740        assert!(p2.diff.as_ref().is_some_and(|d| d.hi > CALIBRATION), "the full model's miss is kept: {p2:?}");
2741        assert!(p2.pruned.as_ref().is_some_and(|r| r.diff.hi < 0.0 && r.model < p2.grade_only), "{p2:?}");
2742        let asked = asked.into_inner();
2743        let first_pruned = asked.iter().position(|v| *v == Value::Pruned);
2744        assert!(
2745            first_pruned.is_some_and(|i| asked[..i].iter().all(|v| *v == Value::Full) && asked[i..].iter().all(|v| *v == Value::Pruned)),
2746            "the full model, then the rerun once: {asked:?}"
2747        );
2748        let text = render(&Report {
2749            rules: RULES,
2750            amendment: AMENDMENT,
2751            rules_v2: RULES_V2,
2752            policy: "fixed",
2753            summary: Summary::default(),
2754            records: 0,
2755            graded: 0,
2756            malformed: 0,
2757            policies: BTreeMap::new(),
2758            checks: Some(Checks {
2759                p0: P0 { verdict: Verdict::Pass, checks: 1, empty: 0, differ: 0, first: Vec::new() },
2760                p1: P1 {
2761                    verdict: Verdict::Pass,
2762                    replayed: 1,
2763                    reproduced: 1,
2764                    empty: 0,
2765                    seen: 0,
2766                    tests: 0,
2767                    switches: 0,
2768                    max_delta: 0.0,
2769                    fold: true,
2770                    first: Vec::new(),
2771                },
2772                p2,
2773                p3: conduct(&[], Spend::default(), Spend::default(), None, 0.0),
2774                p4: P4::not_run("x"),
2775                p5: off_policy(&[], &[], &[]),
2776                readout: readout(&[], &[], &Summary::default()),
2777            }),
2778        });
2779        assert!(text.contains("P2 calibration: PASS by the pruned model: leave-future-out log-loss model "), "{text}");
2780        assert!(
2781            text.contains("  pre-registered rerun, the model pruned to grade, route and dilution: log-loss ")
2782                && text.contains(": PASS: P2 passes on the pruned model"),
2783            "{text}"
2784        );
2785    }
2786
2787    /// P5 estimates nothing without a judged unit: NOT TESTED, not an estimate of 0 units. One judged
2788    /// unit makes it an estimate (REPORTED).
2789    #[test]
2790    fn off_policy_without_a_judged_unit_is_not_tested() {
2791        let p5 = off_policy(&[], &[], &[]);
2792        assert_eq!((p5.verdict, p5.units), (Verdict::NotTested, 0), "{p5:?}");
2793        let log = [graded("s", 10, &["A", "B"], &[3, 1]), result(outcome::CHANGED, "s", "A", 25, "live")];
2794        let checks = checks_of(&log);
2795        let (ls, _) = labels(&checks, &log);
2796        let p5 = off_policy(&checks, &ls, &[]);
2797        assert_eq!((p5.verdict, p5.units), (Verdict::Reported, 1), "{p5:?}");
2798    }
2799
2800    /// P2 is NOT TESTED, never a pass, when it tested nothing: no label, no unit with a label before
2801    /// its check, or every prediction of both models 1/2.
2802    #[test]
2803    fn calibration_on_nothing_to_learn_from_is_not_tested() {
2804        let empty = calibration(&[], 0, &|_, _, _| fixed_p(by_route));
2805        assert_eq!((empty.verdict, empty.why.as_str()), (Verdict::NotTested, "no judged unit joins a graded check"));
2806        // Every result after every check.
2807        let late: Vec<Label> = world(20, true).into_iter().map(|l| Label { known: vec![(10_000, l.y)], ..l }).collect();
2808        let blind = calibration(&late, 0, &|_, _, _| fixed_p(by_route));
2809        assert_eq!((blind.verdict, blind.informed), (Verdict::NotTested, 0), "{blind:?}");
2810        // One change and one not per check: grade only says 1/2 wherever it knows anything, and so does
2811        // the model.
2812        let balanced: Vec<Label> = world(80, true)
2813            .into_iter()
2814            .enumerate()
2815            .map(|(i, l)| {
2816                let y = f64::from(u8::from(i % 2 == 0));
2817                Label { y, known: vec![(l.known[0].0, y)], ..l }
2818            })
2819            .collect();
2820        let coin = calibration(&balanced, 0, &|_, _, _| fixed_p(|_| 0.5));
2821        assert!(coin.informed > 0 && coin.model.is_some(), "{coin:?}");
2822        assert_eq!((coin.verdict, coin.why.as_str()), (Verdict::NotTested, "every prediction of both models is 1/2"), "{coin:?}");
2823        // The same units under an informative model are tested.
2824        assert_ne!(calibration(&balanced, 0, &|_, _, _| fixed_p(by_route)).verdict, Verdict::NotTested);
2825    }
2826
2827    /// The guard: a model certain of the wrong answer costs a large but finite log-loss, so the mean
2828    /// and its interval stay numbers. Without `CLAMP` this unit's loss is infinite.
2829    #[test]
2830    fn a_certain_wrong_prediction_keeps_the_log_loss_finite() {
2831        assert!(log_loss(1.0, 0.0).is_finite() && log_loss(0.0, 1.0).is_finite());
2832        let certain = calibration(&world(40, true), 0, &|_, _, _| fixed_p(|l: &Label| if l.route == FREE { 1.0 } else { 0.0 }));
2833        assert!(certain.model.is_some_and(f64::is_finite), "{certain:?}");
2834        assert!(certain.diff.as_ref().is_some_and(|d| d.hi.is_finite()), "{certain:?}");
2835        assert_eq!(certain.verdict, Verdict::Fail, "one certain miss outweighs every right call");
2836    }
2837
2838    /// Where free beats asked for grade 1 (randomised logging), DR ranks a policy that hands grade 1
2839    /// over free above the fixed rule, which asks it, and the readout's within-check Q−F says the same.
2840    #[test]
2841    fn a_planted_world_where_free_beats_asked_ranks_free_above_asked() {
2842        let ls = world(120, true);
2843        let past = past_counts(&ls);
2844        let ss = sessions(&ls);
2845        let asks = |_: &Label| [1.0, 0.0, 0.0];
2846        let frees = |_: &Label| [0.0, 1.0, 0.0];
2847        let row = doubly_robust(&ls, &past, &ss, &frees, &asks, "free");
2848        let d = row.dr.value.unwrap();
2849        assert!(d > 0.5 && row.dr.lo > 0.0, "{row:?}");
2850        assert_eq!(row.coverage, 1.0, "randomised: the log covers every route the policy takes");
2851        let back = doubly_robust(&ls, &past, &ss, &asks, &frees, "asked");
2852        assert!(back.dr.value.unwrap() < -0.5 && back.dr.hi < 0.0, "{back:?}");
2853        // The mirror world reverses the ranking.
2854        let mirror = world(120, false);
2855        let row = doubly_robust(&mirror, &past_counts(&mirror), &sessions(&mirror), &frees, &asks, "free");
2856        assert!(row.dr.hi < 0.0, "{row:?}");
2857        // Deterministic logging (every unit asked): the free policy's route is not covered.
2858        let fixed: Vec<Label> = ls.iter().map(|l| Label { route: ASK, mu: [1.0, 0.0, 0.0], ..l.clone() }).collect();
2859        assert_eq!(doubly_robust(&fixed, &past_counts(&fixed), &sessions(&fixed), &frees, &asks, "free").coverage, 0.0);
2860    }
2861
2862    /// The guard: no decision may risk more than the gate's budget. Removing the `risk > gate` test
2863    /// from `conduct` turns this red.
2864    #[test]
2865    fn a_decision_risking_more_than_its_budget_fails_p3() {
2866        let step = |deviates: bool, gate: f64, risk: f64| Step { deviates, gate, risk, at: "x".into() };
2867        let ok = conduct(&[step(false, 0.0, 0.0), step(true, 0.5, 0.25)], Spend::default(), Spend::default(), None, 0.0);
2868        assert_eq!((ok.verdict, ok.deviations, ok.over, ok.cold), (Verdict::Pass, 1, 0, true));
2869        let over = conduct(&[step(false, 0.0, 0.0), step(true, 0.5, 0.75)], Spend::default(), Spend::default(), None, 0.0);
2870        assert_eq!((over.verdict, over.over), (Verdict::Fail, 1));
2871        let stated = |r: f64| Routed { log: crate::select::Log { risk: r, ..crate::select::Log::default() }, ..empty() };
2872        let logged = conduct(&[step(false, 0.0, 0.0), step(true, 0.5, risk(&stated(0.75), true))], Spend::default(), Spend::default(), None, 0.0);
2873        assert_eq!(logged.verdict, Verdict::Fail, "the decision's own risk is what P3 compares");
2874        assert_eq!(risk(&stated(0.75), false), 0.0, "keeping the fixed rule risks nothing");
2875        let warm = conduct(&[step(true, 0.0, 0.0)], Spend::default(), Spend::default(), None, 0.0);
2876        assert_eq!((warm.verdict, warm.cold), (Verdict::Fail, false), "cold start is the fixed rule");
2877        // No deviation puts the gate to no test: NOT TESTED; a failure still fails.
2878        let none = conduct(&[], Spend::default(), Spend::default(), None, 0.0);
2879        assert_eq!((none.verdict, none.why.as_str()), (Verdict::NotTested, "no graded check to replay"));
2880        let kept = conduct(&[step(false, 0.0, 0.0), step(false, 0.5, 0.0)], Spend::default(), Spend::default(), None, 0.0);
2881        assert_eq!(kept.verdict, Verdict::NotTested, "{kept:?}");
2882        assert!(kept.why.contains("no decision left the fixed rule"), "{}", kept.why);
2883        let bad = conduct(&[step(false, 0.0, 0.0), step(false, -1.0, 0.0)], Spend::default(), Spend::default(), None, 0.0);
2884        assert_eq!(bad.verdict, Verdict::Fail, "a negative budget fails without a deviation");
2885    }
2886
2887    /// The guard: with an engineer's budget set, the replayed pools must spend at most it per session.
2888    /// Removing the budget clause from `conduct` turns this red; without a budget, spend only shows.
2889    #[test]
2890    fn pools_spending_past_the_engineers_budget_fail_p3() {
2891        let fine = [Step { deviates: false, gate: 0.0, risk: 0.0, at: "x".into() }, Step { deviates: true, gate: 0.5, risk: 0.25, at: "y".into() }];
2892        let p3 = |budget: Option<f64>| conduct(&fine, Spend::default(), Spend::default(), budget, 24_000.0);
2893        assert_eq!(p3(None).verdict, Verdict::Pass, "no budget: reported, not gated");
2894        assert_eq!(p3(Some(24_000.0)).verdict, Verdict::Pass, "at the budget is within it");
2895        let over = p3(Some(20_000.0));
2896        assert_eq!((over.verdict, over.budget, over.pool), (Verdict::Fail, Some(20_000.0), 24_000.0));
2897        assert!(over.first[0].contains("over the collective's budget of 20000"), "{:?}", over.first);
2898        // Replayed: a budget below what the baseline's pools spend in a session fails while the gate keeps
2899        // the baseline's pool; one above it is met.
2900        let log = text(&labelled(3, 4, 13));
2901        let none = Path::new("/nonexistent/lessons.jsonl");
2902        let (tight, _) = cold_start(&log, none, Some(1.0));
2903        assert_eq!((tight.verdict, tight.budget), (Verdict::Fail, Some(1.0)), "{tight:?}");
2904        assert!(tight.pool > 1.0 && tight.pool <= 4.0 * crate::whole::TOKENS as f64, "four checks a session, none past the baseline's pool: {tight:?}");
2905        let (loose, _) = cold_start(&log, none, Some(1e12));
2906        // Met; with no deviation on this short log the gate itself is not tested.
2907        assert_eq!((loose.verdict, loose.first.len()), (Verdict::NotTested, 0), "{loose:?}");
2908    }
2909
2910    fn empty() -> Routed<'static> {
2911        Routed { ask: Vec::new(), free: Vec::new(), placebo: Vec::new(), p: Vec::new(), pf: Vec::new(), log: crate::select::Log::default() }
2912    }
2913
2914    #[test]
2915    fn the_cold_start_replay_of_a_fixed_log_is_the_fixed_rule_and_counts_spend() {
2916        let mut stop = graded("s", 1, &["A", "B"], &[3, 1]);
2917        stop.channel = "stop".into();
2918        stop.tokens = 1200;
2919        let log = [stop, graded("s", 2, &["C", "D"], &[2, 1]), graded("t", 3, &["E"], &[3])];
2920        let (p3, targets) = cold_start(&text(&log), Path::new("/nonexistent/lessons.jsonl"), None);
2921        assert_eq!((p3.verdict, p3.checks, p3.deviations, p3.cold, p3.budget), (Verdict::NotTested, 3, 0, true, None), "no fit, no deviation: {p3:?}");
2922        assert_eq!(p3.policy, Spend { checks: 3, questions: 3, blocks: 1, free: 2, tokens: 1200, usd: 0.0 });
2923        assert_eq!(p3.policy, p3.fixed);
2924        assert_eq!(targets[1], (vec![0.0, 0.0], vec![1.0, 1.0]));
2925    }
2926
2927    /// A record logs the applies its session already had (`nofree`), and every pass decides its check
2928    /// under them as the hook did: such a lesson is never handed over free, by the fixed rule (P0's
2929    /// reference and the logged decision), by the replayed policy (P1), or in the cold start (P3's spend).
2930    #[test]
2931    fn every_pass_replays_a_check_under_the_lessons_its_session_had() {
2932        let none = Path::new("/nonexistent/lessons.jsonl");
2933        // A live check without a 3, its session already had A: the fixed rule hands over only B.
2934        let mut o = graded("s", 1, &["A", "B"], &[2, 1]);
2935        o.check = crate::select::check_id("s", "live", 1, 1);
2936        o.policy = "fixed".into();
2937        o.free = vec!["B".into()];
2938        o.pf = vec![0.0, 1.0];
2939        o.nofree = vec!["A".into()];
2940        let pass = as_logged(&text(std::slice::from_ref(&o)), none);
2941        assert_eq!(pass.checks[0].fixed, (Vec::<String>::new(), vec!["B".to_string()]), "the fixed rule for a session that had A");
2942        assert_eq!((pass.p0.verdict, pass.p1.verdict), (Verdict::Pass, Verdict::Pass), "{:?} {:?}", pass.p0.first, pass.p1.first);
2943        let (p3, targets) = cold_start(&text(std::slice::from_ref(&o)), none, None);
2944        assert_eq!((p3.policy.free, p3.fixed.free, p3.deviations), (1, 1, 0), "{p3:?}");
2945        assert_eq!(targets[0], (vec![0.0, 0.0], vec![0.0, 1.0]));
2946        // The same decision without its `nofree` is no fixed-rule decision: the rule would hand A over too.
2947        o.nofree.clear();
2948        let pass = as_logged(&text(std::slice::from_ref(&o)), none);
2949        assert_eq!((pass.p0.verdict, pass.p1.verdict), (Verdict::Fail, Verdict::Fail));
2950    }
2951
2952    /// The guard: the replay's pools are chosen under the loosest latency limit, as `price` replays
2953    /// them, so a pool a hook's limit would allow above the baseline counts against the engineer's
2954    /// budget. Under no limit (None) every pool above the baseline is forbidden and P3 would understate
2955    /// the spend.
2956    #[test]
2957    fn the_replays_pools_may_grow_where_a_hooks_limit_would_let_them() {
2958        let pool = policy::PoolFit {
2959            yields: vec![(50.0, 1.0); 8],
2960            per_lesson: 400.0,
2961            latency: (1000.0, 0.1, 500.0),
2962            latency_n: 30,
2963            eta: 0.0,
2964            slope: (0.0, 0.0),
2965            not: (-3.0, 0.0),
2966        };
2967        let gate = summary::Gate { gain: vec![0.0; policy::DRAWS], allowance: 1.0, ..summary::Gate::default() };
2968        let s = Summary { fit: Fit { pool, ..Fit::default() }, gate, ..Summary::default() };
2969        let baseline = crate::whole::TOKENS;
2970        assert!(pool_of(&s, "x") > baseline, "a larger pool is worth more and its latency fits: {}", pool_of(&s, "x"));
2971        assert_eq!(crate::select::pool_tokens_under(Policy::Learned, &s, None, "x"), baseline, "without a limit, never above the baseline");
2972        // Closed gate: the baseline, as in production.
2973        let closed = Summary { gate: summary::Gate::default(), ..s.clone() };
2974        assert_eq!(pool_of(&closed, "x"), baseline);
2975    }
2976
2977    /// The cold start folds the replayed decision as the hook would have logged it: its own routes,
2978    /// propensities, placebo chance, source and question-count draw, on the logged check's applies and had lessons.
2979    #[test]
2980    fn the_cold_start_folds_the_replayed_decision_with_its_own_propensities() {
2981        let mut o = graded("s", 1, &["A", "B", "C"], &[2, 1, 1]);
2982        (o.policy, o.source, o.placebo, o.psi, o.nofree) = ("fixed".into(), "fixed".into(), vec!["C".into()], 0.5, vec!["A".into()]);
2983        let ls: Vec<Challenge> = ["A", "B", "C"].iter().map(|id| Challenge { id: id.to_string(), ..Default::default() }).collect();
2984        let r = Routed {
2985            ask: vec![&ls[1]],
2986            free: Vec::new(),
2987            placebo: vec![&ls[2]],
2988            p: vec![0.0, 1.0, 0.0],
2989            pf: vec![0.0; 3],
2990            log: crate::select::Log {
2991                policy: "learned",
2992                source: policy::EXPERIMENT,
2993                fit: "9-abcdef01".into(),
2994                psi: 1.0,
2995                xk: Some(2),
2996                xs: Some(1),
2997                ..crate::select::Log::default()
2998            },
2999        };
3000        let d = decided(o.clone(), &r);
3001        assert_eq!((d.chosen, d.free, d.placebo, d.p, d.psi), (vec!["B".to_string()], Vec::new(), vec!["C".to_string()], vec![0.0, 1.0, 0.0], 1.0));
3002        assert_eq!((d.policy.as_str(), d.source.as_str(), d.fit.as_str()), ("learned", "experiment", "9-abcdef01"));
3003        assert_eq!((d.xk, d.xs), (Some(2), Some(1)), "the test's k and s, which the summary folds");
3004        assert_eq!((d.lessons, d.grades, d.nofree, d.check), (o.lessons, o.grades, o.nofree, o.check), "the logged check's");
3005    }
3006
3007    /// Leave-future-out over time: a label is known before a check at its value then. A veto after
3008    /// the check, or a stronger verdict, is a result from after it and reaches only later checks.
3009    #[test]
3010    fn a_later_veto_reaches_no_prediction_before_it() {
3011        let mut a = graded("s", 10, &["A"], &[1]);
3012        a.check = "0000000000aa".into();
3013        let later = |ms: i64, lesson: &str| {
3014            let mut c = graded("s", ms, &[lesson], &[1]);
3015            c.check = format!("{ms:012x}");
3016            c
3017        };
3018        let log = [
3019            a,
3020            Outcome { check: "0000000000aa".into(), ..result(outcome::CHANGED, "s", "A", 15, "queued") },
3021            later(50, "B"),
3022            Outcome { check: format!("{:012x}", 50), ..result(outcome::IGNORED, "s", "B", 55, "queued") },
3023            result(outcome::VETOED, "s", "A", 100, ""),
3024            later(200, "C"),
3025            Outcome { check: format!("{:012x}", 200), ..result(outcome::IGNORED, "s", "C", 205, "queued") },
3026        ];
3027        let checks = checks_of(&log);
3028        let (ls, _) = labels(&checks, &log);
3029        assert_eq!(ls[0].known, [(15, 1.0), (100, 0.0)], "changed, then vetoed");
3030        assert_eq!((ls[0].y, ls[0].at(15), ls[0].at(50), ls[0].at(200)), (0.0, None, Some((15, 1.0)), Some((100, 0.0))), "{:?}", ls[0]);
3031        // Grade only before B knows A as changed, before C as not.
3032        let past = past_counts(&ls);
3033        assert_eq!((past[1][1][FREE], past[2][1][FREE]), ((1, 1), (2, 0)), "{past:?}");
3034        // So does the value model's training log.
3035        let label_of = |s: &Summary, lesson: &str| {
3036            let at = s.lessons.iter().position(|l| l == lesson).unwrap() as u32;
3037            s.applies.iter().find(|x| x.lesson == at).map(|x| x.label)
3038        };
3039        let all: Vec<&Label> = ls.iter().collect();
3040        assert_eq!(label_of(&known(&checks, &all[..1], 50), "A"), Some(summary::Label::Changed));
3041        assert_eq!(label_of(&known(&checks, &all[..2], 200), "A"), Some(summary::Label::Ignored));
3042        // An ignored verdict then a change: unknown before the first, then 0, then 1.
3043        assert_eq!(values(&[(5, 0), (9, 1)], &[]), [(5, 0.0), (9, 1.0)]);
3044        assert_eq!(values(&[(5, 1)], &[(5, 3)]), [(5, 0.0)], "results at the same ms land together");
3045        assert_eq!(values(&[(5, 1)], &[(2, 2)]), [(5, 0.0)], "a correction after the check and before the verdict outranks it");
3046    }
3047
3048    #[test]
3049    fn eval_checks_read_graded_lines_channels_and_cost() {
3050        let ctx = "#borg-predict-cost 0.0500\n#borg-graded n=2 L1:3:0,L2:1:1\n#borg-p L1=1,L2=1\n#borg-asked L1,L2\n#borg-predict-cost 0.0700\n#borg-graded n=1 La:b:2:0\n#borg-queued La:b\n#borg-graded n=0 \n";
3051        let cost =
3052            "live usd=0.05 lessons=3\ngraded applied=2 ask=2 free=0 dropped\ngraded applied=1 ask=0 free=1 queued\ngraded applied=0 ask=0 free=0 dropped\n";
3053        let cs = eval_checks("s", ctx, cost);
3054        assert_eq!(cs.iter().map(|c| c.channel).collect::<Vec<_>>(), ["live", "stop", "stop"]);
3055        assert_eq!(cs.iter().map(|c| c.usd).collect::<Vec<_>>(), [0.05, 0.07, 0.0], "each check's own call");
3056        let applies: Vec<Vec<(String, u8)>> = cs.into_iter().map(|c| c.applies).collect();
3057        assert_eq!(applies, [vec![("L1".into(), 3), ("L2".into(), 1)], vec![("La:b".into(), 2)], vec![]], "an id may hold a colon");
3058        // Without an aligned cost log, a #borg-live delivery after the check marks it live.
3059        let cs = eval_checks("s", ctx, "");
3060        assert_eq!(cs.iter().map(|c| c.channel).collect::<Vec<_>>(), ["stop", "stop", "stop"]);
3061        let live = "#borg-graded n=1 L1:3:0\n#borg-asked L1\n#borg-live L1 ms=5\n#borg-graded n=1 L2:3:0\n#borg-asked L2\n";
3062        assert_eq!(eval_checks("s", live, "").iter().map(|c| c.channel).collect::<Vec<_>>(), ["live", "stop"]);
3063    }
3064
3065    #[test]
3066    fn recall_counts_a_run_whose_check_delivers_a_right_lesson() {
3067        let check = |applies: &[(&str, u8)]| EvalCheck {
3068            session: "s".into(),
3069            channel: "stop",
3070            applies: applies.iter().map(|(i, g)| (i.to_string(), *g)).collect(),
3071            usd: 0.1,
3072        };
3073        let runs = vec![
3074            EvalRun { case: "c1".into(), checks: vec![check(&[("X", 1)]), check(&[("R", 2)])] }, // R handed over free
3075            EvalRun { case: "c1".into(), checks: vec![check(&[("X", 3)])] },
3076            EvalRun { case: "c2".into(), checks: vec![check(&[("R2", 3), ("X", 1)])] }, // a block asks both
3077            EvalRun { case: "c2".into(), checks: vec![check(&[("R2", 1)])] },
3078        ];
3079        let right: BTreeMap<String, BTreeSet<String>> =
3080            [("c1".to_string(), BTreeSet::from(["R".to_string()])), ("c2".to_string(), BTreeSet::from(["R2".to_string()]))].into();
3081        let none = Path::new("/nonexistent/lessons.jsonl");
3082        let base = recalls(&runs, &right, None, 1, none);
3083        assert_eq!((base.per_run.as_slice(), base.deviations), (&[1.0, 0.0, 1.0, 1.0][..], 0));
3084        assert_eq!(base.spend, [3.0 / 5.0, 3.0 / 5.0, 2.0 / 5.0], "questions, free and blocks per check");
3085        // Expected over draws: a policy that delivers on half its seeds recalls a one-check run half the time.
3086        let coin = |u: &[Unit], _: &EvalCheck, seed: u64| vec![if seed.is_multiple_of(2) { Route::Free } else { Route::Not }; u.len()];
3087        let half = recalls(&runs, &right, Some(&coin), conscience::P_DRAWS, none);
3088        assert!(half.per_run.iter().zip(&base.per_run).all(|(h, b)| (h - 0.5 * b).abs() < 0.1), "half of each run the fixed rule recalls: {:?}", half.per_run);
3089        assert_eq!(half.deviations, 5, "every check has a draw off the fixed rule");
3090        // A case short of a seed: not decided, no arm judged.
3091        let all = |u: &[Unit], _: &EvalCheck, _: u64| vec![Route::Ask; u.len()];
3092        let short = against_baseline(&runs[..3], &right, Arms { prior: &all, posterior: &all, test: &all }, none);
3093        assert_eq!((short.verdict, short.p4a.is_none()), (Verdict::NotRun, true), "{short:?}");
3094    }
3095
3096    /// P4's three arms (rules v2), each against its own bar on planted draws where it can fail: P4a
3097    /// fails on any deviation under the prior and tests nothing without an apply; P4b fails below the
3098    /// recall bar and is NOT TESTED where it is the fixed rule, which still meets the default rule; P4c
3099    /// fails when a run's recall moves and is NOT TESTED when no draw leaves the fixed rule. `verdict`
3100    /// is theirs by the default rule.
3101    #[test]
3102    fn p4_judges_each_arm_against_its_own_bar() {
3103        let check = |applies: &[(&str, u8)]| EvalCheck {
3104            session: "s".into(),
3105            channel: "live",
3106            applies: applies.iter().map(|(i, g)| (i.to_string(), *g)).collect(),
3107            usd: 0.0,
3108        };
3109        let runs = vec![
3110            EvalRun { case: "c1".into(), checks: vec![check(&[("X", 1)]), check(&[("R", 2)])] },
3111            EvalRun { case: "c1".into(), checks: vec![check(&[("X", 3)])] },
3112            EvalRun { case: "c2".into(), checks: vec![check(&[("R2", 3), ("X", 1)])] },
3113            EvalRun { case: "c2".into(), checks: vec![check(&[("R2", 1)])] },
3114        ];
3115        let right: BTreeMap<String, BTreeSet<String>> =
3116            [("c1".to_string(), BTreeSet::from(["R".to_string()])), ("c2".to_string(), BTreeSet::from(["R2".to_string()]))].into();
3117        let none = Path::new("/nonexistent/lessons.jsonl");
3118        let fixed = |u: &[Unit], _: &EvalCheck, _: u64| policy::fixed_routes(u, &[]);
3119        let never = |u: &[Unit], _: &EvalCheck, _: u64| vec![Route::Not; u.len()];
3120        let all = |u: &[Unit], _: &EvalCheck, _: u64| vec![Route::Ask; u.len()];
3121        // As the test: what the fixed rule hands over is asked on odd seeds, so nothing is withheld.
3122        let test = |u: &[Unit], _: &EvalCheck, seed: u64| {
3123            policy::fixed_routes(u, &[]).into_iter().map(|r| if r == Route::Free && seed % 2 == 1 { Route::Ask } else { r }).collect()
3124        };
3125        let parts = |p: &P4| [&p.p4a, &p.p4b, &p.p4c].map(|x| x.as_ref().map(|x| x.verdict));
3126        // The decision rule is the fixed rule under both fits, the test moves routes but no recall.
3127        let met = against_baseline(&runs, &right, Arms { prior: &fixed, posterior: &fixed, test: &test }, none);
3128        assert_eq!(parts(&met), [Some(Verdict::Pass), Some(Verdict::NotTested), Some(Verdict::Pass)], "{met:?}");
3129        assert_eq!((met.verdict, met.why.as_str(), met.applying), (Verdict::Pass, "", 5), "P4b NOT TESTED meets the default rule: {met:?}");
3130        let c = met.p4c.as_ref().unwrap();
3131        assert_eq!((c.arm.deviations, c.arm.same), (3, 4), "the three checks that hand a lesson over: {c:?}");
3132        assert!(met.p4b.as_ref().unwrap().why.contains("so it is the fixed rule"), "{met:?}");
3133        // P4a: a deviation under the prior fails it and the default rule, and is listed.
3134        let a = against_baseline(&runs, &right, Arms { prior: &all, posterior: &fixed, test: &test }, none);
3135        assert_eq!((a.verdict, parts(&a)[0], a.why.as_str()), (Verdict::Fail, Some(Verdict::Fail), "P4a FAIL"), "{a:?}");
3136        let pa = a.p4a.as_ref().unwrap();
3137        assert_eq!((pa.arm.deviations, pa.why.as_str()), (3, "3 of 5 checks that apply a lesson decide otherwise than the fixed rule"), "{pa:?}");
3138        assert!(pa.arm.first[0].starts_with("case c1 session s check 0 (live): ask against the fixed rule's free"), "{:?}", pa.arm.first);
3139        // P4b: losing the right lessons misses the bar; keeping them passes.
3140        let b = against_baseline(&runs, &right, Arms { prior: &fixed, posterior: &never, test: &test }, none);
3141        assert_eq!((b.verdict, parts(&b)[1]), (Verdict::Fail, Some(Verdict::Fail)), "{b:?}");
3142        assert_eq!(b.p4b.as_ref().unwrap().arm.delta.as_ref().unwrap().value, Some(-0.75));
3143        let b = against_baseline(&runs, &right, Arms { prior: &fixed, posterior: &all, test: &test }, none);
3144        assert_eq!((b.verdict, parts(&b)[1]), (Verdict::Pass, Some(Verdict::Pass)), "{b:?}");
3145        // P4c: a test that withholds fails; one that never leaves the fixed rule tests nothing, and the
3146        // default rule is not met.
3147        let c = against_baseline(&runs, &right, Arms { prior: &fixed, posterior: &fixed, test: &never }, none);
3148        assert_eq!((c.verdict, parts(&c)[2]), (Verdict::Fail, Some(Verdict::Fail)), "{c:?}");
3149        assert_eq!(c.p4c.as_ref().unwrap().why, "3 of 4 runs recall otherwise than the fixed rule");
3150        let c = against_baseline(&runs, &right, Arms { prior: &fixed, posterior: &fixed, test: &fixed }, none);
3151        assert_eq!((c.verdict, parts(&c)[2], c.why.as_str()), (Verdict::NotTested, Some(Verdict::NotTested), "P4c NOT TESTED"), "{c:?}");
3152        // No check applies a lesson: P4a tests nothing.
3153        let bare: Vec<EvalRun> = runs.iter().map(|r| EvalRun { case: r.case.clone(), checks: vec![check(&[])] }).collect();
3154        let n = against_baseline(&bare, &right, Arms { prior: &fixed, posterior: &fixed, test: &fixed }, none);
3155        assert_eq!((n.applying, parts(&n)[0], n.verdict), (0, Some(Verdict::NotTested), Verdict::NotTested), "{n:?}");
3156    }
3157
3158    /// P4's baseline (`recalls` without a policy: select/policy.rs `fixed_routes`) is P0's reference
3159    /// (conscience.rs `graded_without`, no cap) by position, on a grade table with and without lessons
3160    /// the session had: the two checks judge against one fixed rule.
3161    #[test]
3162    fn the_recall_baseline_is_the_fixed_rule_p0_checks() {
3163        // P0's reference as routes: each copy of a lesson by its own place in the applies.
3164        fn reference(applied: &[(&Challenge, u8)], had: &[String]) -> Vec<Route> {
3165            let (ask, free) = conscience::graded_without(applied, None, had);
3166            let held = |v: &[&Challenge], x: &Challenge| v.iter().any(|y| std::ptr::eq(*y, x));
3167            applied
3168                .iter()
3169                .map(|(x, _)| match (held(&ask, x), held(&free, x)) {
3170                    (true, _) => Route::Ask,
3171                    (_, true) => Route::Free,
3172                    _ => Route::Not,
3173                })
3174                .collect()
3175        }
3176        // A check's applies as `recalls` reads them.
3177        fn challenges(applies: &[(String, u8)]) -> Vec<Challenge> {
3178            applies.iter().map(|(id, _)| Challenge { id: id.clone(), ..Default::default() }).collect()
3179        }
3180        fn applied<'a>(cs: &'a [Challenge], applies: &[(String, u8)]) -> Vec<(&'a Challenge, u8)> {
3181            cs.iter().zip(applies.iter().map(|(_, g)| *g)).collect()
3182        }
3183        let lessons: Vec<String> = (0..12).map(|i| format!("L{i}")).collect();
3184        let named = |gs: &[u8]| -> Vec<(String, u8)> { gs.iter().zip(&lessons).map(|(g, id)| (id.clone(), *g)).collect() };
3185        let twice = |gs: &[u8], again: u8| [named(gs), vec![(lessons[0].clone(), again)]].concat();
3186        let table = [
3187            Vec::new(),
3188            named(&[3]),
3189            named(&[1, 3, 2]),                            // a 3 blocks: every 3, 2 and 1
3190            named(&[1, 2, 1]),                            // no 3: handed over free
3191            named(&[1, 2, 3, 1, 2, 1, 1, 2, 1, 1, 2, 3]), // a block past the cap: the 3s and 2s, then the first 1s
3192            named(&[2, 1, 1, 2, 1, 1, 2, 1, 1, 2, 1, 1]), // free past the cap: the 2s, then the first 1s
3193            twice(&[1; 10], 1),                           // L0 named again past the cap: that copy waits
3194            twice(&[1, 2], 3),                            // L0 named again as a 3: both copies asked
3195        ];
3196        let hads: [Vec<String>; 4] = [Vec::new(), vec![lessons[0].clone()], vec![lessons[1].clone(), "Z".into()], lessons.clone()];
3197        let mut moved = 0;
3198        for row in &table {
3199            let cs = challenges(row);
3200            let applied = applied(&cs, row);
3201            for had in &hads {
3202                let want = reference(&applied, had);
3203                assert_eq!(policy::fixed_routes(&crate::select::units(&applied), had), want, "{row:?} had {had:?}");
3204                moved += usize::from(want != reference(&applied, &[]));
3205            }
3206        }
3207        assert!(moved > 0, "a lesson the session had changes some row's routes");
3208        // `recalls` decides its baseline by that rule: a policy that is P0's reference never deviates
3209        // from it and recalls as it does.
3210        let checks = table.iter().map(|row| EvalCheck { session: "s".into(), channel: "stop", applies: row.clone(), usd: 0.0 }).collect();
3211        let runs = [EvalRun { case: "c".into(), checks }];
3212        let right: BTreeMap<String, BTreeSet<String>> = [("c".to_string(), BTreeSet::from([lessons[11].clone()]))].into();
3213        let p0 = |_: &[Unit], c: &EvalCheck, _: u64| reference(&applied(&challenges(&c.applies), &c.applies), &[]);
3214        let none = Path::new("/nonexistent/lessons.jsonl");
3215        let (base, same) = (recalls(&runs, &right, None, 1, none), recalls(&runs, &right, Some(&p0), conscience::P_DRAWS, none));
3216        assert_eq!((same.deviations, &same.per_run, same.spend), (0, &base.per_run, base.spend));
3217    }
3218
3219    /// A labelled log under the fixed rule: `sessions` sessions of `checks` checks (with ids, every
3220    /// fourth at the stop), each asked or free apply delivered and judged (changed more often the higher
3221    /// its grade), each session settled at its end as `borg learn` settles it.
3222    fn labelled(sessions: usize, checks: usize, seed: u64) -> Vec<Outcome> {
3223        let mut rng = memory::Rng::new(seed);
3224        let (mut log, mut ms) = (Vec::new(), 0);
3225        for s in 0..sessions {
3226            let session = format!("s{s}");
3227            for c in 0..checks {
3228                ms += 10;
3229                let n = 1 + (rng.next_u64() % 4) as usize;
3230                let mut lessons: Vec<String> = Vec::new();
3231                while lessons.len() < n {
3232                    let l = format!("L{}", rng.next_u64() % 12);
3233                    if !lessons.contains(&l) {
3234                        lessons.push(l);
3235                    }
3236                }
3237                let grades: Vec<u8> = (0..n).map(|_| 1 + (rng.next_u64() % 3) as u8).collect();
3238                let mut o = graded(&session, ms, &lessons.iter().map(String::as_str).collect::<Vec<_>>(), &grades);
3239                o.channel = if c % 4 == 3 { "stop" } else { "live" }.into();
3240                o.check = crate::select::check_id(&session, &o.channel, ms, 1);
3241                o.policy = "fixed".into();
3242                let cs: Vec<Challenge> = lessons.iter().map(|id| Challenge { id: id.clone(), ..Default::default() }).collect();
3243                o.free = ids(&conscience::graded_capped(&cs.iter().zip(grades.iter().copied()).collect::<Vec<_>>(), None).1);
3244                o.pf = holds(&o.lessons, &o.free);
3245                // Per delivered apply: its lesson, delivery route, verdict channel and grade.
3246                let routed: Vec<(String, &str, String, u8)> = o
3247                    .lessons
3248                    .iter()
3249                    .zip(&grades)
3250                    .filter_map(|(l, g)| match (o.chosen.contains(l), o.free.contains(l)) {
3251                        (true, _) => Some((l.clone(), outcome::ROUTE_ASKED, o.channel.clone(), *g)),
3252                        (_, true) => Some((l.clone(), outcome::ROUTE_FREE, "queued".to_string(), *g)),
3253                        _ => None,
3254                    })
3255                    .collect();
3256                let check = o.check.clone();
3257                log.push(o);
3258                for (l, route, ch, g) in routed {
3259                    ms += 1;
3260                    log.push(Outcome { check: check.clone(), route: route.into(), ..result(outcome::DELIVERY, &session, &l, ms, "") });
3261                    let changed = rng.unit() < [0.0, 0.15, 0.35, 0.5][usize::from(g)];
3262                    let kind = if changed { outcome::CHANGED } else { outcome::IGNORED };
3263                    log.push(Outcome { check: check.clone(), judge: 2, ..result(kind, &session, &l, ms, &ch) });
3264                }
3265            }
3266            ms += 10;
3267            log.push(Outcome { lessons: Vec::new(), reason: outcome::UNJUDGED_NONE.into(), ..result(outcome::NOT_CORRECTED, &session, "", ms, "") });
3268        }
3269        log
3270    }
3271
3272    /// How a planted question-count test's lessons fare (`tested_log`): lesson j (A and B 2s, C a 1)
3273    /// at the drawn count s changes the work with chance `change(j, s, asked)`; handed over, it is
3274    /// delivered with chance `delivered` (else dropped at delivery, never judged); delivered, the judge
3275    /// gives a verdict with chance `seen(asked)` (else it could not tell).
3276    struct Plant {
3277        change: fn(usize, usize, bool) -> f64,
3278        delivered: f64,
3279        seen: fn(bool) -> f64,
3280    }
3281
3282    /// No dilution: an asked 2 changes the work 0.8 of the time at every count, a free 2 0.2, a 1
3283    /// never; every lesson delivered and judged.
3284    const UNDILUTED: Plant = Plant {
3285        change: |j, _, ask| {
3286            if j == 2 {
3287                0.0
3288            } else if ask {
3289                0.8
3290            } else {
3291                0.2
3292            }
3293        },
3294        delivered: 1.0,
3295        seen: |_| 1.0,
3296    };
3297
3298    /// A planted question-count test: `sessions` sessions of two live checks of two 2s and a 1 (no 3,
3299    /// so k = 3), the draw s the check's number mod 4, the top s asked in the fixed rule's order and the
3300    /// rest handed over, with the draw's propensities (position i asked with chance (k − i)/(k + 1)),
3301    /// each lesson faring as `plant` says, drawn from `seed`.
3302    fn tested_log(sessions: usize, plant: &Plant, seed: u64) -> Vec<Outcome> {
3303        let (lessons, grades) = (["A", "B", "C"], [2u8, 2, 1]);
3304        let (mut log, mut n, mut ms) = (Vec::new(), 0usize, 0);
3305        let mut rng = memory::Rng::new(seed);
3306        for x in 0..sessions {
3307            let session = format!("t{x}");
3308            for _ in 0..2 {
3309                let s = n % 4;
3310                n += 1;
3311                ms += 10;
3312                let check = format!("{n:012x}");
3313                let owned = |v: &[&str]| v.iter().map(|l| l.to_string()).collect::<Vec<_>>();
3314                log.push(Outcome {
3315                    chosen: owned(&lessons[..s]),
3316                    free: owned(&lessons[s..]),
3317                    check: check.clone(),
3318                    policy: "learned".into(),
3319                    source: if s == 0 { policy::EXPERIMENT_CONTROL } else { policy::EXPERIMENT }.into(),
3320                    xk: Some(3),
3321                    xs: Some(s as u32),
3322                    p: vec![0.75, 0.5, 0.25],
3323                    pf: vec![0.25, 0.5, 0.75],
3324                    ..graded(&session, ms, &lessons, &grades)
3325                });
3326                for (j, l) in lessons.iter().enumerate() {
3327                    let ask = j < s;
3328                    let (changed, delivered, seen) =
3329                        (rng.unit() < (plant.change)(j, s, ask), ask || rng.unit() < plant.delivered, rng.unit() < (plant.seen)(ask));
3330                    let channel = if ask { "live" } else { "queued" };
3331                    if !delivered {
3332                        let route = outcome::ROUTE_DROPPED_CHARS.into();
3333                        log.push(Outcome { check: check.clone(), route, ..result(outcome::DELIVERY, &session, l, ms + 1, channel) });
3334                        continue;
3335                    }
3336                    let kind = match (seen, changed) {
3337                        (false, _) => outcome::UNCLEAR,
3338                        (true, true) => outcome::CHANGED,
3339                        (true, false) => outcome::IGNORED,
3340                    };
3341                    log.push(Outcome { check: check.clone(), judge: 2, ..result(kind, &session, l, ms + 1, channel) });
3342                }
3343            }
3344        }
3345        log
3346    }
3347
3348    fn readout_of(log: &[Outcome]) -> TestReadout {
3349        test_readout(&summary::fold(&text(log), Summary::default()))
3350    }
3351
3352    /// The question-count test's readout (rules v2) reads the summary's fold: not due, and then no
3353    /// estimate, before `TEST_SESSIONS` sessions with a drawn check (or `TEST_CHECKS` checks); due,
3354    /// dilution against one asked for each m up to k, and asking a 2 against handing it over by the
3355    /// logged propensities, which finds the planted gain of asking; over the drawn checks the summary
3356    /// still holds, which it says.
3357    #[test]
3358    fn the_question_count_readout_waits_until_due_and_then_finds_the_planted_gain_of_asking() {
3359        let early = readout_of(&tested_log(TEST_SESSIONS as usize - 1, &UNDILUTED, 7));
3360        assert_eq!((early.due, early.checks, early.control, early.sessions), (false, 58, 15, 29), "{early:?}");
3361        assert!(early.by_asked.is_empty() && early.ask_free.is_none(), "nothing read before it is due: {early:?}");
3362        let log = tested_log(TEST_SESSIONS as usize, &UNDILUTED, 7);
3363        let s = summary::fold(&text(&log), Summary::default());
3364        let r = test_readout(&s);
3365        assert_eq!((r.due, r.checks, r.control, r.refused, r.sessions, r.kept), (true, 60, 15, 0, 30, 60), "{r:?}");
3366        // k = 3 at every check: m of 2 and 3 against 1, each over all 60 drawn checks.
3367        let by: Vec<(u16, usize)> = r.by_asked.iter().map(|(m, e)| (*m, e.n)).collect();
3368        assert_eq!(by, [(2, 60), (3, 60)], "{r:?}");
3369        // Asked, a 2 changes the work 0.8 of the time, handed over 0.2: a gain of about 0.6.
3370        let gain = r.ask_free.as_ref().unwrap();
3371        assert_eq!(gain.n, 120, "every 2: {gain:?}");
3372        assert!(gain.value.is_some_and(|v| (v - 0.6).abs() < 0.15) && gain.lo > 0.0, "{gain:?}");
3373        // A draw the gate refused is randomised too, its routes as logged: read with the others.
3374        let mut refused = log.clone();
3375        let g = refused.iter_mut().find(|o| o.kind == outcome::GRADED && o.xs == Some(3)).unwrap();
3376        g.source = policy::GATE.into();
3377        let rr = readout_of(&refused);
3378        assert_eq!((rr.checks, rr.refused, rr.by_asked.iter().map(|(m, e)| (*m, e.n)).collect::<Vec<_>>()), (60, 1, by.clone()), "{rr:?}");
3379        // Compaction drops the oldest checks, never the counts: due on all 60, estimated over the rest.
3380        let mut compacted = s.clone();
3381        compacted.checks.drain(..10);
3382        let rc = test_readout(&compacted);
3383        assert_eq!(
3384            (rc.due, rc.checks, rc.kept, rc.by_asked.iter().map(|(m, e)| (*m, e.n)).collect::<Vec<_>>()),
3385            (true, 60, 50, vec![(2, 50), (3, 50)]),
3386            "{rc:?}"
3387        );
3388        let shown = render(&evaluate(Input {
3389            text: &text(&log),
3390            lessons: Path::new("/nonexistent/lessons.jsonl"),
3391            summary: Summary::default(),
3392            replay: true,
3393            eval: None,
3394        }));
3395        assert!(
3396            shown.contains("question-count test readout (rules v2): due (60 of 300 checks that drew a count, 30 of 30 sessions with one; 15 of them the control arm, 0 refused by the gate)\n")
3397                && shown.contains("  estimated over the 60 drawn checks the summary still holds ")
3398                && shown.contains("  dilution, 2 asked − 1 asked: the test's top lesson's change rate ")
3399                && shown.contains("  grade 2 asked − handed over: "),
3400            "{shown}"
3401        );
3402    }
3403
3404    /// Asking a 2 against handing it over is a Horvitz–Thompson difference over every 2 that could go
3405    /// either way: a verdict the judge gives the asked more often than the handed over is weighed by
3406    /// its chance (select/policy.rs `judged`), so equal change rates read as no gain; a hand-over never
3407    /// delivered changed nothing, so it counts as 0, not out.
3408    #[test]
3409    fn asking_against_handing_over_weighs_verdicts_by_their_chance_and_counts_what_was_never_delivered() {
3410        let sessions = 1000;
3411        // Both routes change the work every time; the asked are judged 9 times in 10, the free 4.
3412        let judging = Plant { change: |j, _, _| if j == 2 { 0.0 } else { 1.0 }, delivered: 1.0, seen: |ask| if ask { 0.9 } else { 0.4 } };
3413        let even = readout_of(&tested_log(sessions, &judging, 11));
3414        let gain = even.ask_free.as_ref().unwrap();
3415        assert_eq!(gain.n, 4 * sessions, "every 2, judged or not: {gain:?}");
3416        assert!(gain.value.is_some_and(|v| v.abs() < 0.1) && gain.lo < 0.0 && gain.hi > 0.0, "equal rates, no gain: {gain:?}");
3417        // Every delivered lesson changes the work and is judged; half the hand-overs are never
3418        // delivered, so handing over changes the work half the time: a gain of 0.5.
3419        let dropped = Plant { change: |j, _, _| if j == 2 { 0.0 } else { 1.0 }, delivered: 0.5, seen: |_| 1.0 };
3420        let gain = readout_of(&tested_log(sessions, &dropped, 13)).ask_free.unwrap();
3421        assert!(gain.value.is_some_and(|v| (v - 0.5).abs() < 0.08), "{gain:?}");
3422    }
3423
3424    /// Dilution compares the same lesson across the uniform draws: with none planted, a 1 asked
3425    /// beside the 2s does not read as dilution; planted, the top lesson's falling rate is found.
3426    #[test]
3427    fn dilution_compares_the_same_lesson_across_draws_and_finds_only_what_is_planted() {
3428        let sessions = 600;
3429        let none = readout_of(&tested_log(sessions, &UNDILUTED, 17));
3430        let rows: Vec<u16> = none.by_asked.iter().map(|x| x.0).collect();
3431        assert_eq!(rows, [2, 3], "{none:?}");
3432        for (m, e) in &none.by_asked {
3433            assert!(e.value.is_some_and(|v| v.abs() < 0.15) && e.lo < 0.0 && e.hi > 0.0, "{m} asked, no dilution planted: {e:?}");
3434        }
3435        // The top lesson asked changes the work 0.9 of the time alone, 0.6 with 2 asked, 0.3 with 3.
3436        let diluted = Plant {
3437            change: |j, s, ask| match (j, ask) {
3438                (0, true) => [0.0, 0.9, 0.6, 0.3][s],
3439                (2, _) => 0.0,
3440                (_, true) => 0.8,
3441                _ => 0.2,
3442            },
3443            delivered: 1.0,
3444            seen: |_| 1.0,
3445        };
3446        let r = readout_of(&tested_log(sessions, &diluted, 19));
3447        for (m, want) in [(2u16, -0.3), (3, -0.6)] {
3448            let e = &r.by_asked.iter().find(|x| x.0 == m).unwrap().1;
3449            assert!(e.value.is_some_and(|v| (v - want).abs() < 0.15) && e.hi < 0.0, "{m} asked, {want} planted: {e:?}");
3450        }
3451    }
3452
3453    /// The cold-start replay decides as the hooks would: with the fit `borg learn` makes when a session
3454    /// ends, the gate's ledger over the policy's own checks. Until the first end it is the fixed rule;
3455    /// after, the learned policy leaves it within the gate's budget. Without the refits it has no model,
3456    /// never leaves the fixed rule, and P3 passes on nothing.
3457    #[test]
3458    fn the_cold_start_replay_refits_at_each_session_end_and_deviates_within_the_gate() {
3459        let (sessions, checks) = (8, 16);
3460        let log = labelled(sessions, checks, 3);
3461        let (p3, targets) = cold_start(&text(&log), Path::new("/nonexistent/lessons.jsonl"), None);
3462        assert_eq!(p3.refits, sessions - 1, "before the first check after each end but the last: {p3:?}");
3463        assert_eq!((p3.verdict, p3.over, p3.cold, p3.checks), (Verdict::Pass, 0, true, sessions * checks), "{p3:?}");
3464        assert!(p3.deviations > 0, "the learned policy decides: {p3:?}");
3465        assert_ne!(p3.policy, p3.fixed, "its own spend: {p3:?}");
3466        assert_eq!(p3.sources.values().sum::<usize>(), p3.checks, "every decision by its source: {:?}", p3.sources);
3467        assert!(p3.sources.get(policy::FIXED).is_some_and(|n| *n >= checks), "the first session's at least: {:?}", p3.sources);
3468        // The first session is decided before any fit: the fixed rule, its choice as the propensities.
3469        let pass = as_logged(&text(&log), Path::new("/nonexistent/lessons.jsonl"));
3470        for (c, t) in pass.checks.iter().zip(&targets).take(checks) {
3471            assert_eq!(t, &(c.p.clone(), c.pf.clone()), "{}", c.line());
3472        }
3473        assert!(pass.checks.iter().zip(&targets).skip(checks).any(|(c, t)| t != &(c.p.clone(), c.pf.clone())), "then its own propensities");
3474    }
3475
3476    /// P2 runs on the value model (select/policy.rs `fit`, `predict`), leave-future-out: the summary it
3477    /// fits on holds exactly the labels whose result came before, no check after them, and while there
3478    /// is none the prior predicts.
3479    #[test]
3480    fn calibration_fits_the_value_model_on_the_labels_before_each_check() {
3481        let log = labelled(6, 12, 5);
3482        let none = Path::new("/nonexistent/lessons.jsonl");
3483        let pass = as_logged(&text(&log), none);
3484        let (ls, unjoined) = labels(&pass.checks, &log);
3485        assert!(ls.len() > 20 && unjoined == 0, "{} labels, {unjoined} unjoined", ls.len());
3486        let p2 = calibration(&ls, unjoined, &|value, past, at| model(&pass.checks, past, at, value));
3487        assert!(matches!(p2.verdict, Verdict::Pass | Verdict::Fail), "{p2:?}");
3488        assert!(p2.model.is_some_and(f64::is_finite) && p2.diff.as_ref().is_some_and(|d| d.n > 0) && p2.informed > 0, "{p2:?}");
3489        let cut = ls[ls.len() / 2].check_ms;
3490        let past: Vec<&Label> = ls.iter().filter(|l| l.first() < cut).collect();
3491        let s = known(&pass.checks, &past, cut);
3492        let judged = s.applies.iter().filter(|a| matches!(a.label, summary::Label::Changed | summary::Label::Ignored)).count();
3493        assert_eq!(judged, past.len(), "exactly the labels before");
3494        let newest = past.iter().filter_map(|l| l.at(cut)).map(|k| k.0).max().unwrap();
3495        assert!(s.checks.iter().all(|c| c.ms <= newest), "no check after them");
3496        assert!(policy::fit(&s, None).model.is_some());
3497        let prior = model(&pass.checks, &[], cut, Value::Full).unwrap();
3498        assert!(ls.iter().all(|l| (0.0..1.0).contains(&prior(l))), "the prior predicts before any label");
3499        assert_eq!(known(&pass.checks, &[], cut), Summary::default());
3500        // The pruned rerun predicts before any label by its own prior (select/policy.rs `prior_pruned`).
3501        let pruned = model(&pass.checks, &[], cut, Value::Pruned).unwrap();
3502        let by = |fit: &Fit, l: &Label| {
3503            let o = &pass.checks[l.check].o;
3504            let units: Vec<Unit> = o
3505                .lessons
3506                .iter()
3507                .zip(&o.grades)
3508                .enumerate()
3509                .map(|(j, (lesson, grade))| Unit { lesson, grade: *grade, rank: o.ranks.get(j).map_or(j, |r| usize::from(*r)) })
3510                .collect();
3511            let route = [Route::Ask, Route::Free, Route::Not][l.route];
3512            let m = routes_of(&pass.checks[l.check]).iter().filter(|r| **r == route).count();
3513            policy::predict(fit, &policy::Feat::of(&units, o.channel == "stop", o.tokens)[l.j], route, m, &o.session, &o.lessons[l.j]).unwrap()
3514        };
3515        assert!(ls.iter().all(|l| pruned(l) == by(&policy::prior_pruned(), l)), "the pruned prior");
3516        // Every prior mean but not now's is 0 (select/policy.rs `NOT_PRIOR`), so an asked or free unit is
3517        // ½ under either prior: the two part where a unit was not delivered.
3518        let not: Vec<Label> = ls.iter().map(|l| Label { route: NOT, ..l.clone() }).collect();
3519        assert!(not.iter().all(|l| pruned(l) == by(&policy::prior_pruned(), l)), "the pruned prior, not delivered");
3520        assert!(not.iter().any(|l| pruned(l) != by(&policy::prior(), l)), "not the full model's prior");
3521    }
3522
3523    /// An evaluation's run directory: per run `<case>-s<seed>/borg-state/<session>.ctx` with its graded
3524    /// lines, and the qrels beside them.
3525    fn eval_dir(name: &str, runs: &[(&str, &str)], qrels: &[(&str, &str)]) -> PathBuf {
3526        let d = std::env::temp_dir().join(format!("borg-replay-{name}-{}", std::process::id()));
3527        let _ = std::fs::remove_dir_all(&d);
3528        for (i, (case, ctx)) in runs.iter().enumerate() {
3529            let state = d.join("runs").join(format!("{case}-s{i}")).join("borg-state");
3530            std::fs::create_dir_all(&state).unwrap();
3531            std::fs::write(state.join(format!("sess{i}.ctx")), ctx).unwrap();
3532        }
3533        let q: String = qrels.iter().map(|(case, id)| format!("{}\n", serde_json::json!({"case": case, "challenge": id, "grade": 2}))).collect();
3534        std::fs::write(d.join("qrels.jsonl"), q).unwrap();
3535        d
3536    }
3537
3538    /// P4's arms are the production functions' (rules v2): P4a select/policy.rs `decide_on_evidence`
3539    /// under the n = 0 prior, P4b the same under the whole log's fit (what `borg learn` would fit, not
3540    /// the folded summary's prior), P4c `choose` under the prior with an open gate, whose draws leave the
3541    /// fixed rule on a live check with lessons it may hand over or ask. A posterior arm on the prior, or
3542    /// a test arm on no live check, would pass on nothing.
3543    #[test]
3544    fn p4_draws_its_arms_from_the_production_rule_the_posterior_and_the_test() {
3545        let log = labelled(6, 12, 7);
3546        // A stop check, and a live one (its question delivered live) with two 2s and a 1 the test may move.
3547        let checks = "#borg-graded n=4 R:2:0,X:1:1,Y:1:2,Z:2:3\n#borg-graded n=3 W:3:0,R:1:1,V:2:2\n#borg-live W ms=5\n";
3548        let d = eval_dir("p4", &[("c1", checks), ("c1", checks)], &[("c1", "R")]);
3549        let (runs, qrels) = (d.join("runs"), d.join("qrels.jsonl"));
3550        let none = Path::new("/nonexistent/lessons.jsonl");
3551        let report = evaluate(Input { text: &text(&log), lessons: none, summary: Summary::default(), replay: true, eval: Some((&runs, &qrels)) });
3552        let p4 = report.checks.map(|c| c.p4).unwrap();
3553        let whole = policy::fit(&summary::fold(&text(&log), Summary::default()), None);
3554        assert!(whole.model.is_some() && whole.labels > 0);
3555        assert_eq!((&p4.fit, p4.labels), (&whole.key, whole.labels), "the store's posterior: {p4:?}");
3556        assert_eq!((p4.runs, p4.checks, p4.applying), (2, 4, 4));
3557        // Each arm is its production function's, drawn as `recalls` draws.
3558        let (runs, right) = (eval_runs(&runs), super::qrels(&qrels));
3559        assert_eq!(runs[0].checks.iter().map(|c| c.channel).collect::<Vec<_>>(), ["stop", "live"]);
3560        let prior = policy::prior();
3561        // Each at `P_DRAWS` draws: the decision rule's one draw is its expectation only if it draws nothing.
3562        let arm = |draw: &Draw| {
3563            let r = recalls(&runs, &right, Some(draw), conscience::P_DRAWS, none);
3564            (r.deviations, r.first, r.spend)
3565        };
3566        let of = |p: &Option<Part>| p.as_ref().map(|p| (p.arm.deviations, p.arm.first.clone(), [p.arm.questions, p.arm.free, p.arm.blocks])).unwrap();
3567        let a = |u: &[Unit], c: &EvalCheck, _: u64| policy::decide_on_evidence(u, &eval_check(c), &prior, &[]);
3568        let b = |u: &[Unit], c: &EvalCheck, _: u64| policy::decide_on_evidence(u, &eval_check(c), &whole, &[]);
3569        let gate = summary::Gate { gain: vec![0.0; policy::DRAWS], allowance: OPEN, ..summary::Gate::default() };
3570        let t = |u: &[Unit], c: &EvalCheck, s: u64| policy::choose(u, &eval_check(c), &prior, &gate, policy::ALPHA, s, &[]).routes;
3571        assert_eq!(of(&p4.p4a), arm(&a), "P4a");
3572        assert_eq!(of(&p4.p4b), arm(&b), "P4b");
3573        assert_eq!(of(&p4.p4c), arm(&t), "P4c");
3574        assert!(p4.p4c.as_ref().unwrap().arm.deviations > 0, "the test's draws leave the fixed rule on the live check: {p4:?}");
3575        let _ = std::fs::remove_dir_all(d);
3576    }
3577}