Skip to main content

borg/select/
summary.rs

1//! What a hook needs to decide, folded from the outcome log once and cached, so no check parses the
2//! whole log: every graded apply with its route and what became of it, the delivery tallies, the
3//! pool's yield and latency, the gate's ledger, the monitor, the checks whose learned decision fell
4//! back to the fixed rule, the randomised question-count test's checks, and the fit
5//! (select/policy.rs).
6//!
7//! **The cache** `<store>/select-summary.json` sits beside the lessons file, local and never synced.
8//! `load` reads it and folds only the log's new tail (from `at`); a missing, corrupt or older cache, or
9//! a log shorter than `at` (rewritten), is rebuilt from the whole log in memory; `peek` (an early or
10//! `PostToolUse` hook) never rebuilds: the prior instead. Neither writes: `refresh` (the live check and
11//! the stop) loads and saves what it folded, and `refit` (`borg learn`) fits and saves. Any error is
12//! the prior, never a panic in a hook.
13//!
14//! **The fold** is pure over an append-only log: `fold` of a prefix, then of the rest, equals `fold` of
15//! the whole at every line boundary, and only whole lines fold (a line being written waits). A result
16//! joins the check that decided it by check id (outcome.rs `check`); a record from before check ids by
17//! the session's last graded check before it that graded the lesson on the route its channel names, as
18//! attention.rs `labels` joins. A later verdict for the same check and lesson supersedes an earlier one
19//! and a censored mark, so nothing counts twice. Kinds it does not use skip serde: the kind is read off
20//! the line's head first (12,577 `regretted` lines from one session cost a substring each).
21//!
22//! **Session ticks**: a session's tick is its place in the order sessions first appear in the folded
23//! log (memory.rs `Clock`'s idea, in line order so the fold stays incremental); ages are in ticks,
24//! never in wall time.
25//!
26//! **Session ends**: a session's delivery tallies (`Session::tally`) count at its end, whatever it
27//! logged: its end hook's `ended` record (outcome.rs `ENDED`) or the `never_delivered` deliveries
28//! before it, or a settle (`asked_not_corrected`, which `borg learn` also writes for a session idle
29//! without its end hook). A delivery recorded after that (a resumed session) moves its apply's count,
30//! so the tallies follow the latest record.
31//!
32//! **What a session had**: a lesson shown to a session (asked, handed over free or delivered early; a
33//! placebo is judged, never shown) is in its `Session::had` from that delivery on in line order, or in
34//! `Summary::fresh` until a first graded check or settle gives the session a tick. An apply of a lesson
35//! its session had before its check (`Apply::had`: the record's `nofree`, the hook's view, or that set,
36//! the log's) counts in no delivery tally, whose rates are those of a lesson the session lacks
37//! (select/policy.rs `Rates`): delivery drops a free one as given before, and a question once its lesson
38//! is done (hook.rs `done_in`: asked, or handed over and acted on, as the drone may before the question
39//! reaches it), drops that say nothing of whether a lesson the session lacks arrives. A lesson waiting
40//! in the session's queue from another check is in the record's `nofree` too, which delivery would drop
41//! as queued twice. A question of one handed over and not acted on is delivered and judged as any
42//! other: its verdict counts (top.rs label health), its delivery stays out of the tallies with the
43//! drops. Before 0.6.0 such an apply of a free lesson counted as undelivered and a question as
44//! delivered, so the learned free rate read low against asking.
45//!
46//! **The tail**: a graded record's `tail` holds lessons the pool's budget dropped that a uniform sample
47//! showed the model anyway, each with the chance `pt`, and its `fill` holds, after the applies'
48//! positions, each tail lesson's position: `shown` plus its place among the dropped lessons in the fill
49//! order (whole.rs `select_filled`), where a budget that held them would have put it (`tail_of`). Each
50//! counts in the pool's yield bins at its position as a shown lesson, applied when it is one of the
51//! applies, so the yield is learned past the budget. Unweighted: a uniform sample's lesson at a position
52//! is one draw of that position's yield, and a 1/pt weight would count it as 1/pt lessons, overstating
53//! the yield's certainty. A bin the budget splits holds all its positions below the budget and a pt
54//! share of those above, so its yield leans to its lower positions.
55//!
56//! **Compaction** bounds the cache: past `MAX_APPLIES` the oldest checks go, past `MAX_SESSIONS` the
57//! oldest sessions with their checks, and with either the sessions before the first kept check's, but
58//! never one of the newest `policy::FIT_SESSIONS` (the sessions a fit reads). What the dropped
59//! sessions' readers need stays in `Past`, and the kept ones' ticks shift down by as many, so every
60//! age stays as it was. A session that logs again after its drop starts a new one.
61//!
62//! **The question-count test** (select/policy.rs `choose`, rules v2): a graded record of the learned
63//! policy that logs k (outcome.rs `xk`) was considered by the test, and one that also logs s (`xs`)
64//! drew its count: played (source `EXPERIMENT`, or `EXPERIMENT_CONTROL` when s is the fixed rule's own
65//! count), or refused by the gate (`GATE`), which then plays the fixed rule. Every drawn check is one
66//! of the test's randomised checks: its routes, as played, and its propensities, over the k + 1 equally
67//! likely counts with the refused ones' routes the fixed rule's, are what the draw made them, so the
68//! readout reads refused draws too. The fold counts them all-time by k and s (`Summary::experiment`,
69//! which compaction keeps) and marks a drawn one's check (`Check::xk`, `xs`), whose applies hold the
70//! verdicts of what it asked and handed over: what the readout reads (select/replay.rs `test_readout`),
71//! never a recount of the log. A record whose k or s cannot be its own (no s, s past k, k past its
72//! applies) counts nowhere. Like every learned check, a drawn one is on the gate's ledger.
73
74use std::collections::{BTreeMap, HashMap};
75use std::io::{Read, Seek};
76use std::path::{Path, PathBuf};
77
78use serde::{Deserialize, Serialize};
79
80use super::Route;
81use super::policy::{self, Fit, Monitor};
82use crate::outcome::{self, Outcome};
83
84/// The cache's format. Protocol: a summary of another version is rebuilt, never read (2: `spend`;
85/// 3: `Pool::stops`, the monitor's weights; 4: `Past`, `LATER` a live check's, tallies at `ENDED`;
86/// 5: `ASK_LIVE`, what a session had (`Session::had`, `Apply::had`, `Apply::nofree`, `Summary::fresh`),
87/// tail yields and counts; 6: `Summary::fell_back`; 7: the question-count test, `Summary::experiment`,
88/// `Check::xk`, `xs`, `Session::tested`; 8: a stop's results on a live check's hand-overs it asked
89/// (`stop_routes`), a live question of a check without a 3 out of `ASK_LIVE` and `WAIT`, `counted`;
90/// 9: the judge's `not_arisen` and `consequence_remains` verdicts, `Label::NotArisen`, `Label::Remains`,
91/// `Apply::jv`, the session-end judge's own judge level).
92pub const SV: u32 = 9;
93/// The cache beside the lessons file. Protocol.
94pub const CACHE: &str = "select-summary.json";
95/// The monitor's auto-revert mark beside the lessons file: while it exists the store keeps the fixed
96/// rule, whatever the cache holds (sticky: removing it is the engineer's call, and resumes learning
97/// until the monitor trips again). Protocol.
98pub const REVERTED: &str = "select-reverted";
99/// Graded applies a summary keeps at most. Guard: bounds the cache a hook reads; past it the oldest
100/// checks holding a quarter of them go (`Summary::dropped` counts their applies), whose labels the
101/// forgetting already weighs least.
102pub const MAX_APPLIES: usize = 50_000;
103/// Sessions a summary keeps at most. Guard: bounds the session table, which `MAX_APPLIES` does not
104/// when sessions grade few applies (a session is about 100 bytes of cache, so 4,096 are 0.4 MB against
105/// the applies' 5 MB); past it the oldest quarter go, with their checks, into `Past`.
106pub const MAX_SESSIONS: usize = 4_096;
107// A compaction keeps three quarters of `MAX_SESSIONS`: never fewer sessions than a fit reads.
108const _: () = assert!(MAX_SESSIONS - MAX_SESSIONS / 4 >= policy::FIT_SESSIONS);
109/// Sessions not in the table yet whose deliveries a summary keeps (`Summary::fresh`). Guard: bounds the
110/// cache against sessions shown lessons (an early delivery at a prompt) that never reach a graded check,
111/// which no other bound counts; far more than run at once, about 0.1 MB. Past it the oldest quarter go,
112/// and one of them graded after all counts its applies of lessons it had as a session without them.
113pub const MAX_FRESH: usize = 1_024;
114/// Model calls whose latency the summary keeps, the newest: of all, and of each harness's stops
115/// (`Pool::stops`). Guard: bounds the cache, which a long-lived store's calls would grow without end.
116pub const LATENCY_KEEP: usize = 2_000;
117
118/// What delivery did with a decided apply (outcome.rs `delivery`, or an older `asked` record).
119#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
120#[serde(rename_all = "lowercase")]
121pub enum Delivered {
122    /// Nothing recorded yet (and, at its session's end, not delivered).
123    #[default]
124    Unknown,
125    Yes,
126    /// Dropped at delivery (the session had it, the budget was spent) or never delivered.
127    Dropped,
128}
129
130/// What the judge made of an apply.
131#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
132#[serde(rename_all = "lowercase")]
133pub enum Label {
134    /// No verdict yet.
135    #[default]
136    Open,
137    /// Changed the work and avoids the consequence (`asked_then_changed`).
138    Changed,
139    /// Changed nothing on its point (`asked_ignored`).
140    Ignored,
141    /// The judge could not tell (`asked_unclear`; before 0.7.5 also a change that left the consequence).
142    Unclear,
143    /// Its session settled without a verdict (`asked_not_corrected` with an unjudged reason).
144    Censored,
145    /// Its point never came up in the work (`asked_not_arisen`, 0.7.5 on): a verdict, read as "nothing in
146    /// the work", no change on the lesson's point (select/policy.rs `Data::of`, `judged`; replay.rs
147    /// `unit_outcome`). Appended, so older caches keep their labels' places.
148    #[serde(rename = "not_arisen")]
149    NotArisen,
150    /// Changed on its point but the consequence remains (`asked_consequence_remains`, 0.7.5 on): read as
151    /// an unclear verdict everywhere but the label health (top.rs), which counts it apart.
152    Remains,
153}
154
155impl Label {
156    /// Does a verdict of kind `next` replace this one? A verdict (changed, ignored, not arisen) replaces
157    /// anything; a pending one (unclear, remains) an open or censored mark or another pending one, so
158    /// the latest pending verdict shows; a censored mark only an open one.
159    fn yields_to(self, next: Label) -> bool {
160        match next {
161            Label::Changed | Label::Ignored | Label::NotArisen => true,
162            Label::Unclear | Label::Remains => matches!(self, Label::Open | Label::Censored | Label::Unclear | Label::Remains),
163            Label::Censored => self == Label::Open,
164            Label::Open => false,
165        }
166    }
167
168    /// Whether the judge left it pending (`Unclear`, `Remains`): no verdict for the fit, the readout or
169    /// the judge-missingness model, as an unclear one has always been.
170    #[must_use]
171    pub fn pending(self) -> bool {
172        matches!(self, Label::Unclear | Label::Remains)
173    }
174
175    /// Whether it is a verdict that settles its apply (`Changed`, `Ignored`, `NotArisen`).
176    #[must_use]
177    pub fn verdict(self) -> bool {
178        matches!(self, Label::Changed | Label::Ignored | Label::NotArisen)
179    }
180}
181
182fn is_default<T: Default + PartialEq>(v: &T) -> bool {
183    *v == T::default()
184}
185
186/// One graded apply: its lesson, grade and rank, the route its check decided with its propensities
187/// (logged `p`, `pf`; `psi` a placebo's chance of the draw), and what came of it.
188#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
189pub struct Apply {
190    /// Its check (`Summary::checks`) and lesson (`Summary::lessons`).
191    pub check: u32,
192    pub lesson: u32,
193    pub grade: u8,
194    #[serde(default, skip_serializing_if = "is_default")]
195    pub rank: u16,
196    pub route: Route,
197    #[serde(default, skip_serializing_if = "is_default")]
198    pub p: f64,
199    #[serde(default, skip_serializing_if = "is_default")]
200    pub pf: f64,
201    #[serde(default, skip_serializing_if = "is_default")]
202    pub psi: f64,
203    #[serde(default, skip_serializing_if = "is_default")]
204    pub delivered: Delivered,
205    #[serde(default, skip_serializing_if = "is_default")]
206    pub label: Label,
207    /// The judge of its verdict (`Summary::judges`: template version, model and prompt).
208    #[serde(default, skip_serializing_if = "Option::is_none")]
209    pub judge: Option<u32>,
210    /// The judge template version (outcome.rs `judge`) of the answer its label shows, a pending one
211    /// (`Label::pending`) too; 0 none. Read by the label health only (top.rs: the verdict shares from
212    /// `predict::PURE_UNCLEAR_FROM` on), never by the fit, whose judge levels are `judge`'s.
213    #[serde(default, skip_serializing_if = "is_default")]
214    pub jv: u8,
215    /// The judge saw it without the drone's declaration.
216    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
217    pub stripped: bool,
218    /// Left for later, then delivered later in the session.
219    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
220    pub later: bool,
221    /// A live question still waiting at the stop, asked there.
222    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
223    pub waited: bool,
224    /// Its lesson was shown to its session before its check, or was waiting in its queue from another
225    /// check (the record's `nofree`; module doc: what a session had): in no delivery tally (`counted`),
226    /// though a question of it may still be delivered and judged.
227    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
228    pub had: bool,
229    /// Its check could not hand it over free: in the record's `nofree`, the `had` its decision read
230    /// (select.rs `Ctx::had`), so the gate's ledger and the monitor value the check against the fixed
231    /// rule it was decided against (select/policy.rs `ledger`, `monitor`). Never the log's view, which
232    /// `had` adds and the decision may not have seen.
233    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
234    pub nofree: bool,
235    /// The session's delivered applies still waiting for a verdict when its check ran.
236    #[serde(default, skip_serializing_if = "is_default")]
237    pub pending: u16,
238}
239
240/// One graded check with applies.
241#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
242pub struct Check {
243    /// select.rs `check_id`; empty for a record from before check ids.
244    #[serde(default, skip_serializing_if = "String::is_empty")]
245    pub id: String,
246    /// Its session's tick (`Summary::sessions`).
247    pub tick: u32,
248    pub ms: i64,
249    /// The stop's (else live).
250    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
251    pub stop: bool,
252    /// Decided under the learned policy (outcome.rs `policy` "learned"): on the gate's ledger.
253    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
254    pub learned: bool,
255    /// Its pool's tokens (0 unknown) and its model and prompt (`Summary::models`).
256    #[serde(default, skip_serializing_if = "is_default")]
257    pub tokens: u32,
258    #[serde(default, skip_serializing_if = "is_default")]
259    pub model: u32,
260    /// Its applies: `Summary::applies[first..first + n]`; how many it asked and handed over.
261    pub first: u32,
262    pub n: u16,
263    #[serde(default, skip_serializing_if = "is_default")]
264    pub m_q: u16,
265    #[serde(default, skip_serializing_if = "is_default")]
266    pub m_f: u16,
267    /// Counted into its session's delivery tallies (at the session's end, module doc).
268    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
269    pub tallied: bool,
270    /// A check whose question-count test drew its count (module doc), played or refused: k, the fixed
271    /// rule's delivered non-3 lessons that may go free, and s, the drawn number of them to ask
272    /// (outcome.rs `xk`, `xs`). None on every other check.
273    #[serde(default, skip_serializing_if = "Option::is_none")]
274    pub xk: Option<u32>,
275    #[serde(default, skip_serializing_if = "Option::is_none")]
276    pub xs: Option<u32>,
277}
278
279/// The delivery tallies of a session, (applies, delivered), counted when it ends (`counted`): a stop's
280/// free lessons, a live check's, a live check's lessons left for later, and of a live check with a 3
281/// its questions waiting for the stop and its questions delivered. Protocol: the indices of `Session::tally`, part of the cache's layout
282/// (`SV`).
283pub const FREE_STOP: usize = 0;
284pub const FREE_LIVE: usize = 1;
285pub const LATER: usize = 2;
286pub const WAIT: usize = 3;
287pub const ASK_LIVE: usize = 4;
288/// How many delivery tallies a session keeps, `FREE_STOP` to `ASK_LIVE`. Protocol: the width of
289/// `Session::tally` and `Past::tally`, part of the cache's layout (`SV`).
290pub const TALLIES: usize = 5;
291const _: () = assert!(ASK_LIVE + 1 == TALLIES);
292
293/// One session, in tick order.
294#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
295pub struct Session {
296    pub id: String,
297    /// Ended (its first end record, module doc).
298    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
299    pub ended: bool,
300    /// Its graded checks, applies or not: what its pools cost (select/policy.rs `price`).
301    #[serde(default, skip_serializing_if = "is_default")]
302    pub checks: u32,
303    /// `FREE_STOP` to `ASK_LIVE`: (applies, delivered).
304    #[serde(default, skip_serializing_if = "is_default")]
305    pub tally: [(u32, u32); TALLIES],
306    /// The lessons shown to it so far (`Summary::lessons`), sorted (module doc: what a session had).
307    #[serde(default, skip_serializing_if = "Vec::is_empty")]
308    pub had: Vec<u32>,
309    /// A check of it drew the question-count test's count: counted once in `Experiment::sessions`.
310    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
311    pub tested: bool,
312}
313
314/// What a session not in the table yet was shown (`Summary::fresh`), until its first graded check or
315/// settle makes it its `Session::had`; `seq`, the log offset after its first delivery, orders the
316/// guard's drops (`MAX_FRESH`).
317#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
318pub struct Fresh {
319    pub seq: u64,
320    pub had: Vec<u32>,
321}
322
323/// The pool's evidence: per log2 bin of fill position (positions 2^b − 1 to 2^(b+1) − 2), lessons
324/// shown and applied; tokens and lessons shown in all; the model calls' (tokens, ms); and per
325/// harness, its stops' model calls (ms, failed), what borg top shows against the harness's stop
326/// budget (top.rs `Latency`).
327#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
328pub struct Pool {
329    #[serde(default, skip_serializing_if = "Vec::is_empty")]
330    pub bins: Vec<(u64, u64)>,
331    #[serde(default, skip_serializing_if = "is_default")]
332    pub tokens: u64,
333    #[serde(default, skip_serializing_if = "is_default")]
334    pub shown: u64,
335    #[serde(default, skip_serializing_if = "Vec::is_empty")]
336    pub latency: Vec<(u32, u32)>,
337    /// Keyed by a harness borg knows (harness/mod.rs `ALL`), the newest `LATENCY_KEEP` of each.
338    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
339    pub stops: BTreeMap<String, Vec<(u32, bool)>>,
340    /// The tail samples' lessons, shown past the pool, and those applied (`tail_of`), as borg top shows
341    /// them; also in `bins`.
342    #[serde(default, skip_serializing_if = "is_default")]
343    pub tail: (u64, u64),
344}
345
346/// Early deliveries the judge gave a verdict, and those that changed the work: shown; a learned early
347/// rule waits for each delivery's relative score in the log (conscience.rs `RELATIVE`).
348#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
349pub struct Early {
350    #[serde(default, skip_serializing_if = "is_default")]
351    pub judged: u32,
352    #[serde(default, skip_serializing_if = "is_default")]
353    pub changed: u32,
354}
355
356/// What the checks' model calls spent, per channel (`STOP`, `LIVE`): calls, the extra rounds a stop's
357/// block cost its session, and dollars as the CLIs reported them (outcome.rs `usd`; 0 before 0.6.0).
358/// Measured and shown, never a limit.
359#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
360pub struct Spent {
361    #[serde(default, skip_serializing_if = "is_default")]
362    pub calls: u64,
363    #[serde(default, skip_serializing_if = "is_default")]
364    pub rounds: u64,
365    #[serde(default, skip_serializing_if = "is_default")]
366    pub usd: f64,
367}
368
369/// `Summary::spend`'s channels. Protocol: its indices, part of the cache's layout (`SV`).
370pub const STOP: usize = 0;
371pub const LIVE: usize = 1;
372
373/// Why a graded check's learned decision fell back to the fixed rule, as its record's `reason` names it
374/// (outcome.rs `DECIDED_BUSY`, `DECIDED_NO_LOCK`, `DECIDED_NO_RECORD`). Protocol: the indices of
375/// `Summary::fell_back`, part of the cache's layout (`SV`).
376pub const FELL_BACK: [&str; 3] = [outcome::DECIDED_BUSY, outcome::DECIDED_NO_LOCK, outcome::DECIDED_NO_RECORD];
377
378/// The randomised question-count test's checks (module doc), all-time: per (k, s) the checks the test
379/// ran, each having drawn count s of k, played or refused, sorted (`ran`); of them the control arm's (`EXPERIMENT_CONTROL`: s the
380/// fixed rule's own count) and, per k, those the gate refused (`GATE`), sorted, each also in `ran`;
381/// the sessions with a drawn check. What `borg top` and the readout count
382/// (select/replay.rs `test_readout`), never a recount of the log.
383#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
384pub struct Experiment {
385    #[serde(default, skip_serializing_if = "Vec::is_empty")]
386    pub ran: Vec<(u32, u32, u64)>,
387    #[serde(default, skip_serializing_if = "is_default")]
388    pub control: u64,
389    #[serde(default, skip_serializing_if = "Vec::is_empty")]
390    pub refused: Vec<(u32, u64)>,
391    #[serde(default, skip_serializing_if = "is_default")]
392    pub sessions: u32,
393}
394
395impl Experiment {
396    /// Checks that drew a count, and those the gate refused.
397    #[must_use]
398    pub fn totals(&self) -> (u64, u64) {
399        (self.ran.iter().map(|c| c.2).sum(), self.refused.iter().map(|c| c.1).sum())
400    }
401}
402
403/// Signals beside the judge, counted before (`Summary::signals[0]`) and after (`[1]`) the first check
404/// of the learned policy: sessions, corrections, vetoes, regrets, green test runs.
405#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
406pub struct Signals {
407    #[serde(default, skip_serializing_if = "is_default")]
408    pub sessions: u32,
409    #[serde(default, skip_serializing_if = "is_default")]
410    pub corrections: u32,
411    #[serde(default, skip_serializing_if = "is_default")]
412    pub vetoes: u32,
413    #[serde(default, skip_serializing_if = "is_default")]
414    pub regrets: u32,
415    #[serde(default, skip_serializing_if = "is_default")]
416    pub tested: u32,
417}
418
419/// The conservative gate's ledger over the learned policy's checks under the current fit
420/// (select/policy.rs `ledger_add_without`): per joint draw, the replayed value of what the policy did
421/// minus the fixed rule's for the lessons its session had (A); α × the fixed rule's replayed value
422/// (B). A deviation passes while A + its own gain stays ≥ −B at the `DELTA` quantile. B is quality
423/// (mistakes avoided), not money.
424#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
425pub struct Gate {
426    #[serde(default, skip_serializing_if = "Vec::is_empty")]
427    pub gain: Vec<f64>,
428    #[serde(default, skip_serializing_if = "is_default")]
429    pub allowance: f64,
430    #[serde(default, skip_serializing_if = "is_default")]
431    pub checks: u32,
432    #[serde(default, skip_serializing_if = "is_default")]
433    pub deviated: u32,
434}
435
436/// What compaction took off the session table (module doc), as the totals its readers need: those of
437/// the dropped sessions with graded checks and their checks (`Summary::checked`), and their delivery
438/// tallies as (delivered, not) per half-life of `policy::HALF_LIVES` (same order), each session's
439/// weighted by its age at the first kept session (`Summary::tallies` ages them on from there).
440#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
441pub struct Past {
442    #[serde(default, skip_serializing_if = "is_default")]
443    pub sessions: u32,
444    #[serde(default, skip_serializing_if = "is_default")]
445    pub checks: u64,
446    #[serde(default, skip_serializing_if = "Vec::is_empty")]
447    pub tally: Vec<[(f64, f64); TALLIES]>,
448}
449
450impl Past {
451    /// `gone`, the oldest sessions, added; what was here already ages by their count.
452    fn add(&mut self, gone: &[Session]) {
453        if gone.is_empty() {
454            return;
455        }
456        let n = gone.len() as u32;
457        self.tally.resize(policy::HALF_LIVES.len(), [(0.0, 0.0); TALLIES]);
458        for (sums, &h) in self.tally.iter_mut().zip(&policy::HALF_LIVES) {
459            let aged = policy::decay(n, h);
460            for e in sums.iter_mut() {
461                *e = (e.0 * aged, e.1 * aged);
462            }
463            for (t, x) in gone.iter().enumerate() {
464                weigh(sums, &x.tally, policy::decay(n - t as u32, h));
465            }
466        }
467        for x in gone.iter().filter(|x| x.checks > 0) {
468            self.sessions += 1;
469            self.checks += u64::from(x.checks);
470        }
471    }
472}
473
474/// A session's `tally`, (applies, delivered), into `sums`, (delivered, not), at weight `w`.
475fn weigh(sums: &mut [(f64, f64); TALLIES], tally: &[(u32, u32); TALLIES], w: f64) {
476    for (s, &(n, k)) in sums.iter_mut().zip(tally) {
477        s.0 += w * f64::from(k);
478        s.1 += w * f64::from(n.saturating_sub(k));
479    }
480}
481
482/// The selection state of one store (module doc).
483#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
484pub struct Summary {
485    /// `SV` when written.
486    pub sv: u32,
487    /// The bytes of `outcomes.jsonl` folded so far, and a hash chained over its lines.
488    pub at: u64,
489    /// The value model decisions draw from; the prior without data.
490    #[serde(default)]
491    pub fit: Fit,
492    #[serde(default, skip_serializing_if = "String::is_empty")]
493    pub hash: String,
494    #[serde(default, skip_serializing_if = "Vec::is_empty")]
495    pub sessions: Vec<Session>,
496    /// Sessions shown lessons before they have a tick, by session id (module doc: what a session had).
497    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
498    pub fresh: BTreeMap<String, Fresh>,
499    /// Lesson ids, model-and-prompt keys and judge keys, by index.
500    #[serde(default, skip_serializing_if = "Vec::is_empty")]
501    pub lessons: Vec<String>,
502    #[serde(default, skip_serializing_if = "Vec::is_empty")]
503    pub models: Vec<String>,
504    #[serde(default, skip_serializing_if = "Vec::is_empty")]
505    pub judges: Vec<String>,
506    #[serde(default, skip_serializing_if = "Vec::is_empty")]
507    pub checks: Vec<Check>,
508    #[serde(default, skip_serializing_if = "Vec::is_empty")]
509    pub applies: Vec<Apply>,
510    #[serde(default, skip_serializing_if = "is_default")]
511    pub pool: Pool,
512    #[serde(default, skip_serializing_if = "is_default")]
513    pub early: Early,
514    #[serde(default, skip_serializing_if = "is_default")]
515    pub signals: [Signals; 2],
516    #[serde(default, skip_serializing_if = "is_default")]
517    pub spend: [Spent; 2],
518    /// Graded checks whose learned decision fell back to the fixed rule, per reason (`FELL_BACK`), with
519    /// applies or none: a guard that binds often shows (top.rs `Selection::fallbacks`).
520    #[serde(default, skip_serializing_if = "is_default")]
521    pub fell_back: [u64; FELL_BACK.len()],
522    /// The question-count test's checks (module doc).
523    #[serde(default, skip_serializing_if = "is_default")]
524    pub experiment: Experiment,
525    /// A check of the learned policy was folded: the signals count as after.
526    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
527    pub era: bool,
528    #[serde(default, skip_serializing_if = "is_default")]
529    pub gate: Gate,
530    #[serde(default, skip_serializing_if = "is_default")]
531    pub monitor: Monitor,
532    /// Applies compaction dropped, and what it kept of the sessions it dropped.
533    #[serde(default, skip_serializing_if = "is_default")]
534    pub dropped: u64,
535    #[serde(default, skip_serializing_if = "is_default")]
536    pub past: Past,
537}
538
539impl Default for Summary {
540    /// The prior: nothing folded, every decision the fixed rule's.
541    fn default() -> Self {
542        Summary {
543            sv: SV,
544            at: 0,
545            fit: Fit::default(),
546            hash: String::new(),
547            sessions: Vec::new(),
548            fresh: BTreeMap::new(),
549            lessons: Vec::new(),
550            models: Vec::new(),
551            judges: Vec::new(),
552            checks: Vec::new(),
553            applies: Vec::new(),
554            pool: Pool::default(),
555            early: Early::default(),
556            signals: Default::default(),
557            spend: Default::default(),
558            fell_back: Default::default(),
559            experiment: Experiment::default(),
560            era: false,
561            gate: Gate::default(),
562            monitor: Monitor::default(),
563            dropped: 0,
564            past: Past::default(),
565        }
566    }
567}
568
569impl Summary {
570    /// What a fit on this summary is keyed by: the bytes folded and the line hash's first 8 hex digits
571    /// (protocol: logged with each check, `Log::fit`).
572    #[must_use]
573    pub fn key(&self) -> String {
574        format!("{}-{}", self.at, self.hash.get(..8).unwrap_or(&self.hash))
575    }
576
577    /// Does every index point inside its table, and do the checks tile the applies in order? A cache
578    /// that parses but fails this is corrupt (`read`): the fold indexes by them.
579    fn consistent(&self) -> bool {
580        let mut next = 0u32;
581        let checks = self.checks.iter().all(|c| {
582            let ok = c.first == next && (c.tick as usize) < self.sessions.len() && (c.model as usize) < self.models.len().max(1);
583            next = c.first + u32::from(c.n);
584            ok
585        });
586        let applies = self.applies.iter().enumerate().all(|(i, a)| {
587            let inside = self.checks.get(a.check as usize).is_some_and(|c| (c.first as usize..c.first as usize + usize::from(c.n)).contains(&i));
588            inside && (a.lesson as usize) < self.lessons.len() && a.judge.is_none_or(|j| (j as usize) < self.judges.len())
589        });
590        let gate = self.gate.gain.is_empty() || self.gate.gain.len() == policy::DRAWS;
591        let past = self.past.tally.is_empty() || self.past.tally.len() == policy::HALF_LIVES.len();
592        let had = self.sessions.iter().flat_map(|x| &x.had).chain(self.fresh.values().flat_map(|f| &f.had)).all(|l| (*l as usize) < self.lessons.len());
593        checks && next as usize == self.applies.len() && applies && gate && past && had
594    }
595
596    /// Every folded session's delivery tallies as (delivered, not), each weighted by its age in
597    /// sessions under half-life `h` (select/policy.rs `decay`), the compacted ones included (`Past`,
598    /// kept for the half-lives a fit chooses from, `policy::HALF_LIVES`).
599    #[must_use]
600    pub fn tallies(&self, h: Option<u32>) -> [(f64, f64); TALLIES] {
601        let now = self.sessions.len() as u32;
602        let mut sums = [(0.0, 0.0); TALLIES];
603        if let Some(past) = policy::HALF_LIVES.iter().position(|x| *x == h).and_then(|i| self.past.tally.get(i)) {
604            let w = policy::decay(now, h);
605            for (s, p) in sums.iter_mut().zip(past) {
606                *s = (w * p.0, w * p.1);
607            }
608        }
609        for (t, x) in self.sessions.iter().enumerate() {
610            weigh(&mut sums, &x.tally, policy::decay(now.saturating_sub(t as u32), h));
611        }
612        sums
613    }
614
615    /// Sessions with graded checks, and their graded checks, the compacted ones included (`Past`):
616    /// what spend per session divides by (top.rs).
617    #[must_use]
618    pub fn checked(&self) -> (u64, u64) {
619        let kept = self.sessions.iter().filter(|x| x.checks > 0);
620        (u64::from(self.past.sessions) + kept.clone().count() as u64, self.past.checks + kept.map(|x| u64::from(x.checks)).sum::<u64>())
621    }
622}
623
624/// The lookups a fold needs, rebuilt from the summary at its start (never stored).
625#[derive(Default)]
626struct Index {
627    sessions: HashMap<String, u32>,
628    lessons: HashMap<String, u32>,
629    models: HashMap<String, u32>,
630    judges: HashMap<String, u32>,
631    checks: HashMap<String, u32>,
632    /// (tick, lesson) → its applies, oldest first.
633    by_lesson: HashMap<(u32, u32), Vec<u32>>,
634    /// tick → its checks not yet tallied.
635    untallied: HashMap<u32, Vec<u32>>,
636    /// tick → its delivered applies without a verdict.
637    open: HashMap<u32, u32>,
638}
639
640impl Index {
641    fn of(s: &Summary) -> Index {
642        let table = |v: &[String]| v.iter().enumerate().map(|(i, x)| (x.clone(), i as u32)).collect::<HashMap<_, _>>();
643        let mut ix = Index {
644            sessions: s.sessions.iter().enumerate().map(|(i, x)| (x.id.clone(), i as u32)).collect(),
645            lessons: table(&s.lessons),
646            models: table(&s.models),
647            judges: table(&s.judges),
648            ..Index::default()
649        };
650        for (ci, c) in s.checks.iter().enumerate() {
651            if !c.id.is_empty() {
652                ix.checks.insert(c.id.clone(), ci as u32);
653            }
654            if !c.tallied {
655                ix.untallied.entry(c.tick).or_default().push(ci as u32);
656            }
657            for i in c.first..c.first + u32::from(c.n) {
658                let Some(a) = s.applies.get(i as usize) else { continue };
659                ix.by_lesson.entry((c.tick, a.lesson)).or_default().push(i);
660                if waiting(a) {
661                    *ix.open.entry(c.tick).or_default() += 1;
662                }
663            }
664        }
665        ix
666    }
667}
668
669/// Is `a` delivered (or drawn as a placebo) and still without a verdict?
670fn waiting(a: &Apply) -> bool {
671    a.label == Label::Open && a.route != Route::Not && a.delivered != Delivered::Dropped
672}
673
674/// The index of `name` in `table`, added when new.
675fn intern(table: &mut Vec<String>, ix: &mut HashMap<String, u32>, name: &str) -> u32 {
676    if let Some(&i) = ix.get(name) {
677        return i;
678    }
679    table.push(name.to_string());
680    ix.insert(name.to_string(), table.len() as u32 - 1);
681    table.len() as u32 - 1
682}
683
684/// The kinds the fold reads with serde; any other is skipped (module doc).
685const USED: [&str; 13] = [
686    outcome::GRADED,
687    outcome::ASKED,
688    outcome::DELIVERY,
689    outcome::ENDED,
690    outcome::CHANGED,
691    outcome::IGNORED,
692    outcome::UNCLEAR,
693    outcome::NOT_ARISEN,
694    outcome::REMAINS,
695    outcome::NOT_CORRECTED,
696    outcome::CORRECTED,
697    outcome::MISSED,
698    outcome::VETOED,
699];
700
701/// The kind at the head of an outcome line (`{"kind":"<kind>"`, as outcome.rs writes every record),
702/// or None for a line in another shape (read with serde instead).
703fn kind_of(line: &str) -> Option<&str> {
704    let rest = line.strip_prefix("{\"kind\":\"")?;
705    rest.split_once('"').map(|(k, _)| k)
706}
707
708/// `from` with the outcome lines of `text` (appended after `from.at`) folded in; a last line without
709/// its newline is left for the next fold.
710#[must_use]
711pub fn fold(text: &str, from: Summary) -> Summary {
712    let mut s = from;
713    let mut ix = Index::of(&s);
714    for raw in text.split_inclusive('\n') {
715        if !raw.ends_with('\n') {
716            break;
717        }
718        s.at += raw.len() as u64;
719        let mut h = blake3::Hasher::new();
720        h.update(s.hash.as_bytes());
721        h.update(raw.as_bytes());
722        // 16 hex digits (64 bits). Protocol: the chain `key` reads.
723        s.hash = h.finalize().to_hex()[..16].to_string();
724        s.line(raw.trim_end(), &mut ix);
725    }
726    s
727}
728
729impl Summary {
730    fn line(&mut self, line: &str, ix: &mut Index) {
731        let era = usize::from(self.era);
732        match kind_of(line) {
733            Some(outcome::REGRETTED) => {
734                self.signals[era].regrets += 1;
735                return;
736            }
737            Some(outcome::TESTED) => {
738                self.signals[era].tested += 1;
739                return;
740            }
741            Some(k) if !USED.contains(&k) => return,
742            _ => {}
743        }
744        let Ok(o) = serde_json::from_str::<Outcome>(line) else { return };
745        match o.kind.as_str() {
746            outcome::GRADED => self.graded(&o, ix),
747            outcome::CHANGED => self.verdict(&o, Label::Changed, ix),
748            outcome::IGNORED => self.verdict(&o, Label::Ignored, ix),
749            outcome::UNCLEAR => self.verdict(&o, Label::Unclear, ix),
750            outcome::NOT_ARISEN => self.verdict(&o, Label::NotArisen, ix),
751            outcome::REMAINS => self.verdict(&o, Label::Remains, ix),
752            outcome::NOT_CORRECTED => self.settled(&o, ix),
753            outcome::ASKED | outcome::DELIVERY => self.delivered(&o, ix),
754            // A session without a graded check or settle has nothing to tally: no entry for it.
755            outcome::ENDED => {
756                if let Some(&tick) = ix.sessions.get(&o.session) {
757                    self.end(tick, ix);
758                }
759            }
760            outcome::CORRECTED => self.signals[era].corrections += 1,
761            // The `applied_then_corrected` a regret writes (its `cause` the regret) is the regret again,
762            // counted under regrets (memory.rs `is_correction`).
763            outcome::MISSED if o.cause.is_empty() => self.signals[era].corrections += 1,
764            outcome::VETOED => self.signals[era].vetoes += 1,
765            outcome::REGRETTED => self.signals[era].regrets += 1,
766            outcome::TESTED => self.signals[era].tested += 1,
767            _ => {}
768        }
769    }
770
771    /// The tick of `session`, a new one when it first appears (past `MAX_SESSIONS`, after a compaction),
772    /// with what it was shown before (`fresh`).
773    fn tick(&mut self, session: &str, ix: &mut Index) -> u32 {
774        if let Some(&t) = ix.sessions.get(session) {
775            return t;
776        }
777        if self.sessions.len() >= MAX_SESSIONS {
778            self.compact(ix, 0, MAX_SESSIONS / 4);
779        }
780        let had = self.fresh.remove(session).map(|f| f.had).unwrap_or_default();
781        self.sessions.push(Session { id: session.to_string(), had, ..Session::default() });
782        let t = self.sessions.len() as u32 - 1;
783        ix.sessions.insert(session.to_string(), t);
784        self.signals[usize::from(self.era)].sessions += 1;
785        t
786    }
787
788    fn graded(&mut self, o: &Outcome, ix: &mut Index) {
789        let tick = self.tick(&o.session, ix);
790        self.sessions[tick as usize].checks += 1;
791        let stop = o.channel != "live";
792        let spent = &mut self.spend[if stop { STOP } else { LIVE }];
793        spent.calls += 1;
794        spent.rounds += u64::from(stop && !o.chosen.is_empty());
795        spent.usd += o.usd;
796        // A learned decision the fixed rule took over (hook.rs `decide`), by its reason (one this binary
797        // does not know is not counted).
798        if let Some(i) = FELL_BACK.iter().position(|r| *r == o.reason) {
799            self.fell_back[i] += 1;
800        }
801        // A failed call applied nothing because it answered nothing: its pool says nothing of the yield.
802        if o.shown > 0 && !o.failed {
803            self.pool.shown += u64::from(o.shown);
804            self.pool.tokens += u64::from(o.tokens);
805            let bin = |k: u64| (u64::BITS - (k + 1).leading_zeros() - 1) as usize;
806            let last = bin(u64::from(o.shown) - 1);
807            if self.pool.bins.len() <= last {
808                self.pool.bins.resize(last + 1, (0, 0));
809            }
810            for (b, e) in self.pool.bins.iter_mut().enumerate().take(last + 1) {
811                let (lo, hi) = ((1u64 << b) - 1, (1u64 << (b + 1)) - 1);
812                e.0 += u64::from(o.shown).min(hi) - lo;
813            }
814            for &f in o.fill.iter().take(o.lessons.len()).filter(|f| u32::from(**f) < o.shown) {
815                if let Some(e) = self.pool.bins.get_mut(bin(u64::from(f))) {
816                    e.1 += 1;
817                }
818            }
819            // The tail sample, past the pool (module doc): each a shown lesson at its position.
820            for (l, f) in tail_of(o) {
821                let b = bin(u64::from(f));
822                if self.pool.bins.len() <= b {
823                    self.pool.bins.resize(b + 1, (0, 0));
824                }
825                let applied = u64::from(o.lessons.iter().any(|x| x == l));
826                let e = &mut self.pool.bins[b];
827                e.0 += 1;
828                e.1 += applied;
829                self.pool.tail.0 += 1;
830                self.pool.tail.1 += applied;
831            }
832        }
833        if o.dur_ms > 0 && o.tokens > 0 {
834            if self.pool.latency.len() >= LATENCY_KEEP {
835                self.pool.latency.remove(0);
836            }
837            self.pool.latency.push((o.tokens, u32::try_from(o.dur_ms).unwrap_or(u32::MAX)));
838        }
839        // A stop's call against its harness's stop budget; a name borg does not know has no budget, and
840        // would let a log grow the cache's keys.
841        if stop && o.dur_ms > 0 && crate::harness::ALL.iter().any(|h| h.name() == o.harness) {
842            let calls = self.pool.stops.entry(o.harness.clone()).or_default();
843            if calls.len() >= LATENCY_KEEP {
844                calls.remove(0);
845            }
846            calls.push((u32::try_from(o.dur_ms).unwrap_or(u32::MAX), o.failed));
847        }
848        let learned = o.policy == "learned";
849        self.era |= learned;
850        // Malformed, or past what a check's count holds (`Check::n`): no applies.
851        let Ok(n) = u16::try_from(o.lessons.len()) else { return };
852        if o.failed || n == 0 || o.grades.len() != o.lessons.len() {
853            return;
854        }
855        let free = outcome::free_of(o);
856        let model = format!("{}|{}", o.model, o.prompt_hash);
857        let model = intern(&mut self.models, &mut ix.models, &model);
858        let ci = self.checks.len() as u32;
859        let first = self.applies.len() as u32;
860        let pending = u16::try_from(ix.open.get(&tick).copied().unwrap_or(0)).unwrap_or(u16::MAX);
861        let mut routes = Vec::with_capacity(o.lessons.len());
862        for (i, l) in o.lessons.iter().enumerate() {
863            let route = if o.chosen.contains(l) {
864                Route::Ask
865            } else if free.contains(l) {
866                Route::Free
867            } else if o.placebo.contains(l) {
868                Route::Placebo
869            } else {
870                Route::Not
871            };
872            routes.push(route);
873            // Older records logged only `p`; a free lesson's was 1 under the fixed rule.
874            let pf = o.pf.get(i).copied().unwrap_or(f64::from(u8::from(route == Route::Free)));
875            let lesson = intern(&mut self.lessons, &mut ix.lessons, l);
876            let rank = o.ranks.get(i).copied().unwrap_or(i as u16);
877            let psi = if matches!(route, Route::Placebo | Route::Not) { o.psi } else { 0.0 };
878            // Either view suffices: the hook's state may hold a delivery the log has not yet, and the log
879            // one the state the hook read did not (a delivery during the model call).
880            let nofree = o.nofree.contains(l);
881            let had = nofree || self.sessions[tick as usize].had.binary_search(&lesson).is_ok();
882            let p = o.p.get(i).copied().unwrap_or(0.0);
883            let a = Apply { check: ci, lesson, grade: o.grades[i], rank, route, p, pf, psi, had, nofree, pending, ..Apply::default() };
884            if waiting(&a) {
885                *ix.open.entry(tick).or_default() += 1;
886            }
887            self.applies.push(a);
888            ix.by_lesson.entry((tick, lesson)).or_default().push(first + i as u32);
889        }
890        let count = |r: Route| u16::try_from(routes.iter().filter(|x| **x == r).count()).unwrap_or(u16::MAX);
891        self.checks.push(Check {
892            id: o.check.clone(),
893            tick,
894            ms: o.ms,
895            stop: o.channel == "stop",
896            learned,
897            tokens: o.tokens,
898            model,
899            first,
900            n,
901            m_q: count(Route::Ask),
902            m_f: count(Route::Free),
903            tallied: false,
904            xk: None,
905            xs: None,
906        });
907        if learned {
908            self.count_test(o, ci as usize, tick);
909        }
910        if !o.check.is_empty() {
911            ix.checks.insert(o.check.clone(), ci);
912        }
913        ix.untallied.entry(tick).or_default().push(ci);
914        if learned && self.fit.model.is_some() {
915            let units: Vec<super::Unit> =
916                o.lessons.iter().zip(&o.grades).enumerate().map(|(r, (l, g))| super::Unit { lesson: l, grade: *g, rank: r }).collect();
917            let check = policy::Check { session: &o.session, stop: o.channel == "stop", tokens: o.tokens };
918            // Against the fixed rule the decision was gated against: under the lessons it had.
919            policy::ledger_add_without(&self.fit, &mut self.gate, &check, &units, &routes, &o.nofree);
920        }
921        if self.applies.len() > MAX_APPLIES {
922            self.compact(ix, MAX_APPLIES / 4, 0);
923        }
924    }
925
926    /// The question-count test at the learned check `ci` of record `o` (module doc): a drawn count
927    /// counted by its k and s and marked on the check, its session counted once; a refusal also by its k.
928    fn count_test(&mut self, o: &Outcome, ci: usize, tick: u32) {
929        let Some(k) = o.xk.filter(|k| *k as usize <= o.lessons.len()) else { return };
930        let source = o.source.as_str();
931        if ![policy::EXPERIMENT, policy::EXPERIMENT_CONTROL, policy::GATE].contains(&source) {
932            return;
933        }
934        // Every source of the test logs its draw's s (select/policy.rs `choose`): a record without one
935        // is not the test's.
936        let Some(s) = o.xs.filter(|s| *s <= k) else { return };
937        let e = &mut self.experiment;
938        if source == policy::GATE {
939            match e.refused.binary_search_by_key(&k, |c| c.0) {
940                Ok(i) => e.refused[i].1 += 1,
941                Err(i) => e.refused.insert(i, (k, 1)),
942            }
943        }
944        match e.ran.binary_search_by_key(&(k, s), |c| (c.0, c.1)) {
945            Ok(i) => e.ran[i].2 += 1,
946            Err(i) => e.ran.insert(i, (k, s, 1)),
947        }
948        e.control += u64::from(source == policy::EXPERIMENT_CONTROL);
949        (self.checks[ci].xk, self.checks[ci].xs) = (Some(k), Some(s));
950        let x = &mut self.sessions[tick as usize];
951        e.sessions += u32::from(!x.tested);
952        x.tested = true;
953    }
954
955    /// The apply of `lesson` that a result in `o` belongs to: in its check by id, else (an older
956    /// record) the session's last graded check before it that graded the lesson on one of `routes`.
957    fn apply_of(&self, o: &Outcome, lesson: &str, routes: &[Route], ix: &Index) -> Option<usize> {
958        let l = *ix.lessons.get(lesson)?;
959        if !o.check.is_empty() {
960            let c = &self.checks[*ix.checks.get(&o.check)? as usize];
961            return (c.first..c.first + u32::from(c.n)).map(|i| i as usize).find(|&i| self.applies[i].lesson == l && routes.contains(&self.applies[i].route));
962        }
963        let tick = *ix.sessions.get(&o.session)?;
964        ix.by_lesson.get(&(tick, l))?.iter().rev().map(|&i| i as usize).find(|&i| {
965            let a = &self.applies[i];
966            routes.contains(&a.route) && self.checks[a.check as usize].ms < o.ms
967        })
968    }
969
970    /// The routes a result on channel stop names in its check: a stop check's questions; a live check's
971    /// questions waiting for the stop, and its hand-overs in place of questions the stop asked in their
972    /// stead (hook.rs `stop_ask`: `#borg-routed`, a delivery with the reason "in place of a hand-over"),
973    /// whose apply stays the free one its check decided, as the question-count test drew it (its
974    /// verdict and delivery land there: intent to treat). A lesson is on one route in its check.
975    fn stop_routes(&self, o: &Outcome, ix: &Index) -> &'static [Route] {
976        let live = ix.checks.get(&o.check).is_some_and(|&ci| self.checks.get(ci as usize).is_some_and(|c| !c.stop));
977        if live { &[Route::Ask, Route::Free] } else { &[Route::Ask] }
978    }
979
980    /// Whether check `ci` graded a 3: a stop may ask its live questions while they wait (hook.rs
981    /// `Verdict::Ask`), and without one no stop does.
982    fn three(&self, ci: usize) -> bool {
983        let Some(c) = self.checks.get(ci) else { return false };
984        self.applies.get(c.first as usize..c.first as usize + usize::from(c.n)).is_some_and(|a| a.iter().any(|a| a.grade == 3))
985    }
986
987    /// Sets apply `i`'s label to `next` when it yields to it, keeping the session's open count.
988    fn label(&mut self, i: usize, next: Label, ix: &mut Index) {
989        let a = &self.applies[i];
990        if !a.label.yields_to(next) {
991            return;
992        }
993        let tick = self.checks[a.check as usize].tick;
994        let before = waiting(a);
995        self.applies[i].label = next;
996        if before
997            && !waiting(&self.applies[i])
998            && let Some(n) = ix.open.get_mut(&tick)
999        {
1000            *n = n.saturating_sub(1);
1001        }
1002    }
1003
1004    fn verdict(&mut self, o: &Outcome, label: Label, ix: &mut Index) {
1005        if o.channel == "early" {
1006            if !label.pending() {
1007                self.early.judged += 1;
1008                self.early.changed += u32::from(label == Label::Changed);
1009            }
1010            return;
1011        }
1012        let routes: &[Route] = match o.channel.as_str() {
1013            outcome::PLACEBO => &[Route::Placebo],
1014            "stop" => self.stop_routes(o, ix),
1015            "live" => &[Route::Ask],
1016            "queued" => &[Route::Free],
1017            _ => &[Route::Ask, Route::Free],
1018        };
1019        for l in &o.lessons {
1020            let Some(i) = self.apply_of(o, l, routes, ix) else { continue };
1021            self.label(i, label, ix);
1022            if self.applies[i].label == label {
1023                self.applies[i].jv = o.judge;
1024            }
1025            if !label.pending() {
1026                let model = self.models.get(self.checks[self.applies[i].check as usize].model as usize).cloned().unwrap_or_default();
1027                // The session-end judge (outcome.rs `AT_END`) is its own instrument: another prompt, the
1028                // whole session's work in view, after every check. A check's verdict and an older record
1029                // have no `at`: their level is as before.
1030                let at = if o.at.is_empty() { String::new() } else { format!("@{}", o.at) };
1031                let key = format!("v{}{at}|{model}", o.judge);
1032                self.applies[i].judge = Some(intern(&mut self.judges, &mut ix.judges, &key));
1033                self.applies[i].stripped = o.stripped;
1034            }
1035        }
1036    }
1037
1038    /// A settle record: the session ended (`end`); a lesson it settles without a verdict (an unjudged
1039    /// reason) is censored. A settle that names the binary that wrote it (0.7.3 on, outcome.rs
1040    /// `settle_with`) also censors every delivered apply of the lesson in the session still without a
1041    /// verdict, whatever the reason: a later delivery took its place in the judge's list (hook.rs
1042    /// `pending`, the latest delivery wins), so none of them is judged now, and a lesson handed over
1043    /// free and then asked, or asked and then handed over, leaves no delivered apply open in an ended
1044    /// session, which the fit (policy.rs `judged`) and the readout (replay.rs `unit_outcome`) would
1045    /// skip. An older settle folds as it did when its hooks decided on it, so the replay (P1) still
1046    /// reproduces their decisions. One never delivered (`Delivered::Unknown`) stays as it was.
1047    fn settled(&mut self, o: &Outcome, ix: &mut Index) {
1048        let tick = self.tick(&o.session, ix);
1049        self.end(tick, ix);
1050        for l in &o.lessons {
1051            if o.reason != outcome::UNJUDGED_NONE
1052                && let Some(i) = self.apply_of(o, l, &[Route::Ask, Route::Free, Route::Placebo], ix)
1053            {
1054                self.label(i, Label::Censored, ix);
1055            }
1056            if o.version.is_empty() {
1057                continue;
1058            }
1059            let Some(&lesson) = ix.lessons.get(l) else { continue };
1060            let open: Vec<usize> = ix
1061                .by_lesson
1062                .get(&(tick, lesson))
1063                .into_iter()
1064                .flatten()
1065                .map(|&i| i as usize)
1066                .filter(|&i| self.applies[i].delivered == Delivered::Yes && waiting(&self.applies[i]))
1067                .collect();
1068            for i in open {
1069                self.label(i, Label::Censored, ix);
1070            }
1071        }
1072    }
1073
1074    /// The end of session `tick` (module doc): its checks not yet tallied count now.
1075    fn end(&mut self, tick: u32, ix: &mut Index) {
1076        self.sessions[tick as usize].ended = true;
1077        for ci in ix.untallied.remove(&tick).unwrap_or_default() {
1078            self.tally(ci as usize);
1079        }
1080    }
1081
1082    /// Counts check `ci`'s applies into its session's delivery tallies (`counted`).
1083    fn tally(&mut self, ci: usize) {
1084        let three = self.three(ci);
1085        let c = &mut self.checks[ci];
1086        c.tallied = true;
1087        let (tick, stop, range) = (c.tick as usize, c.stop, c.first as usize..c.first as usize + usize::from(c.n));
1088        for i in range {
1089            let Some(a) = self.applies.get(i) else { continue };
1090            for (which, hit) in counted(a, stop, three).into_iter().flatten() {
1091                let t = &mut self.sessions[tick].tally[which];
1092                t.0 += 1;
1093                t.1 += u32::from(hit);
1094            }
1095        }
1096    }
1097
1098    /// Changes apply `i` by `set` (its delivery, never its route or `had`); when its check is tallied
1099    /// already (its session ended, then resumed), its counts in the tallies move with it.
1100    fn update(&mut self, i: usize, set: impl FnOnce(&mut Apply)) {
1101        let Some(ci) = self.applies.get(i).map(|a| a.check as usize) else { return };
1102        let Some(c) = self.checks.get(ci) else { return };
1103        let (tallied, stop, tick, three) = (c.tallied, c.stop, c.tick as usize, self.three(ci));
1104        let before = counted(&self.applies[i], stop, three);
1105        set(&mut self.applies[i]);
1106        let after = counted(&self.applies[i], stop, three);
1107        let Some(x) = self.sessions.get_mut(tick).filter(|_| tallied) else { return };
1108        for (b, a) in before.into_iter().zip(after) {
1109            if let (Some((which, was)), Some((_, is))) = (b, a)
1110                && was != is
1111            {
1112                let hits = &mut x.tally[which].1;
1113                *hits = if is { *hits + 1 } else { hits.saturating_sub(1) };
1114            }
1115        }
1116    }
1117
1118    /// `lesson` shown to `session` (module doc: what a session had): into the `Session::had` of its tick,
1119    /// or, without one yet, its `fresh` entry (past `MAX_FRESH`, the oldest quarter go first). Its index.
1120    fn show(&mut self, tick: Option<u32>, session: &str, lesson: &str, ix: &mut Index) -> u32 {
1121        let l = intern(&mut self.lessons, &mut ix.lessons, lesson);
1122        let had = match tick {
1123            Some(t) => &mut self.sessions[t as usize].had,
1124            None => {
1125                if self.fresh.len() >= MAX_FRESH && !self.fresh.contains_key(session) {
1126                    let mut seqs: Vec<u64> = self.fresh.values().map(|f| f.seq).collect();
1127                    seqs.sort_unstable();
1128                    let keep = seqs[MAX_FRESH / 4];
1129                    self.fresh.retain(|_, f| f.seq >= keep);
1130                }
1131                let seq = self.at;
1132                &mut self.fresh.entry(session.to_string()).or_insert_with(|| Fresh { seq, had: Vec::new() }).had
1133            }
1134        };
1135        if let Err(at) = had.binary_search(&l) {
1136            had.insert(at, l);
1137        }
1138        l
1139    }
1140
1141    /// A delivery (outcome.rs `delivery` with its route, or an older `asked` record): the decided
1142    /// apply's fate; and, shown to the drone (not a placebo), the lesson the session had (`show`) and
1143    /// every apply of it an earlier check of the session left for later now delivered later. A
1144    /// `never_delivered` one ends the session.
1145    fn delivered(&mut self, o: &Outcome, ix: &mut Index) {
1146        let (fate, routes): (Delivered, &[Route]) = match (o.kind.as_str(), o.route.as_str()) {
1147            (outcome::DELIVERY, outcome::ROUTE_ASKED) if o.channel == "stop" => (Delivered::Yes, self.stop_routes(o, ix)),
1148            (outcome::DELIVERY, outcome::ROUTE_ASKED) => (Delivered::Yes, &[Route::Ask]),
1149            (outcome::DELIVERY, outcome::ROUTE_FREE) => (Delivered::Yes, &[Route::Free]),
1150            (outcome::DELIVERY, outcome::ROUTE_PLACEBO) => (Delivered::Yes, &[Route::Placebo]),
1151            (outcome::DELIVERY, _) => (Delivered::Dropped, &[Route::Ask, Route::Free, Route::Placebo]),
1152            (_, _) if o.channel == "queued" => (Delivered::Yes, &[Route::Free]),
1153            (_, _) if o.channel == "stop" => (Delivered::Yes, self.stop_routes(o, ix)),
1154            (_, _) if o.channel == "live" => (Delivered::Yes, &[Route::Ask]),
1155            _ => (Delivered::Yes, &[]),
1156        };
1157        // A placebo is judged, never shown: not had, and no later delivery of anything.
1158        let shown = fate == Delivered::Yes && o.route != outcome::ROUTE_PLACEBO;
1159        let Some(&tick) = ix.sessions.get(&o.session) else {
1160            // An early delivery before the session's first check: what that check's applies had.
1161            for l in o.lessons.iter().filter(|_| shown) {
1162                self.show(None, &o.session, l, ix);
1163            }
1164            return;
1165        };
1166        for l in &o.lessons {
1167            let own = if routes.is_empty() { None } else { self.apply_of(o, l, routes, ix) };
1168            if let Some(i) = own {
1169                let before = waiting(&self.applies[i]);
1170                let c = &self.checks[self.applies[i].check as usize];
1171                let waited = fate == Delivered::Yes && o.channel == "stop" && !c.stop && self.applies[i].route == Route::Ask;
1172                self.update(i, |a| {
1173                    a.delivered = fate;
1174                    a.waited |= waited;
1175                });
1176                let after = waiting(&self.applies[i]);
1177                let open = ix.open.entry(tick).or_default();
1178                match (before, after) {
1179                    (true, false) => *open = open.saturating_sub(1),
1180                    (false, true) => *open += 1,
1181                    _ => {}
1182                }
1183            }
1184            if !shown {
1185                continue;
1186            }
1187            let lesson = self.show(Some(tick), &o.session, l, ix);
1188            let own_check = own.map(|i| self.applies[i].check);
1189            for &i in ix.by_lesson.get(&(tick, lesson)).map_or(&[][..], Vec::as_slice) {
1190                let a = &self.applies[i as usize];
1191                if a.route == Route::Not && Some(a.check) != own_check && self.checks[a.check as usize].ms < o.ms {
1192                    self.update(i as usize, |a| a.later = true);
1193                }
1194            }
1195        }
1196        // Never delivered because the session ended first: the end hook's, before its `ended`.
1197        if o.kind == outcome::DELIVERY && o.route == outcome::ROUTE_NEVER {
1198            self.end(tick, ix);
1199        }
1200    }
1201
1202    /// Compaction (module doc): drops the oldest checks holding at least `applies` applies; then the
1203    /// oldest sessions, at least `sessions` of them and every one before the first kept check's, with
1204    /// their checks, but none of the newest `policy::FIT_SESSIONS` and an even count (the monitor's
1205    /// halves are the ticks' parities, select/policy.rs `monitor`), into `Past`; and the lessons, models
1206    /// and judges nothing kept names (an apply, or what a kept or fresh session had).
1207    fn compact(&mut self, ix: &mut Index, applies: usize, sessions: usize) {
1208        let cut = self.checks.iter().position(|c| c.first as usize >= applies).unwrap_or(self.checks.len());
1209        let len = self.sessions.len();
1210        let oldest = self.checks[cut..].iter().map(|c| c.tick as usize).min().unwrap_or(len);
1211        let gone = oldest.max(sessions).min(len.saturating_sub(policy::FIT_SESSIONS));
1212        let gone = gone - gone % 2;
1213        self.past.add(&self.sessions[..gone]);
1214        self.sessions.drain(..gone);
1215        let (checks, all) = (std::mem::take(&mut self.checks), std::mem::take(&mut self.applies));
1216        for (ci, mut c) in checks.into_iter().enumerate() {
1217            if ci < cut || (c.tick as usize) < gone {
1218                continue;
1219            }
1220            let of = all.get(c.first as usize..c.first as usize + usize::from(c.n)).unwrap_or_default();
1221            let check = self.checks.len() as u32;
1222            (c.first, c.tick) = (self.applies.len() as u32, c.tick - gone as u32);
1223            self.applies.extend(of.iter().map(|a| Apply { check, ..a.clone() }));
1224            self.checks.push(c);
1225        }
1226        self.dropped += (all.len() - self.applies.len()) as u64;
1227        let had = self.sessions.iter().flat_map(|x| &x.had).chain(self.fresh.values().flat_map(|f| &f.had)).copied();
1228        let lessons = prune(&mut self.lessons, self.applies.iter().map(|a| a.lesson).chain(had));
1229        let judges = prune(&mut self.judges, self.applies.iter().filter_map(|a| a.judge));
1230        let models = prune(&mut self.models, self.checks.iter().map(|c| c.model));
1231        let new = |map: &[u32], i: u32| map.get(i as usize).copied().unwrap_or(i);
1232        for a in &mut self.applies {
1233            (a.lesson, a.judge) = (new(&lessons, a.lesson), a.judge.map(|j| new(&judges, j)));
1234        }
1235        // `prune` keeps the order, so each `had` stays sorted.
1236        for had in self.sessions.iter_mut().map(|x| &mut x.had).chain(self.fresh.values_mut().map(|f| &mut f.had)) {
1237            for l in had.iter_mut() {
1238                *l = new(&lessons, *l);
1239            }
1240        }
1241        for c in &mut self.checks {
1242            c.model = new(&models, c.model);
1243        }
1244        *ix = Index::of(self);
1245    }
1246}
1247
1248/// The delivery tallies an apply of a stop's (else a live) check counts into, each with whether it
1249/// counts as delivered: a free lesson, by its check's channel; a lesson left for later, at a live check
1250/// only (ρ, select/policy.rs `Rates::later`, is shown only and is a lesson left for later during the
1251/// turn: a stop's arrives later only if a next prompt brings it again); a live question of a check
1252/// with a 3 (`three`), whether it reached the drone (during the turn, or waiting for the stop and asked
1253/// in its block) and whether it waited for the stop. None for an apply of a lesson its session had
1254/// (`Apply::had`; module doc: the rates are those of a lesson the session lacks, and a question of it
1255/// may still be delivered and judged), an ask at the stop (it blocks: certain), a live question of a
1256/// check without a 3 (no stop asks it: it arrives at a tool call or the next prompt, as a hand-over
1257/// does, and is valued at the free rate, select/policy.rs `Valuer::ask`) and a placebo.
1258fn counted(a: &Apply, stop: bool, three: bool) -> [Option<(usize, bool)>; 2] {
1259    if a.had {
1260        return [None; 2];
1261    }
1262    match a.route {
1263        Route::Free => [Some((if stop { FREE_STOP } else { FREE_LIVE }, a.delivered == Delivered::Yes)), None],
1264        Route::Not if !stop => [Some((LATER, a.later)), None],
1265        Route::Ask if !stop && three => [Some((ASK_LIVE, a.delivered == Delivered::Yes)), Some((WAIT, a.waited))],
1266        _ => [None; 2],
1267    }
1268}
1269
1270/// A graded record's tail sample (module doc) with each lesson's fill position: `fill` past the
1271/// applies' (aligned with `tail`), each one past the pool (`shown`). Empty without a tail, and for a
1272/// record not in that shape or without its chance `pt` (0 < pt ≤ 1): no uniform sample then.
1273fn tail_of(o: &Outcome) -> Vec<(&str, u16)> {
1274    let at = o.fill.get(o.lessons.len()..).unwrap_or_default();
1275    let past = at.iter().all(|f| u32::from(*f) >= o.shown && *f != u16::MAX);
1276    if o.tail.is_empty() || at.len() != o.tail.len() || !past || !(o.pt > 0.0 && o.pt <= 1.0) {
1277        return Vec::new();
1278    }
1279    o.tail.iter().map(String::as_str).zip(at.iter().copied()).collect()
1280}
1281
1282/// `table` cut to the names `used` points at, in their order; and for each old index, its new one.
1283fn prune(table: &mut Vec<String>, used: impl Iterator<Item = u32>) -> Vec<u32> {
1284    let mut keep = vec![false; table.len()];
1285    for i in used {
1286        if let Some(k) = keep.get_mut(i as usize) {
1287            *k = true;
1288        }
1289    }
1290    let mut map = Vec::with_capacity(keep.len());
1291    for (name, k) in std::mem::take(table).into_iter().zip(keep) {
1292        map.push(table.len() as u32);
1293        if k {
1294            table.push(name);
1295        }
1296    }
1297    map
1298}
1299
1300/// The cache of the store whose lessons file is `lessons`.
1301#[must_use]
1302pub fn cache_path(lessons: &Path) -> PathBuf {
1303    lessons.with_file_name(CACHE)
1304}
1305
1306/// The auto-revert mark of that store.
1307#[must_use]
1308pub fn reverted_path(lessons: &Path) -> PathBuf {
1309    lessons.with_file_name(REVERTED)
1310}
1311
1312/// The summary of the store whose lessons file is `lessons` (module doc): the cache with the log's
1313/// new tail folded in, rebuilt in memory when it cannot be resumed. Never writes.
1314#[must_use]
1315pub fn load(lessons: &Path) -> Summary {
1316    read(lessons, true)
1317}
1318
1319/// `load` without a rebuild, for a hook that must stay cheap (an early delivery, `PostToolUse`): the
1320/// prior when the cache cannot be resumed.
1321#[must_use]
1322pub fn peek(lessons: &Path) -> Summary {
1323    read(lessons, false)
1324}
1325
1326/// The live check's and the stop's `load`: the summary, saved when it holds more than the cache did
1327/// (a fold of a new tail, a rebuild). A failed save costs the next hook the same fold, nothing else.
1328pub fn refresh(lessons: &Path) -> Summary {
1329    let (s, cached) = read_at(lessons, true);
1330    if cached != Some(s.at) {
1331        let _ = save(lessons, &s);
1332    }
1333    s
1334}
1335
1336fn read(lessons: &Path, rebuild_ok: bool) -> Summary {
1337    read_at(lessons, rebuild_ok).0
1338}
1339
1340/// `read`, and the `at` of the cache it resumed (None: none, or one it could not use).
1341fn read_at(lessons: &Path, rebuild_ok: bool) -> (Summary, Option<u64>) {
1342    let log = outcome::path_beside(lessons);
1343    let len = std::fs::metadata(&log).map_or(0, |m| m.len());
1344    let cached = std::fs::read(cache_path(lessons))
1345        .ok()
1346        .and_then(|b| serde_json::from_slice::<Summary>(&b).ok())
1347        .filter(|s| s.sv == SV && s.at <= len && s.consistent());
1348    let reverted = reverted_path(lessons).exists();
1349    let mut resumed = cached.as_ref().map(|s| s.at);
1350    let Some(mut s) = cached.or_else(|| rebuild_ok.then(|| rebuild(lessons))) else {
1351        return (Summary { monitor: Monitor { reverted, ..Monitor::default() }, ..Summary::default() }, None);
1352    };
1353    if s.at < len {
1354        match tail(&log, s.at) {
1355            Some(text) => s = fold(&text, s),
1356            None if rebuild_ok => (s, resumed) = (rebuild(lessons), None),
1357            None => (s, resumed) = (Summary::default(), None),
1358        }
1359    }
1360    // The mark is the revert, not the cache's copy of it: removing the mark resumes learning (`REVERTED`).
1361    s.monitor.reverted = reverted;
1362    (s, resumed)
1363}
1364
1365/// The log's bytes from `at`, or None when they cannot be read as text.
1366fn tail(log: &Path, at: u64) -> Option<String> {
1367    let mut f = std::fs::File::open(log).ok()?;
1368    f.seek(std::io::SeekFrom::Start(at)).ok()?;
1369    let mut bytes = Vec::new();
1370    f.read_to_end(&mut bytes).ok()?;
1371    String::from_utf8(bytes).ok()
1372}
1373
1374/// Writes `s` as the cache beside `lessons`: a temp file, then a rename, so a reader never sees half.
1375pub fn save(lessons: &Path, s: &Summary) -> std::io::Result<()> {
1376    let target = cache_path(lessons);
1377    let tmp = target.with_extension(format!("{}.tmp", std::process::id()));
1378    std::fs::write(&tmp, serde_json::to_vec(s).map_err(std::io::Error::other)?)?;
1379    std::fs::rename(&tmp, &target).inspect_err(|_| {
1380        let _ = std::fs::remove_file(&tmp);
1381    })
1382}
1383
1384/// The summary from the whole outcome log beside `lessons` (`borg debug select --rebuild`, a cache that
1385/// cannot be resumed), folded from the prior: no fit.
1386#[must_use]
1387pub fn rebuild(lessons: &Path) -> Summary {
1388    let text = std::fs::read_to_string(outcome::path_beside(lessons)).unwrap_or_default();
1389    fold(&text, Summary::default())
1390}
1391
1392/// `s` refitted (select/policy.rs `fit`) under an engineer's `budget` (pool tokens per session), with
1393/// the gate's ledger replayed under the new fit and the monitor read; a revert stays.
1394#[must_use]
1395pub fn with_fit(mut s: Summary, budget: Option<f64>) -> Summary {
1396    s.fit = policy::fit(&s, budget);
1397    s.gate = policy::ledger(&s);
1398    let sticky = s.monitor.reverted;
1399    s.monitor = policy::monitor(&s);
1400    s.monitor.reverted |= sticky;
1401    s
1402}
1403
1404/// `borg learn`: the summary beside `lessons` refitted (`with_fit`, the collective's budget from its
1405/// config, select.rs `budget_of`), its revert mark written when the monitor tripped, and the cache
1406/// saved.
1407pub fn refit(lessons: &Path) -> Summary {
1408    let s = with_fit(load(lessons), super::budget_of(lessons));
1409    if s.monitor.reverted {
1410        let _ = std::fs::write(reverted_path(lessons), format!("{}\n", serde_json::to_string(&s.monitor).unwrap_or_default()));
1411    }
1412    let _ = save(lessons, &s);
1413    s
1414}
1415
1416#[cfg(test)]
1417mod tests {
1418    use super::*;
1419
1420    fn rec(kind: &str, session: &str, lessons: &[&str], ms: i64) -> Outcome {
1421        Outcome { kind: kind.into(), session: session.into(), lessons: lessons.iter().map(|l| l.to_string()).collect(), ms, ..Default::default() }
1422    }
1423
1424    /// A graded check: `ask`ed and `free` lessons by id, the rest left for later.
1425    fn graded(session: &str, check: &str, lessons: &[&str], grades: &[u8], ask: &[&str], free: &[&str], ms: i64) -> Outcome {
1426        let owned = |v: &[&str]| v.iter().map(|l| l.to_string()).collect::<Vec<_>>();
1427        Outcome {
1428            grades: grades.to_vec(),
1429            ranks: (0..lessons.len() as u16).collect(),
1430            applied: lessons.len() as u16,
1431            chosen: owned(ask),
1432            free: owned(free),
1433            channel: "live".into(),
1434            check: check.into(),
1435            policy: "learned".into(),
1436            p: lessons.iter().map(|l| f64::from(u8::from(ask.contains(l)))).collect(),
1437            pf: lessons.iter().map(|l| f64::from(u8::from(free.contains(l)))).collect(),
1438            shown: 20,
1439            tokens: 6000,
1440            fill: (0..lessons.len() as u16).map(|i| 3 * i).collect(),
1441            dur_ms: 9000,
1442            ..rec(outcome::GRADED, session, lessons, ms)
1443        }
1444    }
1445
1446    fn verdict(kind: &str, session: &str, lesson: &str, check: &str, channel: &str, ms: i64) -> Outcome {
1447        Outcome { check: check.into(), channel: channel.into(), judge: 2, ..rec(kind, session, &[lesson], ms) }
1448    }
1449
1450    fn delivery(session: &str, lesson: &str, check: &str, route: &str, ms: i64) -> Outcome {
1451        Outcome { check: check.into(), route: route.into(), ..rec(outcome::DELIVERY, session, &[lesson], ms) }
1452    }
1453
1454    /// `graded` at the stop.
1455    fn stop(session: &str, check: &str, lessons: &[&str], grades: &[u8], ask: &[&str], free: &[&str], ms: i64) -> Outcome {
1456        Outcome { channel: "stop".into(), ..graded(session, check, lessons, grades, ask, free, ms) }
1457    }
1458
1459    /// What the end hook writes of a queue line still waiting: `never_delivered`.
1460    fn never(session: &str, check: &str, lessons: &[&str], ms: i64) -> Outcome {
1461        Outcome { check: check.into(), route: outcome::ROUTE_NEVER.into(), channel: "queued".into(), ..rec(outcome::DELIVERY, session, lessons, ms) }
1462    }
1463
1464    fn lines(log: &[Outcome]) -> String {
1465        log.iter().map(|o| format!("{}\n", serde_json::to_string(o).unwrap())).collect()
1466    }
1467
1468    /// A log with every kind the fold reads, older records without check ids among them.
1469    fn log() -> Vec<Outcome> {
1470        let legacy = Outcome {
1471            check: String::new(),
1472            policy: String::new(),
1473            pf: Vec::new(),
1474            free: Vec::new(),
1475            ..graded("old", "", &["A", "B", "C"], &[2, 1, 1], &[], &[], 1)
1476        };
1477        let mut placebo = graded("s", "c3", &["A", "B", "C"], &[1, 1, 2], &[], &["C"], 40);
1478        placebo.placebo = vec!["A".into()];
1479        placebo.psi = 0.5;
1480        vec![
1481            legacy,
1482            Outcome { channel: "queued".into(), ..rec(outcome::ASKED, "old", &["A"], 2) },
1483            Outcome { channel: "queued".into(), ..rec(outcome::CHANGED, "old", &["A"], 3) },
1484            Outcome { channel: "queued".into(), ..rec(outcome::IGNORED, "old", &["B"], 4) },
1485            rec(outcome::NOT_CORRECTED, "old", &["C"], 5),
1486            graded("s", "c1", &["A", "B"], &[3, 2], &["A", "B"], &[], 10),
1487            delivery("s", "A", "c1", outcome::ROUTE_ASKED, 11),
1488            delivery("s", "B", "c1", outcome::ROUTE_DROPPED_DONE, 11),
1489            rec(outcome::REGRETTED, "s", &["A"], 12),
1490            Outcome { cause: "R1".into(), credit: 0.5, ..rec(outcome::REGRETTED, "s", &["B"], 12) },
1491            verdict(outcome::UNCLEAR, "s", "A", "c1", "live", 13),
1492            verdict(outcome::CHANGED, "s", "A", "c1", "live", 14),
1493            graded("s", "c2", &["D", "E"], &[1, 2], &[], &["E"], 20),
1494            Outcome { channel: "early".into(), ..rec(outcome::CHANGED, "s", &["Q"], 21) },
1495            delivery("s", "E", "c2", outcome::ROUTE_FREE, 22),
1496            Outcome { check: "c9".into(), channel: "live".into(), ..rec(outcome::ASKED, "s", &["D"], 30) },
1497            placebo,
1498            delivery("s", "A", "c3", outcome::ROUTE_PLACEBO, 41),
1499            verdict(outcome::IGNORED, "s", "A", "c3", outcome::PLACEBO, 42),
1500            verdict(outcome::CHANGED, "s", "C", "c3", "queued", 43),
1501            rec(outcome::VETOED, "s", &["C"], 44),
1502            Outcome { reason: outcome::UNJUDGED_TRIES.into(), check: "c2".into(), ..rec(outcome::NOT_CORRECTED, "s", &["E"], 50) },
1503            rec(outcome::TESTED, "s", &["A"], 51),
1504            Outcome { kind: "graded".into(), failed: true, tokens: 6000, dur_ms: 30_000, ..graded("s", "c4", &[], &[], &[], &[], 52) },
1505        ]
1506    }
1507
1508    fn label_of(s: &Summary, check: &str, lesson: &str) -> (Route, Label, Delivered) {
1509        let c = s.checks.iter().find(|c| c.id == check).unwrap();
1510        let a = s.applies[c.first as usize..(c.first + u32::from(c.n)) as usize].iter().find(|a| s.lessons[a.lesson as usize] == lesson).unwrap();
1511        (a.route, a.label, a.delivered)
1512    }
1513
1514    #[test]
1515    fn results_join_their_check_by_id_and_older_ones_by_the_last_check_before() {
1516        let s = fold(&lines(&log()), Summary::default());
1517        assert_eq!(s.checks.len(), 4, "the failed check has no applies");
1518        // The older check: no id, its results by the session's last check before them, on the route
1519        // their channel names.
1520        let old = &s.applies[..3];
1521        // C settled by an older binary (no reason) without a verdict: censored.
1522        assert_eq!(
1523            old.iter().map(|a| (a.route, a.label)).collect::<Vec<_>>(),
1524            [(Route::Free, Label::Changed), (Route::Free, Label::Ignored), (Route::Free, Label::Censored)]
1525        );
1526        assert_eq!(old[0].delivered, Delivered::Yes);
1527        assert_eq!(old[0].pf, 1.0, "an older record's free lesson had pf 1");
1528        // A verdict supersedes an unclear one; a dropped ask stays without a verdict.
1529        assert_eq!(label_of(&s, "c1", "A"), (Route::Ask, Label::Changed, Delivered::Yes));
1530        assert_eq!(label_of(&s, "c1", "B"), (Route::Ask, Label::Open, Delivered::Dropped));
1531        // A placebo's verdict labels the placebo, never the free lesson beside it.
1532        assert_eq!(label_of(&s, "c3", "A"), (Route::Placebo, Label::Ignored, Delivered::Yes));
1533        assert_eq!(label_of(&s, "c3", "C"), (Route::Free, Label::Changed, Delivered::Unknown));
1534        // Settled without a verdict: censored; D was left for later by c2 and asked after it.
1535        assert_eq!(label_of(&s, "c2", "E").1, Label::Censored);
1536        let d = s.applies.iter().find(|a| s.lessons[a.lesson as usize] == "D").unwrap();
1537        assert!(d.later && d.route == Route::Not);
1538        // c2b leaves A for later; c3 then draws A as a placebo, judged but never shown: no later delivery.
1539        let mut more = log();
1540        more.insert(16, graded("s", "c2b", &["A"], &[1], &[], &[], 35));
1541        let s2 = fold(&lines(&more), Summary::default());
1542        assert!(!s2.applies[s2.checks.iter().find(|c| c.id == "c2b").unwrap().first as usize].later, "a placebo is no delivery");
1543        assert_eq!(s.applies.iter().find(|a| a.route == Route::Placebo).map(|a| a.psi), Some(0.5));
1544        assert_eq!((s.early.judged, s.early.changed), (1, 1));
1545        assert!(s.applies.iter().filter(|a| a.label == Label::Changed).all(|a| a.judge.is_some()));
1546        assert_eq!(s.judges, ["v0||", "v2||"], "the older verdicts' judge (version 0) and the new one's, each with its check's model");
1547        // Signals and tallies.
1548        assert_eq!((s.signals[1].regrets, s.signals[1].vetoes, s.signals[1].tested), (2, 1, 1));
1549        assert_eq!(s.sessions.iter().map(|x| x.id.as_str()).collect::<Vec<_>>(), ["old", "s"]);
1550        assert!(s.sessions.iter().all(|x| x.ended));
1551        assert_eq!(s.sessions[1].tally[FREE_LIVE], (2, 1), "E delivered, C not");
1552        assert_eq!(s.sessions[1].tally[LATER], (2, 1), "c2's D delivered later, c3's B not");
1553        assert_eq!(s.pool.latency.len(), 5, "every timed call, the failed one too");
1554        assert_eq!(s.pool.bins[0], (4, 4), "position 0 shown by the four answered calls, applied in each");
1555        assert_eq!(s.pool.bins[2], (16, 6), "positions 3 to 6: fills 3 and 6 of the three-lesson checks, 3 of the two-lesson ones");
1556    }
1557
1558    /// An early delivery, as hook.rs `record_delivery` writes it.
1559    fn early(session: &str, lessons: &[&str], ms: i64) -> Outcome {
1560        Outcome { channel: "early".into(), ..rec(outcome::ASKED, session, lessons, ms) }
1561    }
1562
1563    /// Lines for the state round 0.6.0 added: a session shown a lesson before its first check, a
1564    /// check's `nofree` and tail sample, live questions' fates.
1565    fn more() -> Vec<Outcome> {
1566        let tailed = Outcome {
1567            nofree: vec!["N1".into()],
1568            tail: vec!["T1".into(), "T2".into()],
1569            pt: 0.5,
1570            fill: vec![0, 3, 25, 25, 40],
1571            ..graded("n", "n1", &["A", "N1", "T1"], &[3, 1, 2], &["A"], &["T1"], 61)
1572        };
1573        vec![
1574            early("n", &["N1"], 60),
1575            tailed,
1576            delivery("n", "A", "n1", outcome::ROUTE_ASKED, 62),
1577            delivery("n", "T1", "n1", outcome::ROUTE_FREE, 62),
1578            rec(outcome::ENDED, "n", &[], 63),
1579        ]
1580    }
1581
1582    #[test]
1583    fn a_fold_of_the_whole_equals_its_folds_at_every_line_boundary() {
1584        let text = lines(&[log(), more()].concat());
1585        // With a fit, so the gate's ledger folds too.
1586        let mut prior = Summary::default();
1587        let fitted = with_fit(fold(&text, Summary::default()), None);
1588        prior.fit = fitted.fit.clone();
1589        assert!(prior.fit.model.is_some(), "the log has labels");
1590        let whole = fold(&text, prior.clone());
1591        assert!(whole.gate.checks > 0, "learned checks reached the ledger");
1592        let mut at = 0;
1593        let mut one = prior.clone();
1594        for line in text.split_inclusive('\n') {
1595            let split = fold(&text[at + line.len()..], fold(&text[..at + line.len()], prior.clone()));
1596            assert_eq!(split, whole, "split after byte {}", at + line.len());
1597            one = fold(line, one);
1598            at += line.len();
1599        }
1600        assert_eq!(one, whole, "line by line");
1601        assert_eq!(whole.at, text.len() as u64);
1602        // A refit replays the same ledger the folds built.
1603        let refit = with_fit(whole.clone(), None);
1604        assert_eq!(refit.fit.key, whole.key());
1605    }
1606
1607    #[test]
1608    fn a_line_being_written_waits_for_its_newline() {
1609        let text = lines(&log());
1610        let cut = text.len() - 10;
1611        let s = fold(&text[..cut], Summary::default());
1612        let last_newline = text[..cut].rfind('\n').unwrap() + 1;
1613        assert_eq!(s.at, last_newline as u64);
1614        assert_eq!(fold(&text[s.at as usize..], s), fold(&text, Summary::default()));
1615    }
1616
1617    #[test]
1618    fn kinds_it_does_not_use_cost_a_substring() {
1619        // A regret counts without serde (this one would not parse); an unknown kind is never read.
1620        let text =
1621            [r#"{"kind":"regretted",broken"#, r#"{"kind":"something_new","session":"z"}"#, r#"{"kind":"graded","session":"s","lessons":[],"ms":1,"repo":""}"#]
1622                .map(|l| format!("{l}\n"))
1623                .concat();
1624        let text = text.as_str();
1625        let s = fold(text, Summary::default());
1626        assert_eq!(s.signals[0].regrets, 1);
1627        assert_eq!(s.sessions.len(), 1, "only the graded line registered a session");
1628        assert_eq!(kind_of("{\"kind\":\"asked\",\"x\":1}"), Some("asked"));
1629        assert_eq!(kind_of(" {\"kind\":\"asked\"}"), None);
1630    }
1631
1632    /// A temp store: its lessons file (never written) and the outcomes beside it.
1633    fn store(name: &str, text: &str) -> PathBuf {
1634        let d = std::env::temp_dir().join(format!("borg-summary-{name}-{}", std::process::id()));
1635        let _ = std::fs::remove_dir_all(&d);
1636        std::fs::create_dir_all(&d).unwrap();
1637        std::fs::write(d.join("outcomes.jsonl"), text).unwrap();
1638        d.join("lessons.jsonl")
1639    }
1640
1641    #[test]
1642    fn load_resumes_the_cache_and_rebuilds_what_it_cannot() {
1643        let text = lines(&log());
1644        let half = text[..text.len() / 2].rfind('\n').unwrap() + 1;
1645        let lessons = store("load", &text[..half]);
1646        let whole = fold(&text, Summary::default());
1647        // Saved at half the log, then the rest appended: loading folds only the tail.
1648        save(&lessons, &load(&lessons)).unwrap();
1649        std::fs::write(outcome::path_beside(&lessons), &text).unwrap();
1650        assert_eq!(load(&lessons), whole);
1651        assert_eq!(peek(&lessons), whole);
1652        // A corrupt cache: load rebuilds, peek takes the prior.
1653        std::fs::write(cache_path(&lessons), "{\"sv\":1,\"at\":").unwrap();
1654        assert_eq!(load(&lessons), whole);
1655        assert_eq!(peek(&lessons), Summary::default());
1656        // Another format, and a log shorter than the cache read (rewritten): rebuilt.
1657        let mut other = whole.clone();
1658        other.sv = SV + 1;
1659        save(&lessons, &other).unwrap();
1660        assert_eq!(load(&lessons), whole);
1661        let mut ahead = whole.clone();
1662        ahead.at += 1_000;
1663        save(&lessons, &ahead).unwrap();
1664        assert_eq!(load(&lessons), whole);
1665        // A cache that parses but points outside its tables is corrupt too: never indexed in a hook.
1666        let mut broken = whole.clone();
1667        broken.checks[1].first += 1;
1668        save(&lessons, &broken).unwrap();
1669        assert_eq!((load(&lessons), peek(&lessons)), (whole.clone(), Summary::default()));
1670        let mut broken = whole.clone();
1671        broken.applies[0].lesson = 99;
1672        save(&lessons, &broken).unwrap();
1673        assert_eq!(load(&lessons), whole);
1674        let mut broken = whole.clone();
1675        broken.sessions[1].had.push(99);
1676        save(&lessons, &broken).unwrap();
1677        assert_eq!(load(&lessons), whole, "what a session had points outside the lessons");
1678        assert!(whole.consistent() && Summary::default().consistent());
1679        // A refit summary, its monitor's bound unset before enough sessions, loads as saved (bit for
1680        // bit only as serde_json parses floats: without its `float_roundtrip` a few land 1 ULP off).
1681        let fitted = with_fit(whole.clone(), None);
1682        assert!(fitted.fit.model.is_some() && fitted.monitor.ucb.is_none());
1683        save(&lessons, &fitted).unwrap();
1684        let parsed: Summary = serde_json::from_slice(&serde_json::to_vec(&fitted).unwrap()).unwrap();
1685        assert_eq!(load(&lessons), parsed);
1686        // The revert mark is sticky: read on every load.
1687        std::fs::write(reverted_path(&lessons), "{}\n").unwrap();
1688        assert!(load(&lessons).monitor.reverted && peek(&lessons).monitor.reverted);
1689        // The mark is the revert, not the cache's copy of it (`refit` saves both): removing the mark
1690        // resumes learning.
1691        save(&lessons, &Summary { monitor: Monitor { reverted: true, ..fitted.monitor.clone() }, ..fitted.clone() }).unwrap();
1692        assert!(load(&lessons).monitor.reverted);
1693        std::fs::remove_file(reverted_path(&lessons)).unwrap();
1694        assert!(!load(&lessons).monitor.reverted && !peek(&lessons).monitor.reverted);
1695        // `refresh` saves only what it folded past the cache.
1696        std::fs::write(outcome::path_beside(&lessons), &text[..half]).unwrap();
1697        std::fs::remove_file(cache_path(&lessons)).unwrap();
1698        assert_eq!(refresh(&lessons).at, half as u64, "no cache: rebuilt and saved");
1699        // The same summary written pretty: a rewrite would make it compact again.
1700        let pretty = serde_json::to_vec_pretty(&peek(&lessons)).unwrap();
1701        std::fs::write(cache_path(&lessons), &pretty).unwrap();
1702        assert_eq!(refresh(&lessons).at, half as u64);
1703        assert_eq!(std::fs::read(cache_path(&lessons)).unwrap(), pretty, "nothing new: not rewritten");
1704        std::fs::write(outcome::path_beside(&lessons), &text).unwrap();
1705        assert_eq!(refresh(&lessons), whole);
1706        assert_eq!(peek(&lessons), whole, "the tail it folded is saved");
1707        // No store at all: the prior, no panic.
1708        assert_eq!(load(Path::new("/nonexistent/borg-summary/lessons.jsonl")), Summary::default());
1709        let _ = std::fs::remove_dir_all(lessons.parent().unwrap());
1710    }
1711
1712    #[test]
1713    fn compaction_keeps_the_newest_checks_and_their_joins() {
1714        let text = lines(&log());
1715        let mut s = fold(&text, Summary::default());
1716        let kept = s.checks.len() - 1;
1717        let mut ix = Index::of(&s);
1718        let first = s.checks[1].first as u64;
1719        s.compact(&mut ix, 1, 0);
1720        assert_eq!((s.checks.len(), s.dropped), (kept, first));
1721        assert_eq!(s.checks[0].first, 0);
1722        assert!(s.applies.iter().all(|a| (a.check as usize) < s.checks.len()));
1723        // A later verdict still finds its check.
1724        let more = lines(&[graded("s", "c5", &["Z"], &[2], &[], &["Z"], 60), verdict(outcome::CHANGED, "s", "Z", "c5", "queued", 61)]);
1725        let s = fold(&more, s);
1726        assert_eq!(label_of(&s, "c5", "Z").1, Label::Changed);
1727    }
1728
1729    #[test]
1730    fn every_ended_session_counts_its_deliveries_and_a_resumed_one_moves_them() {
1731        let ended = |session: &str, ms| rec(outcome::ENDED, session, &[], ms);
1732        let log = [
1733            // A stop asks nothing and hands A and B over free; the session ends before a next prompt.
1734            stop("a", "a1", &["A", "B"], &[2, 1], &[], &["A", "B"], 1),
1735            never("a", "a1", &["A", "B"], 2),
1736            ended("a", 3),
1737            // Its one question corrected, a session leaves no settle line: its end alone counts it.
1738            graded("b", "b1", &["C", "D"], &[3, 1], &["C"], &["D"], 10),
1739            delivery("b", "C", "b1", outcome::ROUTE_ASKED, 11),
1740            delivery("b", "D", "b1", outcome::ROUTE_FREE, 11),
1741            rec(outcome::CORRECTED, "b", &["C"], 12),
1742            ended("b", 13),
1743            // An end hook from before `ended`: its `never_delivered` deliveries end the session.
1744            stop("c", "c1", &["E"], &[2], &[], &["E"], 20),
1745            never("c", "c1", &["E"], 21),
1746            // Still open: nothing counts yet.
1747            stop("d", "d1", &["F"], &[2], &[], &["F"], 30),
1748            // A session without a graded check has nothing to count: no entry.
1749            ended("e", 31),
1750        ];
1751        let s = fold(&lines(&log), Summary::default());
1752        let of = |s: &Summary, id: &str| s.sessions.iter().find(|x| x.id == id).cloned().unwrap();
1753        assert_eq!(of(&s, "a").tally[FREE_STOP], (2, 0), "no next prompt came");
1754        assert_eq!((of(&s, "b").tally[FREE_LIVE], of(&s, "b").tally[WAIT]), ((1, 1), (1, 0)), "D delivered; C asked during the turn");
1755        assert_eq!(of(&s, "c").tally[FREE_STOP], (1, 0));
1756        assert_eq!(of(&s, "d").tally, [(0, 0); TALLIES]);
1757        assert_eq!(s.sessions.iter().map(|x| (x.id.as_str(), x.ended)).collect::<Vec<_>>(), [("a", true), ("b", true), ("c", true), ("d", false)]);
1758        // Resumed, `a` hands A over at its next prompt after all: the count follows the latest record.
1759        let resumed = fold(&lines(&[delivery("a", "A", "a1", outcome::ROUTE_FREE, 40)]), s);
1760        assert_eq!(of(&resumed, "a").tally[FREE_STOP], (2, 1));
1761    }
1762
1763    #[test]
1764    fn left_for_later_is_a_live_checks_rate() {
1765        let log = [
1766            // The stop leaves L and M for later and the next turn's live check asks L: not what ρ is,
1767            // a lesson left for later during the turn delivered later.
1768            stop("s", "k1", &["L", "M"], &[1, 1], &[], &[], 1),
1769            graded("s", "k2", &["L"], &[3], &["L"], &[], 5),
1770            delivery("s", "L", "k2", outcome::ROUTE_ASKED, 6),
1771            // A live check leaves N for later, and its turn's stop asks it.
1772            graded("s", "k3", &["N"], &[1], &[], &[], 7),
1773            stop("s", "k4", &["N"], &[3], &["N"], &[], 8),
1774            Outcome { channel: "stop".into(), ..delivery("s", "N", "k4", outcome::ROUTE_ASKED, 9) },
1775            rec(outcome::ENDED, "s", &[], 10),
1776        ];
1777        let s = fold(&lines(&log), Summary::default());
1778        assert_eq!(s.sessions[0].tally[LATER], (1, 1), "k3's N alone");
1779        // The stop's applies still say what came of them.
1780        let k1 = s.checks[0].first as usize;
1781        assert!(s.applies[k1].later && !s.applies[k1 + 1].later, "L arrived later, M never");
1782    }
1783
1784    #[test]
1785    fn a_lesson_its_session_had_counts_in_no_delivery_tally() {
1786        let ended = |session: &str, ms| rec(outcome::ENDED, session, &[], ms);
1787        let log = [
1788            // Delivered early before the session's first check; an older binary then dropped E's free
1789            // hand-over without a record: not a lesson that failed to arrive.
1790            early("a", &["E"], 1),
1791            stop("a", "a1", &["E", "F"], &[2, 1], &[], &["E", "F"], 2),
1792            Outcome { channel: "queued".into(), ..rec(outcome::ASKED, "a", &["F"], 3) },
1793            ended("a", 4),
1794            // Handed over at the session's first check, free again at its next: dropped as given before.
1795            graded("b", "b1", &["G"], &[2], &[], &["G"], 10),
1796            delivery("b", "G", "b1", outcome::ROUTE_FREE, 11),
1797            graded("b", "b2", &["G", "H"], &[2, 1], &[], &["G", "H"], 12),
1798            Outcome { reason: "given before".into(), ..delivery("b", "G", "b2", outcome::ROUTE_DROPPED_DONE, 13) },
1799            delivery("b", "H", "b2", outcome::ROUTE_FREE, 13),
1800            ended("b", 14),
1801            // The hook's state had K, the log no delivery of it (`nofree`): left for later, only M counts.
1802            Outcome { nofree: vec!["K".into()], ..graded("c", "c1", &["K", "M"], &[2, 1], &[], &[], 20) },
1803            ended("c", 21),
1804        ];
1805        let s = fold(&lines(&log), Summary::default());
1806        let of = |id: &str| s.sessions.iter().find(|x| x.id == id).cloned().unwrap();
1807        assert_eq!(of("a").tally[FREE_STOP], (1, 1), "F alone: the session had E");
1808        assert_eq!(of("b").tally[FREE_LIVE], (2, 2), "b1's G and b2's H: at b2 the session had G");
1809        assert_eq!(of("c").tally[LATER], (1, 0), "M alone");
1810        let a1 = s.checks.iter().find(|c| c.id == "a1").unwrap().first as usize;
1811        assert!(s.applies[a1].had && !s.applies[a1 + 1].had);
1812        // What a session was shown before its first check is its own from that check on.
1813        assert!(s.fresh.is_empty());
1814        let names = |x: &Session| x.had.iter().map(|&l| s.lessons[l as usize].clone()).collect::<Vec<_>>();
1815        assert_eq!((names(&of("a")), names(&of("b")), names(&of("c"))), (vec!["E".into(), "F".into()], vec!["G".into(), "H".into()], vec![]));
1816    }
1817
1818    #[test]
1819    fn a_live_question_is_delivered_when_it_reaches_the_drone() {
1820        let at_stop = |o: Outcome| Outcome { channel: "stop".into(), ..o };
1821        let log = [
1822            // Q4 and Q6 were handed over early. Q4, asked again and found done at the stop, counts
1823            // nowhere; Q6, not acted on, reaches the drone and is judged as any question: its verdict
1824            // stays on its apply (top.rs label health), its delivery out of the tallies (`Apply::had`).
1825            early("q", &["Q4", "Q6"], 1),
1826            graded("q", "q1", &["Q1", "Q2", "Q3", "Q4", "Q6"], &[3, 3, 3, 3, 3], &["Q1", "Q2", "Q3", "Q4", "Q6"], &[], 2),
1827            delivery("q", "Q1", "q1", outcome::ROUTE_ASKED, 3),
1828            delivery("q", "Q6", "q1", outcome::ROUTE_ASKED, 3),
1829            verdict(outcome::CHANGED, "q", "Q6", "q1", "live", 4),
1830            // Q2 waited for the stop and was asked in its block; Q3 was not deliverable there.
1831            at_stop(delivery("q", "Q2", "q1", outcome::ROUTE_ASKED, 5)),
1832            Outcome { reason: "not deliverable".into(), ..delivery("q", "Q3", "q1", outcome::ROUTE_DROPPED_DONE, 5) },
1833            Outcome { reason: "done at the stop".into(), ..delivery("q", "Q4", "q1", outcome::ROUTE_DROPPED_DONE, 5) },
1834            // A stop's question blocks: certain, never tallied.
1835            stop("q", "q2", &["Q5"], &[3], &["Q5"], &[], 6),
1836            at_stop(delivery("q", "Q5", "q2", outcome::ROUTE_ASKED, 7)),
1837            rec(outcome::ENDED, "q", &[], 8),
1838        ];
1839        let s = fold(&lines(&log), Summary::default());
1840        assert_eq!((s.sessions[0].tally[ASK_LIVE], s.sessions[0].tally[WAIT]), ((3, 2), (3, 1)));
1841        let q6 = s.checks[0].first as usize + 4;
1842        assert_eq!((label_of(&s, "q1", "Q6"), s.applies[q6].had), ((Route::Ask, Label::Changed, Delivered::Yes), true));
1843        // Learned as the free rates are, Beta(1, 1): (1 + 2) / (2 + 3).
1844        assert!((policy::fit(&s, None).rates.ask_live - 0.6).abs() < 1e-12);
1845        // Before a live question is tallied, the fixed rule's certainty.
1846        assert_eq!((policy::fit(&Summary::default(), None).rates.ask_live, policy::prior().rates.ask_live), (1.0, 1.0));
1847        // Resumed, the session asks Q3 after all: both its counts move.
1848        let s = fold(&lines(&[at_stop(delivery("q", "Q3", "q1", outcome::ROUTE_ASKED, 9))]), s);
1849        assert_eq!((s.sessions[0].tally[ASK_LIVE], s.sessions[0].tally[WAIT]), ((3, 3), (3, 2)));
1850    }
1851
1852    #[test]
1853    fn a_hand_over_the_stop_asked_in_place_is_its_free_applys_delivery_and_verdict() {
1854        // What hook.rs `stop_ask` writes for a live check's question-count test draw: H handed over in
1855        // place of a question, and the stop came before any delivery took it, so it asked H in its block
1856        // with A, the check's waiting question.
1857        let at_stop = |o: Outcome| Outcome { channel: "stop".into(), ..o };
1858        let log = [
1859            graded("s", "k1", &["A", "H"], &[3, 2], &["A"], &["H"], 1),
1860            stop("s", "k2", &[], &[], &[], &[], 2),
1861            at_stop(Outcome { check: "k1".into(), ..rec(outcome::ASKED, "s", &["A"], 3) }),
1862            Outcome { reason: "at the stop".into(), ..at_stop(delivery("s", "A", "k1", outcome::ROUTE_ASKED, 3)) },
1863            at_stop(Outcome { check: "k1".into(), ..rec(outcome::ASKED, "s", &["H"], 3) }),
1864            Outcome { reason: "in place of a hand-over".into(), ..at_stop(delivery("s", "H", "k1", outcome::ROUTE_ASKED, 3)) },
1865            // `#borg-routed H=k1`: the verdict names H's check, on channel stop.
1866            verdict(outcome::CHANGED, "s", "H", "k1", "stop", 4),
1867            verdict(outcome::IGNORED, "s", "A", "k1", "stop", 4),
1868            Outcome { reason: outcome::UNJUDGED_NONE.into(), check: "k1".into(), ..rec(outcome::NOT_CORRECTED, "s", &["A", "H"], 5) },
1869            rec(outcome::ENDED, "s", &[], 6),
1870        ];
1871        let s = fold(&lines(&log), Summary::default());
1872        assert_eq!(label_of(&s, "k1", "H"), (Route::Free, Label::Changed, Delivered::Yes), "the draw's free apply, delivered and judged");
1873        assert_eq!(label_of(&s, "k1", "A"), (Route::Ask, Label::Ignored, Delivered::Yes));
1874        assert_eq!(s.sessions[0].tally[FREE_LIVE], (1, 1), "H arrived");
1875        assert_eq!((s.sessions[0].tally[ASK_LIVE], s.sessions[0].tally[WAIT]), ((1, 1), (1, 1)));
1876        // A stop check's own result stays on its questions.
1877        let log = [stop("t", "t1", &["F", "G"], &[3, 2], &["F"], &["G"], 1), verdict(outcome::CHANGED, "t", "G", "t1", "stop", 2)];
1878        assert_eq!(label_of(&fold(&lines(&log), Summary::default()), "t1", "G").1, Label::Open, "a stop's free lesson is judged on channel queued");
1879    }
1880
1881    #[test]
1882    fn a_live_question_of_a_check_without_a_3_is_no_question_that_waits_for_the_stop() {
1883        let log = [
1884            // A check with a 3: its question waits for the stop and is asked there.
1885            graded("t", "t1", &["A"], &[3], &["A"], &[], 1),
1886            Outcome { channel: "stop".into(), ..delivery("t", "A", "t1", outcome::ROUTE_ASKED, 2) },
1887            // Without a 3 (`live-next`): no stop asks B, and the session ends before a tool call.
1888            graded("t", "t2", &["B", "C"], &[2, 1], &["B"], &[], 3),
1889            Outcome { channel: "queued".into(), ..never("t", "t2", &["B"], 4) },
1890            rec(outcome::ENDED, "t", &[], 5),
1891        ];
1892        let s = fold(&lines(&log), Summary::default());
1893        assert_eq!((s.sessions[0].tally[ASK_LIVE], s.sessions[0].tally[WAIT]), ((1, 1), (1, 1)), "t1's A alone");
1894        assert_eq!(label_of(&s, "t2", "B"), (Route::Ask, Label::Open, Delivered::Dropped), "its apply still says what came of it");
1895        // Resumed, a tool call asks B after all: no tally moves.
1896        let s = fold(&lines(&[delivery("t", "B", "t2", outcome::ROUTE_ASKED, 6)]), s);
1897        assert_eq!((s.sessions[0].tally[ASK_LIVE], s.sessions[0].tally[WAIT]), ((1, 1), (1, 1)));
1898    }
1899
1900    #[test]
1901    fn a_tail_sample_teaches_the_yield_past_the_pool() {
1902        // A pool of four (positions 0 to 3) and a tail of two the budget dropped, at positions 9 and 20 of
1903        // the whole fill order; T1 applied.
1904        let tailed = |pt: f64, at: &[u16]| Outcome {
1905            shown: 4,
1906            tail: vec!["T1".into(), "T2".into()],
1907            pt,
1908            fill: [&[0, 9][..], at].concat(),
1909            ..graded("s", "t1", &["A", "T1"], &[2, 1], &[], &["A", "T1"], 1)
1910        };
1911        let s = fold(&lines(&[tailed(0.25, &[9, 20])]), Summary::default());
1912        // Positions 0, 1–2, 3–6 as the pool showed them; 7–14 and 15–30 each a tail lesson.
1913        assert_eq!(s.pool.bins, [(1, 1), (2, 0), (1, 0), (1, 1), (1, 0)]);
1914        assert_eq!((s.pool.shown, s.pool.tokens), (4, 6000), "the pool's own: the tail is extra");
1915        assert_eq!(s.pool.tail, (2, 1), "the tail's lessons shown and applied, as borg top counts them");
1916        // No chance or one past 1 (no uniform sample), positions missing or inside the pool: the pool alone.
1917        for o in [tailed(0.0, &[9, 20]), tailed(1.5, &[9, 20]), tailed(0.25, &[9]), tailed(0.25, &[2, 20])] {
1918            let s = fold(&lines(&[o]), Summary::default());
1919            assert_eq!((s.pool.bins, s.pool.tail), (vec![(1, 1), (2, 0), (1, 0)], (0, 0)));
1920        }
1921    }
1922
1923    #[test]
1924    fn sessions_shown_lessons_before_a_check_stay_bounded() {
1925        let n = MAX_FRESH + 10;
1926        let text = lines(&(0..n).map(|t| early(&format!("e{t}"), &["L"], t as i64)).collect::<Vec<_>>());
1927        let s = fold(&text, Summary::default());
1928        // The guard: past `MAX_FRESH` the oldest went, the newest stayed.
1929        assert!(s.fresh.len() <= MAX_FRESH, "{} kept", s.fresh.len());
1930        let newest = format!("e{}", n - 1);
1931        assert!(!s.fresh.contains_key("e0") && s.fresh.contains_key(&newest));
1932        assert!(s.sessions.is_empty() && s.consistent());
1933        for at in [text.len() / 2, text.len() - 100] {
1934            let at = text[..at].rfind('\n').unwrap() + 1;
1935            assert_eq!(fold(&text[at..], fold(&text[..at], Summary::default())), s, "split after byte {at}");
1936        }
1937        // The newest graded after all: its free hand-over of what it had counts nowhere.
1938        let s = fold(&lines(&[stop(&newest, "x1", &["L"], &[2], &[], &["L"], 9_999), rec(outcome::ENDED, &newest, &[], 10_000)]), s);
1939        assert_eq!(s.sessions[0].tally[FREE_STOP], (0, 0));
1940    }
1941
1942    #[test]
1943    fn a_regrets_missed_lesson_is_no_correction() {
1944        let log = [
1945            rec(outcome::MISSED, "s", &["A"], 1),
1946            Outcome { cause: "R1".into(), ..rec(outcome::MISSED, "s", &["B"], 2) },
1947            rec(outcome::CORRECTED, "s", &["C"], 3),
1948        ];
1949        assert_eq!(fold(&lines(&log), Summary::default()).signals[0].corrections, 2, "A's and C's: B's is the regret R1 again");
1950    }
1951
1952    #[test]
1953    fn the_monitors_weights_persist_through_save_and_fold() {
1954        let text = lines(&log());
1955        let half = text[..text.len() / 2].rfind('\n').unwrap() + 1;
1956        let lessons = store("monitor", &text[..half]);
1957        let s = Summary { monitor: Monitor { ess: 12.5, max_weight: 3.25, labelled: 7, ..Monitor::default() }, ..load(&lessons) };
1958        save(&lessons, &s).unwrap();
1959        std::fs::write(outcome::path_beside(&lessons), &text).unwrap();
1960        let folded = refresh(&lessons);
1961        assert_eq!(folded.at, text.len() as u64, "the tail folded");
1962        for x in [&folded, &peek(&lessons)] {
1963            assert_eq!((x.monitor.ess, x.monitor.max_weight, x.monitor.labelled), (12.5, 3.25, 7));
1964        }
1965        let _ = std::fs::remove_dir_all(lessons.parent().unwrap());
1966    }
1967
1968    /// `n` sessions, each shown a lesson early that no check grades, then one live check handing its
1969    /// own lesson over free (delivered in the even sessions), then its end.
1970    fn many(n: usize) -> String {
1971        let mut log = Vec::new();
1972        for t in 0..n {
1973            let (id, check, lesson, ms) = (format!("s{t}"), format!("c{t}"), format!("L{t}"), 10 * t as i64);
1974            log.push(early(&id, &[&format!("X{t}")], ms));
1975            log.push(graded(&id, &check, &[&lesson], &[2], &[], &[&lesson], ms));
1976            if t % 2 == 0 {
1977                log.push(delivery(&id, &lesson, &check, outcome::ROUTE_FREE, ms + 1));
1978            }
1979            log.push(rec(outcome::ENDED, &id, &[], ms + 2));
1980        }
1981        lines(&log)
1982    }
1983
1984    #[test]
1985    fn the_session_table_stays_bounded_and_keeps_what_its_readers_need() {
1986        let n = MAX_SESSIONS + 2;
1987        let text = many(n);
1988        let s = fold(&text, Summary::default());
1989        // The guard: past `MAX_SESSIONS` the oldest went, an even count, never the newest.
1990        assert!(s.sessions.len() <= MAX_SESSIONS, "{} sessions kept", s.sessions.len());
1991        assert_eq!((n - s.sessions.len()) % 2, 0, "the monitor's halves keep their sessions");
1992        assert_eq!(s.sessions.last().map(|x| x.id.clone()), Some(format!("s{}", n - 1)));
1993        assert!(s.consistent());
1994        // Their checks went with them, and every lesson only they named; a kept session keeps what it
1995        // was shown, each lesson by its name.
1996        assert_eq!((s.checks.len(), s.dropped), (s.sessions.len(), (n - s.sessions.len()) as u64));
1997        assert_eq!(s.lessons.len(), 2 * s.applies.len());
1998        let newest = s.sessions.last().unwrap();
1999        let shown: Vec<&str> = newest.had.iter().map(|&l| s.lessons[l as usize].as_str()).collect();
2000        assert_eq!(shown, [format!("X{}", n - 1)], "an odd session: its free lesson never came");
2001        let even = &s.sessions[s.sessions.len() - 2];
2002        let shown: Vec<&str> = even.had.iter().map(|&l| s.lessons[l as usize].as_str()).collect();
2003        assert_eq!(shown, [format!("X{}", n - 2), format!("L{}", n - 2)]);
2004        // Every age as before: under every half-life the tallies are all n sessions', and so are the
2005        // sessions and checks spend divides by.
2006        for h in policy::HALF_LIVES {
2007            let want = (0..n).fold((0.0, 0.0), |(k, miss), t| {
2008                let w = policy::decay((n - t) as u32, h);
2009                if t % 2 == 0 { (k + w, miss) } else { (k, miss + w) }
2010            });
2011            let got = s.tallies(h)[FREE_LIVE];
2012            let close = |a: f64, b: f64| (a - b).abs() <= 1e-9 * b.max(1.0);
2013            assert!(close(got.0, want.0) && close(got.1, want.1), "{h:?}: {got:?} against {want:?}");
2014        }
2015        assert_eq!(s.checked(), (n as u64, n as u64));
2016        // A fold split before the compaction, or after it, is the whole fold.
2017        for at in [text.len() / 3, text.len() - 200] {
2018            let at = text[..at].rfind('\n').unwrap() + 1;
2019            assert_eq!(fold(&text[at..], fold(&text[..at], Summary::default())), s, "split after byte {at}");
2020        }
2021    }
2022
2023    /// The question-count test's checks (module doc): a drawn count, played or refused, counts by its k
2024    /// and s and marks its check, its control arm apart, its session once; a refusal also counts by its
2025    /// k; a record whose k or s cannot be its own (a refusal without its s among them), one outside the
2026    /// test and one not of the learned policy count nowhere. The
2027    /// counts are all-time: compaction drops the checks, never them.
2028    #[test]
2029    fn the_question_count_tests_checks_count_by_k_and_s_and_mark_their_check() {
2030        let x = |session: &str, check: &str, source: &str, k: Option<u32>, s: Option<u32>, ms| Outcome {
2031            source: source.into(),
2032            xk: k,
2033            xs: s,
2034            ..graded(session, check, &["A", "B", "C"], &[2, 2, 1], &["A"], &["B", "C"], ms)
2035        };
2036        let text = lines(&[
2037            x("x", "e1", policy::EXPERIMENT, Some(3), Some(1), 10),
2038            x("x", "e2", policy::EXPERIMENT, Some(3), Some(1), 20),
2039            x("x", "e3", policy::EXPERIMENT_CONTROL, Some(3), Some(0), 30),
2040            // No s: no source of the test writes it.
2041            x("x", "g1", policy::GATE, Some(3), None, 40),
2042            // Refused after its draw: randomised, the fixed rule played.
2043            x("x", "g2", policy::GATE, Some(3), Some(2), 45),
2044            // s past k, k past the check's applies.
2045            x("x", "bad", policy::EXPERIMENT, Some(3), Some(4), 50),
2046            x("x", "big", policy::EXPERIMENT, Some(9), Some(1), 60),
2047            x("x", "ev", policy::EVIDENCE, None, None, 70),
2048            Outcome { policy: "fixed".into(), ..x("x", "f1", policy::EXPERIMENT, Some(3), Some(2), 80) },
2049            x("y", "y1", policy::EXPERIMENT, Some(2), Some(2), 90),
2050        ]);
2051        let s = fold(&text, Summary::default());
2052        let e = &s.experiment;
2053        assert_eq!(
2054            (e.ran.as_slice(), e.control, e.refused.as_slice(), e.sessions),
2055            (&[(2, 2, 1), (3, 0, 1), (3, 1, 2), (3, 2, 1)][..], 1, &[(3, 1)][..], 2),
2056            "{e:?}"
2057        );
2058        assert_eq!(e.totals(), (5, 1));
2059        let marked: Vec<(&str, Option<u32>, Option<u32>)> = s.checks.iter().map(|c| (c.id.as_str(), c.xk, c.xs)).filter(|c| c.1.is_some()).collect();
2060        assert_eq!(marked, [("e1", Some(3), Some(1)), ("e2", Some(3), Some(1)), ("e3", Some(3), Some(0)), ("g2", Some(3), Some(2)), ("y1", Some(2), Some(2))]);
2061        assert!(s.sessions.iter().all(|x| x.tested));
2062        // The fold every count shares: a prefix, then the rest, is the whole.
2063        let at = text[..text.len() / 2].rfind('\n').unwrap() + 1;
2064        assert_eq!(fold(&text[at..], fold(&text[..at], Summary::default())), s);
2065        // Compaction takes the checks, not the counts.
2066        let mut compacted = s.clone();
2067        let mut ix = Index::of(&compacted);
2068        compacted.compact(&mut ix, s.applies.len(), 0);
2069        assert_eq!((compacted.checks.len(), &compacted.experiment), (0, &s.experiment));
2070    }
2071
2072    #[test]
2073    fn a_learned_decision_the_fixed_rule_took_over_counts_by_its_reason() {
2074        let fell = |check: &str, reason: &str, applied: &[&str], ms| Outcome {
2075            policy: "fixed".into(),
2076            reason: reason.into(),
2077            ..graded("f", check, applied, &vec![1; applied.len()], &[], applied, ms)
2078        };
2079        let text = lines(&[
2080            fell("f1", outcome::DECIDED_BUSY, &["A"], 1),
2081            fell("f2", outcome::DECIDED_BUSY, &["B"], 2),
2082            // No applies: the check still waited for the lock.
2083            fell("f3", outcome::DECIDED_NO_LOCK, &[], 3),
2084            fell("f4", outcome::DECIDED_NO_RECORD, &["A"], 4),
2085            // Decided by the policy in force, and a reason this binary does not know: no fallback.
2086            graded("f", "f5", &["A"], &[1], &[], &["A"], 5),
2087            fell("f6", "something_new", &["A"], 6),
2088        ]);
2089        let s = fold(&text, Summary::default());
2090        assert_eq!(s.fell_back, [2, 1, 1], "lock_busy, lock_failed, unrecorded");
2091        assert_eq!(s.checked().1, 6, "the graded checks a fallback is one of");
2092        // The fold every count shares: a prefix, then the rest, is the whole.
2093        let at = text[..text.len() / 2].rfind('\n').unwrap() + 1;
2094        assert_eq!(fold(&text[at..], fold(&text[..at], Summary::default())), s);
2095        // Kept by the cache, and a cache of the layout before them (protocol: version 5) is rebuilt,
2096        // never resumed without them.
2097        let lessons = store("fell-back", &text);
2098        save(&lessons, &s).unwrap();
2099        assert_eq!(peek(&lessons).fell_back, s.fell_back);
2100        save(&lessons, &Summary { sv: 5, fell_back: Default::default(), ..s.clone() }).unwrap();
2101        assert_eq!(load(&lessons), s);
2102        let _ = std::fs::remove_dir_all(lessons.parent().unwrap());
2103    }
2104
2105    #[test]
2106    fn the_prior_writes_the_short_line() {
2107        let prior = Summary::default();
2108        assert_eq!((prior.sv, prior.at, &prior.fit), (SV, 0, &Fit::default()));
2109        let line = serde_json::to_string(&prior).unwrap();
2110        assert_eq!(line, format!(r#"{{"sv":{SV},"at":0,"fit":{{}}}}"#));
2111        assert_eq!(serde_json::from_str::<Summary>(&line).unwrap(), prior);
2112        let none = Path::new("/nonexistent/borg-summary/lessons.jsonl");
2113        assert_eq!(load(none), prior);
2114        assert_eq!(rebuild(none), prior);
2115    }
2116}