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