run::round: a pinned run encodes Train and Validation, admits, lowers, scores and records the round

encode.rs reads a model answer into a PacketDraft (the one JSON door for
models) and the encoder step sets everything the model does not write. round
asks every offer first and writes nothing while any prompt is unanswered, then
admits into the round's own packets.cc, lowers, scores in one call and keeps a
RoundRecord with Train rows and Validation only as means and refusal counts.
The Dao stores reproduce the base scores (Train 44.18, Validation 78.56).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Weksa 2026-11-10 03:50:04 +00:00
commit 49879000f7
6 changed files with 994 additions and 27 deletions

229
crates/weksa/src/encode.rs Normal file
View file

@ -0,0 +1,229 @@
//! The encoder step: what a model's answer becomes. This is the one place JSON
//! is read (the xenos boundary): a model answers in JSON, `PacketDraft::parse`
//! reads it, and nothing is stored as JSON. The model writes meaning only;
//! `into_packet` sets the id, schema version, inventory revision, kind,
//! provenance, constraints and extensions, and an empty trace, so a model that
//! saw a Validation item cannot hand its words to whoever reads packets.
use std::fmt;
use serde::{Deserialize, Serialize};
use crate::corpus::CorpusItemId;
use crate::packet::{
Constraints, Context, Discourse, EncoderId, Grade, Packet, PacketId, PacketKind, Predication,
Provenance, ProvenanceSource, Referent, Relation, SCHEMA_VERSION, Stance, Trace,
};
use crate::split::{fnv1a64, hex16};
/// The meaning fields of a packet, as a model writes them.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PacketDraft {
pub confidence: Grade,
#[serde(default)]
pub context: Context,
pub discourse: Discourse,
pub referents: Vec<Referent>,
pub predications: Vec<Predication>,
#[serde(default)]
pub relations: Vec<Relation>,
#[serde(default)]
pub stance: Stance,
}
/// Where an answer stopped being a draft. Position only: a parse message would
/// quote the offending token.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct DraftError {
pub line: usize,
pub column: usize,
}
impl fmt::Display for DraftError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"not a packet draft at line {} column {}",
self.line, self.column
)
}
}
impl fmt::Debug for DraftError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
impl std::error::Error for DraftError {}
impl PacketDraft {
pub fn parse(answer: &str) -> Result<Self, DraftError> {
serde_json::from_str(answer.trim()).map_err(|e| DraftError {
line: e.line(),
column: e.column(),
})
}
/// The draft that says what `packet` says.
pub fn of(packet: &Packet) -> Self {
Self {
confidence: packet.provenance.confidence,
context: packet.context.clone(),
discourse: packet.discourse.clone(),
referents: packet.referents.clone(),
predications: packet.predications.clone(),
relations: packet.relations.clone(),
stance: packet.stance.clone(),
}
}
/// The packet this draft becomes for `item` at inventory revision `rev`.
pub(crate) fn into_packet(self, item: &CorpusItemId, rev: u32, encoder: &EncoderId) -> Packet {
Packet {
id: packet_id(item, rev, encoder),
schema_version: SCHEMA_VERSION,
inventory_rev: rev,
kind: PacketKind::CorpusExample,
provenance: Provenance {
source: ProvenanceSource::ModelDecomposition,
corpus_item: item.clone(),
encoder: encoder.clone(),
confidence: self.confidence,
},
context: self.context,
discourse: self.discourse,
referents: self.referents,
predications: self.predications,
relations: self.relations,
constraints: Constraints::default(),
extensions: vec![],
trace: Trace::default(),
stance: self.stance,
}
}
}
/// `encoder:<hex16>`, a digest of the model id and the prompt digest.
pub fn encoder_id(model: &str, prompt_digest: &str) -> EncoderId {
let digest = fnv1a64(format!("weksa-encoder-v1:{model}:{prompt_digest}").as_bytes());
EncoderId::parse(&format!("encoder:{}", hex16(digest))).expect("an encoder id is well formed")
}
/// `packet:<hex16>`, a digest of the item, the inventory revision and the encoder.
pub fn packet_id(item: &CorpusItemId, rev: u32, encoder: &EncoderId) -> PacketId {
let digest = fnv1a64(format!("weksa-packet-v1:{item}:{rev}:{encoder}").as_bytes());
PacketId::parse(&format!("packet:{}", hex16(digest))).expect("a packet id is well formed")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::daodejing::packets;
fn item() -> CorpusItemId {
CorpusItemId::parse("item:daodejing:1").unwrap()
}
#[test]
fn ids_are_pinned_digests_of_their_inputs() {
let encoder = encoder_id("fake-model", "abcd");
assert_eq!(encoder.as_str(), "encoder:4d35f2befb3108ec");
let encoder = EncoderId::parse("encoder:0123456789abcdef").unwrap();
assert_eq!(
packet_id(&item(), 3, &encoder).as_str(),
"packet:888ba17103e21a9d"
);
// Each input moves the id.
assert_ne!(
encoder_id("other", "abcd"),
encoder_id("fake-model", "abcd")
);
assert_ne!(
encoder_id("fake-model", "abce"),
encoder_id("fake-model", "abcd")
);
let other = CorpusItemId::parse("item:daodejing:2").unwrap();
let base = packet_id(&item(), 3, &encoder);
assert_ne!(packet_id(&other, 3, &encoder), base);
assert_ne!(packet_id(&item(), 4, &encoder), base);
assert_ne!(packet_id(&item(), 3, &encoder_id("m", "d")), base);
}
#[test]
fn the_encoder_step_sets_everything_the_model_does_not_write() {
// A source packet with every non-meaning field set to something loud.
let mut source = packets().remove(0);
source.trace.notes = vec!["a note a model must not hand on".into()];
source.constraints.deterministic = true;
source.extensions = vec![crate::packet::Extension {
key: "extension:1".parse().unwrap(),
value: crate::packet::FeatValue::Flag(true),
}];
let draft = PacketDraft::of(&source);
let encoder = encoder_id("m", "d");
let made = draft.clone().into_packet(&item(), 9, &encoder);
assert_eq!(made.id, packet_id(&item(), 9, &encoder));
assert_eq!(made.schema_version, SCHEMA_VERSION);
assert_eq!(made.inventory_rev, 9);
assert_eq!(made.kind, PacketKind::CorpusExample);
assert_eq!(made.provenance.source, ProvenanceSource::ModelDecomposition);
assert_eq!(made.provenance.corpus_item, item());
assert_eq!(made.provenance.encoder, encoder);
assert_eq!(made.provenance.confidence, source.provenance.confidence);
assert_eq!(made.constraints, Constraints::default());
assert!(made.extensions.is_empty());
assert_eq!(made.trace, Trace::default());
// The meaning is the draft's, whole.
assert_eq!(PacketDraft::of(&made), draft);
}
#[test]
fn parse_reads_a_draft_and_trims() {
let draft = PacketDraft::of(&packets()[0]);
let json = serde_json::to_string(&draft).unwrap();
assert_eq!(PacketDraft::parse(&format!("\n {json} \n")).unwrap(), draft);
// The optional fields default.
let minimal = r#"{"confidence":500,"discourse":{"speech_act":null,"addressee":null,"addressee_consent":null,"features":[]},"referents":[],"predications":[]}"#;
let d = PacketDraft::parse(minimal).unwrap();
assert_eq!(d.context, Context::default());
assert!(d.relations.is_empty());
assert_eq!(d.stance, Stance::default());
}
#[test]
fn parse_refuses_what_a_model_must_not_write() {
let draft = PacketDraft::of(&packets()[0]);
let mut value = serde_json::to_value(&draft).unwrap();
for field in [
"id",
"provenance",
"trace",
"inventory_rev",
"kind",
"extensions",
] {
value[field] = serde_json::json!(null);
assert!(PacketDraft::parse(&value.to_string()).is_err(), "{field}");
value.as_object_mut().unwrap().remove(field);
}
value["confidence"] = serde_json::json!(1001);
assert!(PacketDraft::parse(&value.to_string()).is_err());
value.as_object_mut().unwrap().remove("confidence");
assert!(
PacketDraft::parse(&value.to_string()).is_err(),
"confidence is required"
);
}
#[test]
fn a_draft_error_is_a_position_and_echoes_no_token() {
let err = PacketDraft::parse("{\n \"confidence\": CANARYTOKEN").unwrap_err();
assert_eq!((err.line, err.column), (2, 17));
let err = PacketDraft::parse(r#"{"confidence":500,"CANARYKEY":1}"#).unwrap_err();
for text in [err.to_string(), format!("{err:?}")] {
assert!(!text.contains("CANARY"), "{text}");
}
}
}

View file

@ -6,6 +6,7 @@
pub mod context;
pub mod corpus;
pub mod daodejing;
pub mod encode;
pub mod entity;
pub mod form;
pub mod inventory;
@ -22,6 +23,7 @@ pub mod store;
pub mod validate;
pub use corpus::{CorpusItem, CorpusItemId, NameSpan, Source, Turn};
pub use encode::PacketDraft;
pub use entity::{Entity, EntityOrigin, LanguageForms, Pronunciation};
pub use form::FormError;
pub use inventory::{
@ -29,10 +31,12 @@ pub use inventory::{
Slot, ValueKind,
};
pub use lower::{EntityForms, LowerError, PhoneLine, TARGET_LANGUAGE, lower, phones, pronounce};
pub use model::{AnswerFiles, ModelPort};
pub use packet::{
EncoderId, EntityId, Grade, NodeId, Packet, PacketId, PacketKind, SCHEMA_VERSION, Stance,
};
pub use phones::{Phone, PhoneInventory, SegmentError, Stress};
pub use run::{RoundRecord, RunStores, round};
pub use score::{Embedder, ItemScore, OllamaEmbedder, Scorer, chrf};
pub use speaker::{Annotator, PairRelation, Party, Scene, Speaker};
pub use split::{Split, SplitScheme};

View file

@ -19,11 +19,15 @@ use cultcache_rs::{CultCache, DatabaseEntry};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use crate::context::{EncoderOffer, TrainItems};
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::score::{CHRF_VERSION, SplitMean};
use crate::split::{fnv1a64, hex16};
use crate::store::{CorpusStore, EntityStore, InventoryStore, open_cache};
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.
@ -431,3 +435,172 @@ impl RunStores {
.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.
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()))?;
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 {
scorer.score(&inputs).map_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);
}
let scored: Vec<(&CorpusItem, ItemScore)> = items
.iter()
.zip(&score_at)
.filter_map(|(item, score)| score.clone().map(|s| (item, s)))
.collect();
let means = aggregate(&scored);
let mut train_rows = Vec::new();
let mut refused = RefusalCounts::default();
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), _) => train_rows.push(TrainRow {
item: item.id.clone(),
packet,
outcome,
}),
(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,
};
run.cache
.put(format!("run:{}:round:{n}", run.record.label), &record)
.map_err(store)?;
Ok(RoundOutcome::Recorded(record))
}

View file

@ -353,3 +353,25 @@ pub fn good() -> Packet {
},
}
}
/// A deterministic bag-of-letters embedder, so cosine differs with the text.
pub struct Bag;
impl weksa::Embedder for Bag {
fn model(&self) -> &str {
"bag"
}
fn embed(&self, texts: &[&str]) -> anyhow::Result<Vec<Vec<f32>>> {
Ok(texts
.iter()
.map(|t| {
let mut v = vec![0.0; 27];
v[26] = 1.0;
for c in t.chars().filter(char::is_ascii_alphabetic) {
v[(c.to_ascii_lowercase() as u8 - b'a') as usize] += 1.0;
}
v
})
.collect())
}
}

View file

@ -298,3 +298,564 @@ fn answer_files_write_the_prompt_and_read_the_answer() {
"io error InvalidData"
);
}
// ---- rounds over the Dao De Jing test bed ----
use std::collections::HashMap;
use common::Bag;
use weksa::context::{ENCODE_INSTRUCTIONS, Prompt};
use weksa::daodejing::packets;
use weksa::model::{AnswerFiles, ModelPort, PortError};
use weksa::run::{Outcome, RoundOutcome, RoundRecord, Stage, round};
use weksa::{Embedder, PacketDraft, PacketStore, Scorer};
/// Answers by the item the prompt holds; panics on an item it was not given,
/// and records every prompt it was shown.
struct FakeModel {
name: &'static str,
answers: HashMap<String, String>,
seen: Vec<(String, String)>,
}
impl ModelPort for FakeModel {
fn model(&self) -> &str {
self.name
}
fn answer(&mut self, prompt: &Prompt) -> Result<String, PortError> {
let key = prompt.item_keys()[0].clone();
self.seen.push((prompt.digest(), prompt.text().to_string()));
match self.answers.get(&key) {
Some(answer) => Ok(answer.clone()),
None => panic!("the model was asked about {key}"),
}
}
}
fn draft_of(item: usize) -> PacketDraft {
PacketDraft::of(&packets()[item - 1])
}
fn json(draft: &PacketDraft) -> String {
serde_json::to_string(draft).unwrap()
}
/// A fake that answers the Dao packets for the Train and Validation items.
fn fake(answers: &[(usize, String)]) -> FakeModel {
FakeModel {
name: "fake-model",
answers: answers
.iter()
.map(|(n, a)| (format!("item:daodejing:{n}"), a.clone()))
.collect(),
seen: vec![],
}
}
fn good_answers() -> Vec<(usize, String)> {
(1..=3).map(|n| (n, json(&draft_of(n)))).collect()
}
struct Dao {
_dir: tempfile::TempDir,
root: PathBuf,
corpus: PathBuf,
run: RunStores,
}
/// A run over copies of `data/daodejing/{corpus,inventory,entity}.cc`.
fn dao() -> Dao {
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/daodejing");
let dir = tempfile::tempdir().unwrap();
let copy = |from: &str, to: &str| {
std::fs::copy(src.join(from), dir.path().join(to)).unwrap();
dir.path().join(to)
};
let (corpus, inventory, entities) = (
copy("corpus.cc", "c.cc"),
copy("inventory.cc", "i.cc"),
copy("entity.cc", "e.cc"),
);
let root = dir.path().join("run");
let run = RunStores::create(
&root,
"dao",
RunPaths {
corpus: &corpus,
inventory: &inventory,
entities: &entities,
},
"fake-model",
"bag",
)
.unwrap();
Dao {
_dir: dir,
root,
corpus,
run,
}
}
fn recorded(outcome: RoundOutcome) -> RoundRecord {
match outcome {
RoundOutcome::Recorded(r) => r,
RoundOutcome::Unanswered { prompts } => panic!("unanswered: {prompts:?}"),
}
}
fn two_dp(x: f64) -> f64 {
(x * 100.0).round() / 100.0
}
#[test]
fn round_over_the_dao_stores_scores_train_and_validation() {
let mut dao = dao();
let mut model = fake(&good_answers());
let r = recorded(round(&mut dao.run, &mut model, &Scorer::new(Bag)).unwrap());
let pinned = dao.run.record().clone();
assert_eq!((r.n(), r.inventory_rev()), (1, 3));
let items: Vec<&[String]> = r.calls().iter().map(|c| c.items.as_slice()).collect();
assert_eq!(
items,
[
["item:daodejing:1"],
["item:daodejing:2"],
["item:daodejing:3"]
]
);
for (call, (digest, _)) in r.calls().iter().zip(&model.seen) {
assert_eq!(&call.prompt, digest);
}
// Train: a row per item, with the packet that was admitted and its score.
assert_eq!(r.train().len(), 1);
let row = &r.train()[0];
assert_eq!(row.item, "item:daodejing:1");
let Outcome::Scored { chrf, meaning } = row.outcome else {
panic!("{:?}", row.outcome)
};
assert_eq!(two_dp(chrf), 44.18);
assert!(meaning.is_some());
assert_eq!((r.train_mean().count, r.train_mean().chrf), (1, Some(chrf)));
// Validation: means and refusal counts only.
let v = r.validation_mean();
assert_eq!(v.count, 2);
assert!((v.chrf.unwrap() - 78.56).abs() < 0.01, "{:?}", v.chrf);
assert!(v.meaning.is_some());
assert_eq!(r.validation_refused(), Default::default());
// The record carries the run's pins.
assert_eq!(r.prompt_digest(), pinned.prompt_digest);
assert_eq!(r.lowerer_digest(), pinned.lowerer_digest);
assert_eq!(r.corpus_digest(), pinned.corpus_digest);
assert_eq!(r.entity_digest(), pinned.entity_digest);
assert_eq!(r.model(), "fake-model");
assert_eq!(r.embedder(), "bag");
assert_eq!(r.chrf_version(), weksa::score::CHRF_VERSION);
// It is stored, and the packets are in the round's own store, made by the encoder step.
assert_eq!(
RunStores::open(&dao.root).unwrap().rounds().unwrap(),
std::slice::from_ref(&r)
);
let packets = PacketStore::open(&dao.root.join("round-1/packets.cc")).unwrap();
let all = packets.all().unwrap();
assert_eq!(all.len(), 3);
let encoder = weksa::encode::encoder_id("fake-model", &pinned.prompt_digest);
for p in &all {
assert_eq!(p.provenance.encoder, encoder);
assert_eq!(p.inventory_rev, 3);
assert_eq!(p.trace, Default::default());
}
assert_eq!(
row.packet.as_deref(),
Some(
all.iter()
.find(|p| p.provenance.corpus_item.as_str() == "item:daodejing:1")
.unwrap()
.id
.as_str()
)
);
assert!(!dao.root.join("round-2").exists());
}
#[test]
fn round_never_offers_or_records_test() {
let mut dao = dao();
// The fake panics if asked about item 4 or 5.
let mut model = fake(&good_answers());
recorded(round(&mut dao.run, &mut model, &Scorer::new(Bag)).unwrap());
assert!(
model
.seen
.iter()
.all(|(_, t)| !t.contains("item:daodejing:4") && !t.contains("item:daodejing:5"))
);
let corpus = weksa::CorpusStore::open(&dao.corpus).unwrap();
let mut files = vec![dao.root.join("run.cc")];
for entry in std::fs::read_dir(dao.root.join("round-1")).unwrap() {
files.push(entry.unwrap().path());
}
let mut needles: Vec<String> = vec!["item:daodejing:4".into(), "item:daodejing:5".into()];
needles.extend(
["item:daodejing:4", "item:daodejing:5"].map(|k| corpus.get(k).unwrap().unwrap().text),
);
for file in files {
let bytes = std::fs::read(&file).unwrap();
for needle in &needles {
assert!(
!bytes.windows(needle.len()).any(|w| w == needle.as_bytes()),
"{} holds a Test key or text",
file.display()
);
}
}
// Nor does the record hold any Train or Validation text.
let run_cc = std::fs::read(dao.root.join("run.cc")).unwrap();
for k in ["item:daodejing:1", "item:daodejing:2", "item:daodejing:3"] {
let text = corpus.get(k).unwrap().unwrap().text;
assert!(
!run_cc.windows(text.len()).any(|w| w == text.as_bytes()),
"{k} text in run.cc"
);
}
}
/// The key and prompt of every item a round offers, as a round would build them.
fn prompts(run: &RunStores) -> Vec<(String, Prompt)> {
let inv = run.inventory().inventory().unwrap();
let rev = inv.latest().unwrap().n;
let train = run.train().unwrap();
run.offers()
.unwrap()
.iter()
.map(|o| (o.key().to_string(), Prompt::encode(o, &train, &inv, rev)))
.collect()
}
#[test]
fn unanswered_round_writes_nothing() {
let mut dao = dao();
let run_cc = std::fs::read(dao.root.join("run.cc")).unwrap();
let expected = prompts(&dao.run);
assert_eq!(expected.len(), 3);
let mut files = AnswerFiles::new(dao.run.next_round_dir().unwrap(), "fake-model".into());
let RoundOutcome::Unanswered { prompts: digests } =
round(&mut dao.run, &mut files, &Scorer::new(Bag)).unwrap()
else {
panic!("answered from nothing")
};
let want: Vec<String> = expected.iter().map(|(_, p)| p.digest()).collect();
assert_eq!(digests, want);
let round1 = dao.root.join("round-1");
for (_, p) in &expected {
assert_eq!(
std::fs::read_to_string(round1.join(format!("{}.prompt", p.digest()))).unwrap(),
p.text()
);
}
assert_eq!(
std::fs::read_dir(&round1).unwrap().count(),
3,
"prompts only: no packets.cc"
);
assert!(dao.run.rounds().unwrap().is_empty());
assert_eq!(std::fs::read(dao.root.join("run.cc")).unwrap(), run_cc);
// Two of three answers is still nothing written.
let answers: HashMap<String, String> = good_answers()
.into_iter()
.map(|(n, a)| (format!("item:daodejing:{n}"), a))
.collect();
for (key, p) in &expected[..2] {
std::fs::write(round1.join(format!("{}.answer", p.digest())), &answers[key]).unwrap();
}
let mut files = AnswerFiles::new(dao.run.next_round_dir().unwrap(), "fake-model".into());
let RoundOutcome::Unanswered { prompts: digests } =
round(&mut dao.run, &mut files, &Scorer::new(Bag)).unwrap()
else {
panic!("answered from two of three")
};
assert_eq!(digests, [want[2].clone()]);
assert!(!round1.join("packets.cc").exists());
assert_eq!(std::fs::read(dao.root.join("run.cc")).unwrap(), run_cc);
// The last answer completes round 1; the next round is round 2 and asks again.
let (key, p) = &expected[2];
std::fs::write(round1.join(format!("{}.answer", p.digest())), &answers[key]).unwrap();
let mut files = AnswerFiles::new(dao.run.next_round_dir().unwrap(), "fake-model".into());
let r = recorded(round(&mut dao.run, &mut files, &Scorer::new(Bag)).unwrap());
assert_eq!(r.n(), 1);
let mut files = AnswerFiles::new(dao.run.next_round_dir().unwrap(), "fake-model".into());
assert!(dao.root.join("round-2").parent().is_some());
let RoundOutcome::Unanswered { prompts: again } =
round(&mut dao.run, &mut files, &Scorer::new(Bag)).unwrap()
else {
panic!("round 2 answered from round 1's files")
};
assert_eq!(again.len(), 3);
assert_eq!(
std::fs::read_dir(dao.root.join("round-2")).unwrap().count(),
3
);
assert_eq!(dao.run.rounds().unwrap().len(), 1);
}
struct OtherEmbedder;
impl Embedder for OtherEmbedder {
fn model(&self) -> &str {
"other-embedder"
}
fn embed(&self, texts: &[&str]) -> anyhow::Result<Vec<Vec<f32>>> {
Bag.embed(texts)
}
}
#[test]
fn drift_refuses_the_round() {
let mut dao = dao();
let mut other = fake(&good_answers());
other.name = "other-model";
assert_eq!(
round(&mut dao.run, &mut other, &Scorer::new(Bag)).err(),
Some(RunError::Drift(DriftOf::Model))
);
let mut model = fake(&good_answers());
assert_eq!(
round(&mut dao.run, &mut model, &Scorer::new(OtherEmbedder)).err(),
Some(RunError::Drift(DriftOf::Embedder))
);
assert!(
other.seen.is_empty() && model.seen.is_empty(),
"drift is found before any call"
);
assert!(dao.run.rounds().unwrap().is_empty() && !dao.root.join("round-1").exists());
// An inventory with no revision has no round.
let w = world();
std::fs::write(w.dir.path().join("i.cc"), [0x90]).unwrap();
let mut empty = run_over(w.dir.path());
let mut model = fake(&[]);
assert_eq!(
round(&mut empty, &mut model, &Scorer::new(Bag)).err(),
Some(RunError::NoInventory)
);
}
/// `n`'s good draft, edited.
fn edited(n: usize, edit: impl FnOnce(&mut PacketDraft)) -> String {
let mut d = draft_of(n);
edit(&mut d);
json(&d)
}
fn unknown_concept(d: &mut PacketDraft) {
d.referents[0].concept = "concept:999".parse().unwrap();
}
fn with_relation(d: &mut PacketDraft) {
d.relations.push(weksa::packet::Relation {
relation: "relation:1".parse().unwrap(),
from: d.referents[0].id.clone(),
to: d.referents[1].id.clone(),
features: vec![],
});
}
#[test]
fn refusal_stages_are_counted() {
let run = |answers: [String; 3]| {
let mut dao = dao();
let mut model = fake(
&answers
.into_iter()
.enumerate()
.map(|(i, a)| (i + 1, a))
.collect::<Vec<_>>(),
);
recorded(round(&mut dao.run, &mut model, &Scorer::new(Bag)).unwrap())
};
let junk = "not json at all".to_string();
// Train refused at each stage; Validation refused at the other two.
let r = run([
junk.clone(),
edited(2, unknown_concept),
edited(3, with_relation),
]);
assert_eq!(r.train()[0].outcome, Outcome::Refused(Stage::Parse));
assert_eq!(r.train()[0].packet, None);
assert_eq!((r.train_mean().count, r.train_mean().chrf), (0, None));
assert_eq!(r.validation_refused().parse, 0);
assert_eq!(
(r.validation_refused().admit, r.validation_refused().lower),
(1, 1)
);
assert_eq!(
(r.validation_mean().count, r.validation_mean().chrf),
(0, None)
);
let r = run([
edited(1, unknown_concept),
junk.clone(),
good_answers()[2].1.clone(),
]);
assert_eq!(r.train()[0].outcome, Outcome::Refused(Stage::Admit));
assert_eq!(r.train()[0].packet, None, "a refused packet is not stored");
let v = r.validation_refused();
assert_eq!((v.parse, v.admit, v.lower), (1, 0, 0));
assert_eq!(
r.validation_mean().count,
1,
"only the scored item is counted"
);
assert_eq!(two_dp(r.validation_mean().chrf.unwrap()), 74.99);
let r = run([edited(1, with_relation), good_answers()[1].1.clone(), junk]);
assert_eq!(r.train()[0].outcome, Outcome::Refused(Stage::Lower));
assert!(
r.train()[0].packet.is_some(),
"a packet that lowers badly was admitted"
);
assert_eq!(r.validation_refused().parse, 1);
assert_eq!(two_dp(r.validation_mean().chrf.unwrap()), 82.12);
}
#[test]
fn errors_echo_no_input() {
let canary = "CANARYBYTES";
let tmp = tempfile::tempdir().unwrap();
let mut all: Vec<String> = Vec::new();
let mut note = |e: &dyn std::fmt::Debug, d: &dyn std::fmt::Display| {
all.push(format!("{e:?}"));
all.push(d.to_string());
};
// A draft error, from canary bytes in an answer.
let e = PacketDraft::parse(&format!("{{\"confidence\": {canary}}}")).unwrap_err();
note(&e, &e);
let e = PacketDraft::parse(&format!("{{\"{canary}\": 1}}")).unwrap_err();
note(&e, &e);
// Run errors, from a canary root, label and store path.
let root = tmp.path().join("canaryroot");
let e = RunStores::open(&root).err().unwrap();
note(&e, &e);
let missing = tmp.path().join("canarystore.cc");
let stores = RunPaths {
corpus: &missing,
inventory: &missing,
entities: &missing,
};
let e = RunStores::create(&root, "ok", stores, "m", "bag")
.err()
.unwrap();
note(&e, &e);
let e = RunStores::create(&root, &format!("{canary}!"), stores, "m", "bag")
.err()
.unwrap();
note(&e, &e);
let e = RunStores::create(&root, "ok", stores, &format!("{canary}\n"), "bag")
.err()
.unwrap();
note(&e, &e);
let w = world();
let run = run_over(w.dir.path());
let e = run.offer(&format!("item:{canary}:1")).err().unwrap();
note(&e, &e);
// A port error, from a canary directory.
let blocker = tmp.path().join("canaryfile");
std::fs::write(&blocker, "").unwrap();
let mut files = AnswerFiles::new(blocker.join("canarydir"), "m".into());
let e = files.answer(&prompt()).err().unwrap();
note(&e, &e);
// A round over canary answers records refusals, not the answers.
let mut dao = dao();
let mut model = fake(&[
(1, canary.into()),
(2, format!("{{\"{canary}\":1}}")),
(3, canary.into()),
]);
let r = recorded(round(&mut dao.run, &mut model, &Scorer::new(Bag)).unwrap());
all.push(format!("{r:?}"));
for text in &all {
assert!(!text.to_uppercase().contains("CANARY"), "{text}");
}
assert!(all.len() >= 12);
}
#[test]
fn prompts_come_only_from_context() {
let mut dao = dao();
let mut model = fake(&good_answers());
let r = recorded(round(&mut dao.run, &mut model, &Scorer::new(Bag)).unwrap());
assert_eq!(model.seen.len(), r.calls().len());
for ((digest, text), call) in model.seen.iter().zip(r.calls()) {
assert!(text.starts_with(ENCODE_INSTRUCTIONS));
assert_eq!(call.items.len(), 1);
assert_eq!(text.matches("[item:").count(), 1);
assert!(text.contains(&format!("[{}]", call.items[0])));
assert_eq!(&call.prompt, digest);
assert_eq!(*digest, format!("{:016x}", fnv1a64(text.as_bytes())));
}
}
/// Tripwires over the source, with the limits stated: they read text, so they
/// catch a spelling and not an alias.
#[test]
fn source_tripwires() {
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let read = |rel: &str| std::fs::read_to_string(src.join(rel)).unwrap();
for file in ["run.rs", "model.rs", "encode.rs"] {
let text = read(file);
for banned in ["Split::Test", "Checkpoint"] {
assert!(!text.contains(banned), "{file} names {banned}");
}
}
let mut all = Vec::new();
let mut stack = vec![src.clone()];
while let Some(dir) = stack.pop() {
for entry in std::fs::read_dir(dir).unwrap() {
let path = entry.unwrap().path();
if path.is_dir() {
stack.push(path);
} else if path.extension().is_some_and(|e| e == "rs") {
all.push((
path.strip_prefix(&src)
.unwrap()
.to_str()
.unwrap()
.to_string(),
std::fs::read_to_string(&path).unwrap(),
));
}
}
}
for (file, text) in &all {
let code: String = text
.lines()
.filter(|l| !l.trim_start().starts_with("//"))
.collect::<Vec<_>>()
.join("\n");
if file != "main.rs" {
assert!(!code.contains("std::process"), "{file}");
}
// The Ollama reply is the other xenos boundary: JSON read from a server.
if file != "encode.rs" && file != "score/embed.rs" {
assert!(!code.contains("serde_json::from_str"), "{file}");
}
if file != "context.rs" {
assert!(!code.contains("Prompt {"), "{file}");
}
}
let context = read("context.rs");
assert!(!context.contains("pub fn from_corpus") && !context.contains("pub fn for_round"));
}

View file

@ -6,7 +6,7 @@ use std::net::TcpListener;
use std::sync::{Arc, Mutex};
use anyhow::Result;
use common::{cast, group_in_bucket, item_in, model};
use common::{Bag, cast, group_in_bucket, item_in, model};
use serde_json::Value;
use weksa::CorpusItem;
use weksa::score::{
@ -71,28 +71,6 @@ impl Embedder for Recorder {
}
}
/// A deterministic bag-of-letters embedder, so cosine differs with the text.
struct Bag;
impl Embedder for Bag {
fn model(&self) -> &str {
"bag"
}
fn embed(&self, texts: &[&str]) -> Result<Vec<Vec<f32>>> {
Ok(texts
.iter()
.map(|t| {
let mut v = vec![0.0; 27];
v[26] = 1.0;
for c in t.chars().filter(char::is_ascii_alphabetic) {
v[(c.to_ascii_lowercase() as u8 - b'a') as usize] += 1.0;
}
v
})
.collect())
}
}
fn score_one<E: Embedder>(scorer: &Scorer<E>, reference: &str, output: &str) -> ItemScore {
scorer
.score(&[ScoreInput { reference, output }])