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