Merge feat/scorecard (reviewed: BLOCK; B1/B2 fixed with the review's proofs): multi-seed play regression harness, per-checkpoint trap rule, v0.7.5 baseline

This commit is contained in:
acamilo 2026-10-02 04:56:04 +00:00
commit ef48a6aed9
18 changed files with 4131 additions and 0 deletions

176
docs/scorecard.md Normal file
View file

@ -0,0 +1,176 @@
# The behavioural scorecard
A repeatable, multi-seed "good play" regression harness. The unit tests say the macros do what
they were written to; the trap hunt says a fly stuck in one place got out. Neither says whether a
release plays *better or worse* than the one before it across the places the fly actually is. The
scorecard does: a fixed set of checkpoints, K seeds each, T brain minutes each, on the real
connectome with the macro layer, reduced to one JSON per release and compared release against
release by a test over the paired runs, never by a single run.
It measures and presses nothing. It restores a checkpoint, lets the brain play, and counts. The
ethos check (`docs/loop-review.md`) is untouched: the harness is outside the fly.
```sh
export FLY_ROM=/path/to/the-cartridge # read, never copied
cargo build --release -p fly-scorecard # from services/flysim
fly-scorecard list # the set, resolved, each checkpoint's rung
fly-scorecard suite --label v0.7.5 --out card.json # the set x 3 seeds x 10 brain minutes
fly-scorecard summary card.json # one screen of markdown
fly-scorecard compare old.json new.json # exit 1 when a metric regressed
fly-scorecard run-one --checkpoint X --seed 1 # one run, JSON out (--out FILE)
```
`--runtime session` (the default) runs the session composition the release cut over to
(`fly-legacy-session`, in-process, unpaced); `--runtime legacy` runs the stream's own frame
(`flysim::frame::LegacyFrame`). Both hand the same per-frame observation to the same tally, so a
card from one runtime is comparable with a card from the other. From the same checkpoint and seed
the two give identical reports apart from wall time (`tests/rom_scorecard.rs` holds it), which makes a scorecard
run on both a second piece of shadow evidence. `--mode raw` runs without the macro layer.
## The set
`tools/scorecard/checkpoints.json` names each checkpoint by the environment variable that holds
its path (the ROM tests' own, `rom-env.sh`), never by a path; `--extra id=path` adds more (the
newest live checkpoint, a trap's). The checkpoints are not committed (`.local/` is untracked).
`list` prints the rung each one stands on, from its reward ledger. The set has two or three
states at each of rungs 8, 9, 10, 11, 12 and 15; rungs 13 and 14 have no checkpoint yet and join
the set when the scout makes them (a new entry is a line in the JSON). A checkpoint missing from
the environment is named on stderr and, with `--strict`, an error.
## Seeds
A checkpoint restores a deterministic brain, so two runs from it would be the same run. A seed
therefore chooses how many frames the brain's readout is ignored before the measurement starts
(60 to 1,800 frames, a splitmix of the seed; seed 0 is none). The brain still ticks and its noise
generator still advances, the game sees no button, and from the first measured frame the readout
is the brain's own: the run sits on a different point of its own trajectory. The idle frames are
not measured. The same seed twice is the same run.
## What a run reports
One `RunReport` per (checkpoint, seed). Every number is computed from per-frame observations by
`tally.rs`, which has no emulator in it and is unit-tested on synthetic frames.
| group | what |
| --- | --- |
| rungs | start, end, gained, the brain minute of each climb; reported per brain hour |
| places | the adapter's exploration count, start and end |
| empty pad | frames with the macro layer on, nothing running and no button dealt; seconds, share, longest stretch |
| watchdog | `fly-watchdog` check 10, rule for rule (`watchdog.rs`): probes, suspected, reasons, **confirmed** (two suspected probes in a row) and **ladder events** (one per run of two or more: a trap the recovery ladder would act on) |
| hunt | the trap hunt's windows (two brain minutes, fewer than four tiles or a sequence repeated more than ten times) |
| ratchet | rollbacks, split by game over and stall |
| macros | starts, done, blocked, timeout, refused, by macro |
| funnel | GO SHOP, BUY BALL, THROW BALL, catch: counts at each stage, balls gained and spent, species gained, and how far down the funnel the run got |
| heals | GO HEAL and the nurse's HEAL |
| whiteouts | the whole party fainted (a rising edge) |
| battles | started, ended, wild and trainer, won (a battle or trainer payout), lost (the party fainted in it), caught, other |
| rewards, scenes | counts and totals by adapter kind; frames by scene |
The watchdog's rules are the shell's: the same thresholds, the same order, the same two-probe
memory for the zero-progress, unrewarded and unwon-battle rules. Two things differ, both about
time: a run is short, so the probe cadence is a parameter (default every 120 brain seconds,
first at 240; the stream's is five wall minutes) and the window is the last ten brain minutes or
the whole run when it is shorter; and the first probe compares the exploration count with the
run's starting count, which the live check lacks after a boot.
## Compare
`compare A.json B.json` pairs runs by (checkpoint, seed). Each metric (`compare.rs`, `METRICS`)
has a direction (more is better, less is better, or info), an absolute tolerance and a relative
one. For each metric the pairs give one difference, signed so that positive means B is worse. B
**fails** a metric when it is worse by more than the tolerance **and** a one-sided sign-flip
permutation test over the pairs gives a **Holm-adjusted** p below alpha (default 0.05; Holm over
the judged metrics, so the whole compare, not each metric, has a false-fail rate of at most
alpha when nothing changed; unadjusted, 13 metrics at 0.05 each false-failed about 15% of
releases in a bootstrap of the baseline, with Holm 0 of 200). It reports **better** by the
same two tests, and **pass** otherwise: a change inside the tolerance is noise however consistent,
and one bad run among eighteen is not a regression. The test is exact up to 20 pairs and a
fixed-seed Monte-Carlo beyond, so the same two cards always give the same verdicts. The
comparison also names its caveats (different lengths, different runtimes, fewer than eight
pairs, unpaired runs). Exit status 1 is a failed metric or a failed checkpoint.
**The trap rule.** The pooled test cannot see a fault confined to one place: three seeds of one
checkpoint give a sign-flip p of at least 1/8, and the shift is diluted over thirty-six pairs
(the row-71 bag bug, 131 blocked THROW BALLs in every seed of one checkpoint, passed the pooled
compare even spliced into an otherwise identical suite). So each checkpoint is also judged on its
own, without statistics: it **fails**, named as `trap@<checkpoint>`, when B is trapped on at least
two of its runs and on at least two more than A, or when any run of B has a blocked-macro storm
(50 or more blocked finishes of one macro) and no run of A on that checkpoint does. A run is
trapped on a recovery-ladder event (two suspected watchdog probes in a row, any rule: stalled,
zero-progress, sequence, ...), on at least half its probes suspected, or on a storm. Costs: with
three seeds a checkpoint whose trap is a coin flip in A already (r09-forest-catch, r10-pewter-center
on the baseline) can fail by chance when B traps all three seeds (about 1 in 27 each by bootstrap,
so roughly 7% of releases that changed nothing but the trajectory); five seeds make it 1 in 243.
Identical suites never fail.
The metrics: rungs per hour, places per hour, empty pad %, suspected probes %, ladder events per
hour, rollbacks per hour, blocked macro %, buy ball, throws (THROW BALL that finished, not blocked starts) and catches per hour, battles won and
lost per hour, whiteouts per hour. Blocked throws per hour, heals per hour, macro starts per minute and the trap hunt's
flagged windows are reported, never judged: healing more can follow losing more, and a fly that
fights for most of a run presses NEXT through battle text more than ten times in two minutes,
which the hunt reads as a repeated sequence (nine windows in ten are flagged on the baseline, so
the number has no room to move).
## Cost and size
A run's brain minute costs about 75 CPU seconds however it is split, and the result does not
depend on the thread count (the same seed gives an identical report at one thread and at four).
The split matters for wall time, because a run's sweep pool spins at its barriers: on a quiet
ten-core box two jobs of four threads are fine, but on a box shared with compiles and tests one
job of four threads ran five times slower per brain minute than one-thread jobs did. So the
default is one thread per run and eight runs at a time. The default suite, twelve checkpoints by
three seeds by ten brain minutes, is 360 brain minutes: about three quarters of an hour of ten
quiet cores, about twice that when the box is busy. More seeds tighten the test; longer runs let
rungs climb. Three seeds is the smallest suite whose pair count (36) can reach p < 0.001.
`--resume` keeps the runs an interrupted suite had finished (`<out>.runs.jsonl`).
## What it does not do
- It does not rebuild session ledgers a restore starts empty (the trap hunt's
`FLY_TRAP_SEED_*`); a trap that needs them is that tool's.
- Ten brain minutes rarely climb two rungs. Rungs per hour is a rate over many runs, not a
per-run prediction; a release that is faster by a rung every few hours shows only across the
suite.
- It judges play against the previous release, not against a notion of good. A regression is
"worse than last time"; the absolute numbers say how good last time was.
## Releases and nightly
`tools/scorecard/overlay.sh <ref> <tree>` puts the tool on the tree of an older release (the crate,
the set, the docs, and the one read-only accessor `PokeredTask::with_reader`), so a release that
predates it can be scored and its numbers are its own. The operator's nightly runner builds the
latest release tag on a build box, runs the suite, writes the card and a one-screen summary and
compares with the previous release's card.
## The v0.7.5 baseline
`tools/scorecard/baseline-v0.7.5.json` is the reference card of v0.7.5 (adapter v8,
compatibility `ff09d7dd5483`): the default set, 12 checkpoints by 3 seeds by 10 brain minutes on
the session runtime, 6.0 brain hours, 6,130 s wall on a shared build box.
| headline | v0.7.5 |
| --- | ---: |
| rungs per brain hour | 1.50 (9 of 36 runs climbed) |
| empty-pad time | 6.96% of frames |
| watchdog probes suspected | 2.8% |
| ladder-worthy traps | 1 (one run, `r09-forest-catch`) |
| blocked macro finishes | 0.5% |
| buy ball / throw / catch | 10 / 10 / 8 |
| heals / whiteouts | 9 / 46 |
| battles won / lost | 33 / 45 |
| ratchet rollbacks | 1 |
What the card shows about v0.7.5, worth reading before the next release is compared with it:
- **The fly fights for most of the frames it is given.** On nine of the twelve checkpoints a
battle is half to nine tenths of the frames, and it loses more than it wins (45 lost, 33 won;
46 whiteouts). The longest single battle is 18,354 frames (five brain minutes, a trainer, on
`r11-mart`); `r09-forest-catch` has one of 26,245 frames in a wild battle.
- **`r15-nugget-bridge` keeps walking and finds nothing.** After the Oddish is caught (all three
seeds), the fly spends the rest of the run in the overworld, GO OBJECTIVE and GO OUT
alternating 13 times each in ten minutes, with the exploration count unmoved (2,527). The
watchdog does not flag it (a ring this slow stays under its twenty repeats), so no recovery
step would act on it.
- The shop-to-catch funnel closes: buy ball, throw and catch all occur, across rungs 9 to 15.

View file

@ -476,6 +476,24 @@ dependencies = [
"tracing-subscriber", "tracing-subscriber",
] ]
[[package]]
name = "fly-scorecard"
version = "0.1.1"
dependencies = [
"anyhow",
"clap",
"fly-legacy-session",
"fly-session",
"flybrain-core",
"flybrain-gb",
"flysim",
"libc",
"serde",
"serde_json",
"tempfile",
"tokio",
]
[[package]] [[package]]
name = "fly-session" name = "fly-session"
version = "0.1.1" version = "0.1.1"

View file

@ -11,6 +11,7 @@ members = [
"crates/flybus", "crates/flybus",
"crates/flysim", "crates/flysim",
"crates/flysim-store", "crates/flysim-store",
"crates/fly-scorecard",
] ]
[workspace.package] [workspace.package]

View file

@ -368,6 +368,19 @@ impl PokeredTask {
) )
} }
/// Read the committed boundary's memory image through the cartridge, as the macro engine
/// reads it, for a harness that measures play (the scorecard). `None` before the first
/// observation. Changes nothing.
pub fn with_reader<R>(
&self,
f: impl FnOnce(&mut dyn flybrain_gb::MemoryReader) -> R,
) -> Option<R> {
let inner = self.lock();
let (_, image) = inner.current.as_ref()?;
let mut reader = ImageReader::new(image, &inner.cartridge);
Some(f(&mut reader))
}
/// The brain time of the last transition (its Prepare's clock), in ms: `network.ms`. /// The brain time of the last transition (its Prepare's clock), in ms: `network.ms`.
pub fn brain_ms(&self) -> f64 { pub fn brain_ms(&self) -> f64 {
self.lock().ms self.lock().ms

View file

@ -0,0 +1,32 @@
[package]
name = "fly-scorecard"
version.workspace = true
edition = "2024"
rust-version.workspace = true
license.workspace = true
publish = false
description = "The behavioural scorecard (B2): a repeatable multi-seed good-play regression harness over a fixed checkpoint set, on either runtime, with a release-against-release compare."
[lib]
name = "fly_scorecard"
path = "src/lib.rs"
[[bin]]
name = "fly-scorecard"
path = "src/main.rs"
[dependencies]
# The unchanged engine under test: flysim's frame and macro layer (the legacy runtime), the
# session composition (the session runtime), flybrain-gb's adapter and state readers.
flysim = { path = "../flysim" }
fly-legacy-session = { path = "../fly-legacy-session" }
fly-session = { path = "../fly-session" }
flybrain-core = { path = "../flybrain-core" }
flybrain-gb = { path = "../flybrain-gb" }
anyhow = "1.0"
clap = { version = "4.5", features = ["derive"] }
serde = { workspace = true }
serde_json = { workspace = true }
tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] }
tempfile = "3"
libc = "0.2"

View file

@ -0,0 +1,893 @@
//! Release A against release B: a verdict per metric from the runs, not from one run.
//!
//! The runs of the two suites are paired by `(checkpoint, seed)`. Each pair gives one difference
//! per metric, signed so that positive means B is worse. A metric fails when B is worse than A by
//! more than its tolerance **and** a sign-flip permutation test over the pairs says the shortfall
//! is not noise (one-sided, `alpha`, Holm-adjusted over the judged metrics so the whole compare
//! has a family-wise false-fail rate of at most `alpha` under "nothing changed", where the
//! unadjusted per-metric test had about 15% over 13 metrics). Otherwise it passes, and when B is
//! better by the same two tests it says so. A metric with no direction (`info`) is only reported.
//!
//! The pooled test cannot see a trap confined to one place (three seeds of one checkpoint among
//! thirty-six pairs), so a second, non-statistical rule runs per checkpoint: see [`trap_rule`].
//!
//! The test is exact up to 20 pairs and a fixed-seed Monte-Carlo beyond, so the same two suites
//! always give the same verdicts.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::suite::SuiteReport;
use crate::tally::RunReport;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Direction {
/// More is better.
Up,
/// Less is better.
Down,
/// Reported, never judged.
Info,
}
/// One metric: how to read it off a run, which way is good, and how big a change must be before
/// it can count.
pub struct Metric {
pub name: &'static str,
pub unit: &'static str,
pub direction: Direction,
/// A change smaller than this (in `unit`) is never a regression or an improvement.
pub abs_tol: f64,
/// ... nor one smaller than this share of A's mean.
pub rel_tol: f64,
pub read: fn(&RunReport) -> f64,
}
fn per_hour(count: f64, run: &RunReport) -> f64 {
if run.minutes <= 0.0 { 0.0 } else { count * 60.0 / run.minutes }
}
fn pct(part: f64, whole: f64) -> f64 {
if whole <= 0.0 { 0.0 } else { 100.0 * part / whole }
}
/// The scorecard's metrics, in report order.
pub const METRICS: &[Metric] = &[
Metric {
name: "rungs_per_hour",
unit: "rungs/h",
direction: Direction::Up,
abs_tol: 0.5,
rel_tol: 0.15,
read: |r| per_hour(f64::from(r.rungs.gained), r),
},
Metric {
name: "places_per_hour",
unit: "places/h",
direction: Direction::Up,
abs_tol: 5.0,
rel_tol: 0.15,
read: |r| per_hour(f64::from(r.places_end.saturating_sub(r.places_start)), r),
},
Metric {
name: "empty_pad_pct",
unit: "% of frames",
direction: Direction::Down,
abs_tol: 1.0,
rel_tol: 0.25,
read: |r| 100.0 * r.pad.empty_fraction,
},
Metric {
name: "watchdog_suspected_pct",
unit: "% of probes",
direction: Direction::Down,
abs_tol: 5.0,
rel_tol: 0.25,
read: |r| pct(r.watchdog.suspected as f64, r.watchdog.probes as f64),
},
Metric {
name: "ladder_events_per_hour",
unit: "traps/h",
direction: Direction::Down,
abs_tol: 0.5,
rel_tol: 0.25,
read: |r| per_hour(r.watchdog.ladder_events as f64, r),
},
// The trap hunt's windows are reported, not judged: a fly that fights for most of a run
// presses NEXT through battle text more than ten times in two minutes, which that instrument
// reads as a repeated sequence, so on these checkpoints nine windows in ten are flagged and
// the number has no room to move. The watchdog's rules above are the judged ones.
Metric {
name: "hunt_flagged_pct",
unit: "% of windows",
direction: Direction::Info,
abs_tol: 0.0,
rel_tol: 0.0,
read: |r| pct(r.hunt.flagged as f64, r.hunt.windows as f64),
},
Metric {
name: "ratchet_rollbacks_per_hour",
unit: "rollbacks/h",
direction: Direction::Down,
abs_tol: 1.0,
rel_tol: 0.25,
read: |r| per_hour(f64::from(r.ratchet.rollbacks), r),
},
Metric {
name: "blocked_macro_pct",
unit: "% of finishes",
direction: Direction::Down,
abs_tol: 2.0,
rel_tol: 0.25,
read: |r| {
let finishes = r.macros.done + r.macros.failed();
pct(r.macros.failed() as f64, finishes as f64)
},
},
Metric {
name: "buy_ball_per_hour",
unit: "buys/h",
direction: Direction::Up,
abs_tol: 0.5,
rel_tol: 0.25,
read: |r| per_hour(r.funnel.buy_ball_done as f64, r),
},
Metric {
name: "throws_per_hour",
unit: "throws/h",
direction: Direction::Up,
abs_tol: 0.5,
rel_tol: 0.25,
read: |r| per_hour(r.funnel.throw_ball_done as f64, r),
},
// Reported, never judged on its own: a blocked THROW BALL storm is the trap rule's and the
// watchdog's business, and `throws_per_hour` above counts only throws that happened.
Metric {
name: "throw_ball_blocked_per_hour",
unit: "blocked/h",
direction: Direction::Info,
abs_tol: 0.0,
rel_tol: 0.0,
read: |r| per_hour(r.macros.by_macro.get("THROW BALL").map_or(0, |c| c.blocked) as f64, r),
},
Metric {
name: "catches_per_hour",
unit: "catches/h",
direction: Direction::Up,
abs_tol: 0.5,
rel_tol: 0.25,
read: |r| per_hour(r.funnel.catches as f64, r),
},
Metric {
name: "battles_won_per_hour",
unit: "wins/h",
direction: Direction::Up,
abs_tol: 1.0,
rel_tol: 0.2,
read: |r| per_hour(r.battles.won as f64, r),
},
Metric {
name: "battles_lost_per_hour",
unit: "losses/h",
direction: Direction::Down,
abs_tol: 0.5,
rel_tol: 0.25,
read: |r| per_hour(r.battles.lost as f64, r),
},
Metric {
name: "whiteouts_per_hour",
unit: "whiteouts/h",
direction: Direction::Down,
abs_tol: 0.5,
rel_tol: 0.25,
read: |r| per_hour(r.whiteouts as f64, r),
},
// Reported, never judged: healing more can follow losing more.
Metric {
name: "heals_per_hour",
unit: "heals/h",
direction: Direction::Info,
abs_tol: 0.0,
rel_tol: 0.0,
read: |r| per_hour(r.heals.heal_done as f64, r),
},
Metric {
name: "macro_starts_per_minute",
unit: "starts/min",
direction: Direction::Info,
abs_tol: 0.0,
rel_tol: 0.0,
read: |r| if r.minutes <= 0.0 { 0.0 } else { r.macros.starts as f64 / r.minutes },
},
];
pub fn mean(values: &[f64]) -> f64 {
if values.is_empty() { 0.0 } else { values.iter().sum::<f64>() / values.len() as f64 }
}
pub fn stdev(values: &[f64]) -> f64 {
if values.len() < 2 {
return 0.0;
}
let m = mean(values);
(values.iter().map(|v| (v - m).powi(2)).sum::<f64>() / (values.len() - 1) as f64).sqrt()
}
/// One-sided sign-flip p-value for "the mean of `diffs` is greater than zero by more than chance":
/// the share of sign assignments whose mean is at least the observed one. Exact for up to 20
/// differences, 20,000 fixed-seed draws beyond.
pub fn sign_flip_p(diffs: &[f64]) -> f64 {
let n = diffs.len();
if n == 0 {
return 1.0;
}
let observed: f64 = diffs.iter().sum();
let eps = 1e-9 * (1.0 + observed.abs());
if n <= 20 {
let total = 1u64 << n;
let mut at_least = 0u64;
for mask in 0..total {
let sum: f64 = diffs
.iter()
.enumerate()
.map(|(i, d)| if mask >> i & 1 == 1 { -d } else { *d })
.sum();
if sum >= observed - eps {
at_least += 1;
}
}
return at_least as f64 / total as f64;
}
let draws = 20_000u64;
let mut state = 0x2545_f491_4f6c_dd1du64;
let mut at_least = 1u64; // the observed assignment is one of them
for _ in 0..draws {
let mut sum = 0.0;
let mut bits = 0u64;
for (i, d) in diffs.iter().enumerate() {
if i % 64 == 0 {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
bits = state;
}
sum += if bits >> (i % 64) & 1 == 1 { -d } else { *d };
}
if sum >= observed - eps {
at_least += 1;
}
}
at_least as f64 / (draws + 1) as f64
}
/// Holm's step-down adjustment: the adjusted p of each value (same order), so that rejecting
/// where `adjusted < alpha` controls the family-wise error rate at `alpha` under any dependence
/// between the tests.
pub fn holm_adjust(ps: &[f64]) -> Vec<f64> {
let m = ps.len();
let mut order: Vec<usize> = (0..m).collect();
order.sort_by(|&i, &j| ps[i].total_cmp(&ps[j]));
let mut adjusted = vec![1.0; m];
let mut running = 0.0f64;
for (rank, &i) in order.iter().enumerate() {
running = running.max(((m - rank) as f64 * ps[i]).min(1.0));
adjusted[i] = running;
}
adjusted
}
/// Blocked finishes of one macro in one run that make a storm no watchdog window is needed to
/// read: the row-71 bag bug blocked THROW BALL 131 times in ten brain minutes.
pub const STORM_BLOCKED: u64 = 50;
/// Trapped runs of B on a checkpoint (and this many more than A) that fail the checkpoint.
pub const TRAP_RUNS: usize = 2;
/// Why a run counts as trapped, if it does: a recovery-ladder event (two suspected watchdog
/// probes in a row, any rule including stalled and zero-progress), at least half the probes
/// suspected, or a blocked-macro storm.
pub fn trapped(run: &RunReport) -> Option<String> {
if let Some((name, n)) = storm(run) {
return Some(format!("{n} blocked {name}"));
}
let w = &run.watchdog;
if w.ladder_events > 0 {
return Some(format!("{} ladder event(s), {}/{} probes suspected", w.ladder_events, w.suspected, w.probes));
}
if w.probes >= 2 && w.suspected * 2 >= w.probes {
return Some(format!("{}/{} probes suspected", w.suspected, w.probes));
}
None
}
/// The macro with the most blocked finishes in the run when that is a storm.
pub fn storm(run: &RunReport) -> Option<(String, u64)> {
run.macros
.by_macro
.iter()
.map(|(name, c)| (name.clone(), c.blocked))
.filter(|(_, n)| *n >= STORM_BLOCKED)
.max_by_key(|(_, n)| *n)
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckpointTrap {
pub checkpoint: String,
pub runs_a: usize,
pub runs_b: usize,
pub trapped_a: usize,
pub trapped_b: usize,
pub storms_a: usize,
pub storms_b: usize,
/// What B's trapped runs looked like (seed: reason).
pub detail: Vec<String>,
}
/// The per-checkpoint trap rule, independent of the cross-seed test: a checkpoint FAILS when B is
/// trapped on at least `TRAP_RUNS` of its runs and on at least `TRAP_RUNS` more than A, or when B
/// has a blocked-macro storm on any run and A has none on that checkpoint. A fault confined to one
/// place cannot fail the pooled test (three seeds give a sign-flip p of at least 1/8, and the
/// shift is diluted over every checkpoint), but it is exactly the regression class this exists
/// for. Returns the failing checkpoints.
pub fn trap_rule(a: &SuiteReport, b: &SuiteReport) -> Vec<CheckpointTrap> {
let mut ids: Vec<&str> = b.runs.iter().map(|r| r.checkpoint.as_str()).collect();
ids.sort_unstable();
ids.dedup();
let mut failing = Vec::new();
for id in ids {
let ra: Vec<&RunReport> = a.runs.iter().filter(|r| r.checkpoint == id).collect();
let rb: Vec<&RunReport> = b.runs.iter().filter(|r| r.checkpoint == id).collect();
if ra.is_empty() {
continue;
}
let trapped_a = ra.iter().filter(|r| trapped(r).is_some()).count();
let trapped_b = rb.iter().filter(|r| trapped(r).is_some()).count();
let storms_a = ra.iter().filter(|r| storm(r).is_some()).count();
let storms_b = rb.iter().filter(|r| storm(r).is_some()).count();
let fails = (trapped_b >= TRAP_RUNS && trapped_b >= trapped_a + TRAP_RUNS) || (storms_b > 0 && storms_a == 0);
if fails {
failing.push(CheckpointTrap {
checkpoint: id.to_owned(),
runs_a: ra.len(),
runs_b: rb.len(),
trapped_a,
trapped_b,
storms_a,
storms_b,
detail: rb.iter().filter_map(|r| trapped(r).map(|why| format!("seed {}: {why}", r.seed))).collect(),
});
}
}
failing
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Verdict {
Pass,
Better,
Fail,
Info,
/// No run of A pairs with a run of B.
None,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct MetricVerdict {
pub metric: String,
pub unit: String,
pub direction: Direction,
pub pairs: usize,
pub mean_a: f64,
pub mean_b: f64,
pub delta: f64,
/// The one-sided p of "B is worse" and of "B is better".
pub p_worse: f64,
pub p_better: f64,
/// The same, Holm-adjusted over the judged metrics (what the verdict uses).
#[serde(default)]
pub p_worse_adj: f64,
#[serde(default)]
pub p_better_adj: f64,
/// The smallest change that counts, in the metric's unit.
pub tolerance: f64,
pub verdict: Verdict,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Comparison {
pub schema: String,
pub a: String,
pub b: String,
pub alpha: f64,
pub pairs: usize,
pub unpaired_a: usize,
pub unpaired_b: usize,
pub notes: Vec<String>,
pub metrics: Vec<MetricVerdict>,
/// Checkpoints the per-checkpoint trap rule failed.
#[serde(default)]
pub trapped_checkpoints: Vec<CheckpointTrap>,
/// Every metric that failed, in order, then `trap@<checkpoint>` for each failed checkpoint.
pub failed: Vec<String>,
pub pass: bool,
}
fn key(run: &RunReport) -> (String, u32) {
(run.checkpoint.clone(), run.seed)
}
/// Compares two suites. `alpha` is the one-sided significance level.
pub fn compare(a: &SuiteReport, b: &SuiteReport, alpha: f64) -> Comparison {
let by_key = |suite: &SuiteReport| -> BTreeMap<(String, u32), RunReport> {
suite.runs.iter().map(|run| (key(run), run.clone())).collect()
};
let runs_a = by_key(a);
let runs_b = by_key(b);
let pairs: Vec<(&RunReport, &RunReport)> =
runs_a.iter().filter_map(|(k, ra)| runs_b.get(k).map(|rb| (ra, rb))).collect();
let mut notes = Vec::new();
if a.config.minutes != b.config.minutes {
notes.push(format!(
"the suites ran different lengths ({} and {} brain minutes): rates are comparable, counts are not",
a.config.minutes, b.config.minutes
));
}
if a.runtime != b.runtime {
notes.push(format!("the suites ran on different runtimes ({} and {})", a.runtime, b.runtime));
}
if a.config.probe_s != b.config.probe_s || a.config.window_s != b.config.window_s {
notes.push("the watchdog probes differ between the suites".to_owned());
}
if pairs.len() < 8 {
notes.push(format!(
"only {} paired runs: the permutation test cannot reach alpha {alpha} with fewer than {} pairs",
pairs.len(),
(1.0 / alpha).log2().ceil() as usize
));
}
// First the raw p-values of every metric, then Holm over the judged ones.
struct Raw {
mean_a: f64,
mean_b: f64,
delta: f64,
tolerance: f64,
shortfall: f64,
p_worse: f64,
p_better: f64,
}
let raws: Vec<Raw> = METRICS
.iter()
.map(|metric| {
let va: Vec<f64> = pairs.iter().map(|(ra, _)| (metric.read)(ra)).collect();
let vb: Vec<f64> = pairs.iter().map(|(_, rb)| (metric.read)(rb)).collect();
let (mean_a, mean_b) = (mean(&va), mean(&vb));
let delta = mean_b - mean_a;
// Signed so that positive is worse.
let sign = match metric.direction {
Direction::Up => -1.0,
Direction::Down | Direction::Info => 1.0,
};
let worse: Vec<f64> = va.iter().zip(&vb).map(|(x, y)| sign * (y - x)).collect();
let better: Vec<f64> = worse.iter().map(|d| -d).collect();
Raw {
mean_a,
mean_b,
delta,
tolerance: metric.abs_tol.max(metric.rel_tol * mean_a.abs()),
shortfall: sign * delta,
p_worse: sign_flip_p(&worse),
p_better: sign_flip_p(&better),
}
})
.collect();
let judged: Vec<usize> = (0..METRICS.len()).filter(|&i| METRICS[i].direction != Direction::Info).collect();
let adj_worse = holm_adjust(&judged.iter().map(|&i| raws[i].p_worse).collect::<Vec<_>>());
let adj_better = holm_adjust(&judged.iter().map(|&i| raws[i].p_better).collect::<Vec<_>>());
let mut metrics = Vec::new();
for (i, metric) in METRICS.iter().enumerate() {
let raw = &raws[i];
let slot = judged.iter().position(|&j| j == i);
let (p_worse_adj, p_better_adj) = slot.map_or((raw.p_worse, raw.p_better), |k| (adj_worse[k], adj_better[k]));
let verdict = if pairs.is_empty() {
Verdict::None
} else if metric.direction == Direction::Info {
Verdict::Info
} else if raw.shortfall > raw.tolerance && p_worse_adj < alpha {
Verdict::Fail
} else if -raw.shortfall > raw.tolerance && p_better_adj < alpha {
Verdict::Better
} else {
Verdict::Pass
};
metrics.push(MetricVerdict {
metric: metric.name.to_owned(),
unit: metric.unit.to_owned(),
direction: metric.direction,
pairs: pairs.len(),
mean_a: raw.mean_a,
mean_b: raw.mean_b,
delta: raw.delta,
p_worse: raw.p_worse,
p_better: raw.p_better,
p_worse_adj,
p_better_adj,
tolerance: raw.tolerance,
verdict,
});
}
let trapped_checkpoints = trap_rule(a, b);
let mut failed: Vec<String> = metrics
.iter()
.filter(|m| m.verdict == Verdict::Fail)
.map(|m| m.metric.clone())
.collect();
failed.extend(trapped_checkpoints.iter().map(|t| format!("trap@{}", t.checkpoint)));
Comparison {
schema: "fly-scorecard-compare-v1".to_owned(),
a: a.label.clone(),
b: b.label.clone(),
alpha,
pairs: pairs.len(),
unpaired_a: runs_a.len() - pairs.len(),
unpaired_b: runs_b.len() - pairs.len(),
notes,
pass: failed.is_empty() && !pairs.is_empty(),
failed,
metrics,
trapped_checkpoints,
}
}
impl Comparison {
/// The comparison as a markdown table.
pub fn markdown(&self) -> String {
let mut out = String::new();
out.push_str(&format!(
"# Scorecard: {} vs {}: {}\n\n",
self.a,
self.b,
if self.pass { "PASS" } else { "FAIL" }
));
out.push_str(&format!(
"{} paired runs (alpha {} one-sided, sign-flip test, Holm over the judged metrics); {} only in {}, {} only in {}.\n\n",
self.pairs, self.alpha, self.unpaired_a, self.a, self.unpaired_b, self.b
));
for note in &self.notes {
out.push_str(&format!("- note: {note}\n"));
}
if !self.notes.is_empty() {
out.push('\n');
}
out.push_str(&format!(
"| metric | {} | {} | delta | tolerance | p worse (Holm) | p better (Holm) | verdict |\n",
self.a, self.b
));
out.push_str("| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- |\n");
for m in &self.metrics {
let arrow = match m.direction {
Direction::Up => "up",
Direction::Down => "down",
Direction::Info => "info",
};
out.push_str(&format!(
"| {} ({}, {}) | {:.2} | {:.2} | {:+.2} | {:.2} | {:.3} | {:.3} | {} |\n",
m.metric,
arrow,
m.unit,
m.mean_a,
m.mean_b,
m.delta,
m.tolerance,
m.p_worse_adj,
m.p_better_adj,
match m.verdict {
Verdict::Pass => "pass",
Verdict::Better => "better",
Verdict::Fail => "**FAIL**",
Verdict::Info => "info",
Verdict::None => "n/a",
}
));
}
if !self.trapped_checkpoints.is_empty() {
out.push_str("\n**Per-checkpoint trap rule: FAIL**\n\n");
for t in &self.trapped_checkpoints {
out.push_str(&format!(
"- `{}`: {} trapped / {} storm run(s) of {} in {}, against {} / {} of {} in {} ({})\n",
t.checkpoint,
t.trapped_b,
t.storms_b,
t.runs_b,
self.b,
t.trapped_a,
t.storms_a,
t.runs_a,
self.a,
t.detail.join("; ")
));
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::suite::{SuiteConfig, SuiteReport};
#[test]
fn the_exact_test_has_the_textbook_p() {
// Seven positive differences: only the all-positive assignment is as extreme.
assert!((sign_flip_p(&[1.0; 7]) - 1.0 / 128.0).abs() < 1e-12);
// All-negative: every assignment is at least as extreme as the observed.
assert!((sign_flip_p(&[-1.0; 7]) - 1.0).abs() < 1e-12);
// Nothing observed is no evidence.
assert_eq!(sign_flip_p(&[]), 1.0);
assert!((sign_flip_p(&[0.0; 5]) - 1.0).abs() < 1e-12);
// Mixed: three of four positive, the largest positive.
let p = sign_flip_p(&[3.0, 1.0, 1.0, -1.0]);
assert!(p > 0.0 && p < 0.5, "{p}");
}
#[test]
fn beyond_twenty_pairs_the_draws_are_fixed() {
let diffs: Vec<f64> = (0..30).map(|i| 1.0 + f64::from(i % 3)).collect();
let p = sign_flip_p(&diffs);
assert_eq!(p, sign_flip_p(&diffs));
assert!(p < 0.001, "{p}");
let noise: Vec<f64> = (0..30).map(|i| if i % 2 == 0 { 1.0 } else { -1.0 }).collect();
assert!(sign_flip_p(&noise) > 0.3);
}
fn run(checkpoint: &str, seed: u32, mutate: impl FnOnce(&mut RunReport)) -> RunReport {
let mut r = RunReport {
checkpoint: checkpoint.to_owned(),
seed,
runtime: "session".into(),
mode: "macros".into(),
minutes: 12.0,
..RunReport::default()
};
r.macros.done = 100;
mutate(&mut r);
r
}
fn suite(label: &str, runs: Vec<RunReport>) -> SuiteReport {
SuiteReport {
schema: crate::suite::SCHEMA.to_owned(),
label: label.to_owned(),
build: Default::default(),
runtime: "session".into(),
mode: "macros".into(),
config: SuiteConfig { minutes: 12.0, seeds: vec![1, 2, 3], ..SuiteConfig::default() },
runs,
failed_runs: Vec::new(),
}
}
fn many(label: &str, f: impl Fn(&str, u32, &mut RunReport)) -> SuiteReport {
let mut runs = Vec::new();
for c in ["r08", "r09", "r10", "r11", "r12", "r13"] {
for s in 1..=3 {
runs.push(run(c, s, |r| f(c, s, r)));
}
}
suite(label, runs)
}
#[test]
fn identical_suites_pass_with_nothing_better_or_worse() {
let a = many("a", |_, s, r| r.rungs.gained = s % 2);
let b = many("b", |_, s, r| r.rungs.gained = s % 2);
let c = compare(&a, &b, 0.05);
assert!(c.pass, "{:?}", c.failed);
assert!(c.metrics.iter().all(|m| matches!(m.verdict, Verdict::Pass | Verdict::Info)));
assert_eq!(c.pairs, 18);
}
#[test]
fn a_consistent_drop_in_rungs_fails_and_a_single_bad_run_does_not() {
let a = many("a", |_, _, r| r.rungs.gained = 1);
let b = many("b", |_, _, r| r.rungs.gained = 0);
let c = compare(&a, &b, 0.05);
assert!(!c.pass);
assert_eq!(c.failed, vec!["rungs_per_hour".to_owned()]);
assert!(c.markdown().contains("**FAIL**"));
// One run of eighteen collapses: not significant, not a regression.
let b = many("b", |ck, s, r| r.rungs.gained = if ck == "r10" && s == 2 { 0 } else { 1 });
assert!(compare(&a, &b, 0.05).pass);
}
#[test]
fn a_rise_in_traps_fails_and_a_drop_is_better() {
let calm = many("a", |_, _, _| {});
let trapped = many("b", |_, _, r| {
r.watchdog.ladder_events = 1;
r.watchdog.probes = 4;
r.watchdog.suspected = 3;
});
let up = compare(&calm, &trapped, 0.05);
assert!(up.failed.contains(&"ladder_events_per_hour".to_owned()), "{:?}", up.failed);
assert!(up.failed.contains(&"watchdog_suspected_pct".to_owned()));
let down = compare(&trapped, &calm, 0.05);
assert!(down.pass);
let better: Vec<&str> = down
.metrics
.iter()
.filter(|m| m.verdict == Verdict::Better)
.map(|m| m.metric.as_str())
.collect();
assert!(better.contains(&"ladder_events_per_hour"), "{better:?}");
}
#[test]
fn a_change_inside_the_tolerance_is_noise_however_consistent() {
// 0.25 pp more empty pad on every run: significant, but under the 1 pp floor.
let a = many("a", |_, _, r| r.pad.empty_fraction = 0.10);
let b = many("b", |_, _, r| r.pad.empty_fraction = 0.1025);
let c = compare(&a, &b, 0.05);
let pad = c.metrics.iter().find(|m| m.metric == "empty_pad_pct").unwrap();
assert_eq!(pad.verdict, Verdict::Pass, "{pad:?}");
}
#[test]
fn runs_pair_by_checkpoint_and_seed_and_unpaired_runs_are_reported() {
let a = many("a", |_, _, _| {});
let mut b = many("b", |_, _, _| {});
b.runs.retain(|r| r.checkpoint != "r13");
let c = compare(&a, &b, 0.05);
assert_eq!((c.pairs, c.unpaired_a, c.unpaired_b), (15, 3, 0));
let none = compare(&a, &suite("empty", Vec::new()), 0.05);
assert!(!none.pass);
assert!(none.metrics.iter().all(|m| m.verdict == Verdict::None));
}
fn row71(r: &mut RunReport) {
// The v0.7.3 row-71 bag bug: THROW BALL started and blocked 131 times, suspected on every probe.
let c = r.macros.by_macro.entry("THROW BALL".into()).or_default();
c.start = 132;
c.blocked = 131;
r.macros.blocked = 131;
r.watchdog.probes = 4;
r.watchdog.suspected = 4;
r.watchdog.ladder_events = 1;
}
#[test]
fn a_trap_on_one_checkpoint_fails_though_the_pooled_test_cannot_see_it() {
let a = many("a", |_, _, _| {});
let b = many("b", |ck, _, r| {
if ck == "r10" {
row71(r)
}
});
let c = compare(&a, &b, 0.05);
assert!(!c.pass);
assert!(c.failed.contains(&"trap@r10".to_owned()), "{:?}", c.failed);
assert_eq!(c.trapped_checkpoints.len(), 1);
assert_eq!(c.trapped_checkpoints[0].trapped_b, 3);
assert!(c.markdown().contains("`r10`"));
// ... while the same suite against itself passes.
assert!(compare(&b, &b, 0.05).pass);
assert!(compare(&a, &a, 0.05).pass);
}
#[test]
fn the_trap_rule_wants_two_seeds_or_a_storm_and_a_clean_a() {
let a = many("a", |_, _, _| {});
// One trapped seed with no storm: not enough.
let one = many("b", |ck, s, r| {
if ck == "r10" && s == 1 {
r.watchdog.probes = 4;
r.watchdog.suspected = 3;
r.watchdog.ladder_events = 1;
}
});
assert!(trap_rule(&a, &one).is_empty());
// Two trapped seeds fail it.
let two = many("b", |ck, s, r| {
if ck == "r10" && s <= 2 {
r.watchdog.probes = 4;
r.watchdog.suspected = 3;
r.watchdog.ladder_events = 1;
}
});
assert_eq!(trap_rule(&a, &two)[0].checkpoint, "r10");
// One seed with a storm fails it.
let storm_one = many("b", |ck, s, r| {
if ck == "r11" && s == 3 {
r.macros.by_macro.entry("GO OUT".into()).or_default().blocked = 50;
}
});
assert_eq!(trap_rule(&a, &storm_one)[0].checkpoint, "r11");
// The same storm in A as well is not new.
assert!(trap_rule(&storm_one, &storm_one).is_empty());
// A was trapped on two seeds already: B trapped on the same two is not a new trap.
assert!(trap_rule(&two, &two).is_empty());
}
#[test]
fn a_blocked_throw_is_not_a_throw() {
let r = run("x", 1, |r| {
r.funnel.throw_ball_start = 132;
r.funnel.throw_ball_done = 1;
row71(r);
});
let get = |name: &str| (METRICS.iter().find(|m| m.name == name).unwrap().read)(&r);
assert!((get("throws_per_hour") - 5.0).abs() < 1e-9);
assert!((get("throw_ball_blocked_per_hour") - 131.0 * 5.0).abs() < 1e-9);
}
#[test]
fn holm_adjusts_step_down_and_never_below_the_raw_p() {
let adj = holm_adjust(&[0.01, 0.04, 0.03, 0.20]);
let want = [0.04, 0.09, 0.09, 0.20];
for (x, y) in adj.iter().zip(want) {
assert!((x - y).abs() < 1e-12, "{adj:?}");
}
assert!(holm_adjust(&[]).is_empty());
assert_eq!(holm_adjust(&[0.6, 0.9]), vec![1.0, 1.0]);
}
/// The false-fail rate of the whole compare under "nothing changed but the trajectory":
/// resample each checkpoint's seeds with replacement (A is the committed v0.7.5 card, B a
/// bootstrap of it) and count failing compares. Slow; run with `--ignored --nocapture`.
#[test]
#[ignore = "a simulation: about a minute in release"]
fn null_false_fail_rate() {
let text = include_str!("../../../../../tools/scorecard/baseline-v0.7.5.json");
let a: SuiteReport = serde_json::from_str(text).expect("baseline");
let mut ids: Vec<String> = a.runs.iter().map(|r| r.checkpoint.clone()).collect();
ids.dedup();
let mut state = 0x9e37_79b9_7f4a_7c15u64;
let mut next = move |n: usize| {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
(state % n as u64) as usize
};
let (reps, mut fails, mut metric_fails, mut trap_fails) = (200, 0, 0, 0);
let mut by_checkpoint = BTreeMap::new();
for _ in 0..reps {
let mut b = a.clone();
b.label = "boot".into();
b.runs.clear();
for id in &ids {
let pool: Vec<&RunReport> = a.runs.iter().filter(|r| &r.checkpoint == id).collect();
for (seed, _) in pool.iter().enumerate() {
let mut r = pool[next(pool.len())].clone();
r.seed = pool[seed].seed;
b.runs.push(r);
}
}
let c = compare(&a, &b, 0.05);
if !c.pass {
fails += 1;
}
metric_fails += usize::from(c.failed.iter().any(|f| !f.starts_with("trap@")));
trap_fails += usize::from(!c.trapped_checkpoints.is_empty());
for t in &c.trapped_checkpoints {
*by_checkpoint.entry(t.checkpoint.clone()).or_insert(0usize) += 1;
}
}
println!("null compares: {fails}/{reps} fail ({metric_fails} by a metric, {trap_fails} by the trap rule)");
println!("trap rule by checkpoint: {by_checkpoint:?}");
}
#[test]
fn rates_are_per_brain_hour() {
let r = run("x", 1, |r| {
r.rungs.gained = 1;
r.whiteouts = 2;
});
let get = |name: &str| (METRICS.iter().find(|m| m.name == name).unwrap().read)(&r);
assert!((get("rungs_per_hour") - 5.0).abs() < 1e-9);
assert!((get("whiteouts_per_hour") - 10.0).abs() < 1e-9);
let empty = RunReport::default();
assert_eq!((METRICS[0].read)(&empty), 0.0);
}
}

View file

@ -0,0 +1,16 @@
//! The behavioural scorecard (B2): a repeatable multi-seed regression harness for good play.
//!
//! A fixed set of checkpoints, K seeds each, T brain minutes each, on the real connectome with the
//! macro layer, on the session runtime (default) or the legacy loop. Every run reduces to one
//! [`tally::RunReport`]; a suite is the set of runs ([`suite::SuiteReport`]); two suites compare
//! with a verdict per metric ([`compare::compare`]), by a test over the paired runs rather than
//! by one run.
//!
//! The harness measures and presses nothing. See `docs/scorecard.md`.
pub mod compare;
pub mod obs;
pub mod runner;
pub mod suite;
pub mod tally;
pub mod watchdog;

View file

@ -0,0 +1,403 @@
//! `fly-scorecard`: run the behavioural scorecard, compare two releases, summarise a run.
//!
//! ```sh
//! export FLY_ROM=... # the cartridge, never copied anywhere
//! fly-scorecard list # the set, resolved, with each rung
//! fly-scorecard suite --label v0.7.5 --out card.json # the set x seeds x minutes
//! fly-scorecard compare old.json new.json # exit 1 when a metric regressed
//! fly-scorecard summary card.json # a one-screen markdown
//! fly-scorecard run-one --checkpoint X --seed 1 # one run, JSON on stdout
//! ```
//!
//! The checkpoint set is `tools/scorecard/checkpoints.json`: each entry names the environment
//! variable that holds the checkpoint's path (the ROM tests' own, `rom-env.sh`).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, anyhow, bail};
use clap::{Parser, Subcommand};
use flysim::snapshot::MacroMode;
use fly_scorecard::compare::compare;
use fly_scorecard::runner::{Runtime, RunSpec, build_info, run_legacy, run_session};
use fly_scorecard::tally::RunReport;
use fly_scorecard::suite::{
CheckpointSet, ChildArgs, Job, SCHEMA, SuiteConfig, SuiteReport, note, run_jobs,
};
#[derive(Debug, Parser)]
#[command(name = "fly-scorecard", about = "The behavioural scorecard: multi-seed good-play regression.")]
struct Args {
#[command(subcommand)]
command: Cmd,
}
#[derive(Debug, Subcommand)]
enum Cmd {
/// Resolve the checkpoint set and print each checkpoint's rung.
List {
#[arg(long, default_value = "tools/scorecard/checkpoints.json")]
set: PathBuf,
/// Extra checkpoints, `id=path`.
#[arg(long = "extra", value_name = "ID=PATH")]
extra: Vec<String>,
},
/// One run: a checkpoint, a seed. Prints the run's JSON on stdout.
RunOne {
#[arg(long)]
id: Option<String>,
#[arg(long)]
checkpoint: PathBuf,
#[arg(long, default_value_t = 1)]
seed: u32,
#[arg(long, default_value_t = 10.0)]
minutes: f64,
#[arg(long, default_value = "session")]
runtime: String,
#[arg(long, default_value = "macros")]
mode: String,
#[arg(long, default_value_t = 1)]
threads: usize,
#[arg(long, default_value_t = 120.0)]
probe_s: f64,
#[arg(long, default_value_t = 600.0)]
window_s: f64,
#[arg(long)]
dataset: Option<PathBuf>,
/// Write the JSON here instead of stdout (the emulator library prints on stdout).
#[arg(long)]
out: Option<PathBuf>,
},
/// The set times the seeds, `--jobs` at a time, as one JSON.
Suite {
#[arg(long, default_value = "tools/scorecard/checkpoints.json")]
set: PathBuf,
#[arg(long = "extra", value_name = "ID=PATH")]
extra: Vec<String>,
/// Only these checkpoint ids (comma separated).
#[arg(long, value_delimiter = ',')]
only: Vec<String>,
/// Seeds 1..=K.
#[arg(long, default_value_t = 3)]
seeds: u32,
#[arg(long, default_value_t = 10.0)]
minutes: f64,
#[arg(long, default_value = "session")]
runtime: String,
#[arg(long, default_value = "macros")]
mode: String,
/// Sweep threads per run. One: a run's pool spins at its barriers, so on a box shared with
/// other jobs one-thread runs lose far less than four-thread ones, and the result does
/// not depend on the count.
#[arg(long, default_value_t = 1)]
threads: usize,
/// Runs at a time.
#[arg(long, default_value_t = 8)]
jobs: usize,
#[arg(long, default_value_t = 120.0)]
probe_s: f64,
#[arg(long, default_value_t = 600.0)]
window_s: f64,
/// Names the release or commit under test.
#[arg(long)]
label: String,
#[arg(long)]
out: PathBuf,
/// Also write the one-screen summary here.
#[arg(long)]
md: Option<PathBuf>,
#[arg(long)]
dataset: Option<PathBuf>,
/// Fail instead of running a smaller set when a checkpoint of the set is missing.
#[arg(long)]
strict: bool,
/// Keep the runs an earlier invocation finished (`<out>.runs.jsonl`) and run the rest.
#[arg(long)]
resume: bool,
},
/// Release A against release B. Exit 1 when a metric regressed.
Compare {
a: PathBuf,
b: PathBuf,
#[arg(long, default_value_t = 0.05)]
alpha: f64,
#[arg(long)]
json: Option<PathBuf>,
#[arg(long)]
md: Option<PathBuf>,
},
/// A one-screen markdown of one suite.
Summary {
file: PathBuf,
#[arg(long, default_value = "tools/scorecard/checkpoints.json")]
set: PathBuf,
},
}
fn env_dataset(given: Option<PathBuf>) -> PathBuf {
given
.or_else(|| std::env::var_os("FLY_MACRO_BRAIN").map(PathBuf::from))
.or_else(|| std::env::var_os("FLY_DATASET").map(PathBuf::from))
.unwrap_or_else(|| PathBuf::from("data/fafb-v783"))
}
fn rom() -> Result<PathBuf> {
std::env::var_os("FLY_ROM").map(PathBuf::from).ok_or_else(|| anyhow!("FLY_ROM is not set"))
}
fn mode_of(text: &str) -> Result<MacroMode> {
match text {
"raw" => Ok(MacroMode::Raw),
"macros" => Ok(MacroMode::Macros),
other => bail!("mode {other:?} is not raw or macros"),
}
}
fn parse_extra(extra: &[String]) -> Result<Vec<(String, PathBuf)>> {
extra
.iter()
.map(|item| {
let (id, path) = item.split_once('=').ok_or_else(|| anyhow!("--extra wants ID=PATH, got {item:?}"))?;
Ok((id.to_owned(), PathBuf::from(path)))
})
.collect()
}
/// The rung a checkpoint stands on, from its reward ledger.
fn rung_of(path: &Path) -> Result<(u32, &'static str, usize)> {
use flybrain_gb::adapter::GameAdapter;
let checkpoint = flysim::store::load(path)?;
let mut adapter = flybrain_gb::pokemon_red::PokemonRedReward::new();
adapter.import_state(&checkpoint.runtime.reward).map_err(|e| anyhow!("{e}"))?;
let progress = adapter.progress();
Ok((progress.rank, progress.rank_label, progress.unique_locations))
}
struct Resolved {
id: String,
path: PathBuf,
rung: Option<u32>,
}
fn resolve(set_path: &Path, extra: &[String], only: &[String], strict: bool) -> Result<Vec<Resolved>> {
let set = CheckpointSet::load(set_path)?;
let (found, missing) = set.resolve(&|name| std::env::var(name).ok());
if !missing.is_empty() {
eprintln!("scorecard: {} checkpoints of the set are missing: {}", missing.len(), missing.join(", "));
if strict {
bail!("--strict: the set is not complete");
}
}
let mut out: Vec<Resolved> = found
.into_iter()
.map(|(entry, path)| Resolved { id: entry.id, path, rung: Some(entry.rung) })
.collect();
for (id, path) in parse_extra(extra)? {
if !path.is_file() {
bail!("--extra {id}: {} is not a file", path.display());
}
out.push(Resolved { id, path, rung: None });
}
if !only.is_empty() {
out.retain(|r| only.contains(&r.id));
}
if out.is_empty() {
bail!("no checkpoint to run");
}
Ok(out)
}
fn main() {
if let Err(error) = real_main() {
eprintln!("fly-scorecard: {error:#}");
std::process::exit(2);
}
}
fn real_main() -> Result<()> {
let args = Args::parse();
match args.command {
Cmd::List { set, extra } => {
for r in resolve(&set, &extra, &[], false)? {
match rung_of(&r.path) {
Ok((rank, label, places)) => println!(
"{:<28} set rung {:>2} checkpoint rung {rank:>2} {label} ({places} places)",
r.id,
r.rung.map_or("-".to_owned(), |n| n.to_string())
),
Err(error) => println!("{:<28} unreadable: {error:#}", r.id),
}
}
Ok(())
}
Cmd::RunOne { id, checkpoint, seed, minutes, runtime, mode, threads, probe_s, window_s, dataset, out } => {
let runtime = Runtime::parse(&runtime)?;
let id = id.unwrap_or_else(|| {
checkpoint.file_stem().map_or_else(|| "checkpoint".to_owned(), |s| s.to_string_lossy().into_owned())
});
let spec = RunSpec {
id,
checkpoint,
rom: rom()?,
dataset: env_dataset(dataset),
seed,
minutes,
threads,
mode: mode_of(&mode)?,
tally: RunSpec::tally_config(probe_s, window_s),
};
let report = match runtime {
Runtime::Legacy => run_legacy(&spec)?,
Runtime::Session => tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.enable_all()
.build()?
.block_on(run_session(&spec))?,
};
let text = serde_json::to_string(&report)? + "\n";
match out {
Some(path) => std::fs::write(&path, text).with_context(|| format!("writing {}", path.display()))?,
None => print!("{text}"),
}
Ok(())
}
Cmd::Suite {
set, extra, only, seeds, minutes, runtime, mode, threads, jobs, probe_s, window_s, label, out, md,
dataset, strict, resume,
} => {
Runtime::parse(&runtime)?;
mode_of(&mode)?;
rom()?;
let resolved = resolve(&set, &extra, &only, strict)?;
let exe = std::env::current_exe().context("finding this executable")?;
let seed_list: Vec<u32> = (1..=seeds).collect();
// Every finished run is appended to `<out>.runs.jsonl` at once, so a suite that dies
// (a box that reboots, a job that is killed) keeps what it finished.
let runs_log = out.with_extension("runs.jsonl");
let mut prior: Vec<RunReport> = Vec::new();
if resume {
if let Ok(text) = std::fs::read_to_string(&runs_log) {
prior = text
.lines()
.filter_map(|line| serde_json::from_str::<RunReport>(line).ok())
.filter(|run| run.runtime == runtime && run.mode == mode && run.minutes >= minutes - 0.01)
.collect();
}
} else {
let _ = std::fs::remove_file(&runs_log);
}
let mut queue = Vec::new();
for r in &resolved {
for seed in &seed_list {
if prior.iter().any(|run| run.checkpoint == r.id && run.seed == *seed) {
continue;
}
queue.push(Job { id: r.id.clone(), path: r.path.clone(), seed: *seed });
}
}
if !prior.is_empty() {
eprintln!("scorecard: resuming with {} finished runs, {} to go", prior.len(), queue.len());
}
let child = ChildArgs {
runtime: runtime.clone(),
mode: mode.clone(),
minutes,
threads,
probe_s,
window_s,
dataset: dataset.clone().or_else(|| Some(env_dataset(None))),
};
let progress = out.with_extension("progress.log");
let _ = std::fs::remove_file(&progress);
eprintln!(
"scorecard {label}: {} runs ({} checkpoints x {} seeds) of {minutes} brain min, {jobs} at a time, {threads} threads each",
queue.len(),
resolved.len(),
seed_list.len()
);
let began = std::time::Instant::now();
let outcomes = run_jobs(&exe, queue, &child, jobs, &|outcome| {
let line = match outcome {
Ok(run) => format!(
"{:>6.0}s done {} seed {}: rung {}->{} in {:.1} min, {:.0}s wall",
began.elapsed().as_secs_f64(), run.checkpoint, run.seed, run.rungs.start, run.rungs.end,
run.minutes, run.wall_seconds
),
Err(failed) => format!(
"{:>6.0}s FAILED {} seed {}: {}",
began.elapsed().as_secs_f64(), failed.checkpoint, failed.seed, failed.error
),
};
eprintln!("{line}");
note(&progress, &line);
if let Ok(run) = outcome
&& let Ok(text) = serde_json::to_string(run)
{
note(&runs_log, &text);
}
});
let mut runs = prior;
let mut failed_runs = Vec::new();
for outcome in outcomes {
match outcome {
Ok(run) => runs.push(run),
Err(failed) => failed_runs.push(failed),
}
}
let order: BTreeMap<&str, usize> =
resolved.iter().enumerate().map(|(i, r)| (r.id.as_str(), i)).collect();
runs.sort_by_key(|run| (order.get(run.checkpoint.as_str()).copied().unwrap_or(usize::MAX), run.seed));
let suite = SuiteReport {
schema: SCHEMA.to_owned(),
label,
build: build_info(""),
runtime,
mode,
config: SuiteConfig { minutes, seeds: seed_list, threads, jobs, probe_s, window_s },
runs,
failed_runs,
};
let mut suite = suite;
suite.build.release = suite.label.clone();
std::fs::write(&out, serde_json::to_string_pretty(&suite)? + "\n")
.with_context(|| format!("writing {}", out.display()))?;
let rungs: BTreeMap<String, u32> =
resolved.iter().filter_map(|r| r.rung.map(|n| (r.id.clone(), n))).collect();
let markdown = suite.markdown(&rungs);
if let Some(md) = md {
std::fs::write(&md, &markdown).with_context(|| format!("writing {}", md.display()))?;
}
println!("{markdown}");
eprintln!("scorecard: {:.0} s wall", began.elapsed().as_secs_f64());
if suite.runs.is_empty() {
bail!("every run failed");
}
Ok(())
}
Cmd::Compare { a, b, alpha, json, md } => {
let (sa, sb) = (SuiteReport::load(&a)?, SuiteReport::load(&b)?);
let comparison = compare(&sa, &sb, alpha);
let markdown = comparison.markdown();
if let Some(json) = json {
std::fs::write(&json, serde_json::to_string_pretty(&comparison)? + "\n")?;
}
if let Some(md) = md {
std::fs::write(&md, &markdown)?;
}
println!("{markdown}");
if !comparison.pass {
std::process::exit(1);
}
Ok(())
}
Cmd::Summary { file, set } => {
let suite = SuiteReport::load(&file)?;
let rungs: BTreeMap<String, u32> = CheckpointSet::load(&set)
.map(|s| s.checkpoints.into_iter().map(|e| (e.id, e.rung)).collect())
.unwrap_or_default();
println!("{}", suite.markdown(&rungs));
Ok(())
}
}
}

View file

@ -0,0 +1,146 @@
//! What the scorecard sees of one frame, whichever runtime ran it.
//!
//! The legacy loop hands a harness a live emulator and the frame's events; the session runtime
//! hands it a task object holding the boundary's memory image. Both are reduced to the same
//! [`Frame`] here, so every metric is computed once ([`crate::tally`]) and a comparison between
//! the two runtimes cannot differ in what was measured.
use flybrain_gb::MemoryReader;
use flybrain_gb::pokemon_red::state;
use flybrain_gb::pokemon_red::symbols::ram;
/// One macro event: a start (`outcome` is `None`) or a finish.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MacroEv {
pub name: &'static str,
pub outcome: Option<&'static str>,
}
/// A rollback the ratchet ran at this boundary.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Rolled {
/// The trigger was a game over, else a stall.
pub game_over: bool,
}
/// Facts read off game memory on one frame.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Facts {
/// `wIsInBattle`: 0 none, 1 wild, 2 trainer, `$ff` the frame a battle is lost.
pub battle: u8,
/// Party members with a species (a half-written slot is not counted).
pub party: u8,
/// Of them, those with HP left.
pub alive: u8,
/// Poke Balls of every kind in the bag.
pub balls: u32,
pub money: u32,
/// Species owned (Pokedex bits).
pub owned: u32,
/// The map the player stands on, `0xff` when the adapter cannot place the player.
pub map: u32,
}
impl Facts {
/// Every member of a non-empty party has fainted: the state a whiteout starts from.
pub fn all_fainted(&self) -> bool {
self.party > 0 && self.alive == 0
}
pub fn in_battle(&self) -> bool {
self.battle != 0
}
}
/// Reads [`Facts`] from any memory (a live emulator or a boundary image).
pub fn facts_of(memory: &mut dyn MemoryReader) -> Facts {
let battle = memory.read8(ram::wIsInBattle);
let party = state::party(memory);
let real: Vec<_> = party.mons.iter().filter(|mon| mon.species != 0).collect();
let alive = real.iter().filter(|mon| mon.hp > 0).count();
let balls: u32 = state::bag(memory)
.iter()
.filter(|item| (0x01..=0x04).contains(&item.id))
.map(|item| u32::from(item.count))
.sum();
let money = state::money(memory);
let owned: u32 = (0..19u16).map(|i| memory.read8(ram::wPokedexOwned + i).count_ones()).sum();
let map = state::player(memory).map_or(0xff, |player| u32::from(player.map));
Facts {
battle,
party: real.len() as u8,
alive: alive as u8,
balls,
money,
owned,
map,
}
}
/// One frame, as the scorecard takes it.
#[derive(Clone, Debug)]
pub struct Frame {
/// The brain clock of the frame, ms.
pub ms: f64,
/// The macro layer's events this frame: executed, abandoned and a rollback's, in order.
pub events: Vec<MacroEv>,
/// Rewards paid this frame: the adapter's kind and value.
pub rewards: Vec<(&'static str, f64)>,
pub rank: u32,
/// Distinct places the adapter has observed (the exploration count).
pub places: u32,
/// `(map, x, y)` the adapter placed the player on, when it could.
pub location: Option<(u32, u32, u32)>,
/// The macro layer is on (macros mode).
pub macros_on: bool,
/// No macro runs and the scene dealt no button.
pub pad_empty: bool,
pub scene: &'static str,
pub rollback: Option<Rolled>,
pub facts: Facts,
}
/// The idle frames a seed starts with.
///
/// A checkpoint restores a deterministic brain, so two runs from it with different "seeds" would
/// be the same run. A seed therefore chooses how many frames the readout is ignored before the
/// measurement starts: the brain still ticks, the noise generator still advances, the game sees
/// no button, and from the first measured frame the brain is on a different point of its own
/// trajectory. Seed 0 is no idle at all (the run the trap hunt does from the same checkpoint).
/// Nothing presses for the fly and nothing changes what it chooses once the measurement starts.
pub fn idle_frames(seed: u32) -> u32 {
if seed == 0 {
return 0;
}
// splitmix64 of the seed, so consecutive seeds are unrelated; 1 to 30 seconds of idle.
let mut z = u64::from(seed).wrapping_add(0x9e37_79b9_7f4a_7c15);
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^= z >> 31;
60 + (z % 1741) as u32
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn seed_zero_is_no_idle_and_seeds_differ() {
assert_eq!(idle_frames(0), 0);
let idles: Vec<u32> = (1..=8).map(idle_frames).collect();
assert!(idles.iter().all(|n| (60..=1800).contains(n)));
let mut sorted = idles.clone();
sorted.sort_unstable();
sorted.dedup();
assert_eq!(sorted.len(), idles.len(), "{idles:?}");
assert_eq!(idle_frames(3), idle_frames(3));
}
#[test]
fn a_party_that_has_all_fainted() {
let down = Facts { party: 2, alive: 0, ..Facts::default() };
assert!(down.all_fainted());
assert!(!Facts { party: 2, alive: 1, ..Facts::default() }.all_fainted());
assert!(!Facts::default().all_fainted(), "no party is not a whiteout");
}
}

View file

@ -0,0 +1,397 @@
//! One run on a real brain: a checkpoint restored, the seed's idle frames, then the measured
//! brain minutes, on either runtime.
//!
//! Both runtimes drive the unchanged engine. The legacy runner is the stream's own frame
//! (`flysim::frame::LegacyFrame`, as the trap hunt runs it); the session runner is the session
//! composition the release cut over to (`fly_legacy_session::composition::LegacySession`, the
//! agent, the world and the task under one coordinator, in-process, unpaced). Each hands the same
//! [`Frame`] to the same [`Tally`].
//!
//! Neither runner presses anything or changes what the brain chooses. The seed's idle frames
//! ignore the brain's readout for a while before the measurement starts ([`idle_frames`]); from
//! the first measured frame the readout is the brain's own.
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;
use anyhow::{Context, Result, anyhow};
use flybrain_core::agent::{AgentConfig, NeuralAgent};
use flybrain_core::dataset::{BrainDataset, load_brain_dataset_from_dir};
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
use flybrain_core::lif::SweepPlan;
use flybrain_gb::adapter::GameAdapter;
use flybrain_gb::pokemon_red::PokemonRedReward;
use flybrain_gb::ratchet::Ratchet;
use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator};
use flysim::config::Config;
use flysim::frame::{FrameObserver, LegacyFrame, Parts, RollbackTrigger};
use flysim::macros::{MacroEvent, MacroLayer, macro_layer};
use flysim::snapshot::MacroMode;
use crate::obs::{Frame, MacroEv, Rolled, facts_of, idle_frames};
use crate::tally::{RunReport, Tally, TallyConfig};
use crate::watchdog::Rules;
/// Which runtime ran it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Runtime {
Session,
Legacy,
}
impl Runtime {
pub fn parse(text: &str) -> Result<Self> {
match text {
"session" => Ok(Self::Session),
"legacy" => Ok(Self::Legacy),
other => Err(anyhow!("runtime {other:?} is not session or legacy")),
}
}
pub fn as_str(self) -> &'static str {
match self {
Self::Session => "session",
Self::Legacy => "legacy",
}
}
}
/// Everything one run needs.
#[derive(Clone, Debug)]
pub struct RunSpec {
pub id: String,
pub checkpoint: PathBuf,
pub rom: PathBuf,
pub dataset: PathBuf,
pub seed: u32,
pub minutes: f64,
pub threads: usize,
pub mode: MacroMode,
pub tally: TallyConfig,
}
impl RunSpec {
/// A tally configuration with the probe cadence and window the caller chose.
pub fn tally_config(probe_s: f64, window_s: f64) -> TallyConfig {
TallyConfig {
rules: Rules { window_ms: window_s * 1000.0, ..Rules::default() },
probe_s,
..TallyConfig::default()
}
}
fn identity(&self, runtime: Runtime, idle: u32, wall: f64) -> RunReport {
RunReport {
checkpoint: self.id.clone(),
seed: self.seed,
runtime: runtime.as_str().to_owned(),
mode: self.mode.as_str().to_owned(),
idle_frames: idle,
wall_seconds: wall,
..RunReport::default()
}
}
}
fn conv(event: &MacroEvent) -> MacroEv {
MacroEv { name: event.name, outcome: event.outcome.map(|outcome| outcome.as_str()) }
}
/// The measurement's start: it begins on the first frame after the idle frames, with the rung and
/// the exploration count the run stood on just before it.
struct Measure {
spec: RunSpec,
idle_left: u32,
prev: (u32, u32),
tally: Option<Tally>,
}
impl Measure {
fn new(spec: &RunSpec, rank: u32, places: u32) -> Self {
Self { spec: spec.clone(), idle_left: idle_frames(spec.seed), prev: (rank, places), tally: None }
}
/// Takes one frame; true when the measured minutes are up.
fn take(&mut self, frame: Frame) -> bool {
let (rank, places) = (frame.rank, frame.places);
if self.idle_left > 0 {
self.idle_left -= 1;
self.prev = (rank, places);
return false;
}
let tally = self.tally.get_or_insert_with(|| {
Tally::new(self.spec.tally.clone(), frame.ms, self.prev.0, self.prev.1)
});
tally.push(&frame);
tally.minutes() >= self.spec.minutes
}
fn finish(self, runtime: Runtime, wall: f64) -> Result<RunReport> {
let idle = idle_frames(self.spec.seed);
let tally = self.tally.ok_or_else(|| anyhow!("no frame was measured"))?;
Ok(tally.finish(self.spec.identity(runtime, idle, wall)))
}
}
// -- the legacy runtime -----------------------------------------------------------------------
/// The seed's idle frames, and the pad's state read just before the executor decides.
struct Idle {
left: u32,
pad_empty: bool,
}
impl FrameObserver for Idle {
fn readout(&mut self, _ms: f64, _bound: Option<&[String]>, active: &mut Vec<String>) {
if self.left > 0 {
self.left -= 1;
active.clear();
}
}
fn before_execute(&mut self, _frame: &LegacyFrame, parts: &mut Parts<'_>, _active: &[String]) {
self.pad_empty = parts
.macros
.as_deref()
.is_some_and(|layer| layer.running().is_none() && layer.feed_palette().is_empty());
}
}
fn load_dataset(spec: &RunSpec) -> Result<Arc<BrainDataset>> {
let data = load_brain_dataset_from_dir(&spec.dataset)
.map_err(|e| anyhow!("loading the connectome at {}: {e}", spec.dataset.display()))?;
Ok(Arc::new(data))
}
/// The stream's own frame, restored from the checkpoint as the stream restores it.
pub fn run_legacy(spec: &RunSpec) -> Result<RunReport> {
let began_wall = Instant::now();
let rom = std::fs::read(&spec.rom).with_context(|| format!("reading {}", spec.rom.display()))?;
let checkpoint = flysim::store::load(&spec.checkpoint)
.with_context(|| format!("the checkpoint {}", spec.checkpoint.display()))?;
let data = load_dataset(spec)?;
let mut emulator = Emulator::new(&rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES)
.map_err(|e| anyhow!("the cartridge: {e}"))?;
let mut adapter = PokemonRedReward::new();
let channels =
if spec.mode.dealt() { flybrain_gb::macro_channels("pokemon-red") } else { Vec::new() };
let preset = gameboy_decoder_config_with_macros(&channels);
let hold_ms = preset
.macros
.as_ref()
.or(preset.exclusive.as_ref())
.map(|group| group.hold_ms)
.ok_or_else(|| anyhow!("the preset has no group"))?;
let mut ratchet = Ratchet::with_policy(adapter.recovery_policy());
let mut agent = NeuralAgent::new(Arc::clone(&data), AgentConfig::with_decoder(preset))
.map_err(|e| anyhow!("{e}"))?;
if spec.threads > 1 {
agent.set_sweep_plan(SweepPlan::with_threads(spec.threads).map_err(|e| anyhow!("{e}"))?);
}
let mut frame = LegacyFrame::new();
frame
.restore(
&mut Parts {
agent: &mut agent,
emulator: &mut emulator,
adapter: &mut adapter,
ratchet: &mut ratchet,
macros: None,
},
&checkpoint,
)
.context("the checkpoint should restore")?;
let mut config = Config::default();
config.loop_.game = "pokemon-red".to_string();
config.macros.mode = spec.mode;
// As the service seeds it after a restore: the restored brain's own generator.
let mut macros: Option<MacroLayer> =
macro_layer(&config, hold_ms, agent.network.rng_state() as u32);
if let Some(layer) = macros.as_mut() {
let ledger = AdapterLedger(&adapter);
let _ = layer.observe(&mut emulator, &ledger, agent.network.ms);
}
let start = adapter.progress();
let mut measure = Measure::new(spec, start.rank, start.unique_locations as u32);
let mut observer = Idle { left: measure.idle_left, pad_empty: false };
loop {
let mut parts = Parts {
agent: &mut agent,
emulator: &mut emulator,
adapter: &mut adapter,
ratchet: &mut ratchet,
macros: macros.as_mut(),
};
let transition = frame.transition(&mut parts, &mut observer).context("a frame")?;
let boundary = frame
.boundary(&mut parts, &transition.evaluated.progress, transition.ms)
.context("the boundary")?;
let mut events: Vec<MacroEv> = transition.executed.events.iter().map(conv).collect();
events.extend(transition.evaluated.abandoned.iter().map(conv));
let rolled = boundary.rollback.as_ref().map(|rollback| {
events.extend(rollback.events.iter().map(conv));
Rolled { game_over: rollback.trigger == RollbackTrigger::GameOver }
});
let progress = &transition.evaluated.progress;
let obs = Frame {
ms: transition.ms,
events,
rewards: transition.evaluated.rewards.iter().map(|r| (r.kind, r.value)).collect(),
rank: progress.rank,
places: progress.unique_locations as u32,
location: parts.adapter.location(),
macros_on: parts.macros.is_some(),
pad_empty: observer.pad_empty,
scene: parts.macros.as_deref().map_or("raw", MacroLayer::scene_name),
rollback: rolled,
facts: facts_of(parts.emulator),
};
if measure.take(obs) {
break;
}
}
measure.finish(Runtime::Legacy, began_wall.elapsed().as_secs_f64())
}
// -- the session runtime ----------------------------------------------------------------------
/// The seed's idle frames on the session's executor: the same readout replacement the legacy
/// frame's observer makes.
struct IdleDriver {
left: u32,
}
impl fly_legacy_session::driver::DecisionDriver for IdleDriver {
fn readout(&mut self, _ms: f64, _bound: &[String], active: &mut Vec<String>) {
if self.left > 0 {
self.left -= 1;
active.clear();
}
}
}
/// The session composition the release runs, in-process and unpaced, from the checkpoint.
pub async fn run_session(spec: &RunSpec) -> Result<RunReport> {
use fly_legacy_session::composition::Transport; // overlay:bus01
use fly_legacy_session::composition::{LegacyConfig, LegacySession};
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::types::id;
let began_wall = Instant::now();
let checkpoint = flysim::store::load(&spec.checkpoint)
.with_context(|| format!("the checkpoint {}", spec.checkpoint.display()))?;
let root = tempfile::tempdir().context("a scratch directory")?;
let mut session = LegacySession::start(
root.path(),
LegacyConfig {
mode: ExecutionMode::InProcess,
transport: Transport::default(), // overlay:bus01
placements: Default::default(), // overlay:bus01
rom_path: spec.rom.clone(),
dataset_dir: spec.dataset.clone(),
profile: LegacyProfileKind::Production,
macro_mode: spec.mode,
agent_id: id("fly"),
agent_threads: spec.threads.max(1),
record: false,
},
)
.await
.map_err(|e| anyhow!("{e}"))?;
session.bootstrap().await.map_err(|e| anyhow!("{e}"))?;
session
.import_checkpoint(&checkpoint, &id("e2"))
.await
.map_err(|e| anyhow!("importing the checkpoint: {e}"))?;
// A measurement runs as fast as the brain allows.
session.coordinator.disable_pacing();
let task = session.task.clone();
let (rank, places) = task.inspect(|adapter, _, _| {
let progress = adapter.progress();
(progress.rank, progress.unique_locations as u32)
});
let mut measure = Measure::new(spec, rank, places);
task.set_driver(Box::new(IdleDriver { left: measure.idle_left }));
let outcome = async {
loop {
session.step().await.map_err(|e| anyhow!("{e}"))?;
let feed = task.take_feed();
let ms = task.brain_ms();
let mut events: Vec<MacroEv> = feed.executed.iter().map(conv).collect();
events.extend(feed.abandoned.iter().map(conv));
let rolled = feed.rollback.as_ref().map(|(game_over, rollback_events)| {
events.extend(rollback_events.iter().map(conv));
Rolled { game_over: *game_over }
});
let (rank, places, location, macros_on, pad_empty, scene) =
task.inspect(|adapter, _, macros| {
let progress = adapter.progress();
(
progress.rank,
progress.unique_locations as u32,
adapter.location(),
macros.is_some(),
macros.is_some_and(|l| l.running().is_none() && l.feed_palette().is_empty()),
macros.map_or("raw", MacroLayer::scene_name),
)
});
let facts = task
.with_reader(|memory| facts_of(memory))
.ok_or_else(|| anyhow!("the task has no boundary image"))?;
let obs = Frame {
ms,
events,
rewards: feed.rewards.iter().map(|r| (r.kind, r.value)).collect(),
rank,
places,
location,
macros_on,
pad_empty,
scene,
rollback: rolled,
facts,
};
if measure.take(obs) {
break;
}
}
anyhow::Ok(())
}
.await;
session.stop().await;
outcome?;
measure.finish(Runtime::Session, began_wall.elapsed().as_secs_f64())
}
/// The adapter and the compatibility digest of this build, for the report.
pub fn build_info(release: &str) -> crate::suite::BuildInfo {
use fly_legacy_session::composition::Transport; // overlay:bus01
use fly_legacy_session::composition::{LegacyConfig, compatibility_of};
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::types::id;
let adapter = GameAdapter::id(&PokemonRedReward::new()).to_owned();
let compat = compatibility_of(&LegacyConfig {
mode: ExecutionMode::InProcess,
transport: Transport::default(), // overlay:bus01
placements: Default::default(), // overlay:bus01
rom_path: PathBuf::new(),
dataset_dir: PathBuf::new(),
profile: LegacyProfileKind::Production,
macro_mode: MacroMode::Macros,
agent_id: id("fly"),
agent_threads: 1,
record: false,
});
let digest = flybrain_core::dataset::sha256_hex(compat.as_bytes());
crate::suite::BuildInfo {
release: release.to_owned(),
adapter,
compatibility_sha: digest.chars().take(12).collect(),
}
}

View file

@ -0,0 +1,471 @@
//! A suite: the checkpoint set times the seeds, run as child processes, aggregated.
//!
//! One run is one process (`fly-scorecard run-one`), so two runs never share a thread pool, a
//! tokio runtime or a brain. The suite starts `jobs` children at a time and collects the JSON each
//! prints. A child that fails is recorded as a failed run and never silently dropped: a suite with
//! failed runs says so in its summary and `compare` pairs only what finished.
use std::collections::BTreeMap;
use std::io::Write as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex};
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use crate::compare::{METRICS, mean, stdev};
use crate::tally::RunReport;
pub const SCHEMA: &str = "fly-scorecard-v1";
pub const SET_SCHEMA: &str = "fly-scorecard-set-v1";
/// One checkpoint of the fixed set. Public files name the environment variable that holds the
/// path (the ROM tests' own, `rom-env.sh`), never a path.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SetEntry {
pub id: String,
/// The rung the checkpoint is at, for the report's order and the by-rung table.
pub rung: u32,
pub env: String,
#[serde(default)]
pub note: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct CheckpointSet {
pub schema: String,
pub checkpoints: Vec<SetEntry>,
}
impl CheckpointSet {
pub fn load(path: &Path) -> Result<Self> {
let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
let set: CheckpointSet = serde_json::from_str(&text).context("the checkpoint set")?;
if set.schema != SET_SCHEMA {
bail!("{}: schema {:?}, expected {SET_SCHEMA}", path.display(), set.schema);
}
let mut seen = std::collections::BTreeSet::new();
for entry in &set.checkpoints {
if !seen.insert(entry.id.clone()) {
bail!("{}: checkpoint id {:?} twice", path.display(), entry.id);
}
}
Ok(set)
}
/// The entries whose checkpoint file exists in this environment, with their paths, and the
/// ids that do not (reported, never skipped silently).
pub fn resolve(&self, env: &dyn Fn(&str) -> Option<String>) -> (Vec<(SetEntry, PathBuf)>, Vec<String>) {
let mut found = Vec::new();
let mut missing = Vec::new();
for entry in &self.checkpoints {
match env(&entry.env).map(PathBuf::from).filter(|path| path.is_file()) {
Some(path) => found.push((entry.clone(), path)),
None => missing.push(format!("{} (${})", entry.id, entry.env)),
}
}
(found, missing)
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct SuiteConfig {
/// Brain minutes measured per run.
pub minutes: f64,
pub seeds: Vec<u32>,
pub threads: usize,
pub jobs: usize,
pub probe_s: f64,
pub window_s: f64,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct BuildInfo {
/// The release or commit under test, as the caller names it.
pub release: String,
pub adapter: String,
/// The compatibility string's SHA-256 prefix (the string itself names no private value, but
/// the digest is enough to tell two builds' checkpoints apart).
pub compatibility_sha: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FailedRun {
pub checkpoint: String,
pub seed: u32,
pub error: String,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct SuiteReport {
pub schema: String,
pub label: String,
pub build: BuildInfo,
pub runtime: String,
pub mode: String,
pub config: SuiteConfig,
pub runs: Vec<RunReport>,
pub failed_runs: Vec<FailedRun>,
}
impl SuiteReport {
pub fn load(path: &Path) -> Result<Self> {
let text = std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
let suite: SuiteReport = serde_json::from_str(&text).with_context(|| format!("{} is not a scorecard", path.display()))?;
if suite.schema != SCHEMA {
bail!("{}: schema {:?}, expected {SCHEMA}", path.display(), suite.schema);
}
Ok(suite)
}
pub fn brain_hours(&self) -> f64 {
self.runs.iter().map(|run| run.minutes).sum::<f64>() / 60.0
}
/// The headline: totals over every run, as rates per brain hour where that is the unit.
pub fn headline(&self) -> Headline {
let hours = self.brain_hours();
let sum = |f: &dyn Fn(&RunReport) -> f64| self.runs.iter().map(f).sum::<f64>();
let per_hour = |x: f64| if hours > 0.0 { x / hours } else { 0.0 };
let probes = sum(&|r| r.watchdog.probes as f64);
let windows = sum(&|r| r.hunt.windows as f64);
let frames = sum(&|r| r.frames as f64);
let finishes = sum(&|r| (r.macros.done + r.macros.failed()) as f64);
Headline {
runs: self.runs.len(),
brain_hours: hours,
rungs_per_hour: per_hour(sum(&|r| f64::from(r.rungs.gained))),
runs_with_a_climb: self.runs.iter().filter(|r| r.rungs.gained > 0).count(),
empty_pad_pct: if frames > 0.0 { 100.0 * sum(&|r| r.pad.empty_frames as f64) / frames } else { 0.0 },
suspected_probe_pct: if probes > 0.0 { 100.0 * sum(&|r| r.watchdog.suspected as f64) / probes } else { 0.0 },
ladder_events: self.runs.iter().map(|r| r.watchdog.ladder_events).sum(),
runs_with_a_ladder_event: self.runs.iter().filter(|r| r.watchdog.ladder_events > 0).count(),
hunt_flagged_pct: if windows > 0.0 { 100.0 * sum(&|r| r.hunt.flagged as f64) / windows } else { 0.0 },
blocked_macro_pct: if finishes > 0.0 { 100.0 * sum(&|r| r.macros.failed() as f64) / finishes } else { 0.0 },
buy_ball_done: self.runs.iter().map(|r| r.funnel.buy_ball_done).sum(),
throws: self.runs.iter().map(|r| r.funnel.throw_ball_done).sum(),
catches: self.runs.iter().map(|r| r.funnel.catches).sum(),
heals: self.runs.iter().map(|r| r.heals.heal_done).sum(),
whiteouts: self.runs.iter().map(|r| r.whiteouts).sum(),
battles_won: self.runs.iter().map(|r| r.battles.won).sum(),
battles_lost: self.runs.iter().map(|r| r.battles.lost).sum(),
ratchet_rollbacks: self.runs.iter().map(|r| u64::from(r.ratchet.rollbacks)).sum(),
}
}
/// A one-screen summary: the headline, then a row per checkpoint with its seeds' spread.
pub fn markdown(&self, rungs: &BTreeMap<String, u32>) -> String {
let h = self.headline();
let mut out = String::new();
out.push_str(&format!(
"# Scorecard {}: {} runtime, {}\n\n",
self.label, self.runtime, self.mode
));
out.push_str(&format!(
"{} runs, {:.2} brain hours ({} brain min each, seeds {:?}), adapter `{}`, compatibility `{}`.\n\n",
h.runs,
h.brain_hours,
self.config.minutes,
self.config.seeds,
self.build.adapter,
self.build.compatibility_sha
));
if !self.failed_runs.is_empty() {
out.push_str(&format!("**{} runs failed:**\n", self.failed_runs.len()));
for failed in &self.failed_runs {
out.push_str(&format!("- {} seed {}: {}\n", failed.checkpoint, failed.seed, failed.error));
}
out.push('\n');
}
out.push_str("| headline | value |\n| --- | ---: |\n");
let rows: Vec<(&str, String)> = vec![
("rungs per brain hour", format!("{:.2} ({} of {} runs climbed)", h.rungs_per_hour, h.runs_with_a_climb, h.runs)),
("empty-pad time", format!("{:.2}% of frames", h.empty_pad_pct)),
("watchdog probes suspected", format!("{:.1}%", h.suspected_probe_pct)),
("ladder-worthy traps", format!("{} (in {} runs)", h.ladder_events, h.runs_with_a_ladder_event)),
("trap-hunt windows flagged", format!("{:.1}%", h.hunt_flagged_pct)),
("blocked macro finishes", format!("{:.1}%", h.blocked_macro_pct)),
("buy ball / throw / catch", format!("{} / {} / {}", h.buy_ball_done, h.throws, h.catches)),
("heals / whiteouts", format!("{} / {}", h.heals, h.whiteouts)),
("battles won / lost", format!("{} / {}", h.battles_won, h.battles_lost)),
("ratchet rollbacks", format!("{}", h.ratchet_rollbacks)),
];
for (name, value) in rows {
out.push_str(&format!("| {name} | {value} |\n"));
}
out.push_str("\n| checkpoint | rung | seeds | rungs/h | empty pad % | suspected % | traps | buy/throw/catch | won/lost | whiteouts |\n");
out.push_str("| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | --- | ---: |\n");
let mut by: BTreeMap<&str, Vec<&RunReport>> = BTreeMap::new();
for run in &self.runs {
by.entry(run.checkpoint.as_str()).or_default().push(run);
}
let mut order: Vec<(&str, &Vec<&RunReport>)> = by.iter().map(|(k, v)| (*k, v)).collect();
order.sort_by_key(|(id, runs)| (rungs.get(*id).copied().unwrap_or(runs[0].rungs.start), *id));
for (id, runs) in order {
let rate = |name: &str| -> Vec<f64> {
let metric = METRICS.iter().find(|m| m.name == name).expect("a metric");
runs.iter().map(|r| (metric.read)(r)).collect()
};
let rungs_h = rate("rungs_per_hour");
let pad = rate("empty_pad_pct");
let susp = rate("watchdog_suspected_pct");
let sum = |f: &dyn Fn(&RunReport) -> u64| runs.iter().map(|r| f(r)).sum::<u64>();
out.push_str(&format!(
"| {id} | {} | {} | {:.1} ± {:.1} | {:.1} | {:.0} | {} | {}/{}/{} | {}/{} | {} |\n",
rungs.get(id).copied().unwrap_or(runs[0].rungs.start),
runs.len(),
mean(&rungs_h),
stdev(&rungs_h),
mean(&pad),
mean(&susp),
sum(&|r| r.watchdog.ladder_events as u64),
sum(&|r| r.funnel.buy_ball_done),
sum(&|r| r.funnel.throw_ball_done),
sum(&|r| r.funnel.catches),
sum(&|r| r.battles.won),
sum(&|r| r.battles.lost),
sum(&|r| r.whiteouts),
));
}
out
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Headline {
pub runs: usize,
pub brain_hours: f64,
pub rungs_per_hour: f64,
pub runs_with_a_climb: usize,
pub empty_pad_pct: f64,
pub suspected_probe_pct: f64,
pub ladder_events: usize,
pub runs_with_a_ladder_event: usize,
pub hunt_flagged_pct: f64,
pub blocked_macro_pct: f64,
pub buy_ball_done: u64,
pub throws: u64,
pub catches: u64,
pub heals: u64,
pub whiteouts: u64,
pub battles_won: u64,
pub battles_lost: u64,
pub ratchet_rollbacks: u64,
}
/// One run to do: a checkpoint of the set, a seed.
#[derive(Clone, Debug)]
pub struct Job {
pub id: String,
pub path: PathBuf,
pub seed: u32,
}
/// What every child shares.
#[derive(Clone, Debug)]
pub struct ChildArgs {
pub runtime: String,
pub mode: String,
pub minutes: f64,
pub threads: usize,
pub probe_s: f64,
pub window_s: f64,
pub dataset: Option<PathBuf>,
}
/// Runs the jobs `jobs` at a time as children of this executable, calling `done` as each one
/// finishes (so a caller can write partial results). Returns the finished runs and the failures,
/// in job order.
pub fn run_jobs(
exe: &Path,
jobs: Vec<Job>,
args: &ChildArgs,
parallel: usize,
done: &(dyn Fn(&Result<RunReport, FailedRun>) + Sync),
) -> Vec<Result<RunReport, FailedRun>> {
let queue = Arc::new(Mutex::new(jobs.into_iter().enumerate().collect::<std::collections::VecDeque<_>>()));
let results = Arc::new(Mutex::new(Vec::new()));
std::thread::scope(|scope| {
for _ in 0..parallel.max(1) {
let queue = Arc::clone(&queue);
let results = Arc::clone(&results);
scope.spawn(move || {
loop {
let next = queue.lock().expect("queue").pop_front();
let Some((index, job)) = next else { break };
let outcome = run_child(exe, &job, args);
done(&outcome);
results.lock().expect("results").push((index, outcome));
}
});
}
});
let mut results = Arc::try_unwrap(results).expect("all workers joined").into_inner().expect("results");
results.sort_by_key(|(index, _)| *index);
results.into_iter().map(|(_, outcome)| outcome).collect()
}
/// The child gets SIGKILL when this process dies (PR_SET_PDEATHSIG), so a killed or timed-out
/// suite leaves no `run-one` behind. The parent-pid check closes the race where the parent
/// died between the fork and the prctl.
#[cfg(target_os = "linux")]
fn die_with_parent(command: &mut Command) {
use std::os::unix::process::CommandExt;
// SAFETY: only async-signal-safe calls (prctl, getppid, _exit) run between fork and exec.
unsafe {
let parent = libc::getpid();
command.pre_exec(move || {
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL as libc::c_ulong, 0, 0, 0) != 0 {
return Err(std::io::Error::last_os_error());
}
if libc::getppid() != parent {
libc::_exit(1);
}
Ok(())
});
}
}
#[cfg(not(target_os = "linux"))]
fn die_with_parent(_command: &mut Command) {}
fn run_child(exe: &Path, job: &Job, args: &ChildArgs) -> Result<RunReport, FailedRun> {
let fail = |error: String| FailedRun { checkpoint: job.id.clone(), seed: job.seed, error };
let mut command = Command::new(exe);
command
.arg("run-one")
.arg("--id")
.arg(&job.id)
.arg("--checkpoint")
.arg(&job.path)
.arg("--seed")
.arg(job.seed.to_string())
.arg("--runtime")
.arg(&args.runtime)
.arg("--mode")
.arg(&args.mode)
.arg("--minutes")
.arg(args.minutes.to_string())
.arg("--threads")
.arg(args.threads.to_string())
.arg("--probe-s")
.arg(args.probe_s.to_string())
.arg("--window-s")
.arg(args.window_s.to_string());
if let Some(dataset) = &args.dataset {
command.arg("--dataset").arg(dataset);
}
// The report travels in a file: the emulator library prints the cartridge's header on stdout.
let report = tempfile::NamedTempFile::new().map_err(|e| fail(format!("a scratch file: {e}")))?;
command.arg("--out").arg(report.path());
die_with_parent(&mut command);
let status = command
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::inherit())
.status()
.map_err(|e| fail(format!("starting the child: {e}")))?;
if !status.success() {
return Err(fail(format!("the child exited with {status}")));
}
let text = std::fs::read(report.path()).map_err(|e| fail(format!("the child's report: {e}")))?;
serde_json::from_slice::<RunReport>(&text).map_err(|e| fail(format!("the child's report: {e}")))
}
/// Appends a line to a log, ignoring a failure to: progress is a courtesy.
pub fn note(path: &Path, line: &str) {
if let Ok(mut file) = std::fs::OpenOptions::new().create(true).append(true).open(path) {
let _ = writeln!(file, "{line}");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_set_is_resolved_from_the_environment_and_names_what_is_missing() {
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("a.checkpoint");
std::fs::write(&file, b"x").unwrap();
let set = CheckpointSet {
schema: SET_SCHEMA.to_owned(),
checkpoints: vec![
SetEntry { id: "a".into(), rung: 8, env: "FLY_A".into(), note: String::new() },
SetEntry { id: "b".into(), rung: 9, env: "FLY_B".into(), note: String::new() },
SetEntry { id: "c".into(), rung: 9, env: "FLY_C".into(), note: String::new() },
],
};
let env = |name: &str| match name {
"FLY_A" => Some(file.display().to_string()),
"FLY_C" => Some("/nonexistent/c.checkpoint".to_owned()),
_ => None,
};
let (found, missing) = set.resolve(&env);
assert_eq!(found.len(), 1);
assert_eq!(found[0].0.id, "a");
assert_eq!(missing, vec!["b ($FLY_B)".to_owned(), "c ($FLY_C)".to_owned()]);
}
#[test]
fn the_shipped_set_parses_and_has_unique_ids() {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../../tools/scorecard/checkpoints.json");
let set = CheckpointSet::load(&path).expect("the shipped set");
assert!(set.checkpoints.len() >= 8);
assert!(set.checkpoints.iter().all(|e| e.env.starts_with("FLY_") && e.env.ends_with("_CHECKPOINT")));
assert!(set.checkpoints.iter().all(|e| (8..=15).contains(&e.rung)));
}
#[test]
fn the_committed_baseline_is_a_valid_card_and_passes_against_itself() {
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../../../tools/scorecard/baseline-v0.7.5.json");
let card = SuiteReport::load(&path).expect("the reference card");
assert_eq!(card.label, "v0.7.5");
assert_eq!(card.build.adapter, "pokered-unique8-v8");
assert_eq!(card.runs.len(), 36);
assert!(card.failed_runs.is_empty());
assert!(card.runs.iter().all(|run| run.frames > 30_000 && run.minutes >= 10.0));
let comparison = crate::compare::compare(&card, &card, 0.05);
assert!(comparison.pass, "{:?}", comparison.failed);
assert_eq!(comparison.pairs, 36);
// Nothing in a public card names a path or a host.
let text = std::fs::read_to_string(&path).unwrap();
assert!(!text.contains("/home/") && !text.contains("192.168"));
}
#[test]
fn a_suite_round_trips_and_summarises() {
let mut run = RunReport {
checkpoint: "r08".into(),
seed: 1,
runtime: "session".into(),
mode: "macros".into(),
minutes: 12.0,
frames: 1000,
..RunReport::default()
};
run.rungs.gained = 1;
run.watchdog.probes = 4;
run.macros.done = 9;
run.macros.blocked = 1;
let suite = SuiteReport {
schema: SCHEMA.to_owned(),
label: "t".into(),
build: BuildInfo::default(),
runtime: "session".into(),
mode: "macros".into(),
config: SuiteConfig { minutes: 12.0, seeds: vec![1], ..SuiteConfig::default() },
runs: vec![run],
failed_runs: vec![FailedRun { checkpoint: "r09".into(), seed: 1, error: "boom".into() }],
};
let text = serde_json::to_string(&suite).unwrap();
let back: SuiteReport = serde_json::from_str(&text).unwrap();
assert_eq!(back, suite);
let h = back.headline();
assert!((h.rungs_per_hour - 5.0).abs() < 1e-9);
assert!((h.blocked_macro_pct - 10.0).abs() < 1e-9);
let md = back.markdown(&BTreeMap::new());
assert!(md.contains("r08") && md.contains("1 runs failed") && md.contains("boom"));
}
}

View file

@ -0,0 +1,940 @@
//! One run's frames in, one [`RunReport`] out.
//!
//! Everything the scorecard measures about play is computed here from [`Frame`]s, with no
//! emulator, brain or runtime in sight, so every definition is unit-tested on synthetic frames.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use crate::obs::{Facts, Frame};
use crate::watchdog::{Ev, Probe, Rules, Watchdog};
/// One Game Boy frame of game time, ms (`70,224` cycles at `4,194,304` Hz).
pub const FRAME_MS: f64 = 1000.0 * 70_224.0 / 4_194_304.0;
const MINUTE_MS: f64 = 60_000.0;
/// The trap hunt's window rules (`examples/trap_hunt.rs` in flysim), kept as it has them: two
/// brain minutes, stepped by fifteen seconds, fewer than four tiles or one macro sequence
/// repeated more than ten times (any period up to eight).
pub const HUNT_WINDOW_MS: f64 = 2.0 * MINUTE_MS;
pub const HUNT_STEP_MS: f64 = 15_000.0;
pub const HUNT_MIN_TILES: usize = 4;
pub const HUNT_MAX_REPEATS: usize = 10;
pub const HUNT_MAX_PERIOD: usize = 8;
/// How a run is measured.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TallyConfig {
pub rules: Rules,
/// Brain seconds between watchdog probes.
pub probe_s: f64,
/// Brain seconds before the first probe (a window needs some life in it).
pub first_probe_s: f64,
}
impl Default for TallyConfig {
fn default() -> Self {
Self { rules: Rules::default(), probe_s: 120.0, first_probe_s: 240.0 }
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct RungReport {
pub start: u32,
pub end: u32,
pub gained: u32,
/// `[rung, brain minute]` for every climb.
pub climbs: Vec<(u32, f64)>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct PadReport {
/// Frames with the macro layer on, nothing running and no button dealt.
pub empty_frames: u64,
pub empty_seconds: f64,
pub empty_fraction: f64,
pub longest_empty_seconds: f64,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct WatchdogReport {
pub probes: usize,
pub suspected: usize,
/// Probes that were suspected with the one before also suspected (the loop recovery's
/// "confirmed": two fresh suspected reports in a row).
pub confirmed: usize,
/// Runs of two or more suspected probes: each is one trap the recovery ladder would act on.
pub ladder_events: usize,
pub reasons: BTreeMap<String, usize>,
pub flagged: Vec<Probe>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct HuntWindow {
pub at_min: f64,
pub tiles: usize,
pub macros: usize,
pub cycle: Option<(String, usize)>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct HuntReport {
pub windows: usize,
pub flagged: usize,
/// The first twenty flagged windows.
pub first_flagged: Vec<HuntWindow>,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct RatchetReport {
pub rollbacks: u32,
pub game_over: u32,
pub stall: u32,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct MacroCounts {
pub start: u64,
pub done: u64,
pub blocked: u64,
pub timeout: u64,
pub refused: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct MacroReport {
pub starts: u64,
pub done: u64,
pub blocked: u64,
pub timeout: u64,
pub refused: u64,
pub by_macro: BTreeMap<String, MacroCounts>,
}
impl MacroReport {
/// Finishes that were not `done`, which is what "blocked macro counts" asks for.
pub fn failed(&self) -> u64 {
self.blocked + self.timeout + self.refused
}
}
/// GO SHOP, BUY BALL, THROW BALL, catch, and the bag around them.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct FunnelReport {
pub go_shop_start: u64,
pub go_shop_done: u64,
pub buy_ball_start: u64,
pub buy_ball_done: u64,
pub throw_ball_start: u64,
pub throw_ball_done: u64,
/// `catch` rewards: a wild Pokemon kept.
pub catches: u64,
/// New species owned (Pokedex bits that went up).
pub species_gained: u64,
pub balls_gained: u64,
pub balls_spent: u64,
/// How far down GO SHOP done, BUY BALL done, THROW BALL start, catch the run got, in order of
/// first occurrence (0 to 4).
pub depth: u32,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct HealReport {
pub go_heal_start: u64,
pub go_heal_done: u64,
pub heal_start: u64,
/// The nurse's `HEAL` finished: a party healed.
pub heal_done: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct BattleReport {
pub started: u64,
pub ended: u64,
pub wild: u64,
pub trainer: u64,
/// Ended with a battle or trainer payout.
pub won: u64,
/// Ended with the whole party fainted.
pub lost: u64,
/// A wild Pokemon kept.
pub caught: u64,
/// Ended otherwise (run away, a ball thrown away from the kept Pokemon, ...).
pub other: u64,
pub longest_frames: u64,
pub still_running: bool,
pub macros_in_longest: u64,
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct RewardTotals {
pub n: u64,
pub total: f64,
}
/// One run: a checkpoint, a seed, a runtime, some brain minutes.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct RunReport {
pub checkpoint: String,
pub seed: u32,
pub runtime: String,
pub mode: String,
/// Brain minutes measured (after the seed's idle frames).
pub minutes: f64,
pub frames: u64,
pub idle_frames: u32,
pub wall_seconds: f64,
pub rungs: RungReport,
pub places_start: u32,
pub places_end: u32,
pub pad: PadReport,
pub watchdog: WatchdogReport,
pub hunt: HuntReport,
pub ratchet: RatchetReport,
pub macros: MacroReport,
pub funnel: FunnelReport,
pub heals: HealReport,
pub whiteouts: u64,
pub battles: BattleReport,
pub rewards: BTreeMap<String, RewardTotals>,
pub scenes: BTreeMap<String, u64>,
pub ended_map: u32,
}
/// The battle in progress.
#[derive(Clone, Debug, Default)]
struct Battle {
frames: u64,
macros: u64,
won: bool,
caught: bool,
fainted: bool,
}
pub struct Tally {
config: TallyConfig,
began_ms: f64,
last_ms: f64,
frames: u64,
start_rank: u32,
rank: u32,
start_places: u32,
places: u32,
climbs: Vec<(u32, f64)>,
macros_on: bool,
empty_frames: u64,
empty_run: u64,
longest_empty: u64,
events: Vec<Ev>,
watchdog: Watchdog,
next_probe_ms: f64,
probes: Vec<Probe>,
steps: Vec<(f64, u32, u32, u32)>,
starts: Vec<(f64, &'static str)>,
ratchet: RatchetReport,
macro_report: MacroReport,
funnel: FunnelReport,
funnel_order: [Option<f64>; 4],
heals: HealReport,
whiteouts: u64,
was_fainted: bool,
battles: BattleReport,
battle: Option<Battle>,
rewards: BTreeMap<String, RewardTotals>,
scenes: BTreeMap<String, u64>,
last_facts: Option<Facts>,
ended_map: u32,
}
/// The feed's kind for an adapter reward kind (`flysim::snapshot::RewardKind::from_adapter`), or
/// an empty string where the feed has no counter. The watchdog reads the feed's names.
pub fn feed_kind(adapter_kind: &str) -> &'static str {
flysim::snapshot::RewardKind::from_adapter(adapter_kind).map_or("", |kind| kind.as_str())
}
impl Tally {
/// The first frame's brain clock, rung and exploration count are the run's start. Nothing
/// before it is measured.
pub fn new(config: TallyConfig, began_ms: f64, rank: u32, places: u32) -> Self {
let watchdog = Watchdog::new(config.rules.clone(), places);
let next_probe_ms = began_ms + config.first_probe_s * 1000.0;
Self {
config,
began_ms,
last_ms: began_ms,
frames: 0,
start_rank: rank,
rank,
start_places: places,
places,
climbs: Vec::new(),
macros_on: false,
empty_frames: 0,
empty_run: 0,
longest_empty: 0,
events: Vec::new(),
watchdog,
next_probe_ms,
probes: Vec::new(),
steps: Vec::new(),
starts: Vec::new(),
ratchet: RatchetReport::default(),
macro_report: MacroReport::default(),
funnel: FunnelReport::default(),
funnel_order: [None; 4],
heals: HealReport::default(),
whiteouts: 0,
was_fainted: false,
battles: BattleReport::default(),
battle: None,
rewards: BTreeMap::new(),
scenes: BTreeMap::new(),
last_facts: None,
ended_map: 0xff,
}
}
/// Brain minutes measured so far.
pub fn minutes(&self) -> f64 {
(self.last_ms - self.began_ms) / MINUTE_MS
}
pub fn push(&mut self, frame: &Frame) {
let ms = frame.ms;
self.frames += 1;
self.last_ms = ms;
self.macros_on |= frame.macros_on;
if frame.rank != self.rank {
if frame.rank > self.rank {
self.climbs.push((frame.rank, (ms - self.began_ms) / MINUTE_MS));
self.events.push(Ev::Milestone { ms });
}
self.rank = frame.rank;
}
self.places = frame.places;
if let Some((map, x, y)) = frame.location {
self.steps.push((ms, map, x, y));
}
*self.scenes.entry(frame.scene.to_owned()).or_insert(0) += 1;
// The pad.
if frame.macros_on && frame.pad_empty {
self.empty_frames += 1;
self.empty_run += 1;
self.longest_empty = self.longest_empty.max(self.empty_run);
} else {
self.empty_run = 0;
}
// Macros.
for event in &frame.events {
let counts = self.macro_report.by_macro.entry(event.name.to_owned()).or_default();
match event.outcome {
None => {
counts.start += 1;
self.macro_report.starts += 1;
self.starts.push((ms, event.name));
if let Some(battle) = self.battle.as_mut() {
battle.macros += 1;
}
}
Some("done") => {
counts.done += 1;
self.macro_report.done += 1;
}
Some("blocked") => {
counts.blocked += 1;
self.macro_report.blocked += 1;
}
Some("timeout") => {
counts.timeout += 1;
self.macro_report.timeout += 1;
}
Some("refused") => {
counts.refused += 1;
self.macro_report.refused += 1;
}
Some(_) => {}
}
self.events.push(Ev::Macro { ms, name: event.name, outcome: event.outcome });
self.funnel_and_heals(ms, event.name, event.outcome);
}
// Rewards.
let mut won_now = false;
let mut caught_now = false;
for (kind, value) in &frame.rewards {
let totals = self.rewards.entry((*kind).to_owned()).or_default();
totals.n += 1;
totals.total += value;
self.events.push(Ev::Reward { ms, kind: feed_kind(kind) });
match *kind {
"battle" | "trainer" => won_now = true,
"catch" => {
caught_now = true;
self.funnel.catches += 1;
self.note_stage(3, ms);
}
_ => {}
}
}
// The ratchet.
if let Some(rolled) = frame.rollback {
self.ratchet.rollbacks += 1;
if rolled.game_over {
self.ratchet.game_over += 1;
} else {
self.ratchet.stall += 1;
}
}
// Memory: bag, party, battles.
let facts = frame.facts;
if let Some(last) = self.last_facts {
if facts.balls > last.balls {
self.funnel.balls_gained += u64::from(facts.balls - last.balls);
}
if facts.balls < last.balls {
self.funnel.balls_spent += u64::from(last.balls - facts.balls);
}
if facts.owned > last.owned {
self.funnel.species_gained += u64::from(facts.owned - last.owned);
}
}
self.last_facts = Some(facts);
self.ended_map = facts.map;
let fainted = facts.all_fainted();
if fainted && !self.was_fainted {
self.whiteouts += 1;
}
self.was_fainted = fainted;
match (facts.in_battle(), self.battle.as_mut()) {
(true, None) => {
self.battles.started += 1;
if facts.battle == 2 {
self.battles.trainer += 1;
} else {
self.battles.wild += 1;
}
self.battle = Some(Battle {
frames: 1,
won: won_now,
caught: caught_now,
fainted,
..Battle::default()
});
}
(true, Some(battle)) => {
battle.frames += 1;
battle.won |= won_now;
battle.caught |= caught_now;
battle.fainted |= fainted;
}
(false, Some(battle)) => {
battle.won |= won_now;
battle.caught |= caught_now;
battle.fainted |= fainted;
let battle = self.battle.take().expect("a battle");
self.end_battle(battle);
}
(false, None) => {}
}
// Probes.
while ms >= self.next_probe_ms {
let at_min = (self.next_probe_ms - self.began_ms) / MINUTE_MS;
let probe = self.watchdog.probe(&self.events, self.places, at_min);
self.probes.push(probe);
self.next_probe_ms += self.config.probe_s * 1000.0;
}
}
fn end_battle(&mut self, battle: Battle) {
self.battles.ended += 1;
if battle.frames > self.battles.longest_frames {
self.battles.longest_frames = battle.frames;
self.battles.macros_in_longest = battle.macros;
}
if battle.won {
self.battles.won += 1;
} else if battle.fainted {
self.battles.lost += 1;
} else if battle.caught {
self.battles.caught += 1;
} else {
self.battles.other += 1;
}
if battle.caught {
// A catch that is also a win payout counts once as a win and is still a catch.
if battle.won {
self.battles.caught += 1;
}
}
}
fn funnel_and_heals(&mut self, ms: f64, name: &str, outcome: Option<&str>) {
let f = &mut self.funnel;
let h = &mut self.heals;
let mut stage = None;
match (name, outcome) {
("GO SHOP", None) => f.go_shop_start += 1,
("GO SHOP", Some("done")) => {
f.go_shop_done += 1;
stage = Some(0);
}
("BUY BALL", None) => f.buy_ball_start += 1,
("BUY BALL", Some("done")) => {
f.buy_ball_done += 1;
stage = Some(1);
}
("THROW BALL", None) => {
f.throw_ball_start += 1;
stage = Some(2);
}
("THROW BALL", Some("done")) => f.throw_ball_done += 1,
("GO HEAL", None) => h.go_heal_start += 1,
("GO HEAL", Some("done")) => h.go_heal_done += 1,
("HEAL", None) => h.heal_start += 1,
("HEAL", Some("done")) => h.heal_done += 1,
_ => {}
}
if let Some(stage) = stage {
self.note_stage(stage, ms);
}
}
fn note_stage(&mut self, stage: usize, ms: f64) {
self.funnel_order[stage].get_or_insert(ms);
}
/// The run's report. `checkpoint`, `seed`, `runtime` and the rest of the identity are the
/// caller's.
pub fn finish(mut self, identity: RunReport) -> RunReport {
// The funnel's depth: stages in order of first occurrence, each after the last one.
let mut depth = 0;
let mut after = f64::NEG_INFINITY;
for first in self.funnel_order {
match first {
Some(ms) if ms >= after => {
depth += 1;
after = ms;
}
_ => break,
}
}
self.funnel.depth = depth;
if let Some(battle) = self.battle.take() {
self.battles.still_running = true;
self.battles.longest_frames = self.battles.longest_frames.max(battle.frames);
}
let minutes = self.minutes();
let seconds = |frames: u64| frames as f64 * FRAME_MS / 1000.0;
// The watchdog.
let mut watchdog = WatchdogReport { probes: self.probes.len(), ..Default::default() };
let mut run = 0usize;
for probe in &self.probes {
if probe.suspected {
watchdog.suspected += 1;
run += 1;
if run >= 2 {
watchdog.confirmed += 1;
}
if run == 2 {
watchdog.ladder_events += 1;
}
if let Some(reason) = &probe.reason {
*watchdog.reasons.entry(reason.clone()).or_insert(0) += 1;
}
if watchdog.flagged.len() < 20 {
watchdog.flagged.push(probe.clone());
}
} else {
run = 0;
}
}
let hunt = hunt(&self.steps, &self.starts, self.began_ms, self.last_ms);
let macro_report = std::mem::take(&mut self.macro_report);
RunReport {
minutes,
frames: self.frames,
rungs: RungReport {
start: self.start_rank,
end: self.rank,
gained: self.rank.saturating_sub(self.start_rank),
climbs: self.climbs,
},
places_start: self.start_places,
places_end: self.places,
pad: PadReport {
empty_frames: self.empty_frames,
empty_seconds: seconds(self.empty_frames),
empty_fraction: if self.frames == 0 || !self.macros_on {
0.0
} else {
self.empty_frames as f64 / self.frames as f64
},
longest_empty_seconds: seconds(self.longest_empty),
},
watchdog,
hunt,
ratchet: self.ratchet,
macros: macro_report,
funnel: self.funnel,
heals: self.heals,
whiteouts: self.whiteouts,
battles: self.battles,
rewards: self.rewards,
scenes: self.scenes,
ended_map: self.ended_map,
..identity
}
}
}
/// The longest run of one repeated block in `names`, as `(block, repeats)`
/// (`examples/trap_hunt.rs`: every period up to eight, every offset).
pub fn longest_cycle(names: &[&'static str]) -> Option<(String, usize)> {
let mut best: Option<(String, usize)> = None;
for period in 1..=HUNT_MAX_PERIOD.min(names.len()) {
let mut start = 0;
while start + period <= names.len() {
let block = &names[start..start + period];
let mut repeats = 1;
while start + period * (repeats + 1) <= names.len()
&& &names[start + period * repeats..start + period * (repeats + 1)] == block
{
repeats += 1;
}
if best.as_ref().is_none_or(|(_, known)| repeats > *known) {
best = Some((block.join(", "), repeats));
}
start += period * repeats;
}
}
best
}
/// Every window of the run that is a trap by the trap hunt's rules: it did things (a window with
/// no macro in it is the fly choosing nothing, which is the doctrine working) and either stood on
/// fewer than four distinct tiles or repeated one macro sequence more than ten times.
pub fn hunt(
steps: &[(f64, u32, u32, u32)],
starts: &[(f64, &'static str)],
began_ms: f64,
ended_ms: f64,
) -> HuntReport {
let mut report = HuntReport::default();
let mut at = began_ms;
while at + HUNT_WINDOW_MS <= ended_ms {
let until = at + HUNT_WINDOW_MS;
report.windows += 1;
let tiles: BTreeSet<(u32, u32, u32)> = steps
.iter()
.filter(|(ms, ..)| *ms >= at && *ms < until)
.map(|(_, map, x, y)| (*map, *x, *y))
.collect();
let names: Vec<&'static str> = starts
.iter()
.filter(|(ms, _)| *ms >= at && *ms < until)
.map(|(_, name)| *name)
.collect();
let cycle = longest_cycle(&names).filter(|(_, repeats)| *repeats > HUNT_MAX_REPEATS);
let stuck = tiles.len() < HUNT_MIN_TILES && !names.is_empty();
if stuck || cycle.is_some() {
report.flagged += 1;
if report.first_flagged.len() < 20 {
report.first_flagged.push(HuntWindow {
at_min: (at - began_ms) / MINUTE_MS,
tiles: tiles.len(),
macros: names.len(),
cycle,
});
}
}
at += HUNT_STEP_MS;
}
report
}
#[cfg(test)]
mod tests {
use super::*;
use crate::obs::{MacroEv, Rolled};
fn frame(ms: f64) -> Frame {
Frame {
ms,
events: Vec::new(),
rewards: Vec::new(),
rank: 8,
places: 100,
location: Some((1, (ms / 1000.0) as u32 % 50, 3)),
macros_on: true,
pad_empty: false,
scene: "overworld",
rollback: None,
facts: Facts { party: 2, alive: 2, balls: 3, money: 500, owned: 10, map: 1, battle: 0 },
}
}
fn ev(name: &'static str, outcome: Option<&'static str>) -> MacroEv {
MacroEv { name, outcome }
}
fn run(frames: &[Frame]) -> RunReport {
let mut tally = Tally::new(TallyConfig::default(), 0.0, 8, 100);
for frame in frames {
tally.push(frame);
}
tally.finish(RunReport { checkpoint: "t".into(), ..RunReport::default() })
}
#[test]
fn rungs_climb_and_are_timed() {
let mut a = frame(1000.0);
a.rank = 9;
let mut b = frame(61_000.0);
b.rank = 10;
let report = run(&[a, b]);
assert_eq!((report.rungs.start, report.rungs.end, report.rungs.gained), (8, 10, 2));
assert_eq!(report.rungs.climbs, vec![(9, 1000.0 / 60_000.0), (10, 61_000.0 / 60_000.0)]);
}
#[test]
fn the_empty_pad_is_counted_in_seconds_and_in_its_longest_stretch() {
let mut frames = Vec::new();
for i in 0..10u64 {
let mut f = frame(i as f64 * FRAME_MS);
f.pad_empty = (2..7).contains(&i) || i == 9;
frames.push(f);
}
let report = run(&frames);
assert_eq!(report.pad.empty_frames, 6);
assert!((report.pad.empty_fraction - 0.6).abs() < 1e-9);
assert!((report.pad.longest_empty_seconds - 5.0 * FRAME_MS / 1000.0).abs() < 1e-9);
}
#[test]
fn raw_mode_has_no_pad_to_be_empty() {
let mut f = frame(0.0);
f.macros_on = false;
f.pad_empty = true;
assert_eq!(run(&[f]).pad.empty_fraction, 0.0);
}
#[test]
fn the_shop_to_catch_funnel_counts_each_stage_and_its_depth() {
let mut frames = Vec::new();
let script: [(&'static str, Option<&'static str>); 6] = [
("GO SHOP", None),
("GO SHOP", Some("done")),
("BUY BALL", None),
("BUY BALL", Some("done")),
("THROW BALL", None),
("THROW BALL", Some("done")),
];
for (i, (name, outcome)) in script.iter().enumerate() {
let mut f = frame(i as f64 * 1000.0);
f.events = vec![ev(name, *outcome)];
frames.push(f);
}
let mut f = frame(7000.0);
f.rewards = vec![("catch", 5.0), ("species", 1.0)];
frames.push(f);
let report = run(&frames);
let funnel = &report.funnel;
assert_eq!(
(funnel.go_shop_done, funnel.buy_ball_done, funnel.throw_ball_start, funnel.catches),
(1, 1, 1, 1)
);
assert_eq!(funnel.depth, 4);
assert_eq!(report.macros.starts, 3);
assert_eq!(report.macros.done, 3);
assert_eq!(report.rewards["catch"].n, 1);
}
#[test]
fn a_funnel_that_skips_the_shop_stops_at_depth_zero() {
let mut f = frame(0.0);
f.events = vec![ev("BUY BALL", Some("done"))];
// Stage 0 never occurred: depth counts the unbroken prefix only.
assert_eq!(run(&[f]).funnel.depth, 0);
}
#[test]
fn blocked_refused_and_timed_out_macros_are_counted_by_macro() {
let mut f = frame(0.0);
f.events = vec![
ev("GO ROUTE", Some("refused")),
ev("GO ROUTE", Some("refused")),
ev("GO OUT", Some("blocked")),
ev("GO NPC", Some("timeout")),
ev("NEXT", Some("done")),
];
let report = run(&[f]);
assert_eq!(report.macros.failed(), 4);
assert_eq!(report.macros.by_macro["GO ROUTE"].refused, 2);
assert_eq!(report.macros.done, 1);
}
#[test]
fn heals_are_the_nurses_heal_and_the_walk_to_her() {
let mut f = frame(0.0);
f.events = vec![
ev("GO HEAL", None),
ev("GO HEAL", Some("done")),
ev("HEAL", None),
ev("HEAL", Some("done")),
];
let heals = run(&[f]).heals;
assert_eq!((heals.go_heal_done, heals.heal_done), (1, 1));
}
fn battle_frames(kind: u8, n: usize, from_ms: f64) -> Vec<Frame> {
(0..n)
.map(|i| {
let mut f = frame(from_ms + i as f64 * FRAME_MS);
f.facts.battle = kind;
f
})
.collect()
}
#[test]
fn a_battle_is_won_lost_or_caught_by_what_ended_it() {
let mut frames = Vec::new();
// A won trainer battle.
frames.extend(battle_frames(2, 5, 0.0));
let mut win = frame(100.0);
win.rewards = vec![("trainer", 1.0)];
frames.push(win);
// A wild battle lost: the party faints inside it, then a whiteout.
frames.extend(battle_frames(1, 3, 200.0));
let mut down = battle_frames(1, 3, 300.0);
for f in &mut down {
f.facts.alive = 0;
}
frames.extend(down);
let mut after = frame(400.0);
after.facts.alive = 0;
frames.push(after);
frames.push(frame(500.0));
// A wild battle caught.
frames.extend(battle_frames(1, 4, 600.0));
let mut catch = battle_frames(1, 1, 700.0);
catch[0].rewards = vec![("catch", 3.0)];
frames.extend(catch);
frames.push(frame(800.0));
// One run away from.
frames.extend(battle_frames(1, 2, 900.0));
frames.push(frame(1000.0));
// One still running at the end.
frames.extend(battle_frames(1, 2, 1100.0));
let report = run(&frames);
let b = &report.battles;
assert_eq!((b.started, b.ended), (5, 4));
assert_eq!((b.trainer, b.wild), (1, 4));
assert_eq!((b.won, b.lost, b.caught, b.other), (1, 1, 1, 1));
assert!(b.still_running);
assert_eq!(report.whiteouts, 1);
assert_eq!(report.funnel.catches, 1);
}
#[test]
fn bag_and_dex_changes_become_ball_and_species_counts() {
let mut a = frame(0.0);
a.facts.balls = 5;
let mut b = frame(1000.0);
b.facts.balls = 3;
let mut c = frame(2000.0);
c.facts.balls = 8;
c.facts.owned = 12;
let report = run(&[a, b, c]);
assert_eq!((report.funnel.balls_spent, report.funnel.balls_gained), (2, 5));
assert_eq!(report.funnel.species_gained, 2);
}
#[test]
fn ratchet_rollbacks_are_split_by_trigger() {
let mut a = frame(0.0);
a.rollback = Some(Rolled { game_over: true });
let mut b = frame(1.0);
b.rollback = Some(Rolled { game_over: false });
let report = run(&[a, b]);
assert_eq!((report.ratchet.rollbacks, report.ratchet.game_over, report.ratchet.stall), (2, 1, 1));
}
/// The Viridian cycle on three tiles for twelve minutes: the watchdog confirms it and so does
/// the trap hunt.
#[test]
fn a_ring_is_caught_by_both_instruments() {
let names = ["GO NPC", "GO OUT", "NEXT", "GO FRONTIER"];
let mut frames = Vec::new();
let mut i = 0usize;
let mut ms = 0.0;
while ms < 12.0 * MINUTE_MS {
let mut f = frame(ms);
f.location = Some((1, (i % 3) as u32, 3));
if ((ms / FRAME_MS) as u64).is_multiple_of(180) {
f.events = vec![ev(names[i % 4], None), ev(names[i % 4], Some("done"))];
i += 1;
}
frames.push(f);
ms += FRAME_MS;
}
let report = run(&frames);
assert!(report.watchdog.suspected >= 2, "{:?}", report.watchdog);
assert!(report.watchdog.ladder_events >= 1);
assert!(report.watchdog.confirmed >= 1);
assert!(report.watchdog.reasons.get("sequence").copied().unwrap_or(0) > 0);
assert!(report.hunt.flagged > 0 && report.hunt.windows > 0, "{:?}", report.hunt);
// The run explored nothing: the count never moved.
assert_eq!(report.places_end, report.places_start);
}
/// The same cadence of macros on a fly that keeps finding new tiles is not a trap.
#[test]
fn a_walk_that_finds_places_is_not_flagged() {
let names = ["GO NPC", "GO OUT", "NEXT", "GO FRONTIER"];
let mut frames = Vec::new();
let mut i = 0usize;
let mut ms = 0.0;
while ms < 12.0 * MINUTE_MS {
let mut f = frame(ms);
f.location = Some((1, (ms / 1000.0) as u32, 3));
f.places = 100 + (ms / 10_000.0) as u32;
if ((ms / FRAME_MS) as u64).is_multiple_of(180) {
f.events = vec![ev(names[i % 4], None), ev(names[i % 4], Some("done"))];
i += 1;
}
frames.push(f);
ms += FRAME_MS;
}
let report = run(&frames);
assert_eq!(report.watchdog.suspected, 0, "{:?}", report.watchdog);
assert_eq!(report.hunt.flagged, 0);
assert!(report.watchdog.probes >= 4);
}
#[test]
fn the_hunt_ignores_a_window_with_no_macro_in_it() {
let steps: Vec<(f64, u32, u32, u32)> = (0..9000).map(|i| (i as f64 * 20.0, 1, 1, 1)).collect();
let report = hunt(&steps, &[], 0.0, 180_000.0);
assert!(report.windows > 0);
assert_eq!(report.flagged, 0);
// The same ground with a macro in each window is a stand-still.
let starts: Vec<(f64, &'static str)> = (0..18).map(|i| (i as f64 * 10_000.0, "NEXT")).collect();
assert!(hunt(&steps, &starts, 0.0, 180_000.0).flagged > 0);
}
#[test]
fn the_longest_cycle_finds_the_shortest_block_and_its_repeats() {
let names = ["A", "B", "A", "B", "A", "B", "C"];
assert_eq!(longest_cycle(&names), Some(("A, B".to_string(), 3)));
assert_eq!(longest_cycle(&[]), None);
}
}

View file

@ -0,0 +1,401 @@
//! `fly-watchdog` check 10 (loop suspected), as a function of a run's events.
//!
//! The live check reads the event log's tail, the exploration count from `/status.json` and its
//! own state files; this reads the same three things from a run. The rules, their order and every
//! default are the shell's (`infra/bin/fly-watchdog`, `loop_analyze` and `check_loop`), so a run
//! that would have raised the flag on the stream raises it here. Two differences, both about time:
//!
//! - the probe cadence is a parameter (the stream's is every five wall minutes; a run is short,
//! so the scorecard probes more often), and a window is the last `window_ms` of brain time or
//! the whole run when it is shorter;
//! - the exploration count the first probe compares with is the run's starting count, which the
//! live check does not have for its first probe after a boot.
//!
//! Like the shell, this reads and reports. It never acts.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
/// The thresholds of `fly-watchdog`'s `WD_LOOP_*` variables.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Rules {
pub window_ms: f64,
pub max_period: usize,
pub max_distinct: usize,
pub min_repeats: usize,
pub dominance_pct: usize,
pub min_events: usize,
pub stall_pct: usize,
pub busy_min: usize,
pub fight_min: usize,
}
impl Default for Rules {
fn default() -> Self {
Self {
window_ms: 600_000.0,
max_period: 8,
max_distinct: 4,
min_repeats: 20,
dominance_pct: 95,
min_events: 20,
stall_pct: 90,
busy_min: 100,
fight_min: 24,
}
}
}
/// One line of the event log the check reads: a macro event, a reward or a rung.
#[derive(Clone, Debug, PartialEq)]
pub enum Ev {
/// `<NAME> start` is `outcome: None`; a finish carries its word (done, blocked, timeout,
/// refused).
Macro { ms: f64, name: &'static str, outcome: Option<&'static str> },
/// A reward, with the feed's kind (`wildwin`, `trainer`, `badge`, `pokedex`, `area`, ...), or
/// an empty string for an adapter kind the feed has no counter for.
Reward { ms: f64, kind: &'static str },
Milestone { ms: f64 },
}
/// `loop_analyze`'s result for one window.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Analysis {
pub starts: usize,
pub decisions: usize,
pub distinct: usize,
pub top_name: String,
pub top_count: usize,
pub period: usize,
pub repeats: usize,
pub refused: usize,
pub blocked: usize,
pub timeout: usize,
pub done: usize,
pub rewards: usize,
pub fights: usize,
pub wins: usize,
pub progress: usize,
pub window_from: f64,
pub window_to: f64,
}
fn is_lasting(kind: &str) -> bool {
matches!(kind, "milestone" | "pokedex" | "area" | "trainer" | "badge")
}
/// `loop_analyze`: the window ends at the newest macro event.
pub fn analyze(events: &[Ev], rules: &Rules) -> Analysis {
let last_macro = events.iter().rev().find_map(|event| match event {
Ev::Macro { ms, .. } => Some(*ms),
_ => None,
});
let Some(to) = last_macro else { return Analysis::default() };
let from = to - rules.window_ms;
let mut a = Analysis { window_from: from, window_to: to, ..Analysis::default() };
for event in events {
let (ms, kind) = match event {
Ev::Reward { ms, kind } => (*ms, *kind),
Ev::Milestone { ms } => (*ms, "milestone"),
Ev::Macro { .. } => continue,
};
if ms < from {
continue;
}
if is_lasting(kind) {
a.progress += 1;
}
if kind == "milestone" {
continue;
}
a.rewards += 1;
if matches!(kind, "wildwin" | "trainer" | "badge") {
a.wins += 1;
}
}
let mut seq: Vec<&'static str> = Vec::new();
let mut counts: BTreeMap<&'static str, usize> = BTreeMap::new();
for event in events {
let Ev::Macro { ms, name, outcome } = event else { continue };
if *ms < from {
continue;
}
match outcome {
Some("blocked") => {
a.blocked += 1;
continue;
}
Some("timeout") => {
a.timeout += 1;
continue;
}
Some("done") => {
a.done += 1;
continue;
}
Some("refused") => a.refused += 1,
None => a.starts += 1,
Some(_) => continue,
}
seq.push(name);
if matches!(*name, "MOVE 1" | "MOVE 2" | "MOVE 3" | "MOVE 4") {
a.fights += 1;
}
let n = counts.entry(name).or_insert(0);
*n += 1;
if *n > a.top_count {
a.top_count = *n;
a.top_name = (*name).to_owned();
}
}
a.decisions = seq.len();
a.distinct = counts.len();
let k = seq.len();
let mut p = 1;
while p <= rules.max_period && p * 2 <= k {
let mut r = 1;
while (r + 1) * p <= k {
let same = (0..p).all(|j| seq[k - 1 - j] == seq[k - 1 - r * p - j]);
if !same {
break;
}
r += 1;
}
if r >= 2 {
a.period = p;
a.repeats = r;
break;
}
p += 1;
}
a
}
/// One probe's verdict.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Probe {
/// Brain minutes into the run.
pub at_min: f64,
pub suspected: bool,
pub reason: Option<String>,
pub decisions: usize,
pub distinct: usize,
pub period: usize,
pub repeats: usize,
pub done: usize,
pub failed: usize,
pub rewards: usize,
pub fights: usize,
pub wins: usize,
pub places_delta: i64,
}
/// `check_loop`'s memory between probes.
#[derive(Clone, Debug)]
pub struct Watchdog {
pub rules: Rules,
prev_places: i64,
prev_idle: bool,
prev_busy: bool,
prev_unwon: bool,
}
impl Watchdog {
/// `places` is the exploration count the run starts with.
pub fn new(rules: Rules, places: u32) -> Self {
Self {
rules,
prev_places: i64::from(places),
prev_idle: false,
prev_busy: false,
prev_unwon: false,
}
}
/// One probe over every event so far.
pub fn probe(&mut self, events: &[Ev], places: u32, at_min: f64) -> Probe {
let rules = &self.rules;
let a = analyze(events, rules);
let delta = i64::from(places) - self.prev_places;
self.prev_places = i64::from(places);
// `grown` is 1 unless the count is known not to have grown.
let grown = delta > 0;
let idle = a.decisions > 0 && a.done == 0 && !grown;
let busy = a.decisions >= rules.busy_min && a.rewards == 0 && !grown;
let unwon = a.fights >= rules.fight_min && a.wins == 0 && !grown;
let failed = a.refused + a.blocked + a.timeout;
let mut reason = None;
if a.decisions > 0 && !grown {
reason = if a.decisions >= rules.min_events
&& failed * 100 >= a.decisions * rules.stall_pct
{
Some("stalled")
} else if idle && self.prev_idle {
Some("zero-progress")
} else if a.distinct <= rules.max_distinct && a.repeats >= rules.min_repeats {
Some("sequence")
} else if a.decisions >= rules.min_events
&& a.top_count * 100 >= a.decisions * rules.dominance_pct
{
Some("dominant")
} else if busy && self.prev_busy {
Some("unrewarded")
} else if unwon && self.prev_unwon {
Some("unwon-battles")
} else {
None
};
}
self.prev_idle = idle;
self.prev_busy = busy;
self.prev_unwon = unwon;
Probe {
at_min,
suspected: reason.is_some(),
reason: reason.map(str::to_owned),
decisions: a.decisions,
distinct: a.distinct,
period: a.period,
repeats: a.repeats,
done: a.done,
failed,
rewards: a.rewards,
fights: a.fights,
wins: a.wins,
places_delta: delta,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn start(ms: f64, name: &'static str) -> [Ev; 2] {
[
Ev::Macro { ms, name, outcome: None },
Ev::Macro { ms: ms + 1.0, name, outcome: Some("done") },
]
}
fn cycle(names: &[&'static str], times: usize) -> Vec<Ev> {
let mut events = Vec::new();
let mut ms = 0.0;
for _ in 0..times {
for name in names {
events.extend(start(ms, name));
ms += 3000.0;
}
}
events
}
#[test]
fn the_viridian_cycle_is_a_sequence_when_nothing_is_explored() {
// GO NPC, GO OUT, NEXT, GO FRONTIER, every three brain seconds, 25 times.
let events = cycle(&["GO NPC", "GO OUT", "NEXT", "GO FRONTIER"], 25);
let a = analyze(&events, &Rules::default());
assert_eq!((a.period, a.repeats, a.distinct), (4, 25, 4));
let mut watchdog = Watchdog::new(Rules::default(), 100);
let probe = watchdog.probe(&events, 100, 5.0);
assert!(probe.suspected);
assert_eq!(probe.reason.as_deref(), Some("sequence"));
// The same sequence on a fly that is still finding places is a long walk, not a loop.
let mut watchdog = Watchdog::new(Rules::default(), 100);
assert!(!watchdog.probe(&events, 101, 5.0).suspected);
}
#[test]
fn a_pad_of_one_refusing_button_is_a_stall() {
let mut events = Vec::new();
for i in 0..30 {
events.push(Ev::Macro {
ms: 1000.0 * i as f64,
name: "GO ROUTE",
outcome: Some("refused"),
});
}
let mut watchdog = Watchdog::new(Rules::default(), 7);
let probe = watchdog.probe(&events, 7, 1.0);
assert_eq!(probe.reason.as_deref(), Some("stalled"));
assert_eq!(probe.failed, 30);
}
#[test]
fn unrewarded_needs_two_probes() {
// Ten distinct names (a period past the cap), all done, no reward, 120 decisions, no new
// ground: row 58's shape. The first probe remembers it and only the second flags.
let names = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"];
let mut events = Vec::new();
let mut ms = 0.0;
for _ in 0..12 {
for name in names {
events.extend(start(ms, name));
ms += 1000.0;
}
}
let mut watchdog = Watchdog::new(Rules::default(), 5);
let first = watchdog.probe(&events, 5, 3.0);
assert!(!first.suspected, "{first:?}");
let second = watchdog.probe(&events, 5, 5.0);
assert_eq!(second.reason.as_deref(), Some("unrewarded"), "{second:?}");
// One new place clears it.
let third = watchdog.probe(&events, 6, 7.0);
assert!(!third.suspected);
}
#[test]
fn rewards_and_rungs_inside_the_window_are_counted() {
let mut events = cycle(&["GO FRONTIER", "NEXT"], 3);
events.push(Ev::Reward { ms: 100.0, kind: "wildwin" });
events.push(Ev::Reward { ms: 200.0, kind: "" });
events.push(Ev::Milestone { ms: 300.0 });
let a = analyze(&events, &Rules::default());
assert_eq!((a.rewards, a.wins, a.progress), (2, 1, 1));
// A reward before the window's start is not in it.
let rules = Rules { window_ms: 1000.0, ..Rules::default() };
let late = analyze(&events, &rules);
assert_eq!(late.rewards, 0);
}
#[test]
fn a_window_with_no_macro_is_not_a_loop() {
let mut watchdog = Watchdog::new(Rules::default(), 5);
let probe = watchdog.probe(&[Ev::Reward { ms: 5.0, kind: "wildwin" }], 5, 5.0);
assert!(!probe.suspected);
assert_eq!(probe.decisions, 0);
}
#[test]
fn the_shortest_period_wins() {
let events = cycle(&["X", "Y"], 40);
let a = analyze(&events, &Rules::default());
assert_eq!((a.period, a.repeats), (2, 40));
}
#[test]
fn fights_without_a_win_flag_on_the_second_probe_only() {
let mut events = Vec::new();
let moves = ["MOVE 1", "MOVE 2"];
let mut ms = 0.0;
// Alternate MOVE n with a varying filler so no short cycle or dominant name forms.
let fillers = ["NEXT", "TALK", "YES", "NO", "BACK", "MENU", "CLOSE"];
for i in 0..30usize {
events.extend(start(ms, moves[i % 2]));
ms += 1000.0;
events.extend(start(ms, fillers[(i * 3 + i / 4) % fillers.len()]));
ms += 1000.0;
}
let rules = Rules { min_repeats: 1000, ..Rules::default() };
let mut watchdog = Watchdog::new(rules, 9);
let first = watchdog.probe(&events, 9, 4.0);
assert!(!first.suspected, "{first:?}");
let second = watchdog.probe(&events, 9, 6.0);
assert_eq!(second.reason.as_deref(), Some("unwon-battles"), "{second:?}");
// A win in the window clears it.
events.push(Ev::Reward { ms: 100.0, kind: "wildwin" });
let third = watchdog.probe(&events, 9, 8.0);
assert!(!third.suspected);
}
}

View file

@ -0,0 +1,79 @@
//! The scorecard on the real cartridge and connectome: a short run per runtime from a real
//! checkpoint. ROM-gated: `FLY_ROM`, `FLY_DOOR_CHECKPOINT` (rom-env.sh) and `data/fafb-v783`;
//! without them each test prints why and returns (source rom-env.sh, or it covers nothing).
//!
//! What it holds:
//! - a run measures something (frames, a pad, macros) and its minutes are the minutes asked for;
//! - the same seed twice is the same run, and two seeds are not (the idle frames);
//! - the session runtime and the legacy loop, from the same checkpoint and seed, give the same
//! report: what the scorecard measures does not depend on which runtime ran it.
use std::path::PathBuf;
use fly_scorecard::runner::{RunSpec, run_legacy, run_session};
use fly_scorecard::tally::RunReport;
use flysim::snapshot::MacroMode;
fn spec(seed: u32) -> Option<RunSpec> {
let rom = std::env::var_os("FLY_ROM").map(PathBuf::from);
let checkpoint = std::env::var_os("FLY_DOOR_CHECKPOINT").map(PathBuf::from);
let dataset = fly_session::legacy_parity::fafb_dir();
let (Some(rom), Some(checkpoint), Some(dataset)) = (rom, checkpoint, dataset) else {
eprintln!("skipping: FLY_ROM, FLY_DOOR_CHECKPOINT or data/fafb-v783 missing");
return None;
};
Some(RunSpec {
id: "door".to_owned(),
checkpoint,
rom,
dataset,
seed,
minutes: 0.4,
threads: 2,
mode: MacroMode::Macros,
tally: RunSpec::tally_config(5.0, 20.0),
})
}
/// A report with what legitimately differs between runs of the same thing blanked.
fn essence(mut report: RunReport) -> RunReport {
report.wall_seconds = 0.0;
report.runtime = String::new();
report
}
#[test]
fn the_legacy_loop_is_measured_reproducibly_and_seeds_differ() {
let (Some(a), Some(b), Some(c)) = (spec(0), spec(3), spec(4)) else { return };
let first = run_legacy(&a).expect("a legacy run");
assert!(first.frames > 1000, "{} frames", first.frames);
assert!((first.minutes - 0.4).abs() < 0.01, "{} minutes", first.minutes);
assert_eq!(first.idle_frames, 0);
assert!(first.macros.starts > 0, "the macro layer dealt nothing");
assert!(first.scenes.values().sum::<u64>() == first.frames);
assert_eq!(essence(first.clone()), essence(run_legacy(&a).expect("a second run")));
let (x, y) = (run_legacy(&b).expect("seed 3"), run_legacy(&c).expect("seed 4"));
assert_ne!(x.idle_frames, y.idle_frames);
assert!(x.idle_frames > 0);
// Different starting points of the brain's own trajectory: the runs need not agree.
eprintln!(
"seed 0/3/4 macro starts {}/{}/{}, pad {:.3}/{:.3}/{:.3}",
first.macros.starts,
x.macros.starts,
y.macros.starts,
first.pad.empty_fraction,
x.pad.empty_fraction,
y.pad.empty_fraction
);
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn the_session_runtime_and_the_legacy_loop_measure_the_same_run() {
let Some(spec) = spec(2) else { return };
let legacy = run_legacy(&spec).expect("the legacy run");
let session = run_session(&spec).await.expect("the session run");
assert_eq!(session.runtime, "session");
assert_eq!(legacy.runtime, "legacy");
assert!(session.frames > 1000);
assert_eq!(essence(legacy), essence(session));
}

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,77 @@
{
"schema": "fly-scorecard-set-v1",
"checkpoints": [
{
"id": "r08-viridian-city",
"rung": 8,
"env": "FLY_SCORECARD_R08_CHECKPOINT",
"note": "Viridian City on its first visit, few places known"
},
{
"id": "r09-viridian-mart",
"rung": 9,
"env": "FLY_ROW66_MART_CHECKPOINT",
"note": "the Viridian mart, rung 9 on the ledger (the shop and ball funnel)"
},
{
"id": "r09-forest-catch",
"rung": 9,
"env": "FLY_CATCH_CHECKPOINT",
"note": "Viridian Forest, one ball in the bag"
},
{
"id": "r09-forest-row60",
"rung": 9,
"env": "FLY_ROW60_CHECKPOINT",
"note": "rung 9, the row 60 state"
},
{
"id": "r10-pewter-center",
"rung": 10,
"env": "FLY_CENTER_CHECKPOINT",
"note": "Pewter City, at the Pokemon Center"
},
{
"id": "r10-pewter-gym",
"rung": 10,
"env": "FLY_ROW67_CHECKPOINT",
"note": "the live Pewter Gym battle"
},
{
"id": "r11-mart",
"rung": 11,
"env": "FLY_MART_CHECKPOINT",
"note": "rung 11, at a mart"
},
{
"id": "r11-badge",
"rung": 11,
"env": "FLY_BADGE_CHECKPOINT",
"note": "Boulder Badge in hand"
},
{
"id": "r12-mt-moon",
"rung": 12,
"env": "FLY_MT_MOON_CHECKPOINT",
"note": "Mt. Moon entered"
},
{
"id": "r12-row64",
"rung": 12,
"env": "FLY_ROW64_CHECKPOINT",
"note": "rung 12, the row 64 live state"
},
{
"id": "r15-yard",
"rung": 15,
"env": "FLY_ROW65_YARD_CHECKPOINT",
"note": "rung 15, a yard past Cerulean"
},
{
"id": "r15-nugget-bridge",
"rung": 15,
"env": "FLY_ROW71_CHECKPOINT",
"note": "Route 25, the bag-window trap's state"
}
]
}

43
tools/scorecard/overlay.sh Executable file
View file

@ -0,0 +1,43 @@
#!/usr/bin/env bash
# Put the scorecard on an older release's tree, so a release that predates the tool can be scored.
#
# tools/scorecard/overlay.sh <scorecard-ref> <target-tree>
#
# Copies the fly-scorecard crate, the checkpoint set and the docs from <scorecard-ref> of this
# repository into <target-tree> (a checkout of the release to score), adds the crate to the
# workspace, and applies the one accessor the session runtime needs
# (`PokeredTask::with_reader`, read-only). Nothing else in the release changes, so the numbers
# are the release's own. A no-op on a tree that already has the tool.
set -euo pipefail
ref="${1:?usage: overlay.sh <scorecard-ref> <target-tree>}"
target="${2:?usage: overlay.sh <scorecard-ref> <target-tree>}"
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# SCORECARD_REPO names the repository holding <scorecard-ref> when this script was extracted
# from it (a copy outside any checkout).
repo="${SCORECARD_REPO:-$(git -C "$here" rev-parse --show-toplevel)}"
ws="$target/services/flysim/Cargo.toml"
task="$target/services/flysim/crates/fly-legacy-session/src/task.rs"
[ -f "$ws" ] && [ -f "$task" ] || { echo "overlay: $target is not a flybrain tree with the session runtime" >&2; exit 1; }
if [ ! -d "$target/services/flysim/crates/fly-scorecard" ]; then
git -C "$repo" archive "$ref" services/flysim/crates/fly-scorecard tools/scorecard docs/scorecard.md \
| tar -x -C "$target"
fi
# One crate source fits releases on both sides of BUS-01: a tree whose LegacyConfig has no
# `transport`/`placements` fields loses the lines that set them (marked `overlay:bus01`).
comp="$target/services/flysim/crates/fly-legacy-session/src/composition.rs"
if ! grep -q 'pub placements:' "$comp" 2>/dev/null; then
sed -i '/overlay:bus01/d' "$target/services/flysim/crates/fly-scorecard/src/runner.rs"
fi
if ! grep -q '"crates/fly-scorecard"' "$ws"; then
sed -i 's#^ "crates/flysim-store",# "crates/flysim-store",\n "crates/fly-scorecard",#' "$ws"
grep -q '"crates/fly-scorecard"' "$ws" || { echo "overlay: could not add the crate to the workspace" >&2; exit 1; }
fi
if ! grep -q 'pub fn with_reader' "$task"; then
(cd "$target" && git apply --recount "$here/with-reader.patch" 2>/dev/null) \
|| (cd "$target" && patch -p1 --forward < "$here/with-reader.patch") \
|| { echo "overlay: with-reader.patch does not apply to this tree" >&2; exit 1; }
fi
echo "overlay: scorecard from $ref on $target"

View file

@ -0,0 +1,24 @@
diff --git a/services/flysim/crates/fly-legacy-session/src/task.rs b/services/flysim/crates/fly-legacy-session/src/task.rs
index f85694e..2cd14c2 100644
--- a/services/flysim/crates/fly-legacy-session/src/task.rs
+++ b/services/flysim/crates/fly-legacy-session/src/task.rs
@@ -368,6 +368,19 @@ impl PokeredTask {
)
}
+ /// Read the committed boundary's memory image through the cartridge, as the macro engine
+ /// reads it, for a harness that measures play (the scorecard). `None` before the first
+ /// observation. Changes nothing.
+ pub fn with_reader<R>(
+ &self,
+ f: impl FnOnce(&mut dyn flybrain_gb::MemoryReader) -> R,
+ ) -> Option<R> {
+ let inner = self.lock();
+ let (_, image) = inner.current.as_ref()?;
+ let mut reader = ImageReader::new(image, &inner.cartridge);
+ Some(f(&mut reader))
+ }
+
/// The brain time of the last transition (its Prepare's clock), in ms: `network.ms`.
pub fn brain_ms(&self) -> f64 {
self.lock().ms