Skip to main content

borg/
ope.rs

1//! `borg debug ope`: off-policy estimates of the usefulness belief's hand-set weights, from the
2//! outcome log alone. Reports, never applies: no constant changes.
3//!
4//! **What is estimated.** The per-ask change rate under a candidate policy: of the lessons a check
5//! asks, the share the drone then changed its work on. The candidates differ from the policy in force
6//! in one weight of the belief (memory.rs `Weights`), the others held.
7//!
8//! **Which records count.** The weights reach a logged propensity on one path only: the Thompson slot
9//! draw over a pool (conscience.rs `budget_pool`/`widen_pool` and `propensity`, the bm25 and the
10//! non-graded paths), whose `asked` records carry the pool (outcome.rs `pool`, `base`, `scoped`). On the
11//! default graded path p comes from the model's grades (0 or 1) or the learned cut (attention.rs), both
12//! free of these weights: a candidate's p equals the logged p there, so those records say nothing about
13//! the weights. The weights do order the shortlist the model grades, but nothing there is randomised or
14//! logged. So a decision is an `asked` record with p and a pool; the rest is skipped and counted
15//! (`Skipped`): no p, p = 0, no pool, no result yet, and `graded` records.
16//!
17//! **Leak-free replay.** For each decision the beliefs come from memory.rs `derive` over the outcomes
18//! before its ms (sorted once, stably), under the candidate's weights, then the same `propensity` the
19//! live path ran, on the logged pool with score = base × (0.5 + the candidate's mean) and the
20//! decision's session. A lesson's counts depend only on the records that name it, so `evaluate`
21//! derives over those records alone (an index per lesson), which keeps a run linear in the log. The
22//! logged pool is held fixed: other weights could move a lesson across the LOW/BLOCK bars or change
23//! the widen path's forced picks, which the replay does not model. "Before its ms" is what the live
24//! draw saw only when every record arrived by its ms: a team record arrives a sync round after its ms,
25//! so the draw may not have seen it. A decision whose replay under the current weights misses its
26//! logged p (by more than `AGREE`) was drawn from other records than the replay's, and its weights
27//! would be biased: it is counted (`Report::drifted`) and left out of every estimate.
28//!
29//! **The estimate.** Self-normalised inverse propensity scoring over the asked lessons, w = p under the
30//! candidate / logged p, reward 1 when the session's result after the ask is a change; the effective
31//! sample size (Σw)²/Σw²; a 95% interval from a bootstrap over whole sessions (a session's rewards are
32//! not independent), seeded, so a run is deterministic.
33
34use std::collections::{BTreeMap, HashMap};
35use std::path::Path;
36
37use serde::Serialize;
38
39use crate::conscience::{self, Challenge};
40use crate::memory::{self, Memory, Weights};
41use crate::outcome::{self, Outcome};
42use crate::{collective, learn};
43
44/// One hand-set weight: its name, current value, the outcome kinds it weighs (its evidence), and how a
45/// candidate sets it.
46pub struct Knob {
47    pub name: &'static str,
48    pub current: f64,
49    pub kinds: &'static [&'static str],
50    pub set: fn(&mut Weights, f64),
51}
52
53/// The three hand-set weights: the veto's (`VETOED_W`), a regret's (`REGRET`) and a green test run's
54/// (`TESTED_W`).
55pub const KNOBS: [Knob; 3] = [
56    Knob { name: "veto", current: memory::VETOED_W as f64, kinds: &[outcome::VETOED], set: |w, v| w.vetoed = v },
57    Knob { name: "regret", current: memory::REGRET, kinds: &[outcome::REGRETTED], set: |w, v| w.regret = v },
58    Knob { name: "tested", current: memory::TESTED_W, kinds: &[outcome::TESTED], set: |w, v| w.tested = v },
59];
60
61/// Candidates around a weight: half, itself, double. Derived from the current value, never hand-picked;
62/// one knob moves at a time, the others stay current.
63pub fn grid(current: f64) -> [f64; 3] {
64    [current / 2.0, current, current * 2.0]
65}
66
67/// The policy in force.
68pub const CURRENT: Weights = memory::WEIGHTS;
69
70/// One logged Thompson check: its `asked` record's index in the log, ms and session, the asked lessons
71/// with their logged p and reward, and the pool (id, base, scoped).
72#[derive(Debug, Clone, PartialEq)]
73pub struct Decision {
74    pub at: usize,
75    pub ms: i64,
76    pub session: String,
77    pub asked: Vec<(String, f64, f64)>,
78    pub pool: Vec<(String, f64, bool)>,
79}
80
81/// What `decisions` left out, and why. `no_p`, `zero_p` and `pending` count asked lessons; `no_pool`
82/// and `graded` count records.
83#[derive(Debug, Default, Clone, PartialEq, Serialize)]
84pub struct Skipped {
85    /// An `asked` record without p (or with p not aligned with its lessons): older logs, BORG_ONLY.
86    pub no_p: usize,
87    /// A lesson asked with p = 0: no inverse weight exists.
88    pub zero_p: usize,
89    /// An `asked` record with p but no pool: the graded rule, the learned cut, a live ask, a team record,
90    /// a log from before pools. The weights do not move them.
91    pub no_pool: usize,
92    /// An asked lesson with no result in its session at or after the ask yet.
93    pub pending: usize,
94    /// A `graded` record: its p comes from the model's grades or the learned cut, free of the weights.
95    pub graded: usize,
96}
97
98/// A result's rank, as memory.rs folds a session: vetoed > corrected > changed > ignored.
99fn rank(kind: &str) -> Option<u8> {
100    match kind {
101        outcome::VETOED => Some(3),
102        outcome::CORRECTED => Some(2),
103        outcome::CHANGED => Some(1),
104        outcome::IGNORED | outcome::NOT_CORRECTED => Some(0),
105        _ => None,
106    }
107}
108
109/// The logged Thompson checks of `outcomes`, in log order, and what was skipped. A lesson's reward is
110/// 1 when the strongest result of its session at or after the ask is a change, else 0: a correction or
111/// a veto after the ask means asking did not help.
112pub fn decisions(outcomes: &[Outcome]) -> (Vec<Decision>, Skipped) {
113    let mut results: HashMap<(&str, &str), Vec<(i64, u8)>> = HashMap::new();
114    for o in outcomes {
115        if let Some(r) = rank(&o.kind) {
116            for l in &o.lessons {
117                results.entry((o.session.as_str(), l.as_str())).or_default().push((o.ms, r));
118            }
119        }
120    }
121    let mut skipped = Skipped::default();
122    let mut out = Vec::new();
123    for (at, o) in outcomes.iter().enumerate() {
124        if o.kind == outcome::GRADED {
125            skipped.graded += 1;
126            continue;
127        }
128        // A free delivery (early, queued) asks nothing and draws from no pool the weights move.
129        if o.kind != outcome::ASKED || outcome::free(o) {
130            continue;
131        }
132        if o.p.is_empty() || o.p.len() != o.lessons.len() {
133            skipped.no_p += o.lessons.len();
134            continue;
135        }
136        let aligned = o.pool.len() == o.base.len() && o.pool.len() == o.scoped.len();
137        if o.pool.is_empty() || !aligned || !o.lessons.iter().all(|l| o.pool.contains(l)) {
138            skipped.no_pool += 1;
139            continue;
140        }
141        let mut asked = Vec::new();
142        for (l, &p) in o.lessons.iter().zip(&o.p) {
143            if p <= 0.0 {
144                skipped.zero_p += 1;
145                continue;
146            }
147            let after = results.get(&(o.session.as_str(), l.as_str())).and_then(|v| v.iter().filter(|(ms, _)| *ms >= o.ms).map(|(_, r)| *r).max());
148            match after {
149                Some(r) => asked.push((l.clone(), p, if r == 1 { 1.0 } else { 0.0 })),
150                None => skipped.pending += 1,
151            }
152        }
153        if !asked.is_empty() {
154            let pool = o.pool.iter().zip(&o.base).zip(&o.scoped).map(|((id, b), s)| (id.clone(), *b, *s)).collect();
155            out.push(Decision { at, ms: o.ms, session: o.session.clone(), asked, pool });
156        }
157    }
158    (out, skipped)
159}
160
161/// The pool's lessons as `derive` needs them: their ids.
162fn pool_lessons(d: &Decision) -> Vec<Challenge> {
163    d.pool.iter().map(|(id, _, _)| Challenge { id: id.clone(), ..Default::default() }).collect()
164}
165
166/// Each pooled lesson's chance of a slot under weights `w`, given its counts `mem`: the logged pool
167/// with each belief and score under `w`, through the live `propensity`.
168fn slot_p(mem: &HashMap<String, Memory>, d: &Decision, w: &Weights) -> HashMap<String, f64> {
169    let pool: Vec<Challenge> = d
170        .pool
171        .iter()
172        .map(|(id, _, scoped)| {
173            let m = &mem[id];
174            Challenge {
175                id: id.clone(),
176                scope: if *scoped { vec![conscience::ANY.into()] } else { Vec::new() },
177                belief: (m.alpha_with(w), m.beta_with(w)),
178                ..Default::default()
179            }
180        })
181        .collect();
182    let scored: Vec<(f64, &Challenge)> = pool
183        .iter()
184        .zip(&d.pool)
185        .map(|(c, (_, base, _))| {
186            let (a, b) = c.belief;
187            (base * (0.5 + a / (a + b)), c)
188        })
189        .collect();
190    conscience::propensity(&scored, &d.session)
191}
192
193/// Each pooled lesson's chance of a slot under `cand`, as of the decision: beliefs from memory::derive
194/// over the records of `log` before `d.ms` (the cut is made here: nothing at or after the decision
195/// reaches it) with the candidate weights, then conscience::propensity on the logged pool with s =
196/// base × (0.5 + mean) and the decision's session.
197pub fn replay(log: &[Outcome], d: &Decision, cand: &Weights) -> HashMap<String, f64> {
198    let prefix: Vec<Outcome> = log.iter().filter(|o| o.ms < d.ms).cloned().collect();
199    slot_p(&memory::derive(&prefix, &pool_lessons(d), None), d, cand)
200}
201
202/// One estimate of a policy's per-ask change rate.
203#[derive(Debug, Clone, PartialEq, Serialize)]
204pub struct Estimate {
205    /// SNIPS: Σwr/Σw; None without weight.
206    pub value: Option<f64>,
207    /// The 95% bootstrap interval (0, 0 without a value).
208    pub lo: f64,
209    pub hi: f64,
210    /// Effective sample size (Σw)²/Σw².
211    pub ess: f64,
212    /// Units (asked lessons) behind it.
213    pub n: usize,
214}
215
216/// How far a replayed p may lie from the logged one and still count as the same draw: the logged p is
217/// rounded (outcome.rs `round_p`), and the draw's estimate is Monte Carlo (conscience::P_DRAWS).
218pub const AGREE: f64 = 0.01;
219
220/// Resamples behind a CI: precision, not a knob (as conscience::P_DRAWS).
221pub const RESAMPLES: usize = conscience::P_DRAWS;
222
223/// The bootstrap's seed: fixed, so a run is deterministic.
224const SEED: u64 = 0x006f_7065;
225
226/// Self-normalised IPS over units (w = p_cand / p_logged, reward, session): Σwr/Σw; None when Σw = 0.
227/// ESS = (Σw)²/Σw². CI: the 2.5th and 97.5th percentiles of `RESAMPLES` bootstrap resamples of whole
228/// sessions (the session's rewards are not independent), drawn with memory::Rng from `seed`:
229/// deterministic.
230pub fn snips(units: &[(f64, f64, usize)], seed: u64) -> Estimate {
231    let ratio = |sw: f64, swr: f64| (sw > 0.0).then(|| swr / sw);
232    let sw: f64 = units.iter().map(|u| u.0).sum();
233    let sw2: f64 = units.iter().map(|u| u.0 * u.0).sum();
234    let value = ratio(sw, units.iter().map(|u| u.0 * u.1).sum());
235    let ess = if sw2 > 0.0 { sw * sw / sw2 } else { 0.0 };
236    // Per session (in session order, so the resamples do not depend on the units' order): Σw, Σwr.
237    let mut by: BTreeMap<usize, (f64, f64)> = BTreeMap::new();
238    for (w, r, s) in units {
239        let e = by.entry(*s).or_default();
240        e.0 += w;
241        e.1 += w * r;
242    }
243    let groups: Vec<(f64, f64)> = by.into_values().collect();
244    let mut rng = memory::Rng::new(seed);
245    let mut values: Vec<f64> = Vec::new();
246    if value.is_some() {
247        for _ in 0..RESAMPLES {
248            let (mut sw, mut swr) = (0.0, 0.0);
249            for _ in 0..groups.len() {
250                let g = groups[(rng.next_u64() % groups.len() as u64) as usize];
251                sw += g.0;
252                swr += g.1;
253            }
254            values.extend(ratio(sw, swr));
255        }
256    }
257    values.sort_by(f64::total_cmp);
258    let pct = |q: f64| values.get((q * (values.len().max(1) - 1) as f64).round() as usize).copied().unwrap_or(0.0);
259    Estimate { value, lo: pct(0.025), hi: pct(0.975), ess, n: units.len() }
260}
261
262/// One candidate value of one knob.
263#[derive(Debug, Clone, PartialEq, Serialize)]
264pub struct Row {
265    pub knob: &'static str,
266    pub value: f64,
267    pub est: Estimate,
268    /// Records of the knob's kinds before the last decision (in the whole log without a decision):
269    /// without any, the candidates cannot differ.
270    pub evidence: usize,
271}
272
273/// A knob's best candidate (the highest estimate; ties go to the current value) and whether its CI
274/// lower bound clears the current value's estimate. Never applied.
275#[derive(Debug, Clone, PartialEq, Serialize)]
276pub struct Pick {
277    pub knob: &'static str,
278    pub current: f64,
279    pub best: f64,
280    pub clears: bool,
281}
282
283#[derive(Debug, Clone, PartialEq, Serialize)]
284pub struct Report {
285    /// Records read, `asked` records among them (free deliveries left out: they ask nothing).
286    pub records: usize,
287    pub asked: usize,
288    pub decisions: usize,
289    /// Asked lessons behind the estimates (those of drifted decisions left out).
290    pub units: usize,
291    pub skipped: Skipped,
292    /// Decisions whose replay under the current weights misses the logged p by more than `AGREE`: the
293    /// live draw saw other records (module doc), so they are left out of every estimate.
294    pub drifted: usize,
295    /// The current weights' replay against the logged p: units within 0.01, of all, the largest |Δ|.
296    pub agree: (usize, usize, f64),
297    pub current: Estimate,
298    pub rows: Vec<Row>,
299    pub picks: Vec<Pick>,
300}
301
302/// Evaluates every knob's grid on `outcomes` (`decisions`, `replay`, `snips`).
303pub fn evaluate(outcomes: &[Outcome]) -> Report {
304    let (ds, skipped) = decisions(outcomes);
305    let mut sorted: Vec<&Outcome> = outcomes.iter().collect();
306    sorted.sort_by_key(|o| o.ms);
307    // Per lesson, the positions (in `sorted`) of the records naming it: a lesson's counts depend on
308    // those alone.
309    let mut naming: HashMap<&str, Vec<usize>> = HashMap::new();
310    for (i, o) in sorted.iter().enumerate() {
311        for l in &o.lessons {
312            naming.entry(l.as_str()).or_default().push(i);
313        }
314    }
315    // Every (knob, value), and the distinct candidates behind them (the current one once).
316    let mut cands: Vec<Weights> = vec![CURRENT];
317    let mut grid_rows: Vec<(usize, f64, usize)> = Vec::new();
318    for (k, knob) in KNOBS.iter().enumerate() {
319        for v in grid(knob.current) {
320            let mut c = CURRENT;
321            (knob.set)(&mut c, v);
322            let u = cands.iter().position(|x| *x == c).unwrap_or_else(|| {
323                cands.push(c);
324                cands.len() - 1
325            });
326            grid_rows.push((k, v, u));
327        }
328    }
329    let mut sessions: HashMap<&str, usize> = HashMap::new();
330    let mut units: Vec<Vec<(f64, f64, usize)>> = vec![Vec::new(); cands.len()];
331    let mut agree = (0, 0, 0.0f64);
332    let (mut drifted, mut n_units) = (0, 0);
333    for d in &ds {
334        let cut = sorted.partition_point(|o| o.ms < d.ms);
335        let mut at: Vec<usize> = d.pool.iter().flat_map(|(id, _, _)| naming.get(id.as_str()).into_iter().flatten().copied().take_while(|i| *i < cut)).collect();
336        at.sort_unstable();
337        at.dedup();
338        let prefix: Vec<Outcome> = at.into_iter().map(|i| sorted[i].clone()).collect();
339        let mem = memory::derive(&prefix, &pool_lessons(d), None);
340        let s = sessions.len();
341        let s = *sessions.entry(d.session.as_str()).or_insert(s);
342        let ps: Vec<HashMap<String, f64>> = cands.iter().map(|c| slot_p(&mem, d, c)).collect();
343        // The current weights (candidate 0) must reproduce the logged draw.
344        let mut same = true;
345        for (id, logged, _) in &d.asked {
346            let delta = (ps[0].get(id).copied().unwrap_or(0.0) - logged).abs();
347            agree.0 += usize::from(delta <= AGREE);
348            agree.1 += 1;
349            agree.2 = agree.2.max(delta);
350            same &= delta <= AGREE;
351        }
352        if !same {
353            drifted += 1;
354            continue;
355        }
356        n_units += d.asked.len();
357        for (u, p) in ps.iter().enumerate() {
358            for (id, logged, reward) in &d.asked {
359                units[u].push((p.get(id).copied().unwrap_or(0.0) / logged, *reward, s));
360            }
361        }
362    }
363    let estimates: Vec<Estimate> = units.iter().map(|u| snips(u, SEED)).collect();
364    let last = ds.iter().map(|d| d.ms).max().unwrap_or(i64::MAX);
365    let evidence = |k: &Knob| outcomes.iter().filter(|o| o.ms < last && k.kinds.contains(&o.kind.as_str())).count();
366    let rows: Vec<Row> =
367        grid_rows.iter().map(|&(k, v, u)| Row { knob: KNOBS[k].name, value: v, est: estimates[u].clone(), evidence: evidence(&KNOBS[k]) }).collect();
368    let current = estimates[0].clone();
369    let picks = KNOBS
370        .iter()
371        .map(|k| {
372            let of = rows.iter().filter(|r| r.knob == k.name);
373            let mut best = of.clone().find(|r| r.value == k.current).expect("the grid holds the current value");
374            for r in of {
375                if r.est.value.unwrap_or(f64::NEG_INFINITY) > best.est.value.unwrap_or(f64::NEG_INFINITY) {
376                    best = r;
377                }
378            }
379            let clears = best.value != k.current && current.value.is_some_and(|c| best.est.value.is_some() && best.est.lo > c);
380            Pick { knob: k.name, current: k.current, best: best.value, clears }
381        })
382        .collect();
383    Report {
384        records: outcomes.len(),
385        asked: outcomes.iter().filter(|o| o.kind == outcome::ASKED && !outcome::free(o)).count(),
386        decisions: ds.len(),
387        units: n_units,
388        skipped,
389        drifted,
390        agree,
391        current,
392        rows,
393        picks,
394    }
395}
396
397/// `x` without trailing zeros: 3, 1.5, 0.25.
398fn num(x: f64) -> String {
399    let s = format!("{x:.4}");
400    s.trim_end_matches('0').trim_end_matches('.').to_string()
401}
402
403/// The report as text: counts, the agreement of the replay with the log, the reward, the grid, then a
404/// table per knob with its best candidate.
405pub fn render(r: &Report) -> String {
406    let s = &r.skipped;
407    let mut out = format!(
408        "records: {}, asked: {}\ndecisions: {} with a pool and p > 0 ({} asked lessons)\nskipped: {} lessons without p, {} with p = 0, {} without a result yet; {} asked records without a pool, {} graded records (p free of the weights)\n",
409        r.records, r.asked, r.decisions, r.units, s.no_p, s.zero_p, s.pending, s.no_pool, s.graded
410    );
411    if r.drifted > 0 {
412        out.push_str(&format!(
413            "left out: {} decision(s) whose replay under the current weights misses the logged p by more than {AGREE} (the live draw saw other records, e.g. a team record that arrived after the ask)\n",
414            r.drifted
415        ));
416    }
417    if r.units == 0 {
418        out.push_str(match r.drifted {
419            0 => "too thin: no logged decision carries a pool and a propensity above 0; constants unchanged\n",
420            _ => "too thin: no logged decision left to estimate from; constants unchanged\n",
421        });
422        out.push_str("(only the Thompson slot draw over a logged pool depends on these weights: graded and learned-cut propensities do not, and the shortlist the model grades is not randomised)\n");
423        return out;
424    }
425    out.push_str(&format!(
426        "agreement: {} of {} replayed p within {AGREE} of the logged p under the current weights (max |Δ| {:.4})\n",
427        r.agree.0, r.agree.1, r.agree.2
428    ));
429    out.push_str("reward: 1 when the session's strongest result after the ask is a change (asked_then_changed), 0 for an ignore, a correction or a veto\n");
430    out.push_str("estimate: self-normalised IPS of the per-ask change rate; 95% CI from a bootstrap over sessions; ESS = (Σw)²/Σw²\n");
431    out.push_str("grid: each weight ×0.5, ×1, ×2 around its current value, the others held\n");
432    for (k, pick) in KNOBS.iter().zip(&r.picks) {
433        let rows: Vec<&Row> = r.rows.iter().filter(|x| x.knob == k.name).collect();
434        let evidence = rows.first().map_or(0, |x| x.evidence);
435        out.push_str(&format!("\n{} (current {}, evidence {evidence} records)\n", k.name, num(k.current)));
436        out.push_str(&format!("  {:<8} {:>9} {:>17} {:>8}\n", "value", "estimate", "95% CI", "ESS"));
437        for x in rows {
438            let est = x.est.value.map_or("-".to_string(), |v| format!("{v:.3}"));
439            let ci = if x.est.value.is_some() { format!("[{:.3}, {:.3}]", x.est.lo, x.est.hi) } else { "-".into() };
440            let mark = if x.value == k.current { " (current)" } else { "" };
441            out.push_str(&format!("  {:<8} {est:>9} {ci:>17} {:>8.1}{mark}\n", num(x.value), x.est.ess));
442        }
443        let best = if pick.best == k.current { format!("{} (current)", num(pick.best)) } else { num(pick.best) };
444        out.push_str(&format!("  best: {best}; its CI lower bound clears the current estimate: {}\n", if pick.clears { "yes" } else { "no" }));
445    }
446    out.push_str("\nconstants unchanged\n");
447    out
448}
449
450/// The outcomes beliefs were derived from live (outcome.rs `read_team`), with this machine's records
451/// as written.
452fn store_view(lessons: &Path) -> Vec<Outcome> {
453    // One read of each file: the local records and the team's beside them never overlap.
454    let (mut out, team) = outcome::team_parts(lessons, outcome::on());
455    out.extend(team);
456    out
457}
458
459/// `borg debug ope [--dir DIR | --file OUTCOMES.jsonl] [--json]`: the store of the collective DIR routes to
460/// (the working directory by default), or one outcomes file alone.
461pub fn main(args: &[&str]) -> i32 {
462    let usage = || {
463        eprintln!("usage: borg debug ope [--dir DIR | --file OUTCOMES.jsonl] [--json]");
464        2
465    };
466    let (mut dir, mut file, mut json): (Option<String>, Option<String>, bool) = (None, None, false);
467    let mut it = args.iter();
468    while let Some(a) = it.next() {
469        match (*a, dir.is_none() && file.is_none()) {
470            ("--json", _) => json = true,
471            ("--dir", true) => dir = Some(it.next().map(|d| d.to_string())).flatten(),
472            ("--file", true) => file = Some(it.next().map(|f| f.to_string())).flatten(),
473            _ => return usage(),
474        }
475        if matches!(*a, "--dir" | "--file") && dir.is_none() && file.is_none() {
476            return usage();
477        }
478    }
479    let (source, outcomes) = match file {
480        Some(f) => (format!("file {f}"), outcome::read(Path::new(&f))),
481        None => {
482            let cwd = dir.unwrap_or_else(|| std::env::current_dir().unwrap_or_default().display().to_string());
483            match collective::load().map(|cfg| collective::route(cfg.as_ref(), &cwd, &learn::home())) {
484                Ok(collective::Route::Collective { name, home, .. }) => {
485                    (format!("collective {name} ({})", home.display()), store_view(&home.join("lessons.jsonl")))
486                }
487                Ok(collective::Route::Off) => {
488                    println!("off: {cwd} belongs to no collective; no outcomes are kept here");
489                    return 0;
490                }
491                Err(e) => {
492                    eprintln!("borg debug ope: invalid collectives config ({e}); everything is off");
493                    return 1;
494                }
495            }
496        }
497    };
498    let report = evaluate(&outcomes);
499    match json {
500        true => println!("{}", serde_json::json!({ "source": source, "report": report })),
501        false => print!("{source}\n{}", render(&report)),
502    }
503    0
504}
505
506#[cfg(test)]
507mod tests {
508    use super::*;
509    use crate::outcome::{ASKED, CHANGED, GRADED, IGNORED, VETOED};
510    use std::collections::HashSet;
511
512    fn o(kind: &str, session: &str, lessons: &[&str], ms: i64) -> Outcome {
513        Outcome {
514            kind: kind.into(),
515            session: session.into(),
516            lessons: lessons.iter().map(|l| l.to_string()).collect(),
517            ms,
518            repo: "r".into(),
519            ..Default::default()
520        }
521    }
522
523    /// An `asked` record of `asked` from `pool` (ids with base 1, unscoped) with logged `p`.
524    fn ask(session: &str, asked: &[&str], p: &[f64], pool: &[&str], ms: i64) -> Outcome {
525        Outcome {
526            p: p.to_vec(),
527            pool: pool.iter().map(|l| l.to_string()).collect(),
528            base: vec![1.0; pool.len()],
529            scoped: vec![false; pool.len()],
530            ..o(ASKED, session, asked, ms)
531        }
532    }
533
534    fn tmp(name: &str) -> std::path::PathBuf {
535        let d = std::env::temp_dir().join(format!("borg-ope-{name}-{}", std::process::id()));
536        let _ = std::fs::remove_dir_all(&d);
537        std::fs::create_dir_all(&d).unwrap();
538        d
539    }
540
541    fn write(path: &Path, lines: &[String]) {
542        use std::io::Write;
543        let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path).unwrap();
544        for l in lines {
545            writeln!(f, "{l}").unwrap();
546        }
547    }
548
549    fn json(x: &Outcome) -> String {
550        serde_json::to_string(x).unwrap()
551    }
552
553    #[test]
554    fn replaying_the_current_weights_reproduces_the_logged_p() {
555        let home = tmp("agree");
556        let lessons = home.join("lessons.jsonl");
557        let ids = ["U1", "U2", "U3", "U4", "S1", "S2", "S3", "S4"];
558        let ls: Vec<String> = ids
559            .iter()
560            .map(|id| {
561                let scope: Vec<&str> = if id.starts_with('S') { vec!["Beacon"] } else { vec![] };
562                serde_json::json!({"id": id, "origin_ms": 0, "question": format!("question of {id}"), "scope": scope}).to_string()
563            })
564            .collect();
565        write(&lessons, &ls);
566        let outcomes = home.join("outcomes.jsonl");
567        // History: changes, ignores, a veto and a regret.
568        write(
569            &outcomes,
570            &[
571                o(ASKED, "h0", &["U1", "U2", "S1"], 100),
572                o(CHANGED, "h0", &["U1"], 110),
573                o(IGNORED, "h0", &["U2"], 120),
574                o(ASKED, "h1", &["U3", "S2"], 200),
575                o(VETOED, "h1", &["U3", "S2"], 210),
576                o(ASKED, "h2", &["U4"], 300),
577                Outcome { cause: "R1".into(), credit: 0.5, ..o(outcome::REGRETTED, "h2", &["U4"], 310) },
578            ]
579            .map(|x| json(&x)),
580        );
581        // Three checks through the live chain: load as the session, rank, pool, slots, propensity.
582        let mut logged = Vec::new();
583        for (k, s) in ["d0", "d1", "d2"].iter().enumerate() {
584            let ms = 1000 * (k as i64 + 1);
585            let cs = conscience::load_for(&lessons, None, Some(s));
586            // `rank`'s score, relevance × weight × trust / NEUTRAL, with a relevance that keeps all eight
587            // over the low bar.
588            let relevance = |i: usize, c: &Challenge| (1.0 + 0.07 * i as f64) / c.weight;
589            let mut ranked: Vec<(f64, &Challenge)> =
590                cs.iter().enumerate().map(|(i, c)| (relevance(i, c) * c.weight * c.trust / crate::trust::NEUTRAL, c)).collect();
591            ranked.sort_by(|a, b| b.0.total_cmp(&a.0));
592            let pool = conscience::budget_pool(&ranked, &HashSet::new());
593            assert!(pool.iter().filter(|(_, c)| c.scope.is_empty()).count() > conscience::GENERIC_CAP, "the generic slots overflow");
594            let p = conscience::propensity(&pool, s);
595            let asked = conscience::in_scope_first(conscience::explored(pool.iter().copied()));
596            let record = Outcome {
597                p: asked.iter().map(|c| outcome::round_p(p[&c.id])).collect(),
598                pool: pool.iter().map(|(_, c)| c.id.clone()).collect(),
599                base: pool.iter().map(|(sc, c)| conscience::pool_base(*sc, c)).collect(),
600                scoped: pool.iter().map(|(_, c)| !c.scope.is_empty()).collect(),
601                ..o(ASKED, s, &asked.iter().map(|c| c.id.as_str()).collect::<Vec<_>>(), ms)
602            };
603            logged.extend(record.p.iter().copied());
604            let mut lines = vec![json(&record)];
605            for (i, c) in asked.iter().enumerate() {
606                lines.push(json(&o(if i % 2 == 0 { CHANGED } else { IGNORED }, s, &[&c.id], ms + 10)));
607            }
608            write(&outcomes, &lines);
609        }
610        assert!(logged.iter().any(|p| *p > 0.0 && *p < 1.0), "{logged:?}");
611        let log = outcome::read_team(&lessons);
612        let r = evaluate(&log);
613        assert_eq!(r.decisions, 3);
614        assert_eq!((r.agree.0, r.agree.1), (logged.len(), logged.len()), "{:?}", r.agree);
615        assert!(r.agree.2 <= 1e-4, "within round_p: {:?}", r.agree);
616        // The public replay over the whole prefix agrees too (evaluate derives over the pool's records).
617        let (ds, _) = decisions(&log);
618        for d in &ds {
619            let prefix: Vec<Outcome> = log.iter().filter(|x| x.ms < d.ms).cloned().collect();
620            let p = replay(&prefix, d, &CURRENT);
621            assert!(d.asked.iter().all(|(id, logged, _)| (p[id] - logged).abs() <= 1e-4), "{p:?} {:?}", d.asked);
622        }
623        let _ = std::fs::remove_dir_all(&home);
624    }
625
626    /// A world of `sessions` checks over six unscoped lessons of equal base, three slots: V1-V3 carry
627    /// one early veto each, G1-G3 none. Logged under the current weights as the live path does, beliefs
628    /// derived from the log so far; `helpful_vetoed` says which three the drone changes its work on.
629    fn veto_world(sessions: usize, helpful_vetoed: bool) -> Vec<Outcome> {
630        let ids = ["V1", "V2", "V3", "G1", "G2", "G3"];
631        let ls: Vec<Challenge> = ids.iter().map(|id| Challenge { id: id.to_string(), ..Default::default() }).collect();
632        let mut log: Vec<Outcome> = ["V1", "V2", "V3"].iter().map(|v| o(VETOED, "pre", &[v], 0)).collect();
633        for i in 0..sessions {
634            let s = format!("s{i:03}");
635            let ms = 10 * (i as i64 + 1);
636            let mem = memory::derive(&log, &ls, Some(&s));
637            let cs: Vec<Challenge> = ls
638                .iter()
639                .map(|c| {
640                    let m = &mem[&c.id];
641                    Challenge { explore: m.weight(&c.id, Some(&s)) / m.weight(&c.id, None), belief: (m.alpha(), m.beta()), ..c.clone() }
642                })
643                .collect();
644            let pool: Vec<(f64, &Challenge)> = cs.iter().map(|c| (0.5 + c.belief.0 / (c.belief.0 + c.belief.1), c)).collect();
645            let p = conscience::propensity(&pool, &s);
646            let asked = conscience::in_scope_first(conscience::explored(pool.iter().copied()));
647            let names: Vec<&str> = asked.iter().map(|c| c.id.as_str()).collect();
648            log.push(ask(&s, &names, &names.iter().map(|id| outcome::round_p(p[*id])).collect::<Vec<_>>(), &ids, ms));
649            for id in names {
650                let helps = id.starts_with('V') == helpful_vetoed;
651                log.push(o(if helps { CHANGED } else { IGNORED }, &s, &[id], ms + 1));
652            }
653        }
654        log
655    }
656
657    fn rows<'a>(r: &'a Report, knob: &str) -> Vec<&'a Row> {
658        r.rows.iter().filter(|x| x.knob == knob).collect()
659    }
660
661    #[test]
662    fn a_planted_better_veto_weight_ranks_first() {
663        let r = evaluate(&veto_world(40, false));
664        assert_eq!(r.agree.0, r.agree.1, "{:?}", r.agree);
665        let veto: Vec<f64> = rows(&r, "veto").iter().map(|x| x.est.value.unwrap()).collect();
666        assert!(veto[2] > veto[1] && veto[1] > veto[0], "est(6) > est(3) > est(1.5): {veto:?}");
667        let pick = r.picks.iter().find(|p| p.knob == "veto").unwrap();
668        assert_eq!(pick.best, 6.0);
669        assert!(rows(&r, "veto").iter().all(|x| x.est.ess > 0.0 && x.evidence == 3));
670        // A knob without evidence cannot tell its candidates apart.
671        let tested: Vec<&Estimate> = rows(&r, "tested").iter().map(|x| &x.est).collect();
672        assert!(tested.iter().all(|e| *e == tested[0]) && rows(&r, "tested")[0].evidence == 0);
673        assert_eq!(r.picks.iter().find(|p| p.knob == "tested").unwrap().best, memory::TESTED_W, "a tie keeps the current value");
674        // The mirror world, where the vetoed lessons are the helpful ones: a lighter veto ranks first.
675        let r = evaluate(&veto_world(40, true));
676        let veto: Vec<f64> = rows(&r, "veto").iter().map(|x| x.est.value.unwrap()).collect();
677        assert!(veto[0] > veto[1] && veto[1] > veto[2], "{veto:?}");
678        assert_eq!(r.picks.iter().find(|p| p.knob == "veto").unwrap().best, 1.5);
679        assert!(render(&r).contains("constants unchanged"));
680    }
681
682    #[test]
683    fn zero_and_missing_p_are_skipped_and_counted() {
684        let log = vec![
685            o(ASKED, "a", &["A"], 1),
686            ask("b", &["B"], &[0.0], &["B", "X"], 2),
687            Outcome { p: vec![0.5], ..o(ASKED, "c", &["C"], 3) },
688            o(GRADED, "c", &["C", "Y"], 3),
689            ask("d", &["D"], &[0.5], &["D", "Y"], 4),
690            Outcome { p: vec![1.0], channel: "queued".into(), ..o(ASKED, "e", &["E"], 4) },
691            Outcome { p: vec![0.5], channel: "early".into(), ..o(ASKED, "e", &["F"], 4) },
692            o(CHANGED, "a", &["A"], 5),
693            o(CHANGED, "b", &["B"], 5),
694            o(CHANGED, "c", &["C"], 5),
695        ];
696        let (ds, skipped) = decisions(&log);
697        assert!(ds.is_empty());
698        assert_eq!(skipped, Skipped { no_p: 1, zero_p: 1, no_pool: 1, pending: 1, graded: 1 }, "free deliveries count nowhere");
699        let r = evaluate(&log);
700        assert_eq!((r.units, r.current.value, r.asked), (0, None, 4));
701        assert!(render(&r).contains("too thin"), "{}", render(&r));
702    }
703
704    #[test]
705    fn snips_is_the_mean_under_equal_weights_and_ess_counts_them() {
706        let units: Vec<(f64, f64, usize)> = (0..40).map(|i| (1.0, if i % 4 == 0 { 1.0 } else { 0.0 }, i / 2)).collect();
707        let e = snips(&units, 7);
708        assert_eq!((e.value, e.ess, e.n), (Some(0.25), 40.0, 40));
709        assert!(e.lo <= 0.25 && 0.25 <= e.hi && e.lo < e.hi, "{e:?}");
710        assert_eq!(snips(&units, 7), e, "one seed, one interval");
711        assert_eq!(snips(&[], 7).value, None);
712        // Weights tilt the estimate and shrink the effective sample.
713        let e = snips(&[(3.0, 1.0, 0), (1.0, 0.0, 1)], 7);
714        assert_eq!((e.value, e.ess), (Some(0.75), 1.6));
715    }
716
717    /// The bootstrap resamples whole sessions: four sessions of ten identical rewards (two all 1, two
718    /// all 0) are four independent results, not forty, and the interval is as wide as four allow.
719    #[test]
720    fn the_bootstrap_resamples_sessions_not_units() {
721        let units: Vec<(f64, f64, usize)> = (0..40).map(|i| (1.0, if i / 10 < 2 { 1.0 } else { 0.0 }, i / 10)).collect();
722        let e = snips(&units, 7);
723        assert_eq!(e.value, Some(0.5));
724        // Four sessions: all four drawn from one side has chance 2 × (1/2)^4 = 1/8 > 5%, so the 95%
725        // interval reaches both ends. Forty independent units would give about 0.5 ± 0.16.
726        assert_eq!((e.lo, e.hi), (0.0, 1.0), "{e:?}");
727        let iid: Vec<(f64, f64, usize)> = units.iter().enumerate().map(|(i, u)| (u.0, u.1, i)).collect();
728        let narrow = snips(&iid, 7);
729        assert!(narrow.hi - narrow.lo < 0.5 * (e.hi - e.lo), "{narrow:?}");
730    }
731
732    #[test]
733    fn grid_halves_and_doubles() {
734        assert_eq!(grid(3.0), [1.5, 3.0, 6.0]);
735        let current: Vec<f64> = KNOBS.iter().map(|k| k.current).collect();
736        assert_eq!(current, [memory::VETOED_W as f64, memory::REGRET, memory::TESTED_W]);
737        // Each knob sets its own weight.
738        for k in &KNOBS {
739            let mut c = CURRENT;
740            (k.set)(&mut c, 99.0);
741            assert_ne!(c, CURRENT, "{}", k.name);
742        }
743    }
744
745    /// Four unscoped lessons over three slots (p depends on the beliefs), history `before` the check at
746    /// ms 100, and the check logged with the p the current weights give on that history: the live draw.
747    fn leak_world(before: &[Outcome]) -> Vec<Outcome> {
748        let pool = ["A", "B", "C", "D"];
749        let probe = ask("d", &["A", "B", "C"], &[1.0, 1.0, 1.0], &pool, 100);
750        let (ds, _) = decisions(&[[before, &[probe.clone(), o(CHANGED, "d", &["A"], 110)]].concat()].concat());
751        let p = replay(before, &ds[0], &CURRENT);
752        let logged = Outcome { p: ["A", "B", "C"].iter().map(|l| outcome::round_p(p[*l])).collect(), ..probe };
753        [before, &[logged, o(CHANGED, "d", &["A"], 110)]].concat()
754    }
755
756    #[test]
757    fn replay_is_leak_free() {
758        let history = [o(CHANGED, "h", &["A"], 1), o(IGNORED, "h", &["B"], 2)];
759        let base = leak_world(&history);
760        let veto = |ms: i64| [base.clone(), vec![o(VETOED, "later", &["A", "B"], ms)]].concat();
761        let (ds, _) = decisions(&base);
762        // The public replay takes the whole log and cuts it at the decision itself.
763        let at = |log: &[Outcome]| replay(log, &ds[0], &CURRENT);
764        assert_eq!(at(&veto(100)), at(&base), "a veto at the decision's ms is not seen");
765        assert_eq!(at(&veto(500)), at(&base), "nor one after it");
766        assert_ne!(at(&veto(99)), at(&base), "one before it is");
767        // `evaluate` alike: what comes at or after a decision changes no estimate.
768        let before = evaluate(&base);
769        assert_eq!((before.decisions, before.drifted, before.agree.0, before.agree.1), (1, 0, 1, 1), "{:?}", before.agree);
770        assert_eq!(evaluate(&veto(100)).rows, before.rows);
771        assert_eq!(evaluate(&veto(500)).rows, before.rows);
772        // A veto logged before the check that the live draw saw: replayed as seen.
773        let seen = leak_world(&[history.to_vec(), vec![o(VETOED, "early", &["A", "B"], 99)]].concat());
774        let r = evaluate(&seen);
775        assert_eq!((r.drifted, r.units), (0, 1));
776        assert_ne!(r.rows, before.rows, "it moved the draw");
777    }
778
779    /// A team record stamped before a check but synced after it: the live draw never saw it, the replay
780    /// would. The current weights then miss the logged p, and the decision is left out, not estimated.
781    #[test]
782    fn a_record_the_live_draw_did_not_see_drops_its_decision() {
783        let history = [o(CHANGED, "h", &["A"], 1), o(IGNORED, "h", &["B"], 2)];
784        let late = [leak_world(&history), vec![o(VETOED, "peer", &["A", "B"], 50)]].concat();
785        let r = evaluate(&late);
786        assert_eq!((r.decisions, r.drifted, r.units), (1, 1, 0), "{:?}", r.agree);
787        assert!(r.agree.0 < r.agree.1 && r.current.value.is_none());
788        assert!(render(&r).contains("left out: 1 decision(s)"), "{}", render(&r));
789    }
790
791    #[test]
792    fn replay_scales_with_the_store() {
793        // 2k decisions over 20k records: pools of two unscoped lessons (p = 1, no draw), so this times the
794        // replay's derives, not the propensity.
795        let mut log = Vec::new();
796        for i in 0..2000usize {
797            let (a, b) = (format!("L{}", i % 200), format!("L{}", (i * 7 + 1) % 200));
798            let s = format!("s{i}");
799            let ms = 10 * i as i64 + 5;
800            log.push(ask(&s, &[&a], &[1.0], &[&a, &b], ms));
801            log.push(o(if i % 3 == 0 { CHANGED } else { IGNORED }, &s, &[&a], ms + 1));
802            for k in 0..8 {
803                log.push(o(outcome::NOT_CORRECTED, &format!("x{i}"), &[&format!("L{}", (i + k) % 200)], ms + 2));
804            }
805        }
806        assert_eq!(log.len(), 20_000);
807        let started = std::time::Instant::now();
808        let r = evaluate(&log);
809        assert_eq!(r.decisions, 2000);
810        assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
811    }
812}