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.
1000    fn settled(&mut self, o: &Outcome, ix: &mut Index) {
1001        let tick = self.tick(&o.session, ix);
1002        self.end(tick, ix);
1003        if o.reason == outcome::UNJUDGED_NONE {
1004            return;
1005        }
1006        for l in &o.lessons {
1007            if let Some(i) = self.apply_of(o, l, &[Route::Ask, Route::Free, Route::Placebo], ix) {
1008                self.label(i, Label::Censored, ix);
1009            }
1010        }
1011    }
1012
1013    /// The end of session `tick` (module doc): its checks not yet tallied count now.
1014    fn end(&mut self, tick: u32, ix: &mut Index) {
1015        self.sessions[tick as usize].ended = true;
1016        for ci in ix.untallied.remove(&tick).unwrap_or_default() {
1017            self.tally(ci as usize);
1018        }
1019    }
1020
1021    /// Counts check `ci`'s applies into its session's delivery tallies (`counted`).
1022    fn tally(&mut self, ci: usize) {
1023        let three = self.three(ci);
1024        let c = &mut self.checks[ci];
1025        c.tallied = true;
1026        let (tick, stop, range) = (c.tick as usize, c.stop, c.first as usize..c.first as usize + usize::from(c.n));
1027        for i in range {
1028            let Some(a) = self.applies.get(i) else { continue };
1029            for (which, hit) in counted(a, stop, three).into_iter().flatten() {
1030                let t = &mut self.sessions[tick].tally[which];
1031                t.0 += 1;
1032                t.1 += u32::from(hit);
1033            }
1034        }
1035    }
1036
1037    /// Changes apply `i` by `set` (its delivery, never its route or `had`); when its check is tallied
1038    /// already (its session ended, then resumed), its counts in the tallies move with it.
1039    fn update(&mut self, i: usize, set: impl FnOnce(&mut Apply)) {
1040        let Some(ci) = self.applies.get(i).map(|a| a.check as usize) else { return };
1041        let Some(c) = self.checks.get(ci) else { return };
1042        let (tallied, stop, tick, three) = (c.tallied, c.stop, c.tick as usize, self.three(ci));
1043        let before = counted(&self.applies[i], stop, three);
1044        set(&mut self.applies[i]);
1045        let after = counted(&self.applies[i], stop, three);
1046        let Some(x) = self.sessions.get_mut(tick).filter(|_| tallied) else { return };
1047        for (b, a) in before.into_iter().zip(after) {
1048            if let (Some((which, was)), Some((_, is))) = (b, a)
1049                && was != is
1050            {
1051                let hits = &mut x.tally[which].1;
1052                *hits = if is { *hits + 1 } else { hits.saturating_sub(1) };
1053            }
1054        }
1055    }
1056
1057    /// `lesson` shown to `session` (module doc: what a session had): into the `Session::had` of its tick,
1058    /// or, without one yet, its `fresh` entry (past `MAX_FRESH`, the oldest quarter go first). Its index.
1059    fn show(&mut self, tick: Option<u32>, session: &str, lesson: &str, ix: &mut Index) -> u32 {
1060        let l = intern(&mut self.lessons, &mut ix.lessons, lesson);
1061        let had = match tick {
1062            Some(t) => &mut self.sessions[t as usize].had,
1063            None => {
1064                if self.fresh.len() >= MAX_FRESH && !self.fresh.contains_key(session) {
1065                    let mut seqs: Vec<u64> = self.fresh.values().map(|f| f.seq).collect();
1066                    seqs.sort_unstable();
1067                    let keep = seqs[MAX_FRESH / 4];
1068                    self.fresh.retain(|_, f| f.seq >= keep);
1069                }
1070                let seq = self.at;
1071                &mut self.fresh.entry(session.to_string()).or_insert_with(|| Fresh { seq, had: Vec::new() }).had
1072            }
1073        };
1074        if let Err(at) = had.binary_search(&l) {
1075            had.insert(at, l);
1076        }
1077        l
1078    }
1079
1080    /// A delivery (outcome.rs `delivery` with its route, or an older `asked` record): the decided
1081    /// apply's fate; and, shown to the drone (not a placebo), the lesson the session had (`show`) and
1082    /// every apply of it an earlier check of the session left for later now delivered later. A
1083    /// `never_delivered` one ends the session.
1084    fn delivered(&mut self, o: &Outcome, ix: &mut Index) {
1085        let (fate, routes): (Delivered, &[Route]) = match (o.kind.as_str(), o.route.as_str()) {
1086            (outcome::DELIVERY, outcome::ROUTE_ASKED) if o.channel == "stop" => (Delivered::Yes, self.stop_routes(o, ix)),
1087            (outcome::DELIVERY, outcome::ROUTE_ASKED) => (Delivered::Yes, &[Route::Ask]),
1088            (outcome::DELIVERY, outcome::ROUTE_FREE) => (Delivered::Yes, &[Route::Free]),
1089            (outcome::DELIVERY, outcome::ROUTE_PLACEBO) => (Delivered::Yes, &[Route::Placebo]),
1090            (outcome::DELIVERY, _) => (Delivered::Dropped, &[Route::Ask, Route::Free, Route::Placebo]),
1091            (_, _) if o.channel == "queued" => (Delivered::Yes, &[Route::Free]),
1092            (_, _) if o.channel == "stop" => (Delivered::Yes, self.stop_routes(o, ix)),
1093            (_, _) if o.channel == "live" => (Delivered::Yes, &[Route::Ask]),
1094            _ => (Delivered::Yes, &[]),
1095        };
1096        // A placebo is judged, never shown: not had, and no later delivery of anything.
1097        let shown = fate == Delivered::Yes && o.route != outcome::ROUTE_PLACEBO;
1098        let Some(&tick) = ix.sessions.get(&o.session) else {
1099            // An early delivery before the session's first check: what that check's applies had.
1100            for l in o.lessons.iter().filter(|_| shown) {
1101                self.show(None, &o.session, l, ix);
1102            }
1103            return;
1104        };
1105        for l in &o.lessons {
1106            let own = if routes.is_empty() { None } else { self.apply_of(o, l, routes, ix) };
1107            if let Some(i) = own {
1108                let before = waiting(&self.applies[i]);
1109                let c = &self.checks[self.applies[i].check as usize];
1110                let waited = fate == Delivered::Yes && o.channel == "stop" && !c.stop && self.applies[i].route == Route::Ask;
1111                self.update(i, |a| {
1112                    a.delivered = fate;
1113                    a.waited |= waited;
1114                });
1115                let after = waiting(&self.applies[i]);
1116                let open = ix.open.entry(tick).or_default();
1117                match (before, after) {
1118                    (true, false) => *open = open.saturating_sub(1),
1119                    (false, true) => *open += 1,
1120                    _ => {}
1121                }
1122            }
1123            if !shown {
1124                continue;
1125            }
1126            let lesson = self.show(Some(tick), &o.session, l, ix);
1127            let own_check = own.map(|i| self.applies[i].check);
1128            for &i in ix.by_lesson.get(&(tick, lesson)).map_or(&[][..], Vec::as_slice) {
1129                let a = &self.applies[i as usize];
1130                if a.route == Route::Not && Some(a.check) != own_check && self.checks[a.check as usize].ms < o.ms {
1131                    self.update(i as usize, |a| a.later = true);
1132                }
1133            }
1134        }
1135        // Never delivered because the session ended first: the end hook's, before its `ended`.
1136        if o.kind == outcome::DELIVERY && o.route == outcome::ROUTE_NEVER {
1137            self.end(tick, ix);
1138        }
1139    }
1140
1141    /// Compaction (module doc): drops the oldest checks holding at least `applies` applies; then the
1142    /// oldest sessions, at least `sessions` of them and every one before the first kept check's, with
1143    /// their checks, but none of the newest `policy::FIT_SESSIONS` and an even count (the monitor's
1144    /// halves are the ticks' parities, select/policy.rs `monitor`), into `Past`; and the lessons, models
1145    /// and judges nothing kept names (an apply, or what a kept or fresh session had).
1146    fn compact(&mut self, ix: &mut Index, applies: usize, sessions: usize) {
1147        let cut = self.checks.iter().position(|c| c.first as usize >= applies).unwrap_or(self.checks.len());
1148        let len = self.sessions.len();
1149        let oldest = self.checks[cut..].iter().map(|c| c.tick as usize).min().unwrap_or(len);
1150        let gone = oldest.max(sessions).min(len.saturating_sub(policy::FIT_SESSIONS));
1151        let gone = gone - gone % 2;
1152        self.past.add(&self.sessions[..gone]);
1153        self.sessions.drain(..gone);
1154        let (checks, all) = (std::mem::take(&mut self.checks), std::mem::take(&mut self.applies));
1155        for (ci, mut c) in checks.into_iter().enumerate() {
1156            if ci < cut || (c.tick as usize) < gone {
1157                continue;
1158            }
1159            let of = all.get(c.first as usize..c.first as usize + usize::from(c.n)).unwrap_or_default();
1160            let check = self.checks.len() as u32;
1161            (c.first, c.tick) = (self.applies.len() as u32, c.tick - gone as u32);
1162            self.applies.extend(of.iter().map(|a| Apply { check, ..a.clone() }));
1163            self.checks.push(c);
1164        }
1165        self.dropped += (all.len() - self.applies.len()) as u64;
1166        let had = self.sessions.iter().flat_map(|x| &x.had).chain(self.fresh.values().flat_map(|f| &f.had)).copied();
1167        let lessons = prune(&mut self.lessons, self.applies.iter().map(|a| a.lesson).chain(had));
1168        let judges = prune(&mut self.judges, self.applies.iter().filter_map(|a| a.judge));
1169        let models = prune(&mut self.models, self.checks.iter().map(|c| c.model));
1170        let new = |map: &[u32], i: u32| map.get(i as usize).copied().unwrap_or(i);
1171        for a in &mut self.applies {
1172            (a.lesson, a.judge) = (new(&lessons, a.lesson), a.judge.map(|j| new(&judges, j)));
1173        }
1174        // `prune` keeps the order, so each `had` stays sorted.
1175        for had in self.sessions.iter_mut().map(|x| &mut x.had).chain(self.fresh.values_mut().map(|f| &mut f.had)) {
1176            for l in had.iter_mut() {
1177                *l = new(&lessons, *l);
1178            }
1179        }
1180        for c in &mut self.checks {
1181            c.model = new(&models, c.model);
1182        }
1183        *ix = Index::of(self);
1184    }
1185}
1186
1187/// The delivery tallies an apply of a stop's (else a live) check counts into, each with whether it
1188/// counts as delivered: a free lesson, by its check's channel; a lesson left for later, at a live check
1189/// only (ρ, select/policy.rs `Rates::later`, is shown only and is a lesson left for later during the
1190/// turn: a stop's arrives later only if a next prompt brings it again); a live question of a check
1191/// with a 3 (`three`), whether it reached the drone (during the turn, or waiting for the stop and asked
1192/// in its block) and whether it waited for the stop. None for an apply of a lesson its session had
1193/// (`Apply::had`; module doc: the rates are those of a lesson the session lacks, and a question of it
1194/// may still be delivered and judged), an ask at the stop (it blocks: certain), a live question of a
1195/// check without a 3 (no stop asks it: it arrives at a tool call or the next prompt, as a hand-over
1196/// does, and is valued at the free rate, select/policy.rs `Valuer::ask`) and a placebo.
1197fn counted(a: &Apply, stop: bool, three: bool) -> [Option<(usize, bool)>; 2] {
1198    if a.had {
1199        return [None; 2];
1200    }
1201    match a.route {
1202        Route::Free => [Some((if stop { FREE_STOP } else { FREE_LIVE }, a.delivered == Delivered::Yes)), None],
1203        Route::Not if !stop => [Some((LATER, a.later)), None],
1204        Route::Ask if !stop && three => [Some((ASK_LIVE, a.delivered == Delivered::Yes)), Some((WAIT, a.waited))],
1205        _ => [None; 2],
1206    }
1207}
1208
1209/// A graded record's tail sample (module doc) with each lesson's fill position: `fill` past the
1210/// applies' (aligned with `tail`), each one past the pool (`shown`). Empty without a tail, and for a
1211/// record not in that shape or without its chance `pt` (0 < pt ≤ 1): no uniform sample then.
1212fn tail_of(o: &Outcome) -> Vec<(&str, u16)> {
1213    let at = o.fill.get(o.lessons.len()..).unwrap_or_default();
1214    let past = at.iter().all(|f| u32::from(*f) >= o.shown && *f != u16::MAX);
1215    if o.tail.is_empty() || at.len() != o.tail.len() || !past || !(o.pt > 0.0 && o.pt <= 1.0) {
1216        return Vec::new();
1217    }
1218    o.tail.iter().map(String::as_str).zip(at.iter().copied()).collect()
1219}
1220
1221/// `table` cut to the names `used` points at, in their order; and for each old index, its new one.
1222fn prune(table: &mut Vec<String>, used: impl Iterator<Item = u32>) -> Vec<u32> {
1223    let mut keep = vec![false; table.len()];
1224    for i in used {
1225        if let Some(k) = keep.get_mut(i as usize) {
1226            *k = true;
1227        }
1228    }
1229    let mut map = Vec::with_capacity(keep.len());
1230    for (name, k) in std::mem::take(table).into_iter().zip(keep) {
1231        map.push(table.len() as u32);
1232        if k {
1233            table.push(name);
1234        }
1235    }
1236    map
1237}
1238
1239/// The cache of the store whose lessons file is `lessons`.
1240#[must_use]
1241pub fn cache_path(lessons: &Path) -> PathBuf {
1242    lessons.with_file_name(CACHE)
1243}
1244
1245/// The auto-revert mark of that store.
1246#[must_use]
1247pub fn reverted_path(lessons: &Path) -> PathBuf {
1248    lessons.with_file_name(REVERTED)
1249}
1250
1251/// The summary of the store whose lessons file is `lessons` (module doc): the cache with the log's
1252/// new tail folded in, rebuilt in memory when it cannot be resumed. Never writes.
1253#[must_use]
1254pub fn load(lessons: &Path) -> Summary {
1255    read(lessons, true)
1256}
1257
1258/// `load` without a rebuild, for a hook that must stay cheap (an early delivery, `PostToolUse`): the
1259/// prior when the cache cannot be resumed.
1260#[must_use]
1261pub fn peek(lessons: &Path) -> Summary {
1262    read(lessons, false)
1263}
1264
1265/// The live check's and the stop's `load`: the summary, saved when it holds more than the cache did
1266/// (a fold of a new tail, a rebuild). A failed save costs the next hook the same fold, nothing else.
1267pub fn refresh(lessons: &Path) -> Summary {
1268    let (s, cached) = read_at(lessons, true);
1269    if cached != Some(s.at) {
1270        let _ = save(lessons, &s);
1271    }
1272    s
1273}
1274
1275fn read(lessons: &Path, rebuild_ok: bool) -> Summary {
1276    read_at(lessons, rebuild_ok).0
1277}
1278
1279/// `read`, and the `at` of the cache it resumed (None: none, or one it could not use).
1280fn read_at(lessons: &Path, rebuild_ok: bool) -> (Summary, Option<u64>) {
1281    let log = outcome::path_beside(lessons);
1282    let len = std::fs::metadata(&log).map_or(0, |m| m.len());
1283    let cached = std::fs::read(cache_path(lessons))
1284        .ok()
1285        .and_then(|b| serde_json::from_slice::<Summary>(&b).ok())
1286        .filter(|s| s.sv == SV && s.at <= len && s.consistent());
1287    let reverted = reverted_path(lessons).exists();
1288    let mut resumed = cached.as_ref().map(|s| s.at);
1289    let Some(mut s) = cached.or_else(|| rebuild_ok.then(|| rebuild(lessons))) else {
1290        return (Summary { monitor: Monitor { reverted, ..Monitor::default() }, ..Summary::default() }, None);
1291    };
1292    if s.at < len {
1293        match tail(&log, s.at) {
1294            Some(text) => s = fold(&text, s),
1295            None if rebuild_ok => (s, resumed) = (rebuild(lessons), None),
1296            None => (s, resumed) = (Summary::default(), None),
1297        }
1298    }
1299    // The mark is the revert, not the cache's copy of it: removing the mark resumes learning (`REVERTED`).
1300    s.monitor.reverted = reverted;
1301    (s, resumed)
1302}
1303
1304/// The log's bytes from `at`, or None when they cannot be read as text.
1305fn tail(log: &Path, at: u64) -> Option<String> {
1306    let mut f = std::fs::File::open(log).ok()?;
1307    f.seek(std::io::SeekFrom::Start(at)).ok()?;
1308    let mut bytes = Vec::new();
1309    f.read_to_end(&mut bytes).ok()?;
1310    String::from_utf8(bytes).ok()
1311}
1312
1313/// Writes `s` as the cache beside `lessons`: a temp file, then a rename, so a reader never sees half.
1314pub fn save(lessons: &Path, s: &Summary) -> std::io::Result<()> {
1315    let target = cache_path(lessons);
1316    let tmp = target.with_extension(format!("{}.tmp", std::process::id()));
1317    std::fs::write(&tmp, serde_json::to_vec(s).map_err(std::io::Error::other)?)?;
1318    std::fs::rename(&tmp, &target).inspect_err(|_| {
1319        let _ = std::fs::remove_file(&tmp);
1320    })
1321}
1322
1323/// The summary from the whole outcome log beside `lessons` (`borg debug select --rebuild`, a cache that
1324/// cannot be resumed), folded from the prior: no fit.
1325#[must_use]
1326pub fn rebuild(lessons: &Path) -> Summary {
1327    let text = std::fs::read_to_string(outcome::path_beside(lessons)).unwrap_or_default();
1328    fold(&text, Summary::default())
1329}
1330
1331/// `s` refitted (select/policy.rs `fit`) under an engineer's `budget` (pool tokens per session), with
1332/// the gate's ledger replayed under the new fit and the monitor read; a revert stays.
1333#[must_use]
1334pub fn with_fit(mut s: Summary, budget: Option<f64>) -> Summary {
1335    s.fit = policy::fit(&s, budget);
1336    s.gate = policy::ledger(&s);
1337    let sticky = s.monitor.reverted;
1338    s.monitor = policy::monitor(&s);
1339    s.monitor.reverted |= sticky;
1340    s
1341}
1342
1343/// `borg learn`: the summary beside `lessons` refitted (`with_fit`, the collective's budget from its
1344/// config, select.rs `budget_of`), its revert mark written when the monitor tripped, and the cache
1345/// saved.
1346pub fn refit(lessons: &Path) -> Summary {
1347    let s = with_fit(load(lessons), super::budget_of(lessons));
1348    if s.monitor.reverted {
1349        let _ = std::fs::write(reverted_path(lessons), format!("{}\n", serde_json::to_string(&s.monitor).unwrap_or_default()));
1350    }
1351    let _ = save(lessons, &s);
1352    s
1353}
1354
1355#[cfg(test)]
1356mod tests {
1357    use super::*;
1358
1359    fn rec(kind: &str, session: &str, lessons: &[&str], ms: i64) -> Outcome {
1360        Outcome { kind: kind.into(), session: session.into(), lessons: lessons.iter().map(|l| l.to_string()).collect(), ms, ..Default::default() }
1361    }
1362
1363    /// A graded check: `ask`ed and `free` lessons by id, the rest left for later.
1364    fn graded(session: &str, check: &str, lessons: &[&str], grades: &[u8], ask: &[&str], free: &[&str], ms: i64) -> Outcome {
1365        let owned = |v: &[&str]| v.iter().map(|l| l.to_string()).collect::<Vec<_>>();
1366        Outcome {
1367            grades: grades.to_vec(),
1368            ranks: (0..lessons.len() as u16).collect(),
1369            applied: lessons.len() as u16,
1370            chosen: owned(ask),
1371            free: owned(free),
1372            channel: "live".into(),
1373            check: check.into(),
1374            policy: "learned".into(),
1375            p: lessons.iter().map(|l| f64::from(u8::from(ask.contains(l)))).collect(),
1376            pf: lessons.iter().map(|l| f64::from(u8::from(free.contains(l)))).collect(),
1377            shown: 20,
1378            tokens: 6000,
1379            fill: (0..lessons.len() as u16).map(|i| 3 * i).collect(),
1380            dur_ms: 9000,
1381            ..rec(outcome::GRADED, session, lessons, ms)
1382        }
1383    }
1384
1385    fn verdict(kind: &str, session: &str, lesson: &str, check: &str, channel: &str, ms: i64) -> Outcome {
1386        Outcome { check: check.into(), channel: channel.into(), judge: 2, ..rec(kind, session, &[lesson], ms) }
1387    }
1388
1389    fn delivery(session: &str, lesson: &str, check: &str, route: &str, ms: i64) -> Outcome {
1390        Outcome { check: check.into(), route: route.into(), ..rec(outcome::DELIVERY, session, &[lesson], ms) }
1391    }
1392
1393    /// `graded` at the stop.
1394    fn stop(session: &str, check: &str, lessons: &[&str], grades: &[u8], ask: &[&str], free: &[&str], ms: i64) -> Outcome {
1395        Outcome { channel: "stop".into(), ..graded(session, check, lessons, grades, ask, free, ms) }
1396    }
1397
1398    /// What the end hook writes of a queue line still waiting: `never_delivered`.
1399    fn never(session: &str, check: &str, lessons: &[&str], ms: i64) -> Outcome {
1400        Outcome { check: check.into(), route: outcome::ROUTE_NEVER.into(), channel: "queued".into(), ..rec(outcome::DELIVERY, session, lessons, ms) }
1401    }
1402
1403    fn lines(log: &[Outcome]) -> String {
1404        log.iter().map(|o| format!("{}\n", serde_json::to_string(o).unwrap())).collect()
1405    }
1406
1407    /// A log with every kind the fold reads, older records without check ids among them.
1408    fn log() -> Vec<Outcome> {
1409        let legacy = Outcome {
1410            check: String::new(),
1411            policy: String::new(),
1412            pf: Vec::new(),
1413            free: Vec::new(),
1414            ..graded("old", "", &["A", "B", "C"], &[2, 1, 1], &[], &[], 1)
1415        };
1416        let mut placebo = graded("s", "c3", &["A", "B", "C"], &[1, 1, 2], &[], &["C"], 40);
1417        placebo.placebo = vec!["A".into()];
1418        placebo.psi = 0.5;
1419        vec![
1420            legacy,
1421            Outcome { channel: "queued".into(), ..rec(outcome::ASKED, "old", &["A"], 2) },
1422            Outcome { channel: "queued".into(), ..rec(outcome::CHANGED, "old", &["A"], 3) },
1423            Outcome { channel: "queued".into(), ..rec(outcome::IGNORED, "old", &["B"], 4) },
1424            rec(outcome::NOT_CORRECTED, "old", &["C"], 5),
1425            graded("s", "c1", &["A", "B"], &[3, 2], &["A", "B"], &[], 10),
1426            delivery("s", "A", "c1", outcome::ROUTE_ASKED, 11),
1427            delivery("s", "B", "c1", outcome::ROUTE_DROPPED_DONE, 11),
1428            rec(outcome::REGRETTED, "s", &["A"], 12),
1429            Outcome { cause: "R1".into(), credit: 0.5, ..rec(outcome::REGRETTED, "s", &["B"], 12) },
1430            verdict(outcome::UNCLEAR, "s", "A", "c1", "live", 13),
1431            verdict(outcome::CHANGED, "s", "A", "c1", "live", 14),
1432            graded("s", "c2", &["D", "E"], &[1, 2], &[], &["E"], 20),
1433            Outcome { channel: "early".into(), ..rec(outcome::CHANGED, "s", &["Q"], 21) },
1434            delivery("s", "E", "c2", outcome::ROUTE_FREE, 22),
1435            Outcome { check: "c9".into(), channel: "live".into(), ..rec(outcome::ASKED, "s", &["D"], 30) },
1436            placebo,
1437            delivery("s", "A", "c3", outcome::ROUTE_PLACEBO, 41),
1438            verdict(outcome::IGNORED, "s", "A", "c3", outcome::PLACEBO, 42),
1439            verdict(outcome::CHANGED, "s", "C", "c3", "queued", 43),
1440            rec(outcome::VETOED, "s", &["C"], 44),
1441            Outcome { reason: outcome::UNJUDGED_TRIES.into(), check: "c2".into(), ..rec(outcome::NOT_CORRECTED, "s", &["E"], 50) },
1442            rec(outcome::TESTED, "s", &["A"], 51),
1443            Outcome { kind: "graded".into(), failed: true, tokens: 6000, dur_ms: 30_000, ..graded("s", "c4", &[], &[], &[], &[], 52) },
1444        ]
1445    }
1446
1447    fn label_of(s: &Summary, check: &str, lesson: &str) -> (Route, Label, Delivered) {
1448        let c = s.checks.iter().find(|c| c.id == check).unwrap();
1449        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();
1450        (a.route, a.label, a.delivered)
1451    }
1452
1453    #[test]
1454    fn results_join_their_check_by_id_and_older_ones_by_the_last_check_before() {
1455        let s = fold(&lines(&log()), Summary::default());
1456        assert_eq!(s.checks.len(), 4, "the failed check has no applies");
1457        // The older check: no id, its results by the session's last check before them, on the route
1458        // their channel names.
1459        let old = &s.applies[..3];
1460        // C settled by an older binary (no reason) without a verdict: censored.
1461        assert_eq!(
1462            old.iter().map(|a| (a.route, a.label)).collect::<Vec<_>>(),
1463            [(Route::Free, Label::Changed), (Route::Free, Label::Ignored), (Route::Free, Label::Censored)]
1464        );
1465        assert_eq!(old[0].delivered, Delivered::Yes);
1466        assert_eq!(old[0].pf, 1.0, "an older record's free lesson had pf 1");
1467        // A verdict supersedes an unclear one; a dropped ask stays without a verdict.
1468        assert_eq!(label_of(&s, "c1", "A"), (Route::Ask, Label::Changed, Delivered::Yes));
1469        assert_eq!(label_of(&s, "c1", "B"), (Route::Ask, Label::Open, Delivered::Dropped));
1470        // A placebo's verdict labels the placebo, never the free lesson beside it.
1471        assert_eq!(label_of(&s, "c3", "A"), (Route::Placebo, Label::Ignored, Delivered::Yes));
1472        assert_eq!(label_of(&s, "c3", "C"), (Route::Free, Label::Changed, Delivered::Unknown));
1473        // Settled without a verdict: censored; D was left for later by c2 and asked after it.
1474        assert_eq!(label_of(&s, "c2", "E").1, Label::Censored);
1475        let d = s.applies.iter().find(|a| s.lessons[a.lesson as usize] == "D").unwrap();
1476        assert!(d.later && d.route == Route::Not);
1477        // c2b leaves A for later; c3 then draws A as a placebo, judged but never shown: no later delivery.
1478        let mut more = log();
1479        more.insert(16, graded("s", "c2b", &["A"], &[1], &[], &[], 35));
1480        let s2 = fold(&lines(&more), Summary::default());
1481        assert!(!s2.applies[s2.checks.iter().find(|c| c.id == "c2b").unwrap().first as usize].later, "a placebo is no delivery");
1482        assert_eq!(s.applies.iter().find(|a| a.route == Route::Placebo).map(|a| a.psi), Some(0.5));
1483        assert_eq!((s.early.judged, s.early.changed), (1, 1));
1484        assert!(s.applies.iter().filter(|a| a.label == Label::Changed).all(|a| a.judge.is_some()));
1485        assert_eq!(s.judges, ["v0||", "v2||"], "the older verdicts' judge (version 0) and the new one's, each with its check's model");
1486        // Signals and tallies.
1487        assert_eq!((s.signals[1].regrets, s.signals[1].vetoes, s.signals[1].tested), (2, 1, 1));
1488        assert_eq!(s.sessions.iter().map(|x| x.id.as_str()).collect::<Vec<_>>(), ["old", "s"]);
1489        assert!(s.sessions.iter().all(|x| x.ended));
1490        assert_eq!(s.sessions[1].tally[FREE_LIVE], (2, 1), "E delivered, C not");
1491        assert_eq!(s.sessions[1].tally[LATER], (2, 1), "c2's D delivered later, c3's B not");
1492        assert_eq!(s.pool.latency.len(), 5, "every timed call, the failed one too");
1493        assert_eq!(s.pool.bins[0], (4, 4), "position 0 shown by the four answered calls, applied in each");
1494        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");
1495    }
1496
1497    /// An early delivery, as hook.rs `record_delivery` writes it.
1498    fn early(session: &str, lessons: &[&str], ms: i64) -> Outcome {
1499        Outcome { channel: "early".into(), ..rec(outcome::ASKED, session, lessons, ms) }
1500    }
1501
1502    /// Lines for the state round 0.6.0 added: a session shown a lesson before its first check, a
1503    /// check's `nofree` and tail sample, live questions' fates.
1504    fn more() -> Vec<Outcome> {
1505        let tailed = Outcome {
1506            nofree: vec!["N1".into()],
1507            tail: vec!["T1".into(), "T2".into()],
1508            pt: 0.5,
1509            fill: vec![0, 3, 25, 25, 40],
1510            ..graded("n", "n1", &["A", "N1", "T1"], &[3, 1, 2], &["A"], &["T1"], 61)
1511        };
1512        vec![
1513            early("n", &["N1"], 60),
1514            tailed,
1515            delivery("n", "A", "n1", outcome::ROUTE_ASKED, 62),
1516            delivery("n", "T1", "n1", outcome::ROUTE_FREE, 62),
1517            rec(outcome::ENDED, "n", &[], 63),
1518        ]
1519    }
1520
1521    #[test]
1522    fn a_fold_of_the_whole_equals_its_folds_at_every_line_boundary() {
1523        let text = lines(&[log(), more()].concat());
1524        // With a fit, so the gate's ledger folds too.
1525        let mut prior = Summary::default();
1526        let fitted = with_fit(fold(&text, Summary::default()), None);
1527        prior.fit = fitted.fit.clone();
1528        assert!(prior.fit.model.is_some(), "the log has labels");
1529        let whole = fold(&text, prior.clone());
1530        assert!(whole.gate.checks > 0, "learned checks reached the ledger");
1531        let mut at = 0;
1532        let mut one = prior.clone();
1533        for line in text.split_inclusive('\n') {
1534            let split = fold(&text[at + line.len()..], fold(&text[..at + line.len()], prior.clone()));
1535            assert_eq!(split, whole, "split after byte {}", at + line.len());
1536            one = fold(line, one);
1537            at += line.len();
1538        }
1539        assert_eq!(one, whole, "line by line");
1540        assert_eq!(whole.at, text.len() as u64);
1541        // A refit replays the same ledger the folds built.
1542        let refit = with_fit(whole.clone(), None);
1543        assert_eq!(refit.fit.key, whole.key());
1544    }
1545
1546    #[test]
1547    fn a_line_being_written_waits_for_its_newline() {
1548        let text = lines(&log());
1549        let cut = text.len() - 10;
1550        let s = fold(&text[..cut], Summary::default());
1551        let last_newline = text[..cut].rfind('\n').unwrap() + 1;
1552        assert_eq!(s.at, last_newline as u64);
1553        assert_eq!(fold(&text[s.at as usize..], s), fold(&text, Summary::default()));
1554    }
1555
1556    #[test]
1557    fn kinds_it_does_not_use_cost_a_substring() {
1558        // A regret counts without serde (this one would not parse); an unknown kind is never read.
1559        let text =
1560            [r#"{"kind":"regretted",broken"#, r#"{"kind":"something_new","session":"z"}"#, r#"{"kind":"graded","session":"s","lessons":[],"ms":1,"repo":""}"#]
1561                .map(|l| format!("{l}\n"))
1562                .concat();
1563        let text = text.as_str();
1564        let s = fold(text, Summary::default());
1565        assert_eq!(s.signals[0].regrets, 1);
1566        assert_eq!(s.sessions.len(), 1, "only the graded line registered a session");
1567        assert_eq!(kind_of("{\"kind\":\"asked\",\"x\":1}"), Some("asked"));
1568        assert_eq!(kind_of(" {\"kind\":\"asked\"}"), None);
1569    }
1570
1571    /// A temp store: its lessons file (never written) and the outcomes beside it.
1572    fn store(name: &str, text: &str) -> PathBuf {
1573        let d = std::env::temp_dir().join(format!("borg-summary-{name}-{}", std::process::id()));
1574        let _ = std::fs::remove_dir_all(&d);
1575        std::fs::create_dir_all(&d).unwrap();
1576        std::fs::write(d.join("outcomes.jsonl"), text).unwrap();
1577        d.join("lessons.jsonl")
1578    }
1579
1580    #[test]
1581    fn load_resumes_the_cache_and_rebuilds_what_it_cannot() {
1582        let text = lines(&log());
1583        let half = text[..text.len() / 2].rfind('\n').unwrap() + 1;
1584        let lessons = store("load", &text[..half]);
1585        let whole = fold(&text, Summary::default());
1586        // Saved at half the log, then the rest appended: loading folds only the tail.
1587        save(&lessons, &load(&lessons)).unwrap();
1588        std::fs::write(outcome::path_beside(&lessons), &text).unwrap();
1589        assert_eq!(load(&lessons), whole);
1590        assert_eq!(peek(&lessons), whole);
1591        // A corrupt cache: load rebuilds, peek takes the prior.
1592        std::fs::write(cache_path(&lessons), "{\"sv\":1,\"at\":").unwrap();
1593        assert_eq!(load(&lessons), whole);
1594        assert_eq!(peek(&lessons), Summary::default());
1595        // Another format, and a log shorter than the cache read (rewritten): rebuilt.
1596        let mut other = whole.clone();
1597        other.sv = SV + 1;
1598        save(&lessons, &other).unwrap();
1599        assert_eq!(load(&lessons), whole);
1600        let mut ahead = whole.clone();
1601        ahead.at += 1_000;
1602        save(&lessons, &ahead).unwrap();
1603        assert_eq!(load(&lessons), whole);
1604        // A cache that parses but points outside its tables is corrupt too: never indexed in a hook.
1605        let mut broken = whole.clone();
1606        broken.checks[1].first += 1;
1607        save(&lessons, &broken).unwrap();
1608        assert_eq!((load(&lessons), peek(&lessons)), (whole.clone(), Summary::default()));
1609        let mut broken = whole.clone();
1610        broken.applies[0].lesson = 99;
1611        save(&lessons, &broken).unwrap();
1612        assert_eq!(load(&lessons), whole);
1613        let mut broken = whole.clone();
1614        broken.sessions[1].had.push(99);
1615        save(&lessons, &broken).unwrap();
1616        assert_eq!(load(&lessons), whole, "what a session had points outside the lessons");
1617        assert!(whole.consistent() && Summary::default().consistent());
1618        // A refit summary, its monitor's bound unset before enough sessions, loads as saved (bit for
1619        // bit only as serde_json parses floats: without its `float_roundtrip` a few land 1 ULP off).
1620        let fitted = with_fit(whole.clone(), None);
1621        assert!(fitted.fit.model.is_some() && fitted.monitor.ucb.is_none());
1622        save(&lessons, &fitted).unwrap();
1623        let parsed: Summary = serde_json::from_slice(&serde_json::to_vec(&fitted).unwrap()).unwrap();
1624        assert_eq!(load(&lessons), parsed);
1625        // The revert mark is sticky: read on every load.
1626        std::fs::write(reverted_path(&lessons), "{}\n").unwrap();
1627        assert!(load(&lessons).monitor.reverted && peek(&lessons).monitor.reverted);
1628        // The mark is the revert, not the cache's copy of it (`refit` saves both): removing the mark
1629        // resumes learning.
1630        save(&lessons, &Summary { monitor: Monitor { reverted: true, ..fitted.monitor.clone() }, ..fitted.clone() }).unwrap();
1631        assert!(load(&lessons).monitor.reverted);
1632        std::fs::remove_file(reverted_path(&lessons)).unwrap();
1633        assert!(!load(&lessons).monitor.reverted && !peek(&lessons).monitor.reverted);
1634        // `refresh` saves only what it folded past the cache.
1635        std::fs::write(outcome::path_beside(&lessons), &text[..half]).unwrap();
1636        std::fs::remove_file(cache_path(&lessons)).unwrap();
1637        assert_eq!(refresh(&lessons).at, half as u64, "no cache: rebuilt and saved");
1638        // The same summary written pretty: a rewrite would make it compact again.
1639        let pretty = serde_json::to_vec_pretty(&peek(&lessons)).unwrap();
1640        std::fs::write(cache_path(&lessons), &pretty).unwrap();
1641        assert_eq!(refresh(&lessons).at, half as u64);
1642        assert_eq!(std::fs::read(cache_path(&lessons)).unwrap(), pretty, "nothing new: not rewritten");
1643        std::fs::write(outcome::path_beside(&lessons), &text).unwrap();
1644        assert_eq!(refresh(&lessons), whole);
1645        assert_eq!(peek(&lessons), whole, "the tail it folded is saved");
1646        // No store at all: the prior, no panic.
1647        assert_eq!(load(Path::new("/nonexistent/borg-summary/lessons.jsonl")), Summary::default());
1648        let _ = std::fs::remove_dir_all(lessons.parent().unwrap());
1649    }
1650
1651    #[test]
1652    fn compaction_keeps_the_newest_checks_and_their_joins() {
1653        let text = lines(&log());
1654        let mut s = fold(&text, Summary::default());
1655        let kept = s.checks.len() - 1;
1656        let mut ix = Index::of(&s);
1657        let first = s.checks[1].first as u64;
1658        s.compact(&mut ix, 1, 0);
1659        assert_eq!((s.checks.len(), s.dropped), (kept, first));
1660        assert_eq!(s.checks[0].first, 0);
1661        assert!(s.applies.iter().all(|a| (a.check as usize) < s.checks.len()));
1662        // A later verdict still finds its check.
1663        let more = lines(&[graded("s", "c5", &["Z"], &[2], &[], &["Z"], 60), verdict(outcome::CHANGED, "s", "Z", "c5", "queued", 61)]);
1664        let s = fold(&more, s);
1665        assert_eq!(label_of(&s, "c5", "Z").1, Label::Changed);
1666    }
1667
1668    #[test]
1669    fn every_ended_session_counts_its_deliveries_and_a_resumed_one_moves_them() {
1670        let ended = |session: &str, ms| rec(outcome::ENDED, session, &[], ms);
1671        let log = [
1672            // A stop asks nothing and hands A and B over free; the session ends before a next prompt.
1673            stop("a", "a1", &["A", "B"], &[2, 1], &[], &["A", "B"], 1),
1674            never("a", "a1", &["A", "B"], 2),
1675            ended("a", 3),
1676            // Its one question corrected, a session leaves no settle line: its end alone counts it.
1677            graded("b", "b1", &["C", "D"], &[3, 1], &["C"], &["D"], 10),
1678            delivery("b", "C", "b1", outcome::ROUTE_ASKED, 11),
1679            delivery("b", "D", "b1", outcome::ROUTE_FREE, 11),
1680            rec(outcome::CORRECTED, "b", &["C"], 12),
1681            ended("b", 13),
1682            // An end hook from before `ended`: its `never_delivered` deliveries end the session.
1683            stop("c", "c1", &["E"], &[2], &[], &["E"], 20),
1684            never("c", "c1", &["E"], 21),
1685            // Still open: nothing counts yet.
1686            stop("d", "d1", &["F"], &[2], &[], &["F"], 30),
1687            // A session without a graded check has nothing to count: no entry.
1688            ended("e", 31),
1689        ];
1690        let s = fold(&lines(&log), Summary::default());
1691        let of = |s: &Summary, id: &str| s.sessions.iter().find(|x| x.id == id).cloned().unwrap();
1692        assert_eq!(of(&s, "a").tally[FREE_STOP], (2, 0), "no next prompt came");
1693        assert_eq!((of(&s, "b").tally[FREE_LIVE], of(&s, "b").tally[WAIT]), ((1, 1), (1, 0)), "D delivered; C asked during the turn");
1694        assert_eq!(of(&s, "c").tally[FREE_STOP], (1, 0));
1695        assert_eq!(of(&s, "d").tally, [(0, 0); TALLIES]);
1696        assert_eq!(s.sessions.iter().map(|x| (x.id.as_str(), x.ended)).collect::<Vec<_>>(), [("a", true), ("b", true), ("c", true), ("d", false)]);
1697        // Resumed, `a` hands A over at its next prompt after all: the count follows the latest record.
1698        let resumed = fold(&lines(&[delivery("a", "A", "a1", outcome::ROUTE_FREE, 40)]), s);
1699        assert_eq!(of(&resumed, "a").tally[FREE_STOP], (2, 1));
1700    }
1701
1702    #[test]
1703    fn left_for_later_is_a_live_checks_rate() {
1704        let log = [
1705            // The stop leaves L and M for later and the next turn's live check asks L: not what ρ is,
1706            // a lesson left for later during the turn delivered later.
1707            stop("s", "k1", &["L", "M"], &[1, 1], &[], &[], 1),
1708            graded("s", "k2", &["L"], &[3], &["L"], &[], 5),
1709            delivery("s", "L", "k2", outcome::ROUTE_ASKED, 6),
1710            // A live check leaves N for later, and its turn's stop asks it.
1711            graded("s", "k3", &["N"], &[1], &[], &[], 7),
1712            stop("s", "k4", &["N"], &[3], &["N"], &[], 8),
1713            Outcome { channel: "stop".into(), ..delivery("s", "N", "k4", outcome::ROUTE_ASKED, 9) },
1714            rec(outcome::ENDED, "s", &[], 10),
1715        ];
1716        let s = fold(&lines(&log), Summary::default());
1717        assert_eq!(s.sessions[0].tally[LATER], (1, 1), "k3's N alone");
1718        // The stop's applies still say what came of them.
1719        let k1 = s.checks[0].first as usize;
1720        assert!(s.applies[k1].later && !s.applies[k1 + 1].later, "L arrived later, M never");
1721    }
1722
1723    #[test]
1724    fn a_lesson_its_session_had_counts_in_no_delivery_tally() {
1725        let ended = |session: &str, ms| rec(outcome::ENDED, session, &[], ms);
1726        let log = [
1727            // Delivered early before the session's first check; an older binary then dropped E's free
1728            // hand-over without a record: not a lesson that failed to arrive.
1729            early("a", &["E"], 1),
1730            stop("a", "a1", &["E", "F"], &[2, 1], &[], &["E", "F"], 2),
1731            Outcome { channel: "queued".into(), ..rec(outcome::ASKED, "a", &["F"], 3) },
1732            ended("a", 4),
1733            // Handed over at the session's first check, free again at its next: dropped as given before.
1734            graded("b", "b1", &["G"], &[2], &[], &["G"], 10),
1735            delivery("b", "G", "b1", outcome::ROUTE_FREE, 11),
1736            graded("b", "b2", &["G", "H"], &[2, 1], &[], &["G", "H"], 12),
1737            Outcome { reason: "given before".into(), ..delivery("b", "G", "b2", outcome::ROUTE_DROPPED_DONE, 13) },
1738            delivery("b", "H", "b2", outcome::ROUTE_FREE, 13),
1739            ended("b", 14),
1740            // The hook's state had K, the log no delivery of it (`nofree`): left for later, only M counts.
1741            Outcome { nofree: vec!["K".into()], ..graded("c", "c1", &["K", "M"], &[2, 1], &[], &[], 20) },
1742            ended("c", 21),
1743        ];
1744        let s = fold(&lines(&log), Summary::default());
1745        let of = |id: &str| s.sessions.iter().find(|x| x.id == id).cloned().unwrap();
1746        assert_eq!(of("a").tally[FREE_STOP], (1, 1), "F alone: the session had E");
1747        assert_eq!(of("b").tally[FREE_LIVE], (2, 2), "b1's G and b2's H: at b2 the session had G");
1748        assert_eq!(of("c").tally[LATER], (1, 0), "M alone");
1749        let a1 = s.checks.iter().find(|c| c.id == "a1").unwrap().first as usize;
1750        assert!(s.applies[a1].had && !s.applies[a1 + 1].had);
1751        // What a session was shown before its first check is its own from that check on.
1752        assert!(s.fresh.is_empty());
1753        let names = |x: &Session| x.had.iter().map(|&l| s.lessons[l as usize].clone()).collect::<Vec<_>>();
1754        assert_eq!((names(&of("a")), names(&of("b")), names(&of("c"))), (vec!["E".into(), "F".into()], vec!["G".into(), "H".into()], vec![]));
1755    }
1756
1757    #[test]
1758    fn a_live_question_is_delivered_when_it_reaches_the_drone() {
1759        let at_stop = |o: Outcome| Outcome { channel: "stop".into(), ..o };
1760        let log = [
1761            // Q4 and Q6 were handed over early. Q4, asked again and found done at the stop, counts
1762            // nowhere; Q6, not acted on, reaches the drone and is judged as any question: its verdict
1763            // stays on its apply (top.rs label health), its delivery out of the tallies (`Apply::had`).
1764            early("q", &["Q4", "Q6"], 1),
1765            graded("q", "q1", &["Q1", "Q2", "Q3", "Q4", "Q6"], &[3, 3, 3, 3, 3], &["Q1", "Q2", "Q3", "Q4", "Q6"], &[], 2),
1766            delivery("q", "Q1", "q1", outcome::ROUTE_ASKED, 3),
1767            delivery("q", "Q6", "q1", outcome::ROUTE_ASKED, 3),
1768            verdict(outcome::CHANGED, "q", "Q6", "q1", "live", 4),
1769            // Q2 waited for the stop and was asked in its block; Q3 was not deliverable there.
1770            at_stop(delivery("q", "Q2", "q1", outcome::ROUTE_ASKED, 5)),
1771            Outcome { reason: "not deliverable".into(), ..delivery("q", "Q3", "q1", outcome::ROUTE_DROPPED_DONE, 5) },
1772            Outcome { reason: "done at the stop".into(), ..delivery("q", "Q4", "q1", outcome::ROUTE_DROPPED_DONE, 5) },
1773            // A stop's question blocks: certain, never tallied.
1774            stop("q", "q2", &["Q5"], &[3], &["Q5"], &[], 6),
1775            at_stop(delivery("q", "Q5", "q2", outcome::ROUTE_ASKED, 7)),
1776            rec(outcome::ENDED, "q", &[], 8),
1777        ];
1778        let s = fold(&lines(&log), Summary::default());
1779        assert_eq!((s.sessions[0].tally[ASK_LIVE], s.sessions[0].tally[WAIT]), ((3, 2), (3, 1)));
1780        let q6 = s.checks[0].first as usize + 4;
1781        assert_eq!((label_of(&s, "q1", "Q6"), s.applies[q6].had), ((Route::Ask, Label::Changed, Delivered::Yes), true));
1782        // Learned as the free rates are, Beta(1, 1): (1 + 2) / (2 + 3).
1783        assert!((policy::fit(&s, None).rates.ask_live - 0.6).abs() < 1e-12);
1784        // Before a live question is tallied, the fixed rule's certainty.
1785        assert_eq!((policy::fit(&Summary::default(), None).rates.ask_live, policy::prior().rates.ask_live), (1.0, 1.0));
1786        // Resumed, the session asks Q3 after all: both its counts move.
1787        let s = fold(&lines(&[at_stop(delivery("q", "Q3", "q1", outcome::ROUTE_ASKED, 9))]), s);
1788        assert_eq!((s.sessions[0].tally[ASK_LIVE], s.sessions[0].tally[WAIT]), ((3, 3), (3, 2)));
1789    }
1790
1791    #[test]
1792    fn a_hand_over_the_stop_asked_in_place_is_its_free_applys_delivery_and_verdict() {
1793        // What hook.rs `stop_ask` writes for a live check's question-count test draw: H handed over in
1794        // place of a question, and the stop came before any delivery took it, so it asked H in its block
1795        // with A, the check's waiting question.
1796        let at_stop = |o: Outcome| Outcome { channel: "stop".into(), ..o };
1797        let log = [
1798            graded("s", "k1", &["A", "H"], &[3, 2], &["A"], &["H"], 1),
1799            stop("s", "k2", &[], &[], &[], &[], 2),
1800            at_stop(Outcome { check: "k1".into(), ..rec(outcome::ASKED, "s", &["A"], 3) }),
1801            Outcome { reason: "at the stop".into(), ..at_stop(delivery("s", "A", "k1", outcome::ROUTE_ASKED, 3)) },
1802            at_stop(Outcome { check: "k1".into(), ..rec(outcome::ASKED, "s", &["H"], 3) }),
1803            Outcome { reason: "in place of a hand-over".into(), ..at_stop(delivery("s", "H", "k1", outcome::ROUTE_ASKED, 3)) },
1804            // `#borg-routed H=k1`: the verdict names H's check, on channel stop.
1805            verdict(outcome::CHANGED, "s", "H", "k1", "stop", 4),
1806            verdict(outcome::IGNORED, "s", "A", "k1", "stop", 4),
1807            Outcome { reason: outcome::UNJUDGED_NONE.into(), check: "k1".into(), ..rec(outcome::NOT_CORRECTED, "s", &["A", "H"], 5) },
1808            rec(outcome::ENDED, "s", &[], 6),
1809        ];
1810        let s = fold(&lines(&log), Summary::default());
1811        assert_eq!(label_of(&s, "k1", "H"), (Route::Free, Label::Changed, Delivered::Yes), "the draw's free apply, delivered and judged");
1812        assert_eq!(label_of(&s, "k1", "A"), (Route::Ask, Label::Ignored, Delivered::Yes));
1813        assert_eq!(s.sessions[0].tally[FREE_LIVE], (1, 1), "H arrived");
1814        assert_eq!((s.sessions[0].tally[ASK_LIVE], s.sessions[0].tally[WAIT]), ((1, 1), (1, 1)));
1815        // A stop check's own result stays on its questions.
1816        let log = [stop("t", "t1", &["F", "G"], &[3, 2], &["F"], &["G"], 1), verdict(outcome::CHANGED, "t", "G", "t1", "stop", 2)];
1817        assert_eq!(label_of(&fold(&lines(&log), Summary::default()), "t1", "G").1, Label::Open, "a stop's free lesson is judged on channel queued");
1818    }
1819
1820    #[test]
1821    fn a_live_question_of_a_check_without_a_3_is_no_question_that_waits_for_the_stop() {
1822        let log = [
1823            // A check with a 3: its question waits for the stop and is asked there.
1824            graded("t", "t1", &["A"], &[3], &["A"], &[], 1),
1825            Outcome { channel: "stop".into(), ..delivery("t", "A", "t1", outcome::ROUTE_ASKED, 2) },
1826            // Without a 3 (`live-next`): no stop asks B, and the session ends before a tool call.
1827            graded("t", "t2", &["B", "C"], &[2, 1], &["B"], &[], 3),
1828            Outcome { channel: "queued".into(), ..never("t", "t2", &["B"], 4) },
1829            rec(outcome::ENDED, "t", &[], 5),
1830        ];
1831        let s = fold(&lines(&log), Summary::default());
1832        assert_eq!((s.sessions[0].tally[ASK_LIVE], s.sessions[0].tally[WAIT]), ((1, 1), (1, 1)), "t1's A alone");
1833        assert_eq!(label_of(&s, "t2", "B"), (Route::Ask, Label::Open, Delivered::Dropped), "its apply still says what came of it");
1834        // Resumed, a tool call asks B after all: no tally moves.
1835        let s = fold(&lines(&[delivery("t", "B", "t2", outcome::ROUTE_ASKED, 6)]), s);
1836        assert_eq!((s.sessions[0].tally[ASK_LIVE], s.sessions[0].tally[WAIT]), ((1, 1), (1, 1)));
1837    }
1838
1839    #[test]
1840    fn a_tail_sample_teaches_the_yield_past_the_pool() {
1841        // A pool of four (positions 0 to 3) and a tail of two the budget dropped, at positions 9 and 20 of
1842        // the whole fill order; T1 applied.
1843        let tailed = |pt: f64, at: &[u16]| Outcome {
1844            shown: 4,
1845            tail: vec!["T1".into(), "T2".into()],
1846            pt,
1847            fill: [&[0, 9][..], at].concat(),
1848            ..graded("s", "t1", &["A", "T1"], &[2, 1], &[], &["A", "T1"], 1)
1849        };
1850        let s = fold(&lines(&[tailed(0.25, &[9, 20])]), Summary::default());
1851        // Positions 0, 1–2, 3–6 as the pool showed them; 7–14 and 15–30 each a tail lesson.
1852        assert_eq!(s.pool.bins, [(1, 1), (2, 0), (1, 0), (1, 1), (1, 0)]);
1853        assert_eq!((s.pool.shown, s.pool.tokens), (4, 6000), "the pool's own: the tail is extra");
1854        assert_eq!(s.pool.tail, (2, 1), "the tail's lessons shown and applied, as borg top counts them");
1855        // No chance or one past 1 (no uniform sample), positions missing or inside the pool: the pool alone.
1856        for o in [tailed(0.0, &[9, 20]), tailed(1.5, &[9, 20]), tailed(0.25, &[9]), tailed(0.25, &[2, 20])] {
1857            let s = fold(&lines(&[o]), Summary::default());
1858            assert_eq!((s.pool.bins, s.pool.tail), (vec![(1, 1), (2, 0), (1, 0)], (0, 0)));
1859        }
1860    }
1861
1862    #[test]
1863    fn sessions_shown_lessons_before_a_check_stay_bounded() {
1864        let n = MAX_FRESH + 10;
1865        let text = lines(&(0..n).map(|t| early(&format!("e{t}"), &["L"], t as i64)).collect::<Vec<_>>());
1866        let s = fold(&text, Summary::default());
1867        // The guard: past `MAX_FRESH` the oldest went, the newest stayed.
1868        assert!(s.fresh.len() <= MAX_FRESH, "{} kept", s.fresh.len());
1869        let newest = format!("e{}", n - 1);
1870        assert!(!s.fresh.contains_key("e0") && s.fresh.contains_key(&newest));
1871        assert!(s.sessions.is_empty() && s.consistent());
1872        for at in [text.len() / 2, text.len() - 100] {
1873            let at = text[..at].rfind('\n').unwrap() + 1;
1874            assert_eq!(fold(&text[at..], fold(&text[..at], Summary::default())), s, "split after byte {at}");
1875        }
1876        // The newest graded after all: its free hand-over of what it had counts nowhere.
1877        let s = fold(&lines(&[stop(&newest, "x1", &["L"], &[2], &[], &["L"], 9_999), rec(outcome::ENDED, &newest, &[], 10_000)]), s);
1878        assert_eq!(s.sessions[0].tally[FREE_STOP], (0, 0));
1879    }
1880
1881    #[test]
1882    fn a_regrets_missed_lesson_is_no_correction() {
1883        let log = [
1884            rec(outcome::MISSED, "s", &["A"], 1),
1885            Outcome { cause: "R1".into(), ..rec(outcome::MISSED, "s", &["B"], 2) },
1886            rec(outcome::CORRECTED, "s", &["C"], 3),
1887        ];
1888        assert_eq!(fold(&lines(&log), Summary::default()).signals[0].corrections, 2, "A's and C's: B's is the regret R1 again");
1889    }
1890
1891    #[test]
1892    fn the_monitors_weights_persist_through_save_and_fold() {
1893        let text = lines(&log());
1894        let half = text[..text.len() / 2].rfind('\n').unwrap() + 1;
1895        let lessons = store("monitor", &text[..half]);
1896        let s = Summary { monitor: Monitor { ess: 12.5, max_weight: 3.25, labelled: 7, ..Monitor::default() }, ..load(&lessons) };
1897        save(&lessons, &s).unwrap();
1898        std::fs::write(outcome::path_beside(&lessons), &text).unwrap();
1899        let folded = refresh(&lessons);
1900        assert_eq!(folded.at, text.len() as u64, "the tail folded");
1901        for x in [&folded, &peek(&lessons)] {
1902            assert_eq!((x.monitor.ess, x.monitor.max_weight, x.monitor.labelled), (12.5, 3.25, 7));
1903        }
1904        let _ = std::fs::remove_dir_all(lessons.parent().unwrap());
1905    }
1906
1907    /// `n` sessions, each shown a lesson early that no check grades, then one live check handing its
1908    /// own lesson over free (delivered in the even sessions), then its end.
1909    fn many(n: usize) -> String {
1910        let mut log = Vec::new();
1911        for t in 0..n {
1912            let (id, check, lesson, ms) = (format!("s{t}"), format!("c{t}"), format!("L{t}"), 10 * t as i64);
1913            log.push(early(&id, &[&format!("X{t}")], ms));
1914            log.push(graded(&id, &check, &[&lesson], &[2], &[], &[&lesson], ms));
1915            if t % 2 == 0 {
1916                log.push(delivery(&id, &lesson, &check, outcome::ROUTE_FREE, ms + 1));
1917            }
1918            log.push(rec(outcome::ENDED, &id, &[], ms + 2));
1919        }
1920        lines(&log)
1921    }
1922
1923    #[test]
1924    fn the_session_table_stays_bounded_and_keeps_what_its_readers_need() {
1925        let n = MAX_SESSIONS + 2;
1926        let text = many(n);
1927        let s = fold(&text, Summary::default());
1928        // The guard: past `MAX_SESSIONS` the oldest went, an even count, never the newest.
1929        assert!(s.sessions.len() <= MAX_SESSIONS, "{} sessions kept", s.sessions.len());
1930        assert_eq!((n - s.sessions.len()) % 2, 0, "the monitor's halves keep their sessions");
1931        assert_eq!(s.sessions.last().map(|x| x.id.clone()), Some(format!("s{}", n - 1)));
1932        assert!(s.consistent());
1933        // Their checks went with them, and every lesson only they named; a kept session keeps what it
1934        // was shown, each lesson by its name.
1935        assert_eq!((s.checks.len(), s.dropped), (s.sessions.len(), (n - s.sessions.len()) as u64));
1936        assert_eq!(s.lessons.len(), 2 * s.applies.len());
1937        let newest = s.sessions.last().unwrap();
1938        let shown: Vec<&str> = newest.had.iter().map(|&l| s.lessons[l as usize].as_str()).collect();
1939        assert_eq!(shown, [format!("X{}", n - 1)], "an odd session: its free lesson never came");
1940        let even = &s.sessions[s.sessions.len() - 2];
1941        let shown: Vec<&str> = even.had.iter().map(|&l| s.lessons[l as usize].as_str()).collect();
1942        assert_eq!(shown, [format!("X{}", n - 2), format!("L{}", n - 2)]);
1943        // Every age as before: under every half-life the tallies are all n sessions', and so are the
1944        // sessions and checks spend divides by.
1945        for h in policy::HALF_LIVES {
1946            let want = (0..n).fold((0.0, 0.0), |(k, miss), t| {
1947                let w = policy::decay((n - t) as u32, h);
1948                if t % 2 == 0 { (k + w, miss) } else { (k, miss + w) }
1949            });
1950            let got = s.tallies(h)[FREE_LIVE];
1951            let close = |a: f64, b: f64| (a - b).abs() <= 1e-9 * b.max(1.0);
1952            assert!(close(got.0, want.0) && close(got.1, want.1), "{h:?}: {got:?} against {want:?}");
1953        }
1954        assert_eq!(s.checked(), (n as u64, n as u64));
1955        // A fold split before the compaction, or after it, is the whole fold.
1956        for at in [text.len() / 3, text.len() - 200] {
1957            let at = text[..at].rfind('\n').unwrap() + 1;
1958            assert_eq!(fold(&text[at..], fold(&text[..at], Summary::default())), s, "split after byte {at}");
1959        }
1960    }
1961
1962    /// The question-count test's checks (module doc): a drawn count, played or refused, counts by its k
1963    /// and s and marks its check, its control arm apart, its session once; a refusal also counts by its
1964    /// k; a record whose k or s cannot be its own (a refusal without its s among them), one outside the
1965    /// test and one not of the learned policy count nowhere. The
1966    /// counts are all-time: compaction drops the checks, never them.
1967    #[test]
1968    fn the_question_count_tests_checks_count_by_k_and_s_and_mark_their_check() {
1969        let x = |session: &str, check: &str, source: &str, k: Option<u32>, s: Option<u32>, ms| Outcome {
1970            source: source.into(),
1971            xk: k,
1972            xs: s,
1973            ..graded(session, check, &["A", "B", "C"], &[2, 2, 1], &["A"], &["B", "C"], ms)
1974        };
1975        let text = lines(&[
1976            x("x", "e1", policy::EXPERIMENT, Some(3), Some(1), 10),
1977            x("x", "e2", policy::EXPERIMENT, Some(3), Some(1), 20),
1978            x("x", "e3", policy::EXPERIMENT_CONTROL, Some(3), Some(0), 30),
1979            // No s: no source of the test writes it.
1980            x("x", "g1", policy::GATE, Some(3), None, 40),
1981            // Refused after its draw: randomised, the fixed rule played.
1982            x("x", "g2", policy::GATE, Some(3), Some(2), 45),
1983            // s past k, k past the check's applies.
1984            x("x", "bad", policy::EXPERIMENT, Some(3), Some(4), 50),
1985            x("x", "big", policy::EXPERIMENT, Some(9), Some(1), 60),
1986            x("x", "ev", policy::EVIDENCE, None, None, 70),
1987            Outcome { policy: "fixed".into(), ..x("x", "f1", policy::EXPERIMENT, Some(3), Some(2), 80) },
1988            x("y", "y1", policy::EXPERIMENT, Some(2), Some(2), 90),
1989        ]);
1990        let s = fold(&text, Summary::default());
1991        let e = &s.experiment;
1992        assert_eq!(
1993            (e.ran.as_slice(), e.control, e.refused.as_slice(), e.sessions),
1994            (&[(2, 2, 1), (3, 0, 1), (3, 1, 2), (3, 2, 1)][..], 1, &[(3, 1)][..], 2),
1995            "{e:?}"
1996        );
1997        assert_eq!(e.totals(), (5, 1));
1998        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();
1999        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))]);
2000        assert!(s.sessions.iter().all(|x| x.tested));
2001        // The fold every count shares: a prefix, then the rest, is the whole.
2002        let at = text[..text.len() / 2].rfind('\n').unwrap() + 1;
2003        assert_eq!(fold(&text[at..], fold(&text[..at], Summary::default())), s);
2004        // Compaction takes the checks, not the counts.
2005        let mut compacted = s.clone();
2006        let mut ix = Index::of(&compacted);
2007        compacted.compact(&mut ix, s.applies.len(), 0);
2008        assert_eq!((compacted.checks.len(), &compacted.experiment), (0, &s.experiment));
2009    }
2010
2011    #[test]
2012    fn a_learned_decision_the_fixed_rule_took_over_counts_by_its_reason() {
2013        let fell = |check: &str, reason: &str, applied: &[&str], ms| Outcome {
2014            policy: "fixed".into(),
2015            reason: reason.into(),
2016            ..graded("f", check, applied, &vec![1; applied.len()], &[], applied, ms)
2017        };
2018        let text = lines(&[
2019            fell("f1", outcome::DECIDED_BUSY, &["A"], 1),
2020            fell("f2", outcome::DECIDED_BUSY, &["B"], 2),
2021            // No applies: the check still waited for the lock.
2022            fell("f3", outcome::DECIDED_NO_LOCK, &[], 3),
2023            fell("f4", outcome::DECIDED_NO_RECORD, &["A"], 4),
2024            // Decided by the policy in force, and a reason this binary does not know: no fallback.
2025            graded("f", "f5", &["A"], &[1], &[], &["A"], 5),
2026            fell("f6", "something_new", &["A"], 6),
2027        ]);
2028        let s = fold(&text, Summary::default());
2029        assert_eq!(s.fell_back, [2, 1, 1], "lock_busy, lock_failed, unrecorded");
2030        assert_eq!(s.checked().1, 6, "the graded checks a fallback is one of");
2031        // The fold every count shares: a prefix, then the rest, is the whole.
2032        let at = text[..text.len() / 2].rfind('\n').unwrap() + 1;
2033        assert_eq!(fold(&text[at..], fold(&text[..at], Summary::default())), s);
2034        // Kept by the cache, and a cache of the layout before them (protocol: version 5) is rebuilt,
2035        // never resumed without them.
2036        let lessons = store("fell-back", &text);
2037        save(&lessons, &s).unwrap();
2038        assert_eq!(peek(&lessons).fell_back, s.fell_back);
2039        save(&lessons, &Summary { sv: 5, fell_back: Default::default(), ..s.clone() }).unwrap();
2040        assert_eq!(load(&lessons), s);
2041        let _ = std::fs::remove_dir_all(lessons.parent().unwrap());
2042    }
2043
2044    #[test]
2045    fn the_prior_writes_the_short_line() {
2046        let prior = Summary::default();
2047        assert_eq!((prior.sv, prior.at, &prior.fit), (SV, 0, &Fit::default()));
2048        let line = serde_json::to_string(&prior).unwrap();
2049        assert_eq!(line, format!(r#"{{"sv":{SV},"at":0,"fit":{{}}}}"#));
2050        assert_eq!(serde_json::from_str::<Summary>(&line).unwrap(), prior);
2051        let none = Path::new("/nonexistent/borg-summary/lessons.jsonl");
2052        assert_eq!(load(none), prior);
2053        assert_eq!(rebuild(none), prior);
2054    }
2055}