Weksa/crates/weksa/src/run.rs
Weksa fd0c3b0edb Round: means count a refused item as 0, a failed round discards its packets, the round line is pinned
Validation and Train means are over every item of the split with scored counts
beside them, so refusing a weak item cannot raise a mean. A round that fails
before its record is put (embedder down) removes its packets.cc, and a round
starts from none, so a rerun with revised answers is not refused as a changed
packet. RoundRecord::summary_line owns the printed line and is pinned with exact
values. The RoundRecord compile_fail doctest gives every field and fails on
E0451, with its twin literal in a lib unit test.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 04:14:39 +00:00

738 lines
25 KiB
Rust

//! One golf-loop run: the stores it pinned at open, the rounds it has recorded,
//! and the one writer of both (`RunStores::create` and, for rounds, `round`).
//!
//! A run pins its corpus and entity store files by canonical path and FNV-1a 64
//! digest of their bytes. Every round reopens them only from that record and
//! refuses on drift, and every round record carries the digests. Nothing inside
//! a process whose writer controls the code can stop an item faked into a
//! scratch store; what this makes true is that a run over a scratch store is a
//! different run with a different corpus digest, visible in its record, and a
//! later reader compares the rounds of one run only. `RunStores` is the one
//! public producer of [`TrainItems`] and [`EncoderOffer`]: the CLI paths that
//! take caller stores (`validate`, `packet proof|dao`, `lower`) are unchanged.
use std::fmt;
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use cultcache_rs::{CultCache, DatabaseEntry};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::context::{EncoderOffer, Prompt, TrainItems};
use crate::corpus::{CorpusItem, CorpusItemId};
use crate::encode::{PacketDraft, encoder_id};
use crate::form::{is_attestation, is_slug};
use crate::lower::lower;
use crate::model::{ModelPort, PortError};
use crate::score::{CHRF_VERSION, Embedder, ItemScore, ScoreInput, Scorer, SplitMean, aggregate};
use crate::split::{Split, SplitScheme, fnv1a64, hex16};
use crate::store::{CorpusStore, EntityStore, InventoryStore, PacketStore, open_cache};
/// The digest of the prompt builder's source. Any edit to `context.rs`,
/// comments included, ends a run; code outside that file is not covered.
pub const PROMPT_SOURCE_DIGEST: u64 = fnv1a64(include_bytes!("context.rs"));
/// The digest of the lowerer's source. Any edit to `lower.rs`, comments
/// included, ends a run; code outside that file is not covered.
pub const LOWERER_SOURCE_DIGEST: u64 = fnv1a64(include_bytes!("lower.rs"));
/// What a run pinned at open. Key `run:<label>`.
#[derive(Clone, Debug, PartialEq, Eq, JsonSchema, DatabaseEntry)]
#[cultcache(type = "weksa.loop_run")]
pub struct RunRecord {
#[cultcache(key = 0)]
pub label: String,
/// Canonical absolute path of the corpus store.
#[cultcache(key = 1)]
pub corpus: String,
#[cultcache(key = 2)]
pub inventory: String,
#[cultcache(key = 3)]
pub entities: String,
/// 16 hex of the corpus file's bytes.
#[cultcache(key = 4)]
pub corpus_digest: String,
#[cultcache(key = 5)]
pub entity_digest: String,
#[cultcache(key = 6)]
pub prompt_digest: String,
#[cultcache(key = 7)]
pub lowerer_digest: String,
/// The answering model.
#[cultcache(key = 8)]
pub model: String,
/// The embedder's model.
#[cultcache(key = 9)]
pub embedder: String,
#[cultcache(key = 10)]
pub chrf_version: String,
}
/// Where a round refused: the first stage that did.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub enum Stage {
Parse,
Admit,
Lower,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub enum Outcome {
Scored { chrf: f64, meaning: Option<f64> },
Refused(Stage),
}
/// One model call: the prompt's digest and the item keys it held.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct Call {
pub prompt: String,
pub items: Vec<String>,
}
/// A Train item's row. Validation has no rows.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct TrainRow {
pub item: String,
pub packet: Option<String>,
pub outcome: Outcome,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct RefusalCounts {
pub parse: u32,
pub admit: u32,
pub lower: u32,
}
/// One scored round. It holds no text and no Test reading: per-item rows for
/// Train only, Validation only as means and refusal counts by stage. Only
/// `run::round` builds one.
///
/// ```
/// fn f(r: &weksa::run::RoundRecord) -> u32 { r.n() }
/// ```
///
/// Every field is given, so the literal below fails only on privacy; its twin
/// is the same literal in the unit test `a_round_record_literal_compiles_in_the_lib`.
///
/// ```compile_fail,E0451
/// use weksa::run::{RefusalCounts, RoundRecord};
/// use weksa::score::SplitMean;
/// fn f() -> RoundRecord {
/// RoundRecord {
/// n: 1,
/// inventory_rev: 1,
/// prompt_digest: String::new(),
/// lowerer_digest: String::new(),
/// corpus_digest: String::new(),
/// entity_digest: String::new(),
/// model: String::new(),
/// embedder: String::new(),
/// chrf_version: String::new(),
/// calls: vec![],
/// train: vec![],
/// train_mean: SplitMean::default(),
/// train_scored: 0,
/// validation_mean: SplitMean::default(),
/// validation_scored: 0,
/// validation_refused: RefusalCounts::default(),
/// }
/// }
/// ```
#[derive(Clone, Debug, PartialEq, JsonSchema, DatabaseEntry)]
#[cultcache(type = "weksa.loop_round")]
pub struct RoundRecord {
#[cultcache(key = 0)]
n: u32,
#[cultcache(key = 1)]
inventory_rev: u32,
#[cultcache(key = 2)]
prompt_digest: String,
#[cultcache(key = 3)]
lowerer_digest: String,
#[cultcache(key = 4)]
corpus_digest: String,
#[cultcache(key = 5)]
entity_digest: String,
#[cultcache(key = 6)]
model: String,
#[cultcache(key = 7)]
embedder: String,
#[cultcache(key = 8)]
chrf_version: String,
#[cultcache(key = 9)]
calls: Vec<Call>,
#[cultcache(key = 10)]
train: Vec<TrainRow>,
#[cultcache(key = 11)]
train_mean: SplitMean,
#[cultcache(key = 12)]
validation_mean: SplitMean,
#[cultcache(key = 13)]
validation_refused: RefusalCounts,
/// Train items that lowered and scored; `train_mean` is over all of them
/// and counts a refused item as 0.
#[cultcache(key = 14)]
train_scored: u32,
/// Validation items that lowered and scored; `validation_mean` is over all
/// of them and counts a refused item as 0, so refusing a weak item cannot
/// raise it.
#[cultcache(key = 15)]
validation_scored: u32,
}
impl RoundRecord {
pub fn n(&self) -> u32 {
self.n
}
pub fn inventory_rev(&self) -> u32 {
self.inventory_rev
}
pub fn prompt_digest(&self) -> &str {
&self.prompt_digest
}
pub fn lowerer_digest(&self) -> &str {
&self.lowerer_digest
}
pub fn corpus_digest(&self) -> &str {
&self.corpus_digest
}
pub fn entity_digest(&self) -> &str {
&self.entity_digest
}
pub fn model(&self) -> &str {
&self.model
}
pub fn embedder(&self) -> &str {
&self.embedder
}
pub fn chrf_version(&self) -> &str {
&self.chrf_version
}
pub fn calls(&self) -> &[Call] {
&self.calls
}
pub fn train(&self) -> &[TrainRow] {
&self.train
}
pub fn train_mean(&self) -> &SplitMean {
&self.train_mean
}
pub fn validation_mean(&self) -> &SplitMean {
&self.validation_mean
}
pub fn validation_refused(&self) -> RefusalCounts {
self.validation_refused
}
pub fn train_scored(&self) -> u32 {
self.train_scored
}
pub fn validation_scored(&self) -> u32 {
self.validation_scored
}
/// The one line a recorded round prints. `n` is every item of the split,
/// `scored` those that lowered; a mean counts a refused item as 0.
pub fn summary_line(&self) -> String {
let mean = |value: Option<f64>, places: usize| {
value.map_or("none".to_string(), |v| format!("{v:.places$}"))
};
let refused = self
.train
.iter()
.filter(|row| matches!(row.outcome, Outcome::Refused(_)))
.count();
let (t, v, x) = (
&self.train_mean,
&self.validation_mean,
self.validation_refused,
);
format!(
"round {} rev {} train n={} scored={} chrf={} meaning={} refused={refused} validation n={} scored={} chrf={} meaning={} refused parse={} admit={} lower={}",
self.n,
self.inventory_rev,
t.count,
self.train_scored,
mean(t.chrf, 2),
mean(t.meaning, 4),
v.count,
self.validation_scored,
mean(v.chrf, 2),
mean(v.meaning, 4),
x.parse,
x.admit,
x.lower,
)
}
}
/// What a pinned store or id drifted from.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DriftOf {
Corpus,
Entities,
Prompts,
Lowerer,
Model,
Embedder,
}
/// A run's failure. Display and Debug name a kind, never a path, key, label or
/// any other value the caller supplied.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum RunError {
/// `run.cc` already holds a run.
Exists,
/// `run.cc` holds no run.
NoRun,
/// A field that cannot be a run's: `label`, `model`, `embedder`, `path`.
Malformed(&'static str),
Drift(DriftOf),
/// The inventory store holds no revision.
NoInventory,
Io(ErrorKind),
/// A store or the run file would not read or write.
Store,
/// The embedder failed.
Embed,
}
impl fmt::Display for RunError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
RunError::Exists => f.write_str("the root already holds a run"),
RunError::NoRun => f.write_str("the root holds no run"),
RunError::Malformed(what) => write!(f, "malformed {what}"),
RunError::Drift(of) => write!(f, "drift in {of:?}"),
RunError::NoInventory => f.write_str("the inventory holds no revision"),
RunError::Io(kind) => write!(f, "io error {kind:?}"),
RunError::Store => f.write_str("a store would not read or write"),
RunError::Embed => f.write_str("the embedder failed"),
}
}
}
impl fmt::Debug for RunError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl std::error::Error for RunError {}
/// The three stores a run pins.
#[derive(Clone, Copy)]
pub struct RunPaths<'a> {
pub corpus: &'a Path,
pub inventory: &'a Path,
pub entities: &'a Path,
}
/// A run's open stores, reopened only from its record. The one public producer
/// of [`TrainItems`] and [`EncoderOffer`], and the only writer of `run.cc`.
pub struct RunStores {
root: PathBuf,
cache: CultCache,
record: RunRecord,
corpus: CorpusStore,
inventory: InventoryStore,
entities: EntityStore,
}
fn file_digest(path: &str) -> Option<String> {
std::fs::read(path).ok().map(|b| hex16(fnv1a64(&b)))
}
fn canonical(path: &Path) -> Result<String, RunError> {
std::fs::canonicalize(path)
.map_err(|e| RunError::Io(e.kind()))?
.into_os_string()
.into_string()
.map_err(|_| RunError::Malformed("path"))
}
fn run_cache(root: &Path) -> Result<CultCache, RunError> {
open_cache(&root.join("run.cc"), |c| {
c.register_entry_type::<RunRecord>()?;
c.register_entry_type::<RoundRecord>()
})
.map_err(|_| RunError::Store)
}
fn one_run(cache: &CultCache) -> Result<Option<RunRecord>, RunError> {
Ok(cache
.get_all::<RunRecord>()
.map_err(|_| RunError::Store)?
.into_iter()
.next())
}
impl RunStores {
/// Pins the three stores at `root`, which must hold no run. A store file
/// that does not exist is `Io(NotFound)`.
pub fn create(
root: &Path,
label: &str,
paths: RunPaths<'_>,
model: &str,
embedder: &str,
) -> Result<Self, RunError> {
if !is_slug(label) {
return Err(RunError::Malformed("label"));
}
if !is_attestation(model) {
return Err(RunError::Malformed("model"));
}
if !is_attestation(embedder) {
return Err(RunError::Malformed("embedder"));
}
let mut cache = run_cache(root)?;
if one_run(&cache)?.is_some() {
return Err(RunError::Exists);
}
let record = RunRecord {
label: label.to_string(),
corpus: canonical(paths.corpus)?,
inventory: canonical(paths.inventory)?,
entities: canonical(paths.entities)?,
corpus_digest: String::new(),
entity_digest: String::new(),
prompt_digest: hex16(PROMPT_SOURCE_DIGEST),
lowerer_digest: hex16(LOWERER_SOURCE_DIGEST),
model: model.to_string(),
embedder: embedder.to_string(),
chrf_version: CHRF_VERSION.to_string(),
};
let record = RunRecord {
corpus_digest: file_digest(&record.corpus).ok_or(RunError::Store)?,
entity_digest: file_digest(&record.entities).ok_or(RunError::Store)?,
..record
};
cache
.put(format!("run:{label}"), &record)
.map_err(|_| RunError::Store)?;
Self::with(root, cache, record)
}
/// Reopens the run at `root` from its record, refusing when a pinned store
/// or the prompt or lowerer source no longer matches.
pub fn open(root: &Path) -> Result<Self, RunError> {
if !root.join("run.cc").is_file() {
return Err(RunError::NoRun);
}
let cache = run_cache(root)?;
let record = one_run(&cache)?.ok_or(RunError::NoRun)?;
if record.prompt_digest != hex16(PROMPT_SOURCE_DIGEST) {
return Err(RunError::Drift(DriftOf::Prompts));
}
if record.lowerer_digest != hex16(LOWERER_SOURCE_DIGEST) {
return Err(RunError::Drift(DriftOf::Lowerer));
}
if file_digest(&record.corpus).as_ref() != Some(&record.corpus_digest) {
return Err(RunError::Drift(DriftOf::Corpus));
}
if file_digest(&record.entities).as_ref() != Some(&record.entity_digest) {
return Err(RunError::Drift(DriftOf::Entities));
}
Self::with(root, cache, record)
}
fn with(root: &Path, cache: CultCache, record: RunRecord) -> Result<Self, RunError> {
let store = |_| RunError::Store;
Ok(Self {
root: root.to_path_buf(),
corpus: CorpusStore::open(Path::new(&record.corpus)).map_err(store)?,
inventory: InventoryStore::open(Path::new(&record.inventory)).map_err(store)?,
entities: EntityStore::open(Path::new(&record.entities)).map_err(store)?,
cache,
record,
})
}
pub fn record(&self) -> &RunRecord {
&self.record
}
pub fn inventory(&self) -> &InventoryStore {
&self.inventory
}
/// The pinned entity store, for lowering and admission.
pub fn entities(&self) -> &EntityStore {
&self.entities
}
/// The live Train items of the pinned corpus.
pub fn train(&self) -> anyhow::Result<TrainItems> {
TrainItems::from_corpus(&self.corpus)
}
/// The offer for `key`; the inner error is the gate's refusal. An absent
/// key is an error that names no key.
pub fn offer(
&self,
key: &str,
) -> anyhow::Result<Result<EncoderOffer<'static>, crate::context::OfferRefusal>> {
let item = self
.corpus
.get(key)?
.ok_or_else(|| anyhow::anyhow!("no such item"))?;
Ok(EncoderOffer::for_round(&item))
}
/// The live Train and Validation offers, in key order. Items the gate
/// refuses are skipped and read no further.
pub fn offers(&self) -> anyhow::Result<Vec<EncoderOffer<'static>>> {
Ok(self
.corpus
.all()?
.iter()
.filter_map(|item| EncoderOffer::for_round(item).ok())
.collect())
}
/// The recorded rounds, in order.
pub fn rounds(&self) -> anyhow::Result<Vec<RoundRecord>> {
let mut rounds = self.cache.get_all::<RoundRecord>()?;
rounds.sort_by_key(RoundRecord::n);
Ok(rounds)
}
/// `<root>/round-<n>` for the next unrecorded round `n`.
pub fn next_round_dir(&self) -> anyhow::Result<PathBuf> {
Ok(self
.root
.join(format!("round-{}", self.rounds()?.len() + 1)))
}
}
/// What a round came to.
#[derive(Debug)]
pub enum RoundOutcome {
/// Prompts nobody has answered; nothing was written to the run or admitted.
Unanswered {
prompts: Vec<String>,
},
Recorded(RoundRecord),
}
/// How one item fared: where it was refused, or the text it lowered to, with
/// the key of the packet that was admitted for it.
enum Fate {
Refused(Stage, Option<String>),
Lowered(String, String),
}
/// One round: encodes every live Train and Validation item of the run's pinned
/// corpus through `model`, admits each packet into the round's own
/// `<root>/round-<n>/packets.cc`, lowers, scores, and records the round. The
/// round is all or nothing: while any prompt is unanswered, nothing is written,
/// and a round that fails before its record is put (the embedder down) leaves no
/// `packets.cc` behind, so a rerun with revised answers starts clean. A mean
/// counts an item that was refused or did not lower as 0, so refusing a weak
/// item cannot raise it; `scored` counts beside it say how many were real.
pub fn round<M: ModelPort, E: Embedder>(
run: &mut RunStores,
model: &mut M,
scorer: &Scorer<E>,
) -> Result<RoundOutcome, RunError> {
let store = |_| RunError::Store;
if model.model() != run.record.model {
return Err(RunError::Drift(DriftOf::Model));
}
if scorer.embedder().model() != run.record.embedder {
return Err(RunError::Drift(DriftOf::Embedder));
}
let inventory = run.inventory.inventory().map_err(store)?;
let rev = inventory.latest().ok_or(RunError::NoInventory)?.n;
let train = run.train().map_err(store)?;
let mut calls = Vec::new();
let mut answers = Vec::new();
let mut unanswered = Vec::new();
for offer in run.offers().map_err(store)? {
let prompt = Prompt::encode(&offer, &train, &inventory, rev);
match model.answer(&prompt) {
Ok(answer) => answers.push((offer.key().to_string(), answer)),
Err(PortError::Unanswered) => unanswered.push(prompt.digest()),
Err(PortError::Io(kind)) => return Err(RunError::Io(kind)),
}
calls.push(Call {
prompt: prompt.digest(),
items: prompt.item_keys().to_vec(),
});
}
if !unanswered.is_empty() {
return Ok(RoundOutcome::Unanswered {
prompts: unanswered,
});
}
let dir = run.next_round_dir().map_err(store)?;
std::fs::create_dir_all(&dir).map_err(|e| RunError::Io(e.kind()))?;
// The directory of an unrecorded round holds only a failed attempt's packets.
discard_packets(&dir);
let mut packets = PacketStore::open(&dir.join("packets.cc")).map_err(store)?;
let encoder = encoder_id(model.model(), &run.record.prompt_digest);
let mut items: Vec<CorpusItem> = Vec::new();
let mut fates: Vec<Fate> = Vec::new();
for (key, answer) in &answers {
let item = run.corpus.get(key).map_err(store)?.ok_or(RunError::Store)?;
let id = CorpusItemId::parse(key).map_err(|_| RunError::Store)?;
let fate = match PacketDraft::parse(answer) {
Err(_) => Fate::Refused(Stage::Parse, None),
Ok(draft) => {
let packet = draft.into_packet(&id, rev, &encoder);
let packet_key = packet.id.to_string();
match packets.admit(packet, &run.inventory, &run.corpus, &run.entities) {
Err(_) => Fate::Refused(Stage::Admit, None),
Ok(view) => match lower(&view, &inventory, &run.entities) {
Err(_) => Fate::Refused(Stage::Lower, Some(packet_key)),
Ok(text) => Fate::Lowered(text, packet_key),
},
}
}
};
items.push(item);
fates.push(fate);
}
// One score call over what lowered; none when nothing did.
let lowered: Vec<(usize, &str)> = fates
.iter()
.enumerate()
.filter_map(|(i, fate)| match fate {
Fate::Lowered(text, _) => Some((i, text.as_str())),
Fate::Refused(..) => None,
})
.collect();
let inputs: Vec<ScoreInput> = lowered
.iter()
.map(|(i, text)| ScoreInput {
reference: &items[*i].text,
output: text,
})
.collect();
let scores = if inputs.is_empty() {
Vec::new()
} else {
match scorer.score(&inputs) {
Ok(scores) => scores,
Err(_) => {
discard_packets(&dir);
return Err(RunError::Embed);
}
}
};
let mut score_at: Vec<Option<ItemScore>> = vec![None; items.len()];
for ((i, _), score) in lowered.iter().zip(scores) {
score_at[*i] = Some(score);
}
// An item that did not lower scores 0 in every mean.
let nothing = ItemScore {
chrf: 0.0,
meaning: Some(0.0),
};
let scored: Vec<(&CorpusItem, ItemScore)> = items
.iter()
.zip(&score_at)
.map(|(item, score)| (item, score.clone().unwrap_or_else(|| nothing.clone())))
.collect();
let means = aggregate(&scored);
let mut train_rows = Vec::new();
let mut refused = RefusalCounts::default();
let (mut train_scored, mut validation_scored) = (0, 0);
for ((item, fate), score) in items.iter().zip(&fates).zip(&score_at) {
let (outcome, packet) = match (fate, score) {
(Fate::Lowered(_, key), Some(score)) => (
Outcome::Scored {
chrf: score.chrf,
meaning: score.meaning,
},
Some(key.clone()),
),
(Fate::Refused(stage, key), _) => (Outcome::Refused(*stage), key.clone()),
(Fate::Lowered(..), None) => return Err(RunError::Store),
};
match (SplitScheme::V1.live(item), fate) {
(Some(Split::Train), fate) => {
train_scored += u32::from(matches!(fate, Fate::Lowered(..)));
train_rows.push(TrainRow {
item: item.id.clone(),
packet,
outcome,
});
}
(Some(Split::Validation), Fate::Lowered(..)) => validation_scored += 1,
(Some(Split::Validation), Fate::Refused(stage, _)) => match stage {
Stage::Parse => refused.parse += 1,
Stage::Admit => refused.admit += 1,
Stage::Lower => refused.lower += 1,
},
_ => {}
}
}
let n = run.rounds().map_err(store)?.len() as u32 + 1;
let record = RoundRecord {
n,
inventory_rev: rev,
prompt_digest: run.record.prompt_digest.clone(),
lowerer_digest: run.record.lowerer_digest.clone(),
corpus_digest: run.record.corpus_digest.clone(),
entity_digest: run.record.entity_digest.clone(),
model: run.record.model.clone(),
embedder: run.record.embedder.clone(),
chrf_version: run.record.chrf_version.clone(),
calls,
train: train_rows,
train_mean: means.train,
validation_mean: means.validation,
validation_refused: refused,
train_scored,
validation_scored,
};
run.cache
.put(format!("run:{}:round:{n}", run.record.label), &record)
.map_err(store)?;
Ok(RoundOutcome::Recorded(record))
}
/// Removes a round directory's packet store and its lock.
fn discard_packets(dir: &Path) {
for name in ["packets.cc", "packets.cc.lock"] {
let _ = std::fs::remove_file(dir.join(name));
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The twin of the `RoundRecord` literal in its compile_fail doctest: the
/// same fields, compiling here because the fields are private to this module.
#[test]
fn a_round_record_literal_compiles_in_the_lib() {
let r = RoundRecord {
n: 1,
inventory_rev: 1,
prompt_digest: String::new(),
lowerer_digest: String::new(),
corpus_digest: String::new(),
entity_digest: String::new(),
model: String::new(),
embedder: String::new(),
chrf_version: String::new(),
calls: vec![],
train: vec![],
train_mean: SplitMean::default(),
train_scored: 0,
validation_mean: SplitMean::default(),
validation_scored: 0,
validation_refused: RefusalCounts::default(),
};
assert_eq!(r.n(), 1);
}
}