weksa loop cycle: a Train-only editor proposes an inventory edit, a candidate round scores it, a Ladder-stepped noise-floor rule accepts or rejects on Validation
Reading, decide and LADDER_STEP are pure; Decision (weksa.loop_decision) holds digests and numbers; the latest Accepted decision names the run's head. The candidate round and its decision are one batch put. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a8918c6ff1
commit
ae8deb1e03
9 changed files with 1687 additions and 24 deletions
|
|
@ -263,8 +263,6 @@ impl EditFeedback {
|
|||
}
|
||||
}
|
||||
|
||||
// Called by run::cycle (cut commit 5 of golf-loop-edit-accept).
|
||||
#[allow(dead_code)]
|
||||
/// `last`: whether the previous edit was accepted; `head`: the composite at
|
||||
/// the current inventory, rounded here to the nearest [`LADDER_STEP`].
|
||||
pub(crate) fn new(last: Option<bool>, head: Option<f64>) -> Self {
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ pub mod store;
|
|||
pub mod validate;
|
||||
|
||||
pub use corpus::{CorpusItem, CorpusItemId, NameSpan, Source, Turn};
|
||||
pub use encode::PacketDraft;
|
||||
pub use encode::{EditDraft, PacketDraft};
|
||||
pub use entity::{Entity, EntityOrigin, LanguageForms, Pronunciation};
|
||||
pub use form::FormError;
|
||||
pub use inventory::{
|
||||
|
|
@ -36,7 +36,7 @@ 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 run::{Decision, RoundRecord, RunStores, cycle, round};
|
||||
pub use score::{Embedder, ItemScore, OllamaEmbedder, Scorer, chrf};
|
||||
pub use speaker::{Annotator, PairRelation, Party, Scene, Speaker};
|
||||
pub use split::{Split, SplitScheme};
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ use weksa::corpus::{CorpusItem, ModelFamily, NameSpan, Source, Turn};
|
|||
use weksa::entity::{Entity, EntityOrigin, LanguageForms, Pronunciation};
|
||||
use weksa::inventory::{proof_revision, seed};
|
||||
use weksa::packet::proof_packet;
|
||||
use weksa::run::{RoundOutcome, RunPaths, RunStores, round};
|
||||
use weksa::run::{CycleOutcome, RoundOutcome, RunPaths, RunStores, cycle, round};
|
||||
use weksa::score::ScoreInput;
|
||||
use weksa::{
|
||||
AnswerFiles, CorpusStore, EntityId, EntityStore, InventoryStore, OllamaEmbedder, PacketStore,
|
||||
|
|
@ -98,6 +98,15 @@ enum LoopCommand {
|
|||
#[arg(long, default_value = "http://127.0.0.1:11434")]
|
||||
ollama_url: String,
|
||||
},
|
||||
/// Run one edit-accept cycle of the run at ROOT. The stores are read only
|
||||
/// from the run's record. Prompts without answers are written to the
|
||||
/// cycle's directory and the command exits 3; rerun after the `.answer`
|
||||
/// files exist.
|
||||
Cycle {
|
||||
root: PathBuf,
|
||||
#[arg(long, default_value = "http://127.0.0.1:11434")]
|
||||
ollama_url: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand)]
|
||||
|
|
@ -758,6 +767,25 @@ fn main() -> Result<()> {
|
|||
RoundOutcome::Recorded(r) => println!("{}", r.summary_line()),
|
||||
}
|
||||
}
|
||||
Command::Loop(LoopCommand::Cycle { root, ollama_url }) => {
|
||||
let unreadable = |_| anyhow::anyhow!("a store would not read");
|
||||
let mut run = RunStores::open(&root)?;
|
||||
let mut files = AnswerFiles::new(
|
||||
run.next_cycle_dir().map_err(unreadable)?,
|
||||
run.record().model.clone(),
|
||||
);
|
||||
let scorer = Scorer::new(OllamaEmbedder::new(&ollama_url, &run.record().embedder));
|
||||
match cycle(&mut run, &mut files, &scorer)? {
|
||||
CycleOutcome::Unanswered { prompts } => {
|
||||
for digest in &prompts {
|
||||
println!("unanswered {digest}");
|
||||
}
|
||||
println!("unanswered {} prompts", prompts.len());
|
||||
std::process::exit(3);
|
||||
}
|
||||
CycleOutcome::Decided(decision) => println!("{}", decision.summary_line()),
|
||||
}
|
||||
}
|
||||
Command::Schema { out } => {
|
||||
std::fs::create_dir_all(&out)?;
|
||||
for (name, json) in weksa::schema::published() {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
//! 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`).
|
||||
//! One golf-loop run: the stores it pinned at open, the rounds and decisions it
|
||||
//! has recorded, and the one writer of all of them (`RunStores::create`, `round`
|
||||
//! and `cycle`). A cycle asks an editor for one inventory edit, scores a
|
||||
//! candidate round under it and accepts or rejects on Validation (`decide`); the
|
||||
//! latest Accepted decision names the run's head inventory.
|
||||
//!
|
||||
//! A run pins its corpus and entity store files by canonical path and FNV-1a 64
|
||||
//! digest of their bytes. It works on its own copy of the inventory:
|
||||
|
|
@ -23,9 +26,9 @@ use cultcache_rs::{CultCache, DatabaseEntry};
|
|||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::context::{EncoderOffer, Prompt, TrainItems};
|
||||
use crate::context::{EditFeedback, EncoderOffer, Prompt, TrainItems};
|
||||
use crate::corpus::{CorpusItem, CorpusItemId};
|
||||
use crate::encode::{PacketDraft, encoder_id};
|
||||
use crate::encode::{EditDraft, PacketDraft, encoder_id};
|
||||
use crate::form::{is_attestation, is_slug};
|
||||
use crate::lower::lower;
|
||||
use crate::model::{ModelPort, PortError};
|
||||
|
|
@ -329,6 +332,10 @@ pub enum RunError {
|
|||
Store,
|
||||
/// The embedder failed.
|
||||
Embed,
|
||||
/// Rounds 1 and 2 are not two plain replicates under the run's first inventory.
|
||||
NoFloor,
|
||||
/// A round has no Validation reading.
|
||||
NoValidation,
|
||||
}
|
||||
|
||||
impl fmt::Display for RunError {
|
||||
|
|
@ -342,6 +349,8 @@ impl fmt::Display for RunError {
|
|||
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"),
|
||||
RunError::NoFloor => f.write_str("the run has no noise floor: record two rounds first"),
|
||||
RunError::NoValidation => f.write_str("a reading has no validation item"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -395,7 +404,8 @@ fn canonical(path: &Path) -> Result<String, RunError> {
|
|||
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>()
|
||||
c.register_entry_type::<RoundRecord>()?;
|
||||
c.register_entry_type::<Decision>()
|
||||
})
|
||||
.map_err(|_| RunError::Store)
|
||||
}
|
||||
|
|
@ -480,7 +490,8 @@ impl RunStores {
|
|||
if file_digest(&record.entities).as_ref() != Some(&record.entity_digest) {
|
||||
return Err(RunError::Drift(DriftOf::Entities));
|
||||
}
|
||||
if file_digest_at(&root.join(INVENTORY_FILE)).as_ref() != Some(&record.inventory_digest) {
|
||||
let (path, digest, _) = head_of(&cache, root, &record)?;
|
||||
if file_digest_at(&path).as_ref() != Some(&digest) {
|
||||
return Err(RunError::Drift(DriftOf::Inventory));
|
||||
}
|
||||
Self::with(root, cache, record)
|
||||
|
|
@ -488,10 +499,11 @@ impl RunStores {
|
|||
|
||||
fn with(root: &Path, cache: CultCache, record: RunRecord) -> Result<Self, RunError> {
|
||||
let store = |_| RunError::Store;
|
||||
let (head, _, _) = head_of(&cache, root, &record)?;
|
||||
Ok(Self {
|
||||
root: root.to_path_buf(),
|
||||
corpus: CorpusStore::open(Path::new(&record.corpus)).map_err(store)?,
|
||||
inventory: InventoryStore::open(&root.join(INVENTORY_FILE)).map_err(store)?,
|
||||
inventory: InventoryStore::open(&head).map_err(store)?,
|
||||
entities: EntityStore::open(Path::new(&record.entities)).map_err(store)?,
|
||||
cache,
|
||||
record,
|
||||
|
|
@ -547,6 +559,23 @@ impl RunStores {
|
|||
Ok(rounds)
|
||||
}
|
||||
|
||||
/// The recorded decisions, by cycle.
|
||||
pub fn decisions(&self) -> anyhow::Result<Vec<Decision>> {
|
||||
decisions_of(&self.cache)
|
||||
}
|
||||
|
||||
/// The head inventory file, its digest and its establishing round.
|
||||
fn head(&self) -> Result<(PathBuf, String, u32), RunError> {
|
||||
head_of(&self.cache, &self.root, &self.record)
|
||||
}
|
||||
|
||||
/// `<root>/cycle-<k>` for the next undecided cycle `k`.
|
||||
pub fn next_cycle_dir(&self) -> anyhow::Result<PathBuf> {
|
||||
Ok(self
|
||||
.root
|
||||
.join(format!("cycle-{}", self.decisions()?.len() + 1)))
|
||||
}
|
||||
|
||||
/// `<root>/round-<n>` for the next unrecorded round `n`.
|
||||
pub fn next_round_dir(&self) -> anyhow::Result<PathBuf> {
|
||||
Ok(self
|
||||
|
|
@ -555,8 +584,42 @@ impl RunStores {
|
|||
}
|
||||
}
|
||||
|
||||
/// What a round came to.
|
||||
fn decisions_of(cache: &CultCache) -> anyhow::Result<Vec<Decision>> {
|
||||
let mut decisions = cache.get_all::<Decision>()?;
|
||||
decisions.sort_by_key(Decision::k);
|
||||
Ok(decisions)
|
||||
}
|
||||
|
||||
/// The head is derived, never stored: the latest Accepted decision names it
|
||||
/// (`<root>/cycle-<k>/inventory.cc`, its candidate digest, its candidate round);
|
||||
/// with none it is the copy `create` made and round 1.
|
||||
fn head_of(
|
||||
cache: &CultCache,
|
||||
root: &Path,
|
||||
record: &RunRecord,
|
||||
) -> Result<(PathBuf, String, u32), RunError> {
|
||||
let decisions = decisions_of(cache).map_err(|_| RunError::Store)?;
|
||||
let accepted = decisions.iter().rfind(|d| d.verdict == Verdict::Accepted);
|
||||
match accepted {
|
||||
None => Ok((
|
||||
root.join(INVENTORY_FILE),
|
||||
record.inventory_digest.clone(),
|
||||
1,
|
||||
)),
|
||||
Some(d) => Ok((
|
||||
root.join(format!("cycle-{}", d.k)).join(INVENTORY_FILE),
|
||||
d.candidate_inventory_digest
|
||||
.clone()
|
||||
.ok_or(RunError::Store)?,
|
||||
d.candidate_round.ok_or(RunError::Store)?,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// What a round came to. One is built per call and matched at once, so the
|
||||
/// size of the record is not worth an indirection.
|
||||
#[derive(Debug)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum RoundOutcome {
|
||||
/// Prompts nobody has answered; nothing was written to the run or admitted.
|
||||
Unanswered {
|
||||
|
|
@ -588,7 +651,7 @@ pub fn round<M: ModelPort, E: Embedder>(
|
|||
check_drift(run, model, scorer)?;
|
||||
let store = |_| RunError::Store;
|
||||
let dir = run.next_round_dir().map_err(store)?;
|
||||
let digest = run.record.inventory_digest.clone();
|
||||
let (_, digest, _) = run.head()?;
|
||||
match score_round(run, &run.inventory, &digest, &dir, None, model, scorer)? {
|
||||
RoundOutcome::Recorded(record) => {
|
||||
run.cache
|
||||
|
|
@ -789,6 +852,386 @@ fn score_round<M: ModelPort, E: Embedder>(
|
|||
Ok(RoundOutcome::Recorded(record))
|
||||
}
|
||||
|
||||
/// One validation reading: chrF 0 to 100, meaning 0 to 1, and their composite.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize, JsonSchema)]
|
||||
pub struct Reading {
|
||||
pub chrf: f64,
|
||||
pub meaning: f64,
|
||||
pub composite: f64,
|
||||
}
|
||||
|
||||
impl Reading {
|
||||
/// `None` when the split has no items or no chrF; a missing meaning reads as
|
||||
/// 0. The composite is the mean of chrF as a fraction and meaning.
|
||||
pub fn of(mean: &SplitMean) -> Option<Self> {
|
||||
if mean.count == 0 {
|
||||
return None;
|
||||
}
|
||||
let chrf = mean.chrf?;
|
||||
let meaning = mean.meaning.unwrap_or(0.0);
|
||||
Some(Self {
|
||||
chrf,
|
||||
meaning,
|
||||
composite: (chrf / 100.0 + meaning) / 2.0,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Which metric an edit regressed.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub enum Metric {
|
||||
Chrf,
|
||||
Meaning,
|
||||
}
|
||||
|
||||
/// Why an edit was rejected.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub enum Why {
|
||||
/// The answer was not an edit draft.
|
||||
EditParse,
|
||||
/// The draft asked for no change or too many, or the inventory door refused it.
|
||||
EditAdmit,
|
||||
NoGain,
|
||||
Regressed(Metric),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
|
||||
pub enum Verdict {
|
||||
Accepted,
|
||||
Rejected(Why),
|
||||
}
|
||||
|
||||
/// The smallest composite gain that accepts an edit: the measured floor, but
|
||||
/// never under one [`LADDER_STEP`], so a zero floor from identical replicates
|
||||
/// does not let a rounding-error gain through.
|
||||
pub fn threshold(floor: &Reading) -> f64 {
|
||||
floor.composite.max(LADDER_STEP)
|
||||
}
|
||||
|
||||
/// The accept rule. A metric that falls by more than its tolerance (the floor,
|
||||
/// at least one step) rejects; otherwise the composite must gain strictly more
|
||||
/// than [`threshold`]. Means count a refused Validation item as 0, so refusing a
|
||||
/// weak item cannot raise a reading.
|
||||
pub fn decide(base: &Reading, candidate: &Reading, floor: &Reading) -> Verdict {
|
||||
if candidate.chrf - base.chrf < -floor.chrf.max(100.0 * LADDER_STEP) {
|
||||
Verdict::Rejected(Why::Regressed(Metric::Chrf))
|
||||
} else if candidate.meaning - base.meaning < -floor.meaning.max(LADDER_STEP) {
|
||||
Verdict::Rejected(Why::Regressed(Metric::Meaning))
|
||||
} else if candidate.composite - base.composite > threshold(floor) {
|
||||
Verdict::Accepted
|
||||
} else {
|
||||
Verdict::Rejected(Why::NoGain)
|
||||
}
|
||||
}
|
||||
|
||||
/// One closed edit-accept cycle: digests and numbers, no text. Key
|
||||
/// `run:<label>:cycle:<k>`. Only [`cycle`] builds one.
|
||||
///
|
||||
/// ```
|
||||
/// fn f(d: &weksa::run::Decision) -> u32 { d.k() }
|
||||
/// ```
|
||||
///
|
||||
/// Every field is given, so the literal below fails only on privacy; its twin is
|
||||
/// the same literal in the unit test `a_decision_literal_compiles_in_the_lib`.
|
||||
///
|
||||
/// ```compile_fail,E0451
|
||||
/// use weksa::run::{Call, Decision, Reading, Verdict};
|
||||
/// fn f() -> Decision {
|
||||
/// let r = Reading { chrf: 0.0, meaning: 0.0, composite: 0.0 };
|
||||
/// Decision {
|
||||
/// k: 1,
|
||||
/// base_round: 1,
|
||||
/// base_rev: 1,
|
||||
/// base_inventory_digest: String::new(),
|
||||
/// edit: Call { prompt: String::new(), items: vec![] },
|
||||
/// edit_answer_digest: None,
|
||||
/// candidate_rev: None,
|
||||
/// candidate_inventory_digest: None,
|
||||
/// candidate_round: None,
|
||||
/// base: r,
|
||||
/// candidate: None,
|
||||
/// floor: r,
|
||||
/// threshold: 0.0,
|
||||
/// verdict: Verdict::Accepted,
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
#[derive(Clone, Debug, PartialEq, JsonSchema, DatabaseEntry)]
|
||||
#[cultcache(type = "weksa.loop_decision")]
|
||||
pub struct Decision {
|
||||
#[cultcache(key = 0)]
|
||||
k: u32,
|
||||
/// The head's establishing round: the base of this cycle.
|
||||
#[cultcache(key = 1)]
|
||||
base_round: u32,
|
||||
#[cultcache(key = 2)]
|
||||
base_rev: u32,
|
||||
#[cultcache(key = 3)]
|
||||
base_inventory_digest: String,
|
||||
/// The edit prompt's digest and the Train keys it held.
|
||||
#[cultcache(key = 4)]
|
||||
edit: Call,
|
||||
/// 16 hex of the editor's answer; `None` when it was unreadable.
|
||||
#[cultcache(key = 5)]
|
||||
edit_answer_digest: Option<String>,
|
||||
#[cultcache(key = 6)]
|
||||
candidate_rev: Option<u32>,
|
||||
#[cultcache(key = 7)]
|
||||
candidate_inventory_digest: Option<String>,
|
||||
#[cultcache(key = 8)]
|
||||
candidate_round: Option<u32>,
|
||||
#[cultcache(key = 9)]
|
||||
base: Reading,
|
||||
#[cultcache(key = 10)]
|
||||
candidate: Option<Reading>,
|
||||
#[cultcache(key = 11)]
|
||||
floor: Reading,
|
||||
#[cultcache(key = 12)]
|
||||
threshold: f64,
|
||||
#[cultcache(key = 13)]
|
||||
verdict: Verdict,
|
||||
}
|
||||
|
||||
impl Decision {
|
||||
pub fn k(&self) -> u32 {
|
||||
self.k
|
||||
}
|
||||
pub fn base_round(&self) -> u32 {
|
||||
self.base_round
|
||||
}
|
||||
pub fn base_rev(&self) -> u32 {
|
||||
self.base_rev
|
||||
}
|
||||
pub fn base_inventory_digest(&self) -> &str {
|
||||
&self.base_inventory_digest
|
||||
}
|
||||
pub fn edit(&self) -> &Call {
|
||||
&self.edit
|
||||
}
|
||||
pub fn edit_answer_digest(&self) -> Option<&str> {
|
||||
self.edit_answer_digest.as_deref()
|
||||
}
|
||||
pub fn candidate_rev(&self) -> Option<u32> {
|
||||
self.candidate_rev
|
||||
}
|
||||
pub fn candidate_inventory_digest(&self) -> Option<&str> {
|
||||
self.candidate_inventory_digest.as_deref()
|
||||
}
|
||||
pub fn candidate_round(&self) -> Option<u32> {
|
||||
self.candidate_round
|
||||
}
|
||||
pub fn base(&self) -> &Reading {
|
||||
&self.base
|
||||
}
|
||||
pub fn candidate(&self) -> Option<&Reading> {
|
||||
self.candidate.as_ref()
|
||||
}
|
||||
pub fn floor(&self) -> &Reading {
|
||||
&self.floor
|
||||
}
|
||||
pub fn threshold(&self) -> f64 {
|
||||
self.threshold
|
||||
}
|
||||
pub fn verdict(&self) -> Verdict {
|
||||
self.verdict
|
||||
}
|
||||
|
||||
/// The one line a closed cycle prints.
|
||||
pub fn summary_line(&self) -> String {
|
||||
let candidate_rev = self
|
||||
.candidate_rev
|
||||
.map_or("none".to_string(), |n| n.to_string());
|
||||
let candidate = self
|
||||
.candidate
|
||||
.map_or("none".to_string(), |c| format!("{:.4}", c.composite));
|
||||
let verdict = match self.verdict {
|
||||
Verdict::Accepted => "accepted".to_string(),
|
||||
Verdict::Rejected(why) => format!(
|
||||
"rejected {}",
|
||||
match why {
|
||||
Why::EditParse => "edit-parse",
|
||||
Why::EditAdmit => "edit-admit",
|
||||
Why::NoGain => "no-gain",
|
||||
Why::Regressed(Metric::Chrf) => "regressed-chrf",
|
||||
Why::Regressed(Metric::Meaning) => "regressed-meaning",
|
||||
}
|
||||
),
|
||||
};
|
||||
format!(
|
||||
"cycle {} rev {}->{candidate_rev} base={:.4} candidate={candidate} floor={:.4} threshold={:.4} {verdict}",
|
||||
self.k, self.base_rev, self.base.composite, self.floor.composite, self.threshold
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a cycle came to; built once per call, as [`RoundOutcome`] is.
|
||||
#[derive(Debug)]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum CycleOutcome {
|
||||
/// Prompts nobody has answered; nothing was written to `run.cc`.
|
||||
Unanswered {
|
||||
prompts: Vec<String>,
|
||||
},
|
||||
Decided(Decision),
|
||||
}
|
||||
|
||||
/// The spread of the Validation reading between rounds 1 and 2: two independent
|
||||
/// encodings under the run's first inventory and one spec, measured once per run.
|
||||
fn floor_of(rounds: &[RoundRecord], record: &RunRecord) -> Result<Reading, RunError> {
|
||||
let replicate = |n: u32| {
|
||||
let round = rounds
|
||||
.iter()
|
||||
.find(|r| {
|
||||
r.n == n && r.cycle.is_none() && r.inventory_digest == record.inventory_digest
|
||||
})
|
||||
.ok_or(RunError::NoFloor)?;
|
||||
Reading::of(&round.validation_mean).ok_or(RunError::NoValidation)
|
||||
};
|
||||
let (a, b) = (replicate(1)?, replicate(2)?);
|
||||
Ok(Reading {
|
||||
chrf: (a.chrf - b.chrf).abs(),
|
||||
meaning: (a.meaning - b.meaning).abs(),
|
||||
composite: (a.composite - b.composite).abs(),
|
||||
})
|
||||
}
|
||||
|
||||
/// One edit-accept cycle. The editor is asked for one inventory edit from a
|
||||
/// prompt built over Train items, the head inventory and an [`EditFeedback`];
|
||||
/// the edit is admitted as a candidate revision in `<root>/cycle-<k>/inventory.cc`;
|
||||
/// a candidate round scores it; [`decide`] accepts or rejects on Validation
|
||||
/// against the head's establishing round. Accepting is one write: the candidate
|
||||
/// round and the decision go into `run.cc` in one batch, and the decision names
|
||||
/// the new head. While any prompt is unanswered, or the candidate round fails,
|
||||
/// `run.cc` is untouched. An edit that fails is a rejected decision, not an error.
|
||||
pub fn cycle<M: ModelPort, E: Embedder>(
|
||||
run: &mut RunStores,
|
||||
model: &mut M,
|
||||
scorer: &Scorer<E>,
|
||||
) -> Result<CycleOutcome, RunError> {
|
||||
let store = |_| RunError::Store;
|
||||
check_drift(run, model, scorer)?;
|
||||
let rounds = run.rounds().map_err(store)?;
|
||||
let floor = floor_of(&rounds, &run.record)?;
|
||||
let (head_path, head_digest, base_round) = run.head()?;
|
||||
let base = rounds
|
||||
.iter()
|
||||
.find(|r| r.n == base_round)
|
||||
.ok_or(RunError::Store)?;
|
||||
let base = Reading::of(&base.validation_mean).ok_or(RunError::NoValidation)?;
|
||||
let decisions = run.decisions().map_err(store)?;
|
||||
let k = decisions.len() as u32 + 1;
|
||||
let dir = run.next_cycle_dir().map_err(store)?;
|
||||
let inventory = run.inventory.inventory().map_err(store)?;
|
||||
let base_rev = inventory.latest().ok_or(RunError::NoInventory)?.n;
|
||||
|
||||
let feedback = EditFeedback::new(
|
||||
decisions.last().map(|d| d.verdict == Verdict::Accepted),
|
||||
Some(base.composite),
|
||||
);
|
||||
let train = run.train().map_err(store)?;
|
||||
let prompt = Prompt::mint(&train, &inventory, base_rev, &feedback);
|
||||
let answer = match model.answer(&prompt) {
|
||||
Ok(answer) => Some(answer),
|
||||
Err(PortError::Io(ErrorKind::InvalidData)) => None,
|
||||
Err(PortError::Unanswered) => {
|
||||
return Ok(CycleOutcome::Unanswered {
|
||||
prompts: vec![prompt.digest()],
|
||||
});
|
||||
}
|
||||
Err(PortError::Io(kind)) => return Err(RunError::Io(kind)),
|
||||
};
|
||||
|
||||
let blank = |verdict: Verdict| Decision {
|
||||
k,
|
||||
base_round,
|
||||
base_rev,
|
||||
base_inventory_digest: head_digest.clone(),
|
||||
edit: Call {
|
||||
prompt: prompt.digest(),
|
||||
items: prompt.item_keys().to_vec(),
|
||||
},
|
||||
edit_answer_digest: answer.as_ref().map(|a| hex16(fnv1a64(a.as_bytes()))),
|
||||
candidate_rev: None,
|
||||
candidate_inventory_digest: None,
|
||||
candidate_round: None,
|
||||
base,
|
||||
candidate: None,
|
||||
floor,
|
||||
threshold: threshold(&floor),
|
||||
verdict,
|
||||
};
|
||||
let decision_key = format!("run:{}:cycle:{k}", run.record.label);
|
||||
let reject = |run: &mut RunStores, why: Why| -> Result<CycleOutcome, RunError> {
|
||||
let d = blank(Verdict::Rejected(why));
|
||||
run.cache.put(decision_key.clone(), &d).map_err(store)?;
|
||||
Ok(CycleOutcome::Decided(d))
|
||||
};
|
||||
|
||||
let Some(draft) = answer.as_deref().and_then(|a| EditDraft::parse(a).ok()) else {
|
||||
return reject(run, Why::EditParse);
|
||||
};
|
||||
let Some((revision, entries)) = draft.into_revision(&inventory, base_rev) else {
|
||||
return reject(run, Why::EditAdmit);
|
||||
};
|
||||
let candidate_rev = revision.n;
|
||||
|
||||
// The cycle's directory holds prompts and answers; its inventory and packets
|
||||
// are rebuilt from the head on every attempt.
|
||||
let candidate_file = dir.join(INVENTORY_FILE);
|
||||
std::fs::create_dir_all(&dir).map_err(|e| RunError::Io(e.kind()))?;
|
||||
discard_inventory(&dir);
|
||||
discard_packets(&dir);
|
||||
std::fs::copy(&head_path, &candidate_file).map_err(|e| RunError::Io(e.kind()))?;
|
||||
let mut candidate_store = InventoryStore::open(&candidate_file).map_err(store)?;
|
||||
if candidate_store.admit_revision(revision, entries).is_err() {
|
||||
drop(candidate_store);
|
||||
discard_inventory(&dir);
|
||||
return reject(run, Why::EditAdmit);
|
||||
}
|
||||
let candidate_digest = file_digest_at(&candidate_file).ok_or(RunError::Store)?;
|
||||
|
||||
let record = match score_round(
|
||||
run,
|
||||
&candidate_store,
|
||||
&candidate_digest,
|
||||
&dir,
|
||||
Some(k),
|
||||
model,
|
||||
scorer,
|
||||
)? {
|
||||
RoundOutcome::Unanswered { prompts } => return Ok(CycleOutcome::Unanswered { prompts }),
|
||||
RoundOutcome::Recorded(record) => record,
|
||||
};
|
||||
let candidate = Reading::of(&record.validation_mean).ok_or(RunError::NoValidation)?;
|
||||
let verdict = decide(&base, &candidate, &floor);
|
||||
let decided = Decision {
|
||||
candidate_rev: Some(candidate_rev),
|
||||
candidate_inventory_digest: Some(candidate_digest),
|
||||
candidate_round: Some(record.n),
|
||||
candidate: Some(candidate),
|
||||
verdict,
|
||||
..blank(verdict)
|
||||
};
|
||||
let staged = vec![
|
||||
run.cache
|
||||
.prepare_entry_named(
|
||||
format!("run:{}:round:{}", run.record.label, record.n),
|
||||
&record,
|
||||
)
|
||||
.map_err(store)?
|
||||
.0,
|
||||
run.cache
|
||||
.prepare_entry_named(decision_key.clone(), &decided)
|
||||
.map_err(store)?
|
||||
.0,
|
||||
];
|
||||
run.cache.put_prepared_batch(staged).map_err(store)?;
|
||||
if verdict == Verdict::Accepted {
|
||||
run.inventory = candidate_store;
|
||||
}
|
||||
Ok(CycleOutcome::Decided(decided))
|
||||
}
|
||||
|
||||
/// Removes a round directory's packet store and its lock.
|
||||
fn discard_packets(dir: &Path) {
|
||||
for name in ["packets.cc", "packets.cc.lock"] {
|
||||
|
|
@ -796,6 +1239,13 @@ fn discard_packets(dir: &Path) {
|
|||
}
|
||||
}
|
||||
|
||||
/// Removes a cycle directory's candidate inventory and its lock.
|
||||
fn discard_inventory(dir: &Path) {
|
||||
for name in [INVENTORY_FILE, "inventory.cc.lock"] {
|
||||
let _ = std::fs::remove_file(dir.join(name));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -826,4 +1276,143 @@ mod tests {
|
|||
};
|
||||
assert_eq!(r.n(), 1);
|
||||
}
|
||||
|
||||
/// The twin of the `Decision` literal in its compile_fail doctest.
|
||||
#[test]
|
||||
fn a_decision_literal_compiles_in_the_lib() {
|
||||
let r = Reading {
|
||||
chrf: 0.0,
|
||||
meaning: 0.0,
|
||||
composite: 0.0,
|
||||
};
|
||||
let d = Decision {
|
||||
k: 1,
|
||||
base_round: 1,
|
||||
base_rev: 1,
|
||||
base_inventory_digest: String::new(),
|
||||
edit: Call {
|
||||
prompt: String::new(),
|
||||
items: vec![],
|
||||
},
|
||||
edit_answer_digest: None,
|
||||
candidate_rev: None,
|
||||
candidate_inventory_digest: None,
|
||||
candidate_round: None,
|
||||
base: r,
|
||||
candidate: None,
|
||||
floor: r,
|
||||
threshold: 0.0,
|
||||
verdict: Verdict::Accepted,
|
||||
};
|
||||
assert_eq!(d.k(), 1);
|
||||
}
|
||||
|
||||
fn reading(chrf: f64, meaning: f64, composite: f64) -> Reading {
|
||||
Reading {
|
||||
chrf,
|
||||
meaning,
|
||||
composite,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reading_of_a_mean() {
|
||||
let mean = |count, chrf, meaning| SplitMean {
|
||||
count,
|
||||
chrf,
|
||||
meaning,
|
||||
};
|
||||
assert_eq!(Reading::of(&mean(0, Some(50.0), Some(0.5))), None);
|
||||
assert_eq!(Reading::of(&mean(2, None, Some(0.5))), None);
|
||||
assert_eq!(
|
||||
Reading::of(&mean(2, Some(50.0), Some(0.5))),
|
||||
Some(reading(50.0, 0.5, 0.5))
|
||||
);
|
||||
// A missing meaning reads as 0.
|
||||
assert_eq!(
|
||||
Reading::of(&mean(2, Some(80.0), None)),
|
||||
Some(reading(80.0, 0.0, 0.4))
|
||||
);
|
||||
assert_eq!(
|
||||
Reading::of(&mean(1, Some(0.0), Some(1.0)))
|
||||
.unwrap()
|
||||
.composite,
|
||||
0.5
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_threshold_is_the_floor_but_never_under_a_step() {
|
||||
assert_eq!(threshold(&reading(0.0, 0.0, 0.0)), LADDER_STEP);
|
||||
assert_eq!(threshold(&reading(0.0, 0.0, 0.001)), LADDER_STEP);
|
||||
assert_eq!(threshold(&reading(0.0, 0.0, LADDER_STEP)), LADDER_STEP);
|
||||
assert_eq!(threshold(&reading(0.0, 0.0, 0.25)), 0.25);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decide_pins_each_branch() {
|
||||
let base = reading(50.0, 0.5, 0.5);
|
||||
let zero = reading(0.0, 0.0, 0.0);
|
||||
let rejected = Verdict::Rejected;
|
||||
|
||||
// Floor 0: a chrF drop beyond 100 * LADDER_STEP regresses, inside it does not.
|
||||
let down = |chrf| reading(chrf, 0.5, 0.5);
|
||||
assert_eq!(
|
||||
decide(&base, &down(49.4), &zero),
|
||||
rejected(Why::Regressed(Metric::Chrf))
|
||||
);
|
||||
assert_eq!(decide(&base, &down(49.6), &zero), rejected(Why::NoGain));
|
||||
// The tolerance is the floor when that is larger: exactly at it stands.
|
||||
let floor = reading(8.0, 0.0, 0.0);
|
||||
assert_eq!(decide(&base, &down(42.0), &floor), rejected(Why::NoGain));
|
||||
assert_eq!(
|
||||
decide(&base, &down(41.99), &floor),
|
||||
rejected(Why::Regressed(Metric::Chrf))
|
||||
);
|
||||
// A floor under a step does not narrow it.
|
||||
let small = reading(0.1, 0.001, 0.0);
|
||||
assert_eq!(decide(&base, &down(49.6), &small), rejected(Why::NoGain));
|
||||
assert_eq!(
|
||||
decide(&base, &reading(50.0, 0.498, 0.5), &small),
|
||||
rejected(Why::NoGain)
|
||||
);
|
||||
// Meaning likewise: one step by default, the floor when larger.
|
||||
let meaning = |m| reading(50.0, m, 0.5);
|
||||
assert_eq!(
|
||||
decide(&base, &meaning(0.49), &zero),
|
||||
rejected(Why::Regressed(Metric::Meaning))
|
||||
);
|
||||
assert_eq!(decide(&base, &meaning(0.498), &zero), rejected(Why::NoGain));
|
||||
let floor = reading(0.0, 0.25, 0.0);
|
||||
assert_eq!(decide(&base, &meaning(0.25), &floor), rejected(Why::NoGain));
|
||||
assert_eq!(
|
||||
decide(&base, &meaning(0.2499), &floor),
|
||||
rejected(Why::Regressed(Metric::Meaning))
|
||||
);
|
||||
// A regression rejects whatever the composite gained; chrF is judged first.
|
||||
assert_eq!(
|
||||
decide(&base, &reading(40.0, 0.9, 0.9), &zero),
|
||||
rejected(Why::Regressed(Metric::Chrf))
|
||||
);
|
||||
assert_eq!(
|
||||
decide(&base, &reading(50.0, 0.4, 0.9), &zero),
|
||||
rejected(Why::Regressed(Metric::Meaning))
|
||||
);
|
||||
assert_eq!(
|
||||
decide(&base, &reading(40.0, 0.4, 0.1), &zero),
|
||||
rejected(Why::Regressed(Metric::Chrf))
|
||||
);
|
||||
|
||||
// The gain must exceed the threshold strictly.
|
||||
let gain = |c| reading(50.0, 0.5, c);
|
||||
assert_eq!(decide(&base, &gain(0.504), &zero), rejected(Why::NoGain));
|
||||
assert_eq!(decide(&base, &gain(0.506), &zero), Verdict::Accepted);
|
||||
assert_eq!(decide(&base, &gain(0.5), &zero), rejected(Why::NoGain));
|
||||
assert_eq!(decide(&base, &gain(0.4), &zero), rejected(Why::NoGain));
|
||||
// A floor above the step sets the threshold: a gain equal to it is no gain.
|
||||
let floor = reading(0.0, 0.0, 0.25);
|
||||
assert_eq!(decide(&base, &gain(0.75), &floor), rejected(Why::NoGain));
|
||||
assert_eq!(decide(&base, &gain(0.7501), &floor), Verdict::Accepted);
|
||||
assert_eq!(decide(&base, &gain(0.506), &floor), rejected(Why::NoGain));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +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::run::{Decision, RoundRecord, RunRecord};
|
||||
use crate::speaker::{Scene, Speaker};
|
||||
use cultcache_rs::DatabaseEntry;
|
||||
use schemars::{JsonSchema, schema_for};
|
||||
|
|
@ -27,5 +27,6 @@ pub fn published() -> Vec<(String, String)> {
|
|||
published_for::<Scene>(),
|
||||
published_for::<RunRecord>(),
|
||||
published_for::<RoundRecord>(),
|
||||
published_for::<Decision>(),
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -309,6 +309,7 @@ fn schema_writes_the_published_files() {
|
|||
"weksa.interlingua_packet.schema.json",
|
||||
"weksa.inventory_entry.schema.json",
|
||||
"weksa.inventory_revision.schema.json",
|
||||
"weksa.loop_decision.schema.json",
|
||||
"weksa.loop_round.schema.json",
|
||||
"weksa.loop_run.schema.json",
|
||||
"weksa.scene.schema.json",
|
||||
|
|
@ -1407,6 +1408,102 @@ fn loop_open_and_unanswered_round() {
|
|||
);
|
||||
}
|
||||
|
||||
fn open_dao_run(d: &std::path::Path) {
|
||||
dao_stores(d);
|
||||
let o = weksa(
|
||||
d,
|
||||
&[
|
||||
"loop",
|
||||
"open",
|
||||
"canaryroot",
|
||||
"--label",
|
||||
"smoke",
|
||||
"--answerer",
|
||||
"fake-model",
|
||||
],
|
||||
);
|
||||
assert!(o.status.success(), "{}", out(&o));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_cycle_needs_a_floor() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
open_dao_run(d.path());
|
||||
let o = weksa(d.path(), &["loop", "cycle", "canaryroot"]);
|
||||
assert!(!o.status.success());
|
||||
let text = out(&o);
|
||||
assert!(
|
||||
text.contains("the run has no noise floor: record two rounds first"),
|
||||
"{text}"
|
||||
);
|
||||
for echoed in ["canaryroot", d.path().to_str().unwrap()] {
|
||||
assert!(!text.contains(echoed), "{text}");
|
||||
}
|
||||
assert!(!d.path().join("canaryroot/cycle-1").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_cycle_asks_then_decides() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
open_dao_run(d.path());
|
||||
// Two rounds of refusals: a floor of 0 and a base of 0.
|
||||
for n in 1..=2 {
|
||||
let first = weksa(d.path(), &["loop", "round", "canaryroot"]);
|
||||
assert_eq!(first.status.code(), Some(3), "{}", out(&first));
|
||||
for entry in std::fs::read_dir(d.path().join(format!("canaryroot/round-{n}"))).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
std::fs::write(path.with_extension("answer"), "not json").unwrap();
|
||||
}
|
||||
let second = weksa(d.path(), &["loop", "round", "canaryroot"]);
|
||||
assert!(second.status.success(), "{}", out(&second));
|
||||
}
|
||||
|
||||
// The editor is asked first: one digest, a count, exit 3, the prompt on disk.
|
||||
let ask = weksa(d.path(), &["loop", "cycle", "canaryroot"]);
|
||||
assert_eq!(ask.status.code(), Some(3), "{}", out(&ask));
|
||||
let text = out(&ask);
|
||||
let lines: Vec<&str> = text.lines().collect();
|
||||
assert_eq!(lines.len(), 2, "{text}");
|
||||
let digest = lines[0].strip_prefix("unanswered ").unwrap();
|
||||
assert_eq!(digest.len(), 16, "{text}");
|
||||
assert_eq!(lines[1], "unanswered 1 prompts");
|
||||
for echoed in ["canaryroot", d.path().to_str().unwrap()] {
|
||||
assert!(!text.contains(echoed), "{text}");
|
||||
}
|
||||
let dir = d.path().join("canaryroot/cycle-1");
|
||||
let prompt = std::fs::read_to_string(dir.join(format!("{digest}.prompt"))).unwrap();
|
||||
assert!(prompt.starts_with(weksa::context::MINT_INSTRUCTIONS));
|
||||
|
||||
// An answer that is not an edit closes the cycle as a rejection, with no
|
||||
// embed call and no echo of the answer.
|
||||
std::fs::write(dir.join(format!("{digest}.answer")), "CANARYANSWER").unwrap();
|
||||
let done = weksa(d.path(), &["loop", "cycle", "canaryroot"]);
|
||||
assert!(done.status.success(), "{}", out(&done));
|
||||
assert_eq!(
|
||||
out(&done),
|
||||
"cycle 1 rev 3->none base=0.0000 candidate=none floor=0.0000 threshold=0.0050 rejected edit-parse\n"
|
||||
);
|
||||
|
||||
// The next cycle asks afresh in its own directory.
|
||||
let next = weksa(d.path(), &["loop", "cycle", "canaryroot"]);
|
||||
assert_eq!(next.status.code(), Some(3), "{}", out(&next));
|
||||
let text = out(&next);
|
||||
assert!(text.ends_with("unanswered 1 prompts\n"), "{text}");
|
||||
assert!(!text.to_uppercase().contains("CANARY"), "{text}");
|
||||
let asked = text
|
||||
.lines()
|
||||
.next()
|
||||
.unwrap()
|
||||
.strip_prefix("unanswered ")
|
||||
.unwrap();
|
||||
assert_ne!(asked, digest);
|
||||
assert!(
|
||||
d.path()
|
||||
.join(format!("canaryroot/cycle-2/{asked}.prompt"))
|
||||
.is_file()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loop_errors_echo_no_input() {
|
||||
let d = tempfile::tempdir().unwrap();
|
||||
|
|
|
|||
|
|
@ -472,18 +472,24 @@ fn answer_files_write_the_prompt_and_read_the_answer() {
|
|||
use std::collections::HashMap;
|
||||
|
||||
use common::Bag;
|
||||
use weksa::context::{ENCODE_INSTRUCTIONS, Prompt};
|
||||
use weksa::context::{ENCODE_INSTRUCTIONS, MINT_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.
|
||||
/// and records every prompt it was shown. A prompt that starts with
|
||||
/// `MINT_INSTRUCTIONS` is the editor's and is answered from `edit` (a panic when
|
||||
/// none was given). With `candidate` set, an encode prompt that lists
|
||||
/// `inventory rev:<that revision>` is answered from the candidate answers.
|
||||
struct FakeModel {
|
||||
name: &'static str,
|
||||
answers: HashMap<String, String>,
|
||||
candidate: Option<(u32, HashMap<String, String>)>,
|
||||
edit: Option<Result<String, PortError>>,
|
||||
seen: Vec<(String, String)>,
|
||||
mint_keys: Vec<Vec<String>>,
|
||||
}
|
||||
|
||||
impl ModelPort for FakeModel {
|
||||
|
|
@ -491,9 +497,23 @@ impl ModelPort for FakeModel {
|
|||
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) {
|
||||
if prompt.text().starts_with(MINT_INSTRUCTIONS) {
|
||||
self.mint_keys.push(prompt.item_keys().to_vec());
|
||||
return self.edit.clone().expect("the model was asked for an edit");
|
||||
}
|
||||
let key = prompt.item_keys()[0].clone();
|
||||
let answers = match &self.candidate {
|
||||
Some((rev, candidate))
|
||||
if prompt
|
||||
.text()
|
||||
.contains(&format!("\n\ninventory rev:{rev}\n")) =>
|
||||
{
|
||||
candidate
|
||||
}
|
||||
_ => &self.answers,
|
||||
};
|
||||
match answers.get(&key) {
|
||||
Some(answer) => Ok(answer.clone()),
|
||||
None => panic!("the model was asked about {key}"),
|
||||
}
|
||||
|
|
@ -508,15 +528,22 @@ fn json(draft: &PacketDraft) -> String {
|
|||
serde_json::to_string(draft).unwrap()
|
||||
}
|
||||
|
||||
fn keyed(answers: &[(usize, String)]) -> HashMap<String, String> {
|
||||
answers
|
||||
.iter()
|
||||
.map(|(n, a)| (format!("item:daodejing:{n}"), a.clone()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 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(),
|
||||
answers: keyed(answers),
|
||||
candidate: None,
|
||||
edit: None,
|
||||
seen: vec![],
|
||||
mint_keys: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -528,11 +555,19 @@ struct Dao {
|
|||
_dir: tempfile::TempDir,
|
||||
root: PathBuf,
|
||||
corpus: PathBuf,
|
||||
inventory: PathBuf,
|
||||
entities: PathBuf,
|
||||
run: RunStores,
|
||||
}
|
||||
|
||||
/// A run over copies of `data/daodejing/{corpus,inventory,entity}.cc`.
|
||||
fn dao() -> Dao {
|
||||
dao_over(|_, _| {})
|
||||
}
|
||||
|
||||
/// A Dao run whose stores `edit` (given the corpus and entity paths) changed
|
||||
/// before the run pinned them.
|
||||
fn dao_over(edit: impl FnOnce(&Path, &Path)) -> Dao {
|
||||
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/daodejing");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let copy = |from: &str, to: &str| {
|
||||
|
|
@ -544,6 +579,7 @@ fn dao() -> Dao {
|
|||
copy("inventory.cc", "i.cc"),
|
||||
copy("entity.cc", "e.cc"),
|
||||
);
|
||||
edit(&corpus, &entities);
|
||||
let root = dir.path().join("run");
|
||||
let run = RunStores::create(
|
||||
&root,
|
||||
|
|
@ -561,6 +597,8 @@ fn dao() -> Dao {
|
|||
_dir: dir,
|
||||
root,
|
||||
corpus,
|
||||
inventory,
|
||||
entities,
|
||||
run,
|
||||
}
|
||||
}
|
||||
|
|
@ -1158,13 +1196,69 @@ fn errors_echo_no_input() {
|
|||
]);
|
||||
let r = recorded(round(&mut dao.run, &mut model, &Scorer::new(Bag)).unwrap());
|
||||
all.push(format!("{r:?}"));
|
||||
// Cycle errors, from a canary root, and a decision over a canary edit answer.
|
||||
let canary_root = tmp.path().join("canaryrun");
|
||||
let mut canary_run = RunStores::create(
|
||||
&canary_root,
|
||||
"ok",
|
||||
RunPaths {
|
||||
corpus: &dao.corpus,
|
||||
inventory: &dao.inventory,
|
||||
entities: &dao.entities,
|
||||
},
|
||||
"fake-model",
|
||||
"bag",
|
||||
)
|
||||
.unwrap();
|
||||
let mut model = cycle_fake(&format!("{{\"{canary}\":1}}"));
|
||||
let e = cycle(&mut canary_run, &mut model, &Scorer::new(Bag))
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(e, RunError::NoFloor);
|
||||
all.extend([format!("{e:?}"), e.to_string()]);
|
||||
for _ in 0..2 {
|
||||
let mut m = fake(°raded_answers());
|
||||
recorded(round(&mut canary_run, &mut m, &Scorer::new(Bag)).unwrap());
|
||||
}
|
||||
let d = decided(cycle(&mut canary_run, &mut model, &Scorer::new(Bag)).unwrap());
|
||||
assert_eq!(d.verdict(), Verdict::Rejected(Why::EditParse));
|
||||
all.extend([format!("{d:?}"), d.summary_line()]);
|
||||
let mut non_utf8 = cycle_fake("");
|
||||
non_utf8.edit = Some(Err(PortError::Io(std::io::ErrorKind::InvalidData)));
|
||||
let d = decided(cycle(&mut canary_run, &mut non_utf8, &Scorer::new(Bag)).unwrap());
|
||||
all.extend([format!("{d:?}"), d.summary_line()]);
|
||||
weksa::InventoryStore::open(&canary_root.join("inventory.cc"))
|
||||
.unwrap()
|
||||
.admit_revision(
|
||||
weksa::InventoryRevision {
|
||||
n: 4,
|
||||
parent: Some(3),
|
||||
changes: vec![],
|
||||
frozen: false,
|
||||
},
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
let e = RunStores::open(&canary_root).err().unwrap();
|
||||
assert_eq!(e, RunError::Drift(DriftOf::Inventory));
|
||||
all.extend([format!("{e:?}"), e.to_string()]);
|
||||
let e = RunError::NoValidation;
|
||||
all.extend([format!("{e:?}"), e.to_string()]);
|
||||
assert_eq!(
|
||||
format!("{:?}", RunError::NoFloor),
|
||||
RunError::NoFloor.to_string()
|
||||
);
|
||||
|
||||
for text in &all {
|
||||
assert!(!text.to_uppercase().contains("CANARY"), "{text}");
|
||||
}
|
||||
assert!(all.len() >= 12);
|
||||
assert!(all.len() >= 22);
|
||||
// Debug names the same kind Display does.
|
||||
assert_eq!(format!("{:?}", RunError::NoRun), "the root holds no run");
|
||||
assert_eq!(
|
||||
format!("{:?}", RunError::Drift(DriftOf::Inventory)),
|
||||
"drift in Inventory"
|
||||
);
|
||||
assert_eq!(
|
||||
format!("{:?}", RunError::Drift(DriftOf::Model)),
|
||||
"drift in Model"
|
||||
|
|
@ -1187,6 +1281,607 @@ fn prompts_come_only_from_context() {
|
|||
}
|
||||
}
|
||||
|
||||
// ---- edit-accept cycles ----
|
||||
|
||||
use weksa::run::{CycleOutcome, Decision, LADDER_STEP, Reading, Verdict, Why, cycle};
|
||||
|
||||
const ONE_CONCEPT: &str =
|
||||
r#"{"add":[{"family":"Concept","gloss":"a general meaning the Dao names"}]}"#;
|
||||
|
||||
/// Item 2 refused at Admit (an unknown concept), items 1 and 3 good.
|
||||
fn degraded_answers() -> Vec<(usize, String)> {
|
||||
vec![
|
||||
(1, json(&draft_of(1))),
|
||||
(2, edited(2, unknown_concept)),
|
||||
(3, json(&draft_of(3))),
|
||||
]
|
||||
}
|
||||
|
||||
/// Head answers degrade item 2; candidate answers (for `inventory rev:4`) are
|
||||
/// the good Dao drafts; the editor answers `edit`.
|
||||
fn cycle_fake(edit: &str) -> FakeModel {
|
||||
let mut model = fake(°raded_answers());
|
||||
model.candidate = Some((4, keyed(&good_answers())));
|
||||
model.edit = Some(Ok(edit.to_string()));
|
||||
model
|
||||
}
|
||||
|
||||
fn two_rounds(dao: &mut Dao) {
|
||||
for _ in 0..2 {
|
||||
let mut model = fake(°raded_answers());
|
||||
recorded(round(&mut dao.run, &mut model, &Scorer::new(Bag)).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
fn decided(outcome: CycleOutcome) -> Decision {
|
||||
match outcome {
|
||||
CycleOutcome::Decided(d) => d,
|
||||
CycleOutcome::Unanswered { prompts } => panic!("unanswered: {prompts:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn run_cycle(dao: &mut Dao, model: &mut FakeModel) -> Decision {
|
||||
decided(cycle(&mut dao.run, model, &Scorer::new(Bag)).unwrap())
|
||||
}
|
||||
|
||||
fn head_rev(root: &Path) -> u32 {
|
||||
let run = RunStores::open(root).unwrap();
|
||||
let inv = run.inventory().inventory().unwrap();
|
||||
inv.latest().unwrap().n
|
||||
}
|
||||
|
||||
fn validation(r: &RoundRecord) -> Reading {
|
||||
Reading::of(r.validation_mean()).unwrap()
|
||||
}
|
||||
|
||||
/// The feedback line the editor is shown for a head round, built from outside.
|
||||
fn feedback_line(last: &str, head: &RoundRecord) -> String {
|
||||
let rounded = (validation(head).composite / LADDER_STEP).round() * LADDER_STEP;
|
||||
format!("last edit: {last}; validation composite at head: {rounded:.3}")
|
||||
}
|
||||
|
||||
fn mint_texts(model: &FakeModel) -> Vec<&str> {
|
||||
model
|
||||
.seen
|
||||
.iter()
|
||||
.map(|(_, t)| t.as_str())
|
||||
.filter(|t| t.starts_with(MINT_INSTRUCTIONS))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cycle_accepts_a_gain_past_the_floor() {
|
||||
let mut dao = dao();
|
||||
two_rounds(&mut dao);
|
||||
let source = std::fs::read(&dao.inventory).unwrap();
|
||||
let rounds = dao.run.rounds().unwrap();
|
||||
assert_eq!(validation(&rounds[0]), validation(&rounds[1]), "floor 0");
|
||||
|
||||
let mut model = cycle_fake(ONE_CONCEPT);
|
||||
let d = run_cycle(&mut dao, &mut model);
|
||||
assert_eq!(
|
||||
(d.k(), d.base_round(), d.candidate_round()),
|
||||
(1, 1, Some(3))
|
||||
);
|
||||
assert_eq!((d.base_rev(), d.candidate_rev()), (3, Some(4)));
|
||||
assert_eq!(d.verdict(), Verdict::Accepted);
|
||||
assert_eq!(d.threshold(), LADDER_STEP);
|
||||
assert_eq!(
|
||||
*d.floor(),
|
||||
Reading {
|
||||
chrf: 0.0,
|
||||
meaning: 0.0,
|
||||
composite: 0.0
|
||||
}
|
||||
);
|
||||
assert_eq!(*d.base(), validation(&rounds[0]));
|
||||
let record = dao.run.rounds().unwrap().remove(2);
|
||||
assert_eq!(d.candidate(), Some(&validation(&record)));
|
||||
assert!(d.candidate().unwrap().composite - d.base().composite > LADDER_STEP);
|
||||
|
||||
// The candidate round was scored under the candidate file, as cycle 1's.
|
||||
let file = dao.root.join("cycle-1/inventory.cc");
|
||||
assert_eq!(
|
||||
(record.n(), record.inventory_rev(), record.cycle()),
|
||||
(3, 4, Some(1))
|
||||
);
|
||||
assert_eq!(record.inventory_digest(), hex(&file));
|
||||
assert_eq!(d.candidate_inventory_digest(), Some(hex(&file).as_str()));
|
||||
assert_eq!(
|
||||
d.base_inventory_digest(),
|
||||
hex(&dao.root.join("inventory.cc"))
|
||||
);
|
||||
assert_eq!(d.base_inventory_digest(), dao.run.record().inventory_digest);
|
||||
assert!(dao.root.join("cycle-1/packets.cc").is_file());
|
||||
assert_eq!(d.edit().items, ["item:daodejing:1"]);
|
||||
assert_eq!(
|
||||
d.edit_answer_digest(),
|
||||
Some(format!("{:016x}", fnv1a64(ONE_CONCEPT.as_bytes())).as_str())
|
||||
);
|
||||
assert_eq!(d.edit().prompt, model.seen[0].0);
|
||||
|
||||
// The line, with the readings printed to four places.
|
||||
let (b, c) = (d.base().composite, d.candidate().unwrap().composite);
|
||||
assert_eq!(
|
||||
d.summary_line(),
|
||||
format!(
|
||||
"cycle 1 rev 3->4 base={b:.4} candidate={c:.4} floor=0.0000 threshold=0.0050 accepted"
|
||||
)
|
||||
);
|
||||
|
||||
// The decision made it the head: a reopened run reads rev 4 from the cycle's
|
||||
// file, and the caller's inventory file was never touched.
|
||||
assert_eq!(head_rev(&dao.root), 4);
|
||||
assert_eq!(std::fs::read(&dao.inventory).unwrap(), source);
|
||||
assert_eq!(dao.run.decisions().unwrap(), std::slice::from_ref(&d));
|
||||
assert_eq!(
|
||||
RunStores::open(&dao.root).unwrap().decisions().unwrap(),
|
||||
std::slice::from_ref(&d)
|
||||
);
|
||||
for (_, p) in prompts(&dao.run) {
|
||||
assert!(p.text().contains("\n\ninventory rev:4\n"));
|
||||
}
|
||||
|
||||
// `loop round` reads the head and never moves it; the next cycle's base is
|
||||
// the establishing round 3, not the replicate recorded after it.
|
||||
let mut again = fake(&good_answers());
|
||||
let r = recorded(round(&mut dao.run, &mut again, &Scorer::new(Bag)).unwrap());
|
||||
assert_eq!((r.n(), r.inventory_rev(), r.cycle()), (4, 4, None));
|
||||
assert_eq!(r.inventory_digest(), hex(&file));
|
||||
let mut second = fake(&good_answers());
|
||||
second.candidate = Some((5, keyed(&good_answers())));
|
||||
second.edit = Some(Ok(ONE_CONCEPT.to_string()));
|
||||
let d2 = run_cycle(&mut dao, &mut second);
|
||||
assert_eq!((d2.k(), d2.base_round(), d2.base_rev()), (2, 3, 4));
|
||||
assert_eq!(d2.candidate_rev(), Some(5));
|
||||
assert_eq!(d2.candidate_round(), Some(5));
|
||||
assert_eq!(d2.verdict(), Verdict::Rejected(Why::NoGain));
|
||||
assert_eq!(*d2.floor(), *d.floor(), "the floor is measured once");
|
||||
assert_eq!(head_rev(&dao.root), 4, "a rejected edit moves nothing");
|
||||
assert!(
|
||||
mint_texts(&second)[0].contains(&feedback_line("accepted", &dao.run.rounds().unwrap()[2])),
|
||||
"{}",
|
||||
mint_texts(&second)[0]
|
||||
);
|
||||
assert!(dao.root.join("cycle-2/inventory.cc").is_file());
|
||||
assert_eq!(
|
||||
d2.base_inventory_digest(),
|
||||
d.candidate_inventory_digest().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cycle_rejects_no_gain_and_keeps_the_head() {
|
||||
let mut dao = dao();
|
||||
two_rounds(&mut dao);
|
||||
let mut model = fake(°raded_answers());
|
||||
model.candidate = Some((4, keyed(°raded_answers())));
|
||||
model.edit = Some(Ok(ONE_CONCEPT.to_string()));
|
||||
let d = run_cycle(&mut dao, &mut model);
|
||||
assert_eq!(d.verdict(), Verdict::Rejected(Why::NoGain));
|
||||
assert_eq!((d.candidate_rev(), d.candidate_round()), (Some(4), Some(3)));
|
||||
assert_eq!(d.candidate(), Some(d.base()));
|
||||
let c = d.base().composite;
|
||||
assert_eq!(
|
||||
d.summary_line(),
|
||||
format!(
|
||||
"cycle 1 rev 3->4 base={c:.4} candidate={c:.4} floor=0.0000 threshold=0.0050 rejected no-gain"
|
||||
)
|
||||
);
|
||||
assert_eq!(head_rev(&dao.root), 3);
|
||||
assert_eq!(
|
||||
RunStores::open(&dao.root)
|
||||
.unwrap()
|
||||
.record()
|
||||
.inventory_digest,
|
||||
hex(&dao.root.join("inventory.cc"))
|
||||
);
|
||||
assert_eq!(
|
||||
dao.run.rounds().unwrap().len(),
|
||||
3,
|
||||
"the candidate round is recorded"
|
||||
);
|
||||
|
||||
// Cycle 2 goes to its own directory and is told the last edit was rejected,
|
||||
// with the same head composite.
|
||||
assert_eq!(dao.run.next_cycle_dir().unwrap(), dao.root.join("cycle-2"));
|
||||
let d2 = run_cycle(&mut dao, &mut model);
|
||||
assert_eq!((d2.k(), d2.base_round(), d2.base_rev()), (2, 1, 3));
|
||||
assert!(dao.root.join("cycle-2/inventory.cc").is_file());
|
||||
let mints = mint_texts(&model);
|
||||
assert_eq!(mints.len(), 2);
|
||||
let round1 = dao.run.rounds().unwrap().remove(0);
|
||||
assert!(mints[0].contains(&feedback_line("none", &round1)));
|
||||
assert!(mints[1].contains(&feedback_line("rejected", &round1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unanswered_cycle_writes_nothing() {
|
||||
let mut dao = dao();
|
||||
two_rounds(&mut dao);
|
||||
let run_cc = std::fs::read(dao.root.join("run.cc")).unwrap();
|
||||
let scorer = Scorer::new(Bag);
|
||||
let ask = |dao: &mut Dao| {
|
||||
let mut files = AnswerFiles::new(dao.run.next_cycle_dir().unwrap(), "fake-model".into());
|
||||
cycle(&mut dao.run, &mut files, &scorer).unwrap()
|
||||
};
|
||||
let dir = dao.root.join("cycle-1");
|
||||
|
||||
// The first call asks the editor and nothing else.
|
||||
let CycleOutcome::Unanswered { prompts: asked } = ask(&mut dao) else {
|
||||
panic!("answered from nothing")
|
||||
};
|
||||
assert_eq!(asked.len(), 1);
|
||||
let mint_file = dir.join(format!("{}.prompt", asked[0]));
|
||||
let mint = std::fs::read_to_string(&mint_file).unwrap();
|
||||
assert_eq!(format!("{:016x}", fnv1a64(mint.as_bytes())), asked[0]);
|
||||
assert!(mint.starts_with(MINT_INSTRUCTIONS));
|
||||
assert!(mint.contains("\n\nlast edit: none; validation composite at head: 0.435\n\n"));
|
||||
assert!(mint.contains("\n\ninventory rev:3\n"));
|
||||
assert_eq!(mint.matches("[item:").count(), 1, "one Train block");
|
||||
assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
|
||||
assert_eq!(std::fs::read(dao.root.join("run.cc")).unwrap(), run_cc);
|
||||
|
||||
// With the edit answered, the candidate round asks three encode prompts at rev 4.
|
||||
std::fs::write(dir.join(format!("{}.answer", asked[0])), ONE_CONCEPT).unwrap();
|
||||
let CycleOutcome::Unanswered { prompts: encode } = ask(&mut dao) else {
|
||||
panic!("answered the candidate round from nothing")
|
||||
};
|
||||
assert_eq!(encode.len(), 3);
|
||||
let answers: HashMap<String, String> = keyed(&good_answers());
|
||||
for digest in &encode {
|
||||
let text = std::fs::read_to_string(dir.join(format!("{digest}.prompt"))).unwrap();
|
||||
assert!(text.contains("\n\ninventory rev:4\n"), "{text}");
|
||||
assert!(text.starts_with(ENCODE_INSTRUCTIONS));
|
||||
let key = text
|
||||
.split("[item:")
|
||||
.nth(1)
|
||||
.and_then(|t| t.split(']').next())
|
||||
.map(|k| format!("item:{k}"))
|
||||
.unwrap();
|
||||
std::fs::write(dir.join(format!("{digest}.answer")), &answers[&key]).unwrap();
|
||||
}
|
||||
assert_eq!(
|
||||
std::fs::read(dao.root.join("run.cc")).unwrap(),
|
||||
run_cc,
|
||||
"no round 3 and no decision"
|
||||
);
|
||||
assert_eq!(dao.run.rounds().unwrap().len(), 2);
|
||||
assert!(dao.run.decisions().unwrap().is_empty());
|
||||
|
||||
// Answered, the cycle is decided; the next one uses cycle-2.
|
||||
let d = decided(ask(&mut dao));
|
||||
assert_eq!((d.k(), d.verdict()), (1, Verdict::Accepted));
|
||||
assert_eq!(dao.run.next_cycle_dir().unwrap(), dao.root.join("cycle-2"));
|
||||
let CycleOutcome::Unanswered { prompts: next } = ask(&mut dao) else {
|
||||
panic!("cycle 2 answered from cycle 1's files")
|
||||
};
|
||||
assert_eq!(next.len(), 1);
|
||||
assert!(
|
||||
dao.root
|
||||
.join(format!("cycle-2/{}.prompt", next[0]))
|
||||
.is_file()
|
||||
);
|
||||
assert_ne!(next[0], asked[0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_editor_sees_train_only() {
|
||||
let canary_key = "item:canary:1";
|
||||
let canary_text = "CANARYVALIDATIONTEXT";
|
||||
let mut dao = dao_over(|corpus, entities| {
|
||||
let entities = weksa::EntityStore::open(entities).unwrap();
|
||||
let mut store = weksa::CorpusStore::open(corpus).unwrap();
|
||||
let mut item = store.get("item:daodejing:2").unwrap().unwrap();
|
||||
item.id = canary_key.into();
|
||||
item.text = canary_text.into();
|
||||
item.names = vec![];
|
||||
item.prior_turns = vec![];
|
||||
store.add(item, &entities).unwrap();
|
||||
});
|
||||
let with_canary = |mut m: FakeModel| {
|
||||
m.answers.insert(canary_key.into(), json(&draft_of(2)));
|
||||
if let Some((_, c)) = m.candidate.as_mut() {
|
||||
c.insert(canary_key.into(), json(&draft_of(2)));
|
||||
}
|
||||
m
|
||||
};
|
||||
for _ in 0..2 {
|
||||
let mut m = with_canary(fake(°raded_answers()));
|
||||
recorded(round(&mut dao.run, &mut m, &Scorer::new(Bag)).unwrap());
|
||||
}
|
||||
let mut model = fake(°raded_answers());
|
||||
model.candidate = Some((4, keyed(°raded_answers())));
|
||||
model.edit = Some(Ok(ONE_CONCEPT.to_string()));
|
||||
let mut model = with_canary(model);
|
||||
let d = run_cycle(&mut dao, &mut model);
|
||||
assert_eq!(d.verdict(), Verdict::Rejected(Why::NoGain));
|
||||
|
||||
// A plain round with different answers changes the latest reading, not the
|
||||
// head's: the line the next cycle shows is the head round's.
|
||||
let mut other = with_canary(fake(&good_answers()));
|
||||
let r4 = recorded(round(&mut dao.run, &mut other, &Scorer::new(Bag)).unwrap());
|
||||
let rounds = dao.run.rounds().unwrap();
|
||||
assert_ne!(validation(&r4), validation(&rounds[0]));
|
||||
let d2 = run_cycle(&mut dao, &mut model);
|
||||
assert_eq!(d2.base_round(), 1);
|
||||
|
||||
let corpus = weksa::CorpusStore::open(&dao.corpus).unwrap();
|
||||
let mut held_out: Vec<String> = vec![canary_key.into(), canary_text.into(), "canary".into()];
|
||||
for n in 2..=5 {
|
||||
let item = corpus.get(&format!("item:daodejing:{n}")).unwrap().unwrap();
|
||||
held_out.extend([item.id, item.text]);
|
||||
}
|
||||
let mints = mint_texts(&model);
|
||||
assert_eq!(mints.len(), 2);
|
||||
for text in &mints {
|
||||
assert!(text.starts_with(MINT_INSTRUCTIONS));
|
||||
for needle in &held_out {
|
||||
assert!(
|
||||
!text.to_lowercase().contains(&needle.to_lowercase()),
|
||||
"{needle}"
|
||||
);
|
||||
}
|
||||
assert_eq!(text.matches("[item:").count(), 1);
|
||||
assert!(text.contains("[item:daodejing:1]"));
|
||||
}
|
||||
assert_eq!(
|
||||
model.mint_keys,
|
||||
[["item:daodejing:1"], ["item:daodejing:1"]]
|
||||
);
|
||||
// The one number from the held-out split is the head composite on the ladder.
|
||||
let head = &rounds[0];
|
||||
assert!(mints[0].contains(&format!("\n\n{}\n\n", feedback_line("none", head))));
|
||||
assert!(mints[1].contains(&format!("\n\n{}\n\n", feedback_line("rejected", head))));
|
||||
assert_eq!(
|
||||
mints[0].replace("last edit: none;", "last edit: rejected;"),
|
||||
mints[1],
|
||||
"the two prompts differ by the last-edit word alone"
|
||||
);
|
||||
|
||||
// Nothing the cycle writes or prints holds a held-out key or text.
|
||||
for text in [
|
||||
format!("{d:?}"),
|
||||
d.summary_line(),
|
||||
format!("{d2:?}"),
|
||||
d2.summary_line(),
|
||||
] {
|
||||
for needle in &held_out {
|
||||
assert!(
|
||||
!text.to_lowercase().contains(&needle.to_lowercase()),
|
||||
"{needle}: {text}"
|
||||
);
|
||||
}
|
||||
}
|
||||
let run_cc = std::fs::read(dao.root.join("run.cc")).unwrap();
|
||||
for needle in [canary_text, "item:daodejing:4", "item:daodejing:5"] {
|
||||
assert!(
|
||||
!run_cc.windows(needle.len()).any(|w| w == needle.as_bytes()),
|
||||
"{needle}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edit_refusals_are_decisions() {
|
||||
use std::io::ErrorKind;
|
||||
let nine = format!(
|
||||
r#"{{"add":[{}]}}"#,
|
||||
[r#"{"family":"Concept","gloss":"g"}"#; 9].join(",")
|
||||
);
|
||||
let long = format!(
|
||||
r#"{{"add":[{{"family":"Concept","gloss":"{}"}}]}}"#,
|
||||
"x".repeat(121)
|
||||
);
|
||||
let cases: Vec<(&str, Result<String, PortError>, Why)> = vec![
|
||||
("not json", Ok("not json at all".into()), Why::EditParse),
|
||||
(
|
||||
"non-utf8",
|
||||
Err(PortError::Io(ErrorKind::InvalidData)),
|
||||
Why::EditParse,
|
||||
),
|
||||
(
|
||||
"an id in an entry",
|
||||
Ok(r#"{"add":[{"family":"Concept","gloss":"g","id":"concept:1"}]}"#.into()),
|
||||
Why::EditParse,
|
||||
),
|
||||
("no changes", Ok("{}".into()), Why::EditAdmit),
|
||||
("nine changes", Ok(nine), Why::EditAdmit),
|
||||
(
|
||||
"retiring an absent id",
|
||||
Ok(r#"{"retire":["concept:9999"]}"#.into()),
|
||||
Why::EditAdmit,
|
||||
),
|
||||
("a 121-byte gloss", Ok(long), Why::EditAdmit),
|
||||
(
|
||||
"a control character in a gloss",
|
||||
Ok("{\"add\":[{\"family\":\"Concept\",\"gloss\":\"a\\u0007b\"}]}".into()),
|
||||
Why::EditAdmit,
|
||||
),
|
||||
];
|
||||
for (name, edit, why) in cases {
|
||||
let mut dao = dao();
|
||||
two_rounds(&mut dao);
|
||||
let mut model = cycle_fake("");
|
||||
model.edit = Some(edit.clone());
|
||||
let d = run_cycle(&mut dao, &mut model);
|
||||
assert_eq!(d.verdict(), Verdict::Rejected(why), "{name}");
|
||||
assert_eq!(
|
||||
(d.candidate_rev(), d.candidate_round(), d.candidate()),
|
||||
(None, None, None),
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(d.candidate_inventory_digest(), None, "{name}");
|
||||
let want = match &edit {
|
||||
Ok(a) => Some(format!("{:016x}", fnv1a64(a.as_bytes()))),
|
||||
Err(_) => None,
|
||||
};
|
||||
assert_eq!(d.edit_answer_digest(), want.as_deref(), "{name}");
|
||||
assert_eq!(
|
||||
dao.run.rounds().unwrap().len(),
|
||||
2,
|
||||
"{name}: no candidate round"
|
||||
);
|
||||
assert_eq!(model.seen.len(), 1, "{name}: no encode prompt was asked");
|
||||
let dir = dao.root.join("cycle-1");
|
||||
assert!(!dir.join("inventory.cc").exists(), "{name}");
|
||||
assert!(!dir.join("inventory.cc.lock").exists(), "{name}");
|
||||
assert_eq!(head_rev(&dao.root), 3, "{name}");
|
||||
let tag = if why == Why::EditParse {
|
||||
"edit-parse"
|
||||
} else {
|
||||
"edit-admit"
|
||||
};
|
||||
assert_eq!(
|
||||
d.summary_line(),
|
||||
format!(
|
||||
"cycle 1 rev 3->none base={:.4} candidate=none floor=0.0000 threshold=0.0050 rejected {tag}",
|
||||
d.base().composite
|
||||
),
|
||||
"{name}"
|
||||
);
|
||||
assert_eq!(dao.run.decisions().unwrap(), [d], "{name}");
|
||||
|
||||
// The next cycle is told the last edit was rejected and asks afresh, in
|
||||
// a directory of its own.
|
||||
assert_eq!(dao.run.next_cycle_dir().unwrap(), dao.root.join("cycle-2"));
|
||||
model.edit = Some(Ok(ONE_CONCEPT.into()));
|
||||
let d2 = run_cycle(&mut dao, &mut model);
|
||||
assert_eq!(d2.k(), 2, "{name}");
|
||||
assert!(
|
||||
mint_texts(&model)[1].contains("last edit: rejected;"),
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cycle_needs_a_floor() {
|
||||
let none = |dao: &mut Dao, model: &mut FakeModel| {
|
||||
let before = std::fs::read(dao.root.join("run.cc")).unwrap();
|
||||
let err = cycle(&mut dao.run, model, &Scorer::new(Bag)).err();
|
||||
assert_eq!(std::fs::read(dao.root.join("run.cc")).unwrap(), before);
|
||||
assert!(dao.run.decisions().unwrap().is_empty());
|
||||
assert!(!dao.root.join("cycle-1").exists());
|
||||
assert!(model.seen.is_empty(), "no prompt before the floor");
|
||||
err
|
||||
};
|
||||
let mut dao = dao();
|
||||
let mut model = cycle_fake(ONE_CONCEPT);
|
||||
assert_eq!(none(&mut dao, &mut model), Some(RunError::NoFloor));
|
||||
let mut one = fake(°raded_answers());
|
||||
recorded(round(&mut dao.run, &mut one, &Scorer::new(Bag)).unwrap());
|
||||
assert_eq!(none(&mut dao, &mut model), Some(RunError::NoFloor));
|
||||
assert_eq!(
|
||||
RunError::NoFloor.to_string(),
|
||||
"the run has no noise floor: record two rounds first"
|
||||
);
|
||||
|
||||
// Rounds whose Validation items are all withdrawn have no reading.
|
||||
let mut dao = dao_over(|corpus, _| {
|
||||
let mut store = weksa::CorpusStore::open(corpus).unwrap();
|
||||
for n in [2, 3] {
|
||||
store.withdraw(&format!("item:daodejing:{n}")).unwrap();
|
||||
}
|
||||
});
|
||||
for _ in 0..2 {
|
||||
let mut m = fake(&[(1, json(&draft_of(1)))]);
|
||||
let r = recorded(round(&mut dao.run, &mut m, &Scorer::new(Bag)).unwrap());
|
||||
assert_eq!(r.validation_mean().count, 0);
|
||||
}
|
||||
let mut model = cycle_fake(ONE_CONCEPT);
|
||||
assert_eq!(none(&mut dao, &mut model), Some(RunError::NoValidation));
|
||||
assert_eq!(
|
||||
RunError::NoValidation.to_string(),
|
||||
"a reading has no validation item"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_candidate_round_writes_nothing() {
|
||||
let mut dao = dao();
|
||||
two_rounds(&mut dao);
|
||||
let run_cc = std::fs::read(dao.root.join("run.cc")).unwrap();
|
||||
let mut model = cycle_fake(ONE_CONCEPT);
|
||||
assert_eq!(
|
||||
cycle(&mut dao.run, &mut model, &Scorer::new(Down)).err(),
|
||||
Some(RunError::Embed)
|
||||
);
|
||||
assert_eq!(std::fs::read(dao.root.join("run.cc")).unwrap(), run_cc);
|
||||
assert_eq!(dao.run.rounds().unwrap().len(), 2);
|
||||
assert!(dao.run.decisions().unwrap().is_empty());
|
||||
assert!(!dao.root.join("cycle-1/packets.cc").exists());
|
||||
assert_eq!(head_rev(&dao.root), 3);
|
||||
|
||||
// The rerun starts clean from the head and decides on round 3.
|
||||
let d = run_cycle(&mut dao, &mut model);
|
||||
assert_eq!((d.k(), d.candidate_round()), (1, Some(3)));
|
||||
assert_eq!(d.verdict(), Verdict::Accepted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_changed_head_is_drift() {
|
||||
let revision = |rev: u32| weksa::InventoryRevision {
|
||||
n: rev + 1,
|
||||
parent: Some(rev),
|
||||
changes: vec![],
|
||||
frozen: false,
|
||||
};
|
||||
let append = |file: &Path, rev: u32| {
|
||||
weksa::InventoryStore::open(file)
|
||||
.unwrap()
|
||||
.admit_revision(revision(rev), vec![])
|
||||
.unwrap();
|
||||
};
|
||||
// Before any accept the head is the run's copy.
|
||||
let mut dao = dao();
|
||||
append(&dao.root.join("inventory.cc"), 3);
|
||||
assert_eq!(
|
||||
RunStores::open(&dao.root).err(),
|
||||
Some(RunError::Drift(DriftOf::Inventory))
|
||||
);
|
||||
|
||||
// After an accept it is the cycle's file; the first copy is no longer read.
|
||||
let mut dao2 = self::dao();
|
||||
two_rounds(&mut dao2);
|
||||
let mut model = cycle_fake(ONE_CONCEPT);
|
||||
assert_eq!(
|
||||
run_cycle(&mut dao2, &mut model).verdict(),
|
||||
Verdict::Accepted
|
||||
);
|
||||
drop(dao2.run);
|
||||
assert!(RunStores::open(&dao2.root).is_ok());
|
||||
append(&dao2.root.join("inventory.cc"), 3);
|
||||
assert!(
|
||||
RunStores::open(&dao2.root).is_ok(),
|
||||
"the superseded copy is not the head"
|
||||
);
|
||||
append(&dao2.root.join("cycle-1/inventory.cc"), 4);
|
||||
assert_eq!(
|
||||
RunStores::open(&dao2.root).err(),
|
||||
Some(RunError::Drift(DriftOf::Inventory))
|
||||
);
|
||||
dao.run = RunStores::create(
|
||||
&dao.root.join("again"),
|
||||
"x",
|
||||
RunPaths {
|
||||
corpus: &dao.corpus,
|
||||
inventory: &dao.inventory,
|
||||
entities: &dao.entities,
|
||||
},
|
||||
"fake-model",
|
||||
"bag",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
dao.run.record().inventory,
|
||||
std::fs::canonicalize(&dao.inventory)
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
/// Tripwires over the source, with the limits stated: they read text, so they
|
||||
/// catch a spelling and not an alias.
|
||||
#[test]
|
||||
|
|
@ -1237,4 +1932,52 @@ fn source_tripwires() {
|
|||
}
|
||||
let context = read("context.rs");
|
||||
assert!(!context.contains("pub fn from_corpus") && !context.contains("pub fn for_round"));
|
||||
// The editor's prompt reads Train items, an inventory and an EditFeedback:
|
||||
// no round record, decision, held-out mean or refusal count is named there.
|
||||
for banned in [
|
||||
"RoundRecord",
|
||||
"Decision",
|
||||
"SplitMean",
|
||||
"Aggregate",
|
||||
"validation_mean",
|
||||
"validation_refused",
|
||||
] {
|
||||
assert!(!context.contains(banned), "context.rs names {banned}");
|
||||
}
|
||||
// `EditFeedback::none` is the one public constructor; Decision has none.
|
||||
assert!(!context.contains("pub fn new"));
|
||||
let run = read("run.rs");
|
||||
let code: Vec<&str> = run
|
||||
.lines()
|
||||
.filter(|l| !l.trim_start().starts_with("//"))
|
||||
.collect();
|
||||
let count = |needle: &str| code.iter().filter(|l| l.contains(needle)).count();
|
||||
assert!(!run.contains("pub fn new"));
|
||||
assert_eq!(count("admit_revision("), 1, "one door call");
|
||||
assert_eq!(count("std::fs::copy"), 2, "create's copy and cycle's");
|
||||
assert_eq!(
|
||||
count("record.inventory,"),
|
||||
1,
|
||||
"the source path is read once"
|
||||
);
|
||||
assert_eq!(
|
||||
count("InventoryStore::open"),
|
||||
2,
|
||||
"the head and the cycle's file"
|
||||
);
|
||||
// An entry draft carries no id or revision field.
|
||||
let encode = read("encode.rs");
|
||||
let entry = encode
|
||||
.split("pub struct EntryDraft {")
|
||||
.nth(1)
|
||||
.and_then(|t| t.split('}').next())
|
||||
.unwrap();
|
||||
for banned in ["id", "introduced_rev", "retired_rev"] {
|
||||
assert!(
|
||||
!entry
|
||||
.split_whitespace()
|
||||
.any(|w| w.trim_end_matches(':') == banned),
|
||||
"EntryDraft has a {banned} field"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -134,6 +134,12 @@ fn published_schemas_match() {
|
|||
let published = weksa::schema::published();
|
||||
let mut names: Vec<String> = published.iter().map(|(n, _)| n.clone()).collect();
|
||||
names.sort();
|
||||
for loop_type in ["run", "round", "decision"] {
|
||||
assert!(
|
||||
names.contains(&format!("weksa.loop_{loop_type}.schema.json")),
|
||||
"{loop_type}"
|
||||
);
|
||||
}
|
||||
let mut on_disk: Vec<String> = std::fs::read_dir(&dir)
|
||||
.unwrap()
|
||||
.map(|e| e.unwrap().file_name().into_string().unwrap())
|
||||
|
|
|
|||
201
schemas/cultnet/weksa.loop_decision.schema.json
Normal file
201
schemas/cultnet/weksa.loop_decision.schema.json
Normal file
|
|
@ -0,0 +1,201 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "Decision",
|
||||
"description": "One closed edit-accept cycle: digests and numbers, no text. Key\n`run:<label>:cycle:<k>`. Only [`cycle`] builds one.\n\n```\nfn f(d: &weksa::run::Decision) -> u32 { d.k() }\n```\n\nEvery field is given, so the literal below fails only on privacy; its twin is\nthe same literal in the unit test `a_decision_literal_compiles_in_the_lib`.\n\n```compile_fail,E0451\nuse weksa::run::{Call, Decision, Reading, Verdict};\nfn f() -> Decision {\n let r = Reading { chrf: 0.0, meaning: 0.0, composite: 0.0 };\n Decision {\n k: 1,\n base_round: 1,\n base_rev: 1,\n base_inventory_digest: String::new(),\n edit: Call { prompt: String::new(), items: vec![] },\n edit_answer_digest: None,\n candidate_rev: None,\n candidate_inventory_digest: None,\n candidate_round: None,\n base: r,\n candidate: None,\n floor: r,\n threshold: 0.0,\n verdict: Verdict::Accepted,\n }\n}\n```",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"base": {
|
||||
"$ref": "#/$defs/Reading"
|
||||
},
|
||||
"base_inventory_digest": {
|
||||
"type": "string"
|
||||
},
|
||||
"base_rev": {
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"base_round": {
|
||||
"description": "The head's establishing round: the base of this cycle.",
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"candidate": {
|
||||
"anyOf": [
|
||||
{
|
||||
"$ref": "#/$defs/Reading"
|
||||
},
|
||||
{
|
||||
"type": "null"
|
||||
}
|
||||
]
|
||||
},
|
||||
"candidate_inventory_digest": {
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"candidate_rev": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"candidate_round": {
|
||||
"type": [
|
||||
"integer",
|
||||
"null"
|
||||
],
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"edit": {
|
||||
"description": "The edit prompt's digest and the Train keys it held.",
|
||||
"$ref": "#/$defs/Call"
|
||||
},
|
||||
"edit_answer_digest": {
|
||||
"description": "16 hex of the editor's answer; `None` when it was unreadable.",
|
||||
"type": [
|
||||
"string",
|
||||
"null"
|
||||
]
|
||||
},
|
||||
"floor": {
|
||||
"$ref": "#/$defs/Reading"
|
||||
},
|
||||
"k": {
|
||||
"type": "integer",
|
||||
"format": "uint32",
|
||||
"minimum": 0
|
||||
},
|
||||
"threshold": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"verdict": {
|
||||
"$ref": "#/$defs/Verdict"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"k",
|
||||
"base_round",
|
||||
"base_rev",
|
||||
"base_inventory_digest",
|
||||
"edit",
|
||||
"base",
|
||||
"floor",
|
||||
"threshold",
|
||||
"verdict"
|
||||
],
|
||||
"$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"
|
||||
]
|
||||
},
|
||||
"Metric": {
|
||||
"description": "Which metric an edit regressed.",
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Chrf",
|
||||
"Meaning"
|
||||
]
|
||||
},
|
||||
"Reading": {
|
||||
"description": "One validation reading: chrF 0 to 100, meaning 0 to 1, and their composite.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"chrf": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"composite": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
},
|
||||
"meaning": {
|
||||
"type": "number",
|
||||
"format": "double"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"chrf",
|
||||
"meaning",
|
||||
"composite"
|
||||
]
|
||||
},
|
||||
"Verdict": {
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"Accepted"
|
||||
]
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"Rejected": {
|
||||
"$ref": "#/$defs/Why"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"Rejected"
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
"Why": {
|
||||
"description": "Why an edit was rejected.",
|
||||
"oneOf": [
|
||||
{
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"NoGain"
|
||||
]
|
||||
},
|
||||
{
|
||||
"description": "The answer was not an edit draft.",
|
||||
"type": "string",
|
||||
"const": "EditParse"
|
||||
},
|
||||
{
|
||||
"description": "The draft asked for no change or too many, or the inventory door refused it.",
|
||||
"type": "string",
|
||||
"const": "EditAdmit"
|
||||
},
|
||||
{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"Regressed": {
|
||||
"$ref": "#/$defs/Metric"
|
||||
}
|
||||
},
|
||||
"additionalProperties": false,
|
||||
"required": [
|
||||
"Regressed"
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue