RunStores is the one public producer of TrainItems and EncoderOffer: a run pins its corpus and entity stores by digest
TrainItems::from_corpus and EncoderOffer::for_round become pub(crate). RunStores (run.rs) creates a run over three stores, records their canonical paths and FNV-1a 64 digests plus the prompt and lowerer source digests in run.cc, and reopens only from that record, refusing on drift. RunRecord and RoundRecord are published CultCache types. tests/context.rs and the context.rs doctests move to RunStores; the two mutated-clone gate cases become a unit test. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
2be0a35ae7
commit
e7b4d9a68b
13 changed files with 1029 additions and 71 deletions
|
|
@ -3,8 +3,14 @@
|
|||
//! [`TrainItems`] or by encoding one item an [`EncoderOffer`] holds: Train-only
|
||||
//! minting and per-item encoding (leak-owned-by-flow-and-scorer-3,
|
||||
//! loop-context-builder-2). Instruction text is [`MINT_INSTRUCTIONS`] and
|
||||
//! [`ENCODE_INSTRUCTIONS`], consts in this module, and nothing else: `mint` and
|
||||
//! `encode` take none, so no run-time text can become instructions.
|
||||
//! [`ENCODE_INSTRUCTIONS`], consts in this module; an encode prompt also lists
|
||||
//! the inventory at the run's revision.
|
||||
//!
|
||||
//! Item blocks are data from the run's pinned corpus, reached only through
|
||||
//! `RunStores`, the one public producer of `TrainItems` and `EncoderOffer`
|
||||
//! (forged-item-text-in-prompt). A forged item in a scratch store is a different
|
||||
//! run with a different corpus digest, visible in its record; nothing inside a
|
||||
//! process its forger controls can stop it.
|
||||
|
||||
use std::marker::PhantomData;
|
||||
|
||||
|
|
@ -25,9 +31,12 @@ pub const ENCODE_INSTRUCTIONS: &str = "Encode the line below.";
|
|||
/// item.
|
||||
///
|
||||
/// ```
|
||||
/// let dir = tempfile::tempdir().unwrap();
|
||||
/// let store = weksa::CorpusStore::open(&dir.path().join("c.cc")).unwrap();
|
||||
/// let t = weksa::context::TrainItems::from_corpus(&store).unwrap();
|
||||
/// # let dir = tempfile::tempdir().unwrap();
|
||||
/// # let p = |n: &str| dir.path().join(n);
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e").unwrap();
|
||||
/// let t = run.train().unwrap();
|
||||
/// assert!(t.is_empty());
|
||||
/// ```
|
||||
///
|
||||
|
|
@ -36,17 +45,23 @@ pub const ENCODE_INSTRUCTIONS: &str = "Encode the line below.";
|
|||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// let dir = tempfile::tempdir().unwrap();
|
||||
/// let store = weksa::CorpusStore::open(&dir.path().join("c.cc")).unwrap();
|
||||
/// let t = weksa::context::TrainItems::from_corpus(&store).unwrap();
|
||||
/// # let dir = tempfile::tempdir().unwrap();
|
||||
/// # let p = |n: &str| dir.path().join(n);
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e").unwrap();
|
||||
/// let t = run.train().unwrap();
|
||||
/// let _u = t.clone();
|
||||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// fn s<T: serde::Serialize>(_: &T) {}
|
||||
/// let dir = tempfile::tempdir().unwrap();
|
||||
/// let store = weksa::CorpusStore::open(&dir.path().join("c.cc")).unwrap();
|
||||
/// let t = weksa::context::TrainItems::from_corpus(&store).unwrap();
|
||||
/// # let dir = tempfile::tempdir().unwrap();
|
||||
/// # let p = |n: &str| dir.path().join(n);
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e").unwrap();
|
||||
/// let t = run.train().unwrap();
|
||||
/// s(&t);
|
||||
/// ```
|
||||
pub struct TrainItems {
|
||||
|
|
@ -54,7 +69,7 @@ pub struct TrainItems {
|
|||
}
|
||||
|
||||
impl TrainItems {
|
||||
pub fn from_corpus(corpus: &CorpusStore) -> anyhow::Result<Self> {
|
||||
pub(crate) fn from_corpus(corpus: &CorpusStore) -> anyhow::Result<Self> {
|
||||
let items = corpus
|
||||
.all()?
|
||||
.into_iter()
|
||||
|
|
@ -134,8 +149,9 @@ pub struct EncoderOffer<'cp> {
|
|||
}
|
||||
|
||||
impl<'cp> EncoderOffer<'cp> {
|
||||
/// A round offers Train and Validation items.
|
||||
pub fn for_round(item: &CorpusItem) -> Result<EncoderOffer<'static>, OfferRefusal> {
|
||||
/// A round offers Train and Validation items. `RunStores::offer` and
|
||||
/// `RunStores::offers` are the public producers.
|
||||
pub(crate) fn for_round(item: &CorpusItem) -> Result<EncoderOffer<'static>, OfferRefusal> {
|
||||
match Self::gate(item)? {
|
||||
Split::Test => Err(OfferRefusal::TestBeforeCheckpoint),
|
||||
_ => Ok(Self::of(item)),
|
||||
|
|
@ -188,9 +204,12 @@ impl<'cp> EncoderOffer<'cp> {
|
|||
/// constructors are [`Prompt::mint`] and [`Prompt::encode`].
|
||||
///
|
||||
/// ```
|
||||
/// let dir = tempfile::tempdir().unwrap();
|
||||
/// let store = weksa::CorpusStore::open(&dir.path().join("c.cc")).unwrap();
|
||||
/// let t = weksa::context::TrainItems::from_corpus(&store).unwrap();
|
||||
/// # let dir = tempfile::tempdir().unwrap();
|
||||
/// # let p = |n: &str| dir.path().join(n);
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e").unwrap();
|
||||
/// let t = run.train().unwrap();
|
||||
/// let p = weksa::context::Prompt::mint(&t);
|
||||
/// assert_eq!(p.text(), weksa::context::MINT_INSTRUCTIONS);
|
||||
/// ```
|
||||
|
|
@ -198,17 +217,23 @@ impl<'cp> EncoderOffer<'cp> {
|
|||
/// Instructions are not a parameter:
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// let dir = tempfile::tempdir().unwrap();
|
||||
/// let store = weksa::CorpusStore::open(&dir.path().join("c.cc")).unwrap();
|
||||
/// let t = weksa::context::TrainItems::from_corpus(&store).unwrap();
|
||||
/// # let dir = tempfile::tempdir().unwrap();
|
||||
/// # let p = |n: &str| dir.path().join(n);
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e").unwrap();
|
||||
/// let t = run.train().unwrap();
|
||||
/// let p = weksa::context::Prompt::mint("x", &t);
|
||||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// fn s<T: serde::Serialize>(_: &T) {}
|
||||
/// let dir = tempfile::tempdir().unwrap();
|
||||
/// let store = weksa::CorpusStore::open(&dir.path().join("c.cc")).unwrap();
|
||||
/// let t = weksa::context::TrainItems::from_corpus(&store).unwrap();
|
||||
/// # let dir = tempfile::tempdir().unwrap();
|
||||
/// # let p = |n: &str| dir.path().join(n);
|
||||
/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); }
|
||||
/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") };
|
||||
/// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e").unwrap();
|
||||
/// let t = run.train().unwrap();
|
||||
/// let p = weksa::context::Prompt::mint(&t);
|
||||
/// s(&p);
|
||||
/// ```
|
||||
|
|
@ -303,6 +328,20 @@ mod tests {
|
|||
assert_eq!(check(&both), Some(OfferRefusal::Withdrawn));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_offer_gate_precedence() {
|
||||
let round = |i: &CorpusItem| EncoderOffer::for_round(i).err();
|
||||
let mut no_split = item("item:c:2", "m", &group_in(Split::Test), true);
|
||||
no_split.withdrawn = true;
|
||||
// Withdrawn wins over NoSplit.
|
||||
assert_eq!(round(&no_split), Some(OfferRefusal::Withdrawn));
|
||||
// A withdrawn Test item is Withdrawn, not TestBeforeCheckpoint.
|
||||
let mut test = item("item:c:1", "x", &group_in(Split::Test), false);
|
||||
assert_eq!(round(&test), Some(OfferRefusal::TestBeforeCheckpoint));
|
||||
test.withdrawn = true;
|
||||
assert_eq!(round(&test), Some(OfferRefusal::Withdrawn));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkpoint_offers_each_item_once() {
|
||||
let mut cp = Checkpoint::for_test(1);
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ pub mod inventory;
|
|||
pub mod lower;
|
||||
pub mod packet;
|
||||
pub mod phones;
|
||||
pub mod run;
|
||||
pub mod schema;
|
||||
pub mod score;
|
||||
pub mod speaker;
|
||||
|
|
|
|||
433
crates/weksa/src/run.rs
Normal file
433
crates/weksa/src/run.rs
Normal file
|
|
@ -0,0 +1,433 @@
|
|||
//! 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, TrainItems};
|
||||
use crate::form::{is_attestation, is_slug};
|
||||
use crate::score::{CHRF_VERSION, SplitMean};
|
||||
use crate::split::{fnv1a64, hex16};
|
||||
use crate::store::{CorpusStore, EntityStore, InventoryStore, 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() }
|
||||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// fn f() -> weksa::run::RoundRecord {
|
||||
/// weksa::run::RoundRecord { n: 1 }
|
||||
/// }
|
||||
/// ```
|
||||
#[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,
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)))
|
||||
}
|
||||
}
|
||||
|
|
@ -5,6 +5,7 @@ use crate::corpus::CorpusItem;
|
|||
use crate::entity::Entity;
|
||||
use crate::inventory::{InventoryEntry, InventoryRevision};
|
||||
use crate::packet::Packet;
|
||||
use crate::run::{RoundRecord, RunRecord};
|
||||
use crate::speaker::{Scene, Speaker};
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use schemars::{JsonSchema, schema_for};
|
||||
|
|
@ -24,5 +25,7 @@ pub fn published() -> Vec<(String, String)> {
|
|||
published_for::<Entity>(),
|
||||
published_for::<Speaker>(),
|
||||
published_for::<Scene>(),
|
||||
published_for::<RunRecord>(),
|
||||
published_for::<RoundRecord>(),
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,8 @@ mod embed;
|
|||
mod words;
|
||||
|
||||
use anyhow::{Result, ensure};
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use chrf::{CHRF_VERSION, chrf};
|
||||
pub use diagnostics::{OrderCoverage, PairChrf, SplitLeak, WorstItem, leak_diagnostic};
|
||||
|
|
@ -102,7 +104,7 @@ impl<E: Embedder> Scorer<E> {
|
|||
}
|
||||
|
||||
/// Mean scores of one derived split.
|
||||
#[derive(Clone, Debug, PartialEq, Default)]
|
||||
#[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct SplitMean {
|
||||
pub count: usize,
|
||||
/// `None` when the split has no items.
|
||||
|
|
|
|||
|
|
@ -24,15 +24,22 @@ pub enum SplitScheme {
|
|||
V1,
|
||||
}
|
||||
|
||||
pub fn fnv1a64(bytes: &[u8]) -> u64 {
|
||||
pub const fn fnv1a64(bytes: &[u8]) -> u64 {
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for b in bytes {
|
||||
h ^= u64::from(*b);
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
h ^= bytes[i] as u64;
|
||||
h = h.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
i += 1;
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
/// 16 lowercase hex digits, zero-padded: how a digest is written everywhere.
|
||||
pub(crate) fn hex16(n: u64) -> String {
|
||||
format!("{n:016x}")
|
||||
}
|
||||
|
||||
impl SplitScheme {
|
||||
/// 0..100, FNV-1a 64 of `weksa-split-v1:` + group, mod 100.
|
||||
pub fn bucket(self, group: &str) -> u64 {
|
||||
|
|
|
|||
|
|
@ -199,7 +199,7 @@ fn malformed(key: &str, why: &'static str) -> StoreError {
|
|||
.into()
|
||||
}
|
||||
|
||||
fn open_cache(
|
||||
pub(crate) fn open_cache(
|
||||
path: &Path,
|
||||
register: impl FnOnce(&mut CultCache) -> anyhow::Result<()>,
|
||||
) -> anyhow::Result<CultCache> {
|
||||
|
|
|
|||
|
|
@ -309,6 +309,8 @@ fn schema_writes_the_published_files() {
|
|||
"weksa.interlingua_packet.schema.json",
|
||||
"weksa.inventory_entry.schema.json",
|
||||
"weksa.inventory_revision.schema.json",
|
||||
"weksa.loop_round.schema.json",
|
||||
"weksa.loop_run.schema.json",
|
||||
"weksa.scene.schema.json",
|
||||
"weksa.speaker.schema.json"
|
||||
]
|
||||
|
|
|
|||
|
|
@ -114,6 +114,28 @@ pub fn entities_in(dir: &std::path::Path) -> EntityStore {
|
|||
store
|
||||
}
|
||||
|
||||
/// A run over the stores `world()` and `corpus()` keep in `dir`: `c.cc`,
|
||||
/// `i.cc` and `entities.cc`. Read at the call, so create it after the items.
|
||||
pub fn run_over(dir: &std::path::Path) -> weksa::run::RunStores {
|
||||
for name in ["c.cc", "i.cc", "entities.cc"] {
|
||||
if !dir.join(name).exists() {
|
||||
std::fs::write(dir.join(name), [0x90]).unwrap();
|
||||
}
|
||||
}
|
||||
weksa::run::RunStores::create(
|
||||
&dir.join("run"),
|
||||
"t",
|
||||
weksa::run::RunPaths {
|
||||
corpus: &dir.join("c.cc"),
|
||||
inventory: &dir.join("i.cc"),
|
||||
entities: &dir.join("entities.cc"),
|
||||
},
|
||||
"fake-model",
|
||||
"bag",
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn item_in(key: &str, text: &str, group: &str, source: Source) -> CorpusItem {
|
||||
CorpusItem {
|
||||
id: key.into(),
|
||||
|
|
|
|||
|
|
@ -1,10 +1,10 @@
|
|||
mod common;
|
||||
|
||||
use common::{cast, ent, entities_in, group_in_bucket, item_in, model, world};
|
||||
use common::{cast, ent, entities_in, group_in_bucket, item_in, model, run_over, world};
|
||||
use weksa::context::{
|
||||
ENCODE_INSTRUCTIONS as ENCODE, EncoderOffer, MINT_INSTRUCTIONS as MINT, OfferRefusal, Prompt,
|
||||
TrainItems,
|
||||
ENCODE_INSTRUCTIONS as ENCODE, MINT_INSTRUCTIONS as MINT, OfferRefusal, Prompt,
|
||||
};
|
||||
use weksa::run::RunStores;
|
||||
use weksa::{
|
||||
CorpusItem, CorpusItemId, CorpusStore, NameSpan, PacketId, PacketStore, StoreError,
|
||||
StoreRefusal, Turn,
|
||||
|
|
@ -13,6 +13,7 @@ use weksa::{
|
|||
struct Corpus {
|
||||
_dir: tempfile::TempDir,
|
||||
store: CorpusStore,
|
||||
run: RunStores,
|
||||
}
|
||||
|
||||
/// One live item per split, a withdrawn Train item and a model-written
|
||||
|
|
@ -69,7 +70,12 @@ fn corpus() -> Corpus {
|
|||
&group_in_bucket(90),
|
||||
model(),
|
||||
));
|
||||
Corpus { _dir: dir, store }
|
||||
let run = run_over(dir.path());
|
||||
Corpus {
|
||||
_dir: dir,
|
||||
store,
|
||||
run,
|
||||
}
|
||||
}
|
||||
|
||||
fn get(c: &Corpus, key: &str) -> CorpusItem {
|
||||
|
|
@ -79,7 +85,7 @@ fn get(c: &Corpus, key: &str) -> CorpusItem {
|
|||
#[test]
|
||||
fn train_items_hold_only_live_train() {
|
||||
let c = corpus();
|
||||
let t = TrainItems::from_corpus(&c.store).unwrap();
|
||||
let t = c.run.train().unwrap();
|
||||
assert_eq!(t.keys().collect::<Vec<_>>(), ["item:a:1"]);
|
||||
assert_eq!((t.len(), t.is_empty()), (1, false));
|
||||
}
|
||||
|
|
@ -98,15 +104,14 @@ fn train_items_are_in_key_order() {
|
|||
.add(item_in(key, text, &group_in_bucket(10), cast()), &entities)
|
||||
.unwrap();
|
||||
}
|
||||
let t = TrainItems::from_corpus(&store).unwrap();
|
||||
let t = run_over(dir.path()).train().unwrap();
|
||||
assert_eq!(
|
||||
t.keys().collect::<Vec<_>>(),
|
||||
["item:a:1", "item:m:1", "item:z:1"]
|
||||
);
|
||||
assert_eq!((t.len(), t.is_empty()), (3, false));
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let none = CorpusStore::open(&dir.path().join("c.cc")).unwrap();
|
||||
let none = TrainItems::from_corpus(&none).unwrap();
|
||||
let none = run_over(dir.path()).train().unwrap();
|
||||
assert_eq!((none.len(), none.is_empty()), (0, true));
|
||||
assert_eq!(Prompt::mint(&none).text(), MINT);
|
||||
assert!(Prompt::mint(&none).item_keys().is_empty());
|
||||
|
|
@ -115,7 +120,7 @@ fn train_items_are_in_key_order() {
|
|||
#[test]
|
||||
fn mint_prompt_holds_train_text_only() {
|
||||
let c = corpus();
|
||||
let t = TrainItems::from_corpus(&c.store).unwrap();
|
||||
let t = c.run.train().unwrap();
|
||||
let p = Prompt::mint(&t);
|
||||
assert!(p.text().starts_with(MINT));
|
||||
assert!(p.text().contains("alphamarker"));
|
||||
|
|
@ -142,7 +147,8 @@ fn prompts_render_deterministically() {
|
|||
&entities,
|
||||
)
|
||||
.unwrap();
|
||||
let t = TrainItems::from_corpus(&store).unwrap();
|
||||
let run = run_over(dir.path());
|
||||
let t = run.train().unwrap();
|
||||
assert_eq!(
|
||||
Prompt::mint(&t).text(),
|
||||
format!(
|
||||
|
|
@ -151,7 +157,7 @@ fn prompts_render_deterministically() {
|
|||
);
|
||||
assert_eq!(Prompt::mint(&t).item_keys(), ["item:a:1", "item:a:2"]);
|
||||
|
||||
let offer = EncoderOffer::for_round(&store.get("item:a:2").unwrap().unwrap()).unwrap();
|
||||
let offer = run.offer("item:a:2").unwrap().unwrap();
|
||||
assert_eq!(
|
||||
Prompt::encode(&offer, &t).text(),
|
||||
format!("{ENCODE}\n\n[item:a:2] entity:nibu: Second line.\n\nentities: entity:nibu")
|
||||
|
|
@ -162,28 +168,28 @@ fn prompts_render_deterministically() {
|
|||
#[test]
|
||||
fn encoder_offer_split_gate() {
|
||||
let c = corpus();
|
||||
let train = get(&c, "item:a:1");
|
||||
let validation = get(&c, "item:b:1");
|
||||
let test = get(&c, "item:c:1");
|
||||
let no_split = get(&c, "item:c:2");
|
||||
let withdrawn = get(&c, "item:a:2");
|
||||
assert!(withdrawn.withdrawn);
|
||||
let round = |i: &CorpusItem| EncoderOffer::for_round(i).err();
|
||||
let round = |key: &str| c.run.offer(key).unwrap().err();
|
||||
assert_eq!(round("item:a:1"), None);
|
||||
assert_eq!(round("item:b:1"), None);
|
||||
assert_eq!(round("item:c:1"), Some(OfferRefusal::TestBeforeCheckpoint));
|
||||
assert_eq!(round("item:c:2"), Some(OfferRefusal::NoSplit));
|
||||
assert_eq!(round("item:a:2"), Some(OfferRefusal::Withdrawn));
|
||||
assert!(get(&c, "item:a:2").withdrawn);
|
||||
let absent = c.run.offer("item:z:9").err().unwrap().to_string();
|
||||
assert!(!absent.contains("item:z:9"), "an absent key is not echoed");
|
||||
}
|
||||
|
||||
assert_eq!(round(&train), None);
|
||||
assert_eq!(round(&validation), None);
|
||||
assert_eq!(round(&test), Some(OfferRefusal::TestBeforeCheckpoint));
|
||||
assert_eq!(round(&no_split), Some(OfferRefusal::NoSplit));
|
||||
assert_eq!(round(&withdrawn), Some(OfferRefusal::Withdrawn));
|
||||
|
||||
// Withdrawn wins over NoSplit.
|
||||
let mut both = no_split.clone();
|
||||
both.withdrawn = true;
|
||||
assert_eq!(round(&both), Some(OfferRefusal::Withdrawn));
|
||||
// A withdrawn Test item is Withdrawn, not TestBeforeCheckpoint.
|
||||
let mut test_gone = test.clone();
|
||||
test_gone.withdrawn = true;
|
||||
assert_eq!(round(&test_gone), Some(OfferRefusal::Withdrawn));
|
||||
#[test]
|
||||
fn offers_are_the_live_train_and_validation_items_in_key_order() {
|
||||
let c = corpus();
|
||||
let keys: Vec<String> = c
|
||||
.run
|
||||
.offers()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|o| o.key().to_string())
|
||||
.collect();
|
||||
assert_eq!(keys, ["item:a:1", "item:b:1"]);
|
||||
}
|
||||
|
||||
fn span(slug: &str, start: u32, end: u32) -> NameSpan {
|
||||
|
|
@ -219,13 +225,22 @@ fn cited_world() -> (Corpus, CorpusItem, CorpusItem) {
|
|||
sibling.names = vec![span("someone", 0, 7)];
|
||||
store.add(mine.clone(), &entities).unwrap();
|
||||
store.add(sibling.clone(), &entities).unwrap();
|
||||
(Corpus { _dir: dir, store }, mine, sibling)
|
||||
let run = run_over(dir.path());
|
||||
(
|
||||
Corpus {
|
||||
_dir: dir,
|
||||
store,
|
||||
run,
|
||||
},
|
||||
mine,
|
||||
sibling,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoder_offer_entities_are_the_items_own() {
|
||||
let (c, mine, sibling) = cited_world();
|
||||
let t = TrainItems::from_corpus(&c.store).unwrap();
|
||||
let (c, mine, _sibling) = cited_world();
|
||||
let t = c.run.train().unwrap();
|
||||
assert_eq!(
|
||||
mine.cited_entities()
|
||||
.map(|e| e.as_str())
|
||||
|
|
@ -238,7 +253,7 @@ fn encoder_offer_entities_are_the_items_own() {
|
|||
],
|
||||
"names, speaker, prior-turn speakers, repeats kept"
|
||||
);
|
||||
let offer = EncoderOffer::for_round(&mine).unwrap();
|
||||
let offer = c.run.offer("item:a:1").unwrap().unwrap();
|
||||
let ids: Vec<&str> = offer.entities().iter().map(|e| e.as_str()).collect();
|
||||
assert_eq!(ids, ["entity:brokkr", "entity:hero", "entity:kay"]);
|
||||
assert!(
|
||||
|
|
@ -254,7 +269,7 @@ fn encoder_offer_entities_are_the_items_own() {
|
|||
assert!(p.text().contains("[item:a:1]"));
|
||||
assert!(!p.text().contains("item:a:2") && !p.text().contains("Someone waits"));
|
||||
assert_eq!(p.item_keys(), ["item:a:1"]);
|
||||
let sib = EncoderOffer::for_round(&sibling).unwrap();
|
||||
let sib = c.run.offer("item:a:2").unwrap().unwrap();
|
||||
assert_eq!(sib.entities().len(), 2);
|
||||
}
|
||||
|
||||
|
|
@ -275,7 +290,10 @@ fn offer_and_store_agree() {
|
|||
text: "Where?".into(),
|
||||
}];
|
||||
w.corpus.add(item.clone(), &w.entities).unwrap();
|
||||
let offer = EncoderOffer::for_round(&item).unwrap();
|
||||
let offer = run_over(w.dir.path())
|
||||
.offer("item:nibu:2")
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let mut packets = PacketStore::open(&w.dir.path().join("p.cc")).unwrap();
|
||||
let all = ["nibu", "hero", "kay", "brokkr", "player", "s", "someone"];
|
||||
|
|
@ -348,7 +366,8 @@ fn prior_turns_print_only_text_a_live_train_item_holds() {
|
|||
add("item:c:1", "testsecret line", &group_in_bucket(90), vec![]);
|
||||
store.withdraw("item:a:1").unwrap();
|
||||
|
||||
let t = TrainItems::from_corpus(&store).unwrap();
|
||||
let run = run_over(dir.path());
|
||||
let t = run.train().unwrap();
|
||||
let mint = Prompt::mint(&t);
|
||||
for secret in ["withdrawnsecret", "testsecret", "validation reply"] {
|
||||
assert!(!mint.text().contains(secret), "mint printed {secret}");
|
||||
|
|
@ -359,8 +378,7 @@ fn prior_turns_print_only_text_a_live_train_item_holds() {
|
|||
);
|
||||
|
||||
let encode = |key: &str| {
|
||||
let item = store.get(key).unwrap().unwrap();
|
||||
Prompt::encode(&EncoderOffer::for_round(&item).unwrap(), &t)
|
||||
Prompt::encode(&run.offer(key).unwrap().unwrap(), &t)
|
||||
.text()
|
||||
.to_string()
|
||||
};
|
||||
|
|
@ -397,8 +415,9 @@ fn encode_with_prior(train_text: &str, prior_text: &str) -> (String, Result<(),
|
|||
text: prior_text.into(),
|
||||
}];
|
||||
store.add(reply.clone(), &entities).unwrap();
|
||||
let t = TrainItems::from_corpus(&store).unwrap();
|
||||
let p = Prompt::encode(&EncoderOffer::for_round(&reply).unwrap(), &t);
|
||||
let run = run_over(dir.path());
|
||||
let t = run.train().unwrap();
|
||||
let p = Prompt::encode(&run.offer("item:a:2").unwrap().unwrap(), &t);
|
||||
let text = p.text().to_string();
|
||||
// The store's own rule, as the oracle for key equality; after the prompt is
|
||||
// built, because an admitted probe would itself become a held line.
|
||||
|
|
|
|||
145
crates/weksa/tests/golf_loop.rs
Normal file
145
crates/weksa/tests/golf_loop.rs
Normal file
|
|
@ -0,0 +1,145 @@
|
|||
//! The golf loop: a pinned run encodes Train and Validation through a
|
||||
//! `ModelPort`, admits, lowers, scores, and keeps a typed round record.
|
||||
|
||||
mod common;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use common::{ent, run_over, world};
|
||||
use cultcache_rs::{CultCache, SingleFileMessagePackBackingStore};
|
||||
use weksa::run::{DriftOf, RunError, RunPaths, RunRecord, RunStores};
|
||||
use weksa::split::fnv1a64;
|
||||
|
||||
/// Rewrites the stored run record, as only a test (or a stale file) can.
|
||||
fn rewrite_run(root: &Path, change: impl FnOnce(&mut RunRecord)) {
|
||||
let mut cache = CultCache::new();
|
||||
cache.register_entry_type::<RunRecord>().unwrap();
|
||||
cache
|
||||
.add_generic_backing_store(SingleFileMessagePackBackingStore::new(root.join("run.cc")))
|
||||
.unwrap();
|
||||
cache.pull_all_backing_stores().unwrap();
|
||||
let mut record = cache.get_all::<RunRecord>().unwrap().remove(0);
|
||||
change(&mut record);
|
||||
cache.put(format!("run:{}", record.label), &record).unwrap();
|
||||
}
|
||||
|
||||
fn paths(dir: &Path) -> (PathBuf, PathBuf, PathBuf) {
|
||||
(dir.join("c.cc"), dir.join("i.cc"), dir.join("entities.cc"))
|
||||
}
|
||||
|
||||
fn hex(path: &Path) -> String {
|
||||
format!("{:016x}", fnv1a64(&std::fs::read(path).unwrap()))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_run_pins_its_stores_and_refuses_drift() {
|
||||
let mut w = world();
|
||||
let dir = w.dir.path().to_path_buf();
|
||||
let root = dir.join("run");
|
||||
let (c, i, e) = paths(&dir);
|
||||
let at = |label: &str, model: &str| {
|
||||
RunStores::create(
|
||||
&root,
|
||||
label,
|
||||
RunPaths {
|
||||
corpus: &c,
|
||||
inventory: &i,
|
||||
entities: &e,
|
||||
},
|
||||
model,
|
||||
"bag",
|
||||
)
|
||||
};
|
||||
|
||||
// Opening a root with no run makes none.
|
||||
assert_eq!(RunStores::open(&root).err(), Some(RunError::NoRun));
|
||||
assert!(!root.join("run.cc").exists(), "open must not create run.cc");
|
||||
assert_eq!(
|
||||
at("Bad Label", "m").err(),
|
||||
Some(RunError::Malformed("label"))
|
||||
);
|
||||
assert_eq!(at("t", "").err(), Some(RunError::Malformed("model")));
|
||||
assert!(
|
||||
!root.join("run.cc").exists(),
|
||||
"a refused create writes nothing"
|
||||
);
|
||||
|
||||
let run = at("t", "fake-model").unwrap();
|
||||
let r = run.record();
|
||||
assert_eq!((r.label.as_str(), r.model.as_str()), ("t", "fake-model"));
|
||||
assert_eq!(
|
||||
r.corpus,
|
||||
std::fs::canonicalize(&c).unwrap().to_str().unwrap()
|
||||
);
|
||||
assert_eq!(r.corpus_digest, hex(&c));
|
||||
assert_eq!(r.entity_digest, hex(&e));
|
||||
assert_eq!(r.chrf_version, weksa::score::CHRF_VERSION);
|
||||
assert_eq!(at("u", "fake-model").err(), Some(RunError::Exists));
|
||||
|
||||
// The record is all open reads: the same run, from the same digests.
|
||||
assert_eq!(RunStores::open(&root).unwrap().record(), run.record());
|
||||
|
||||
// A corpus written after the pin is another corpus.
|
||||
let item = common::item_in(
|
||||
"item:nibu:2",
|
||||
"Another line.",
|
||||
&common::group_in_bucket(10),
|
||||
common::cast(),
|
||||
);
|
||||
w.corpus.add(item, &w.entities).unwrap();
|
||||
assert_eq!(
|
||||
RunStores::open(&root).err(),
|
||||
Some(RunError::Drift(DriftOf::Corpus))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_checks_each_pin_by_name() {
|
||||
let mut w = world();
|
||||
let dir = w.dir.path().to_path_buf();
|
||||
let root = dir.join("run");
|
||||
let drift = |change: &dyn Fn(&mut RunRecord)| {
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
run_over(&dir);
|
||||
rewrite_run(&root, change);
|
||||
RunStores::open(&root).err()
|
||||
};
|
||||
assert_eq!(
|
||||
drift(&|r| r.prompt_digest = "0".repeat(16)),
|
||||
Some(RunError::Drift(DriftOf::Prompts))
|
||||
);
|
||||
assert_eq!(
|
||||
drift(&|r| r.lowerer_digest = "0".repeat(16)),
|
||||
Some(RunError::Drift(DriftOf::Lowerer))
|
||||
);
|
||||
assert_eq!(
|
||||
drift(&|r| r.corpus_digest = "0".repeat(16)),
|
||||
Some(RunError::Drift(DriftOf::Corpus))
|
||||
);
|
||||
assert_eq!(
|
||||
drift(&|r| r.entity_digest = "0".repeat(16)),
|
||||
Some(RunError::Drift(DriftOf::Entities))
|
||||
);
|
||||
assert_eq!(drift(&|_| {}), None, "the unchanged record opens");
|
||||
|
||||
// An entity put after the pin is another entity store.
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
run_over(&dir);
|
||||
w.entities.put(ent("kay", "en-US", &["Kay"])).unwrap();
|
||||
assert_eq!(
|
||||
RunStores::open(&root).err(),
|
||||
Some(RunError::Drift(DriftOf::Entities))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_digests_cover_their_files() {
|
||||
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||
let digest = |name: &str| fnv1a64(&std::fs::read(src.join(name)).unwrap());
|
||||
assert_eq!(weksa::run::PROMPT_SOURCE_DIGEST, digest("context.rs"));
|
||||
assert_eq!(weksa::run::LOWERER_SOURCE_DIGEST, digest("lower.rs"));
|
||||
assert_ne!(
|
||||
weksa::run::PROMPT_SOURCE_DIGEST,
|
||||
weksa::run::LOWERER_SOURCE_DIGEST
|
||||
);
|
||||
}
|
||||
227
schemas/cultnet/weksa.loop_round.schema.json
Normal file
227
schemas/cultnet/weksa.loop_round.schema.json
Normal file
|
|
@ -0,0 +1,227 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "RoundRecord",
|
||||
"description": "One scored round. It holds no text and no Test reading: per-item rows for\nTrain only, Validation only as means and refusal counts by stage. Only\n`run::round` builds one.\n\n```\nfn f(r: &weksa::run::RoundRecord) -> u32 { r.n() }\n```\n\n```compile_fail\nfn f() -> weksa::run::RoundRecord {\n weksa::run::RoundRecord { n: 1 }\n}\n```",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"calls": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/Call"
|
||||
}
|
||||
},
|
||||
"chrf_version": {
|
||||
"type": "string"
|
||||
},
|
||||
"corpus_digest": {
|
||||
"type": "string"
|
||||
},
|
||||
"embedder": {
|
||||
"type": "string"
|
||||
},
|
||||
"entity_digest": {
|
||||
"type": "string"
|
||||
},
|
||||
"inventory_rev": {
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"lowerer_digest": {
|
||||
"type": "string"
|
||||
},
|
||||
"model": {
|
||||
"type": "string"
|
||||
},
|
||||
"n": {
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"prompt_digest": {
|
||||
"type": "string"
|
||||
},
|
||||
"train": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"$ref": "#/$defs/TrainRow"
|
||||
}
|
||||
},
|
||||
"train_mean": {
|
||||
"$ref": "#/$defs/SplitMean"
|
||||
},
|
||||
"validation_mean": {
|
||||
"$ref": "#/$defs/SplitMean"
|
||||
},
|
||||
"validation_refused": {
|
||||
"$ref": "#/$defs/RefusalCounts"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"n",
|
||||
"inventory_rev",
|
||||
"prompt_digest",
|
||||
"lowerer_digest",
|
||||
"corpus_digest",
|
||||
"entity_digest",
|
||||
"model",
|
||||
"embedder",
|
||||
"chrf_version",
|
||||
"calls",
|
||||
"train",
|
||||
"train_mean",
|
||||
"validation_mean",
|
||||
"validation_refused"
|
||||
],
|
||||
"$defs": {
|
||||
"Call": {
|
||||
"description": "One model call: the prompt's digest and the item keys it held.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"prompt": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"prompt",
|
||||
"items"
|
||||
]
|
||||
},
|
||||
"Outcome": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"Scored": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"chrf": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"meaning": {
|
||||
"type": [
|
||||
"number",
|
||||
"null"
|
||||
],
|
||||
"format": "double"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"chrf"
|
||||
]
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"Scored"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"Refused": {
|
||||
"$ref": "#/$defs/Stage"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"Refused"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"RefusalCounts": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"admit": {
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"lower": {
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"parse": {
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"parse",
|
||||
"admit",
|
||||
"lower"
|
||||
]
|
||||
},
|
||||
"SplitMean": {
|
||||
"description": "Mean scores of one derived split.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"chrf": {
|
||||
"description": "`None` when the split has no items.",
|
||||
"type": [
|
||||
"number",
|
||||
"null"
|
||||
],
|
||||
"format": "double"
|
||||
},
|
||||
"count": {
|
||||
"type": "integer",
|
||||
"format": "uint",
|
||||
"minimum": 0
|
||||
},
|
||||
"meaning": {
|
||||
"description": "Mean over the items that have a meaning score; `None` when none do.",
|
||||
"type": [
|
||||
"number",
|
||||
"null"
|
||||
],
|
||||
"format": "double"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"count"
|
||||
]
|
||||
},
|
||||
"Stage": {
|
||||
"description": "Where a round refused: the first stage that did.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Parse",
|
||||
"Admit",
|
||||
"Lower"
|
||||
]
|
||||
},
|
||||
"TrainRow": {
|
||||
"description": "A Train item's row. Validation has no rows.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"item": {
|
||||
"type": "string"
|
||||
},
|
||||
"outcome": {
|
||||
"$ref": "#/$defs/Outcome"
|
||||
},
|
||||
"packet": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"item",
|
||||
"outcome"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
58
schemas/cultnet/weksa.loop_run.schema.json
Normal file
58
schemas/cultnet/weksa.loop_run.schema.json
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "RunRecord",
|
||||
"description": "What a run pinned at open. Key `run:<label>`.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"chrf_version": {
|
||||
"type": "string"
|
||||
},
|
||||
"corpus": {
|
||||
"description": "Canonical absolute path of the corpus store.",
|
||||
"type": "string"
|
||||
},
|
||||
"corpus_digest": {
|
||||
"description": "16 hex of the corpus file's bytes.",
|
||||
"type": "string"
|
||||
},
|
||||
"embedder": {
|
||||
"description": "The embedder's model.",
|
||||
"type": "string"
|
||||
},
|
||||
"entities": {
|
||||
"type": "string"
|
||||
},
|
||||
"entity_digest": {
|
||||
"type": "string"
|
||||
},
|
||||
"inventory": {
|
||||
"type": "string"
|
||||
},
|
||||
"label": {
|
||||
"type": "string"
|
||||
},
|
||||
"lowerer_digest": {
|
||||
"type": "string"
|
||||
},
|
||||
"model": {
|
||||
"description": "The answering model.",
|
||||
"type": "string"
|
||||
},
|
||||
"prompt_digest": {
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"label",
|
||||
"corpus",
|
||||
"inventory",
|
||||
"entities",
|
||||
"corpus_digest",
|
||||
"entity_digest",
|
||||
"prompt_digest",
|
||||
"lowerer_digest",
|
||||
"model",
|
||||
"embedder",
|
||||
"chrf_version"
|
||||
]
|
||||
}
|
||||
Loading…
Reference in a new issue