From 0ea07d21faba1d14ada8698ba11a4219bd639bc9 Mon Sep 17 00:00:00 2001 From: Weksa Date: Thu, 12 Nov 2026 14:11:51 +0000 Subject: [PATCH] Ontology entries per language, selected inside Prompt::lower and pinned by the run OntologyEntry, OntologyStore::admit, ontology::select over the view's stance and discourse, OntologyDraft, run keys 15 and 16 with Drift(Ontology), weksa ontology admit and dump. Co-Authored-By: Claude Sonnet 5.5 --- crates/weksa/src/context.rs | 51 ++-- crates/weksa/src/encode.rs | 55 ++++ crates/weksa/src/lib.rs | 4 +- crates/weksa/src/main.rs | 79 +++++- crates/weksa/src/ontology.rs | 164 +++++++++++ crates/weksa/src/run.rs | 70 ++++- crates/weksa/src/schema.rs | 2 + crates/weksa/src/store.rs | 134 ++++++++- crates/weksa/tests/cli.rs | 4 + crates/weksa/tests/common/mod.rs | 12 + crates/weksa/tests/context.rs | 12 +- crates/weksa/tests/golf_loop.rs | 44 ++- crates/weksa/tests/original_corpus.rs | 7 + schemas/cultnet/weksa.loop_run.schema.json | 12 +- .../cultnet/weksa.ontology_entry.schema.json | 264 ++++++++++++++++++ 15 files changed, 869 insertions(+), 45 deletions(-) create mode 100644 crates/weksa/src/ontology.rs create mode 100644 schemas/cultnet/weksa.ontology_entry.schema.json diff --git a/crates/weksa/src/context.rs b/crates/weksa/src/context.rs index 877c974..2b88a08 100644 --- a/crates/weksa/src/context.rs +++ b/crates/weksa/src/context.rs @@ -10,7 +10,9 @@ //! [`Inventory`] and an [`EditFeedback`] and nothing else, so no held-out text, //! key or per-item score can reach it. A lowering prompt names the language it //! is said in on a language line; every language is named by its tag, none by a -//! default. +//! default. A lowering prompt also prints the target language's ontology +//! entries that `ontology::select` chose for the view; the caller never names +//! entries. //! //! Item text may hold line breaks; the renderer indents every continuation line //! (`indented`), so item text cannot forge a `[key]` line or a paragraph. @@ -28,6 +30,7 @@ use serde::Serialize; use crate::corpus::{CorpusItem, CorpusItemId}; use crate::inventory::{Inventory, InventoryEntry, OptionLabel, ValueKind}; use crate::lower::{EntityForms, LowerError, entity}; +use crate::ontology::{Ontology, select}; use crate::packet::{ Context, Discourse, EntityId, Extension, Predication, Referent, Relation, Stance, }; @@ -68,7 +71,7 @@ A feature is {feature, value}; value is {\"Grade\": 0 to 1000}, {\"Option\": lab /// Fixed per run by `PROMPT_SOURCE_DIGEST`. pub const LOWER_INSTRUCTIONS: &str = "\ Say the packet below in the language on the language line, as one utterance of its speaker: all of its meaning and nothing it does not carry. -Every id is the inventory's listed below and every feature value is as listed; a grade is permille, 0 to 1000. The stance is the speaker's felt affect and restraint: it shapes how the utterance is said, not what it says. +Every id is the inventory's listed below and every feature value is as listed; a grade is permille, 0 to 1000. The stance is the speaker's felt affect and restraint: it shapes how the utterance is said, not what it says. The ontology lines are choices this language makes for this speaker and stance: realize each where the packet allows; they add no meaning. A referent with an entity is named by one of that entity's forms on the entities line. Answer with one JSON object and nothing else: {\"text\": \"...\"}. No code fence, no commentary."; @@ -86,7 +89,7 @@ Answer with one JSON object and nothing else: {\"text\": \"...\"}, the continuat /// ```no_run /// # let dir = tempfile::tempdir().unwrap(); /// # let p = |n: &str| dir.path().join(n); -/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") }; +/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc"), ontology: &p("o.cc") }; /// # let panel = ["en-US".to_string()]; /// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded, &panel).unwrap(); /// let t = run.train().unwrap(); @@ -100,8 +103,8 @@ Answer with one JSON object and nothing else: {\"text\": \"...\"}, the continuat /// ```compile_fail /// # let dir = tempfile::tempdir().unwrap(); /// # let p = |n: &str| dir.path().join(n); -/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); } -/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") }; +/// # for n in ["c.cc", "i.cc", "e.cc", "o.cc"] { std::fs::write(p(n), [0x90]).unwrap(); } +/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc"), ontology: &p("o.cc") }; /// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded, &["en-US".to_string()]).unwrap(); /// let t = run.train().unwrap(); /// let _u = t.clone(); @@ -111,8 +114,8 @@ Answer with one JSON object and nothing else: {\"text\": \"...\"}, the continuat /// fn s(_: &T) {} /// # let dir = tempfile::tempdir().unwrap(); /// # let p = |n: &str| dir.path().join(n); -/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); } -/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") }; +/// # for n in ["c.cc", "i.cc", "e.cc", "o.cc"] { std::fs::write(p(n), [0x90]).unwrap(); } +/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc"), ontology: &p("o.cc") }; /// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded, &["en-US".to_string()]).unwrap(); /// let t = run.train().unwrap(); /// s(&t); @@ -334,7 +337,7 @@ impl EditFeedback { /// ```no_run /// # let dir = tempfile::tempdir().unwrap(); /// # let p = |n: &str| dir.path().join(n); -/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") }; +/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc"), ontology: &p("o.cc") }; /// # let panel = ["en-US".to_string()]; /// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded, &panel).unwrap(); /// let t = run.train().unwrap(); @@ -352,8 +355,8 @@ impl EditFeedback { /// ```compile_fail,E0061 /// # let dir = tempfile::tempdir().unwrap(); /// # let p = |n: &str| dir.path().join(n); -/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); } -/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") }; +/// # for n in ["c.cc", "i.cc", "e.cc", "o.cc"] { std::fs::write(p(n), [0x90]).unwrap(); } +/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc"), ontology: &p("o.cc") }; /// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded, &["en-US".to_string()]).unwrap(); /// let t = run.train().unwrap(); /// let inv = run.inventory().inventory().unwrap(); @@ -365,8 +368,8 @@ impl EditFeedback { /// fn s(_: &T) {} /// # let dir = tempfile::tempdir().unwrap(); /// # let p = |n: &str| dir.path().join(n); -/// # for n in ["c.cc", "i.cc", "e.cc"] { std::fs::write(p(n), [0x90]).unwrap(); } -/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc") }; +/// # for n in ["c.cc", "i.cc", "e.cc", "o.cc"] { std::fs::write(p(n), [0x90]).unwrap(); } +/// # let paths = weksa::run::RunPaths { corpus: &p("c.cc"), inventory: &p("i.cc"), entities: &p("e.cc"), ontology: &p("o.cc") }; /// # let run = weksa::run::RunStores::create(&p("run"), "t", paths, "m", "e", weksa::run::LowererReach::ToolLessRelay, weksa::corpus::ModelFamily::Unrecorded, &["en-US".to_string()]).unwrap(); /// let t = run.train().unwrap(); /// let inv = run.inventory().inventory().unwrap(); @@ -523,9 +526,13 @@ impl Prompt { /// [`LOWER_INSTRUCTIONS`], the `language: ` line, the meaning of /// `input` (no kind, constraints, scene, speaker or group), the forms in - /// `language` of every entity its referents cite, and the entries of `inventory` live at the view's revision. `item` - /// goes only to [`Prompt::item_keys`], never into the text. The view's - /// speaker and group fields are never read; a speaker's entity id appears + /// `language` of every entity its referents cite, the `ontology:` section + /// and the entries of `inventory` live at the view's revision. The section + /// holds the entries `ontology::select` chooses from the view's stance and + /// discourse features and `language`, never the caller; the view's speaker + /// and group are still never read. `item` + /// goes only to [`Prompt::item_keys`], never into the text. A speaker's + /// entity id appears /// only when the encoder cites that entity on a referent, which is naming a /// cited entity like any other. A cited entity the port lacks, or one with /// no form in `language`, is an error and no prompt. The caller chooses the @@ -536,6 +543,7 @@ impl Prompt { language: &str, inventory: &Inventory, entities: &dyn EntityForms, + ontology: &Ontology, ) -> Result { let mut forms: BTreeMap<&str, Vec> = BTreeMap::new(); for id in input.referents().iter().filter_map(|r| r.entity.as_ref()) { @@ -556,8 +564,19 @@ impl Prompt { stance: input.stance(), }; let rev = input.inventory_rev(); + let chosen = select(ontology, language, input); + let mut lines = String::new(); + for e in &chosen { + lines.push_str(&format!("\n{} [{}] {}", e.key(), e.layer.name(), e.choice)); + for x in &e.examples { + lines.push_str(&format!(" | e.g. {x}")); + } + } + if chosen.is_empty() { + lines.push_str(" none"); + } let text = format!( - "{LOWER_INSTRUCTIONS}\n\nlanguage: {language}\n\npacket: {}\n\nentities: {}\n\ninventory rev:{rev}{}", + "{LOWER_INSTRUCTIONS}\n\nlanguage: {language}\n\npacket: {}\n\nentities: {}\n\nontology:{lines}\n\ninventory rev:{rev}{}", serde_json::to_string(&meaning).expect("a meaning is plain data"), serde_json::to_string(&forms).expect("forms are plain data"), inventory_lines(inventory, rev) diff --git a/crates/weksa/src/encode.rs b/crates/weksa/src/encode.rs index c9b245e..d616d3d 100644 --- a/crates/weksa/src/encode.rs +++ b/crates/weksa/src/encode.rs @@ -19,10 +19,12 @@ use crate::corpus::CorpusItemId; use crate::inventory::{ Change, Family, InvId, Inventory, InventoryEntry, InventoryRevision, Slot, ValueKind, }; +use crate::ontology::{Condition, Layer, OntologyEntry}; use crate::packet::{ Constraints, Context, Discourse, EncoderId, Grade, Packet, PacketId, PacketKind, Predication, Provenance, ProvenanceSource, Referent, Relation, SCHEMA_VERSION, Stance, Trace, }; +use crate::speaker::Annotator; use crate::split::{fnv1a64, hex16}; /// The meaning fields of a packet, as a model writes them. @@ -271,6 +273,59 @@ impl EditDraft { } } +/// One ontology entry as a model writes it: no language, number, inventory +/// revision or annotator. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct EntryOntologyDraft { + pub layer: Layer, + #[serde(default)] + pub when: Vec, + pub choice: String, + #[serde(default)] + pub examples: Vec, +} + +/// A batch of ontology entries as a model drafts them: the xenos door of a +/// seed answer. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct OntologyDraft { + pub entries: Vec, +} + +impl OntologyDraft { + pub fn parse(answer: &str) -> Result { + from_json(answer) + } + + /// The entries this draft becomes: numbered from `first_n` in draft order, + /// all of `language` read at `inventory_rev`, annotated `annotator`. + /// Whether they are admissible is `OntologyStore::admit`'s to refuse. + pub fn into_entries( + self, + language: &str, + inventory_rev: u32, + first_n: u32, + annotator: &Annotator, + ) -> Vec { + self.entries + .into_iter() + .zip(first_n..) + .map(|(d, n)| OntologyEntry { + language: language.to_string(), + n, + inventory_rev, + layer: d.layer, + when: d.when, + choice: d.choice, + examples: d.examples, + annotator: annotator.clone(), + }) + .collect() + } +} + /// A lowering as the lowerer writes it: the English text, nothing else. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] diff --git a/crates/weksa/src/lib.rs b/crates/weksa/src/lib.rs index efea9ef..2510fae 100644 --- a/crates/weksa/src/lib.rs +++ b/crates/weksa/src/lib.rs @@ -12,6 +12,7 @@ pub mod form; pub mod inventory; pub mod lower; pub mod model; +pub mod ontology; pub mod packet; pub mod phones; pub mod run; @@ -32,6 +33,7 @@ pub use inventory::{ }; pub use lower::{EntityForms, LowerError, PhoneLine, TARGET_LANGUAGE, lower, phones, pronounce}; pub use model::{AnswerFiles, ModelPort}; +pub use ontology::{Condition, Layer, Ontology, OntologyEntry, Test, select}; pub use packet::{ EncoderId, EntityId, Grade, NodeId, Packet, PacketId, PacketKind, SCHEMA_VERSION, Stance, }; @@ -41,7 +43,7 @@ pub use score::{Embedder, ItemScore, OllamaEmbedder, Scorer, chrf}; pub use speaker::{Annotator, PairRelation, Party, Scene, Speaker}; pub use split::{Split, SplitScheme}; pub use store::{ - AddOutcome, CorpusStore, EntityBound, EntityStore, InventoryStore, PacketStore, + AddOutcome, CorpusStore, EntityBound, EntityStore, InventoryStore, OntologyStore, PacketStore, SpeakerStateStore, StoreError, StoreRefusal, }; pub use validate::{LoweringInput, Refusal, SceneRead, validate}; diff --git a/crates/weksa/src/main.rs b/crates/weksa/src/main.rs index 8270565..b9b094e 100644 --- a/crates/weksa/src/main.rs +++ b/crates/weksa/src/main.rs @@ -8,6 +8,7 @@ use clap::error::{ContextKind, ContextValue, ErrorKind}; use clap::{Args, Parser, Subcommand, ValueEnum}; use unicode_normalization::UnicodeNormalization; use weksa::corpus::{CorpusItem, ModelFamily, NameSpan, Source, Turn}; +use weksa::encode::OntologyDraft; use weksa::entity::{Entity, EntityOrigin, LanguageForms, Pronunciation}; use weksa::inventory::{proof_revision, seed}; use weksa::packet::proof_packet; @@ -17,7 +18,7 @@ use weksa::run::{ }; use weksa::score::ScoreInput; use weksa::{ - AnswerFiles, CorpusStore, EntityId, EntityStore, InventoryStore, OllamaEmbedder, PacketStore, + Annotator, AnswerFiles, CorpusStore, EntityId, EntityStore, InventoryStore, OllamaEmbedder, OntologyStore, PacketStore, Scorer, Split, SplitScheme, StoreError, lower, pronounce, validate, }; @@ -36,6 +37,9 @@ struct Cli { /// The entity store. #[arg(long, global = true, default_value = "data/entity/entity.cc")] entities: PathBuf, + /// The language ontology store. + #[arg(long, global = true, default_value = "data/ontology/ontology.cc")] + ontology: PathBuf, #[command(subcommand)] command: Command, } @@ -51,6 +55,8 @@ enum Command { #[command(subcommand)] Entity(EntityCommand), #[command(subcommand)] + Ontology(OntologyCommand), + #[command(subcommand)] Packet(PacketCommand), /// Lower a stored packet to English text. Lower { @@ -81,7 +87,7 @@ enum Command { #[derive(Subcommand)] enum LoopCommand { - /// Pin the global --corpus, --inventory and --entities as a run at ROOT. + /// Pin the global --corpus, --inventory, --entities and --ontology as a run at ROOT. Open { root: PathBuf, #[arg(long)] @@ -105,8 +111,8 @@ enum LoopCommand { panel: Vec, }, /// Run one round of the run at ROOT. The stores are read only from the - /// run's record: the global --corpus, --inventory and --entities are not - /// read. Encode prompts are written first; once they are answered a rerun + /// run's record: the global --corpus, --inventory, --entities and --ontology + /// are not read. Encode prompts are written first; once they are answered a rerun /// writes the lowering prompts. The command exits 3 each time until every /// prompt has an answer. Round { @@ -195,6 +201,28 @@ enum EntityCommand { Dump, } +#[derive(Subcommand)] +enum OntologyCommand { + /// Admit a model's ontology draft (a JSON file) for one language as a + /// batch, numbered from the language's latest plus one and annotated as + /// the model that drafted it. + Admit { + answer: PathBuf, + #[arg(long)] + language: String, + /// The inventory revision the draft's conditions are read at. + #[arg(long)] + inventory_rev: u32, + #[arg(long)] + model_family: ModelFamilyArg, + /// The attestation string naming the drafting model. + #[arg(long)] + generator: String, + }, + /// Text projection of the ontology for review; not a store. + Dump, +} + #[derive(Args)] struct PutArgs { /// `entity:`. @@ -648,6 +676,48 @@ fn main() -> Result<()> { println!("{} {:?}\n forms: {:?}", e.id, e.origin, e.forms); } } + Command::Ontology(OntologyCommand::Admit { + answer, + language, + inventory_rev, + model_family, + generator, + }) => { + let text = std::fs::read_to_string(&answer).context("the draft would not read")?; + let draft = OntologyDraft::parse(&text)?; + let mut store = OntologyStore::open(&cli.ontology)?; + let first = store + .all()? + .iter() + .filter(|e| e.language == language) + .map(|e| e.n) + .max() + .unwrap_or(0) + + 1; + let annotator = Annotator::Model { + family: model_family.into(), + generator, + }; + let entries = draft.into_entries(&language, inventory_rev, first, &annotator); + let count = entries.len(); + let inventory = InventoryStore::open(&cli.inventory)?; + let outcome = store.admit(entries, &inventory).map_err(refused)?; + println!("{outcome:?} {count} entries of {language}"); + } + Command::Ontology(OntologyCommand::Dump) => { + for e in OntologyStore::open(&cli.ontology)?.all()? { + println!( + "{} {} rev:{} {:?}\n when: {:?}\n {}\n e.g. {:?}", + e.key(), + e.layer.name(), + e.inventory_rev, + e.annotator, + e.when, + e.choice, + e.examples + ); + } + } Command::Inventory(InventoryCommand::Seed) => { let (rev, entries) = seed(); let count = entries.len(); @@ -779,6 +849,7 @@ fn main() -> Result<()> { corpus: &cli.corpus, inventory: &cli.inventory, entities: &cli.entities, + ontology: &cli.ontology, }, &answerer, &embed_model, diff --git a/crates/weksa/src/ontology.rs b/crates/weksa/src/ontology.rs new file mode 100644 index 0000000..4bc38fb --- /dev/null +++ b/crates/weksa/src/ontology.rs @@ -0,0 +1,164 @@ +//! The language ontology: per target language, the choices its culture makes +//! about word, grammar, discourse, sound and script for a speaker in a stance +//! (ruling `persona-drives-ontology`). An entry says when it applies (feature +//! conditions over the lowering view's stance and discourse) and what it +//! chooses. `select` is the only reader that decides which entries a lowering +//! prompt carries, and it runs only inside `Prompt::lower`; +//! `OntologyStore::admit` is the only writer. Entries are immutable. + +use cultcache_rs::DatabaseEntry; +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use crate::inventory::{InvId, Slot}; +use crate::packet::{FeatValue, FeatureValue, Grade}; +use crate::speaker::Annotator; +use crate::validate::LoweringInput; + +pub const MAX_CONDITIONS: usize = 4; +pub const MAX_EXAMPLES: usize = 3; +pub const MAX_CHOICE_BYTES: usize = 200; +pub const MAX_EXAMPLE_BYTES: usize = 120; +pub const MAX_ENTRIES_PER_LANGUAGE: usize = 64; + +/// Which part of the language an entry shapes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub enum Layer { + Lexicon, + Grammar, + Discourse, + Phonology, + Orthography, +} + +impl Layer { + pub fn name(self) -> &'static str { + match self { + Layer::Lexicon => "lexicon", + Layer::Grammar => "grammar", + Layer::Discourse => "discourse", + Layer::Phonology => "phonology", + Layer::Orthography => "orthography", + } + } +} + +/// What a feature's value must be for a condition to hold. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub enum Test { + AtLeast(Grade), + AtMost(Grade), + Is(FeatValue), +} + +/// One feature of one slot of the view, tested. Only `Stance` and `Discourse` +/// reach a lowering view today. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] +pub struct Condition { + pub slot: Slot, + pub feature: InvId, + pub test: Test, +} + +impl Condition { + fn holds(&self, features: &[FeatureValue]) -> bool { + let Some(found) = features.iter().find(|f| f.feature == self.feature) else { + return false; + }; + match (&self.test, &found.value) { + (Test::AtLeast(g), FeatValue::Grade(v)) => v >= g, + (Test::AtMost(g), FeatValue::Grade(v)) => v <= g, + (Test::Is(want), v) => want == v, + _ => false, + } + } + + /// The feature value this condition names, as the inventory check reads it. + pub(crate) fn as_value(&self) -> FeatureValue { + FeatureValue { + feature: self.feature, + value: match &self.test { + Test::AtLeast(g) | Test::AtMost(g) => FeatValue::Grade(*g), + Test::Is(v) => v.clone(), + }, + } + } +} + +/// One choice of one language. Key `onto::`. +#[derive(Clone, Debug, PartialEq, Eq, JsonSchema, DatabaseEntry)] +#[cultcache(type = "weksa.ontology_entry")] +pub struct OntologyEntry { + #[cultcache(key = 0)] + pub language: String, + /// The entry's number within its language, from 1. + #[cultcache(key = 1)] + pub n: u32, + /// The inventory revision the conditions read against. + #[cultcache(key = 2)] + pub inventory_rev: u32, + #[cultcache(key = 3)] + pub layer: Layer, + /// Every condition must hold; none means the entry always applies. + #[cultcache(key = 4)] + pub when: Vec, + #[cultcache(key = 5)] + pub choice: String, + #[cultcache(key = 6)] + pub examples: Vec, + #[cultcache(key = 7)] + pub annotator: Annotator, +} + +/// `onto::`. +pub fn ontology_key(language: &str, n: u32) -> String { + format!("onto:{language}:{n}") +} + +impl OntologyEntry { + pub fn key(&self) -> String { + ontology_key(&self.language, self.n) + } +} + +/// Every entry of the run's ontology store, by language then number. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Ontology { + entries: Vec, +} + +impl Ontology { + pub fn empty() -> Self { + Self::default() + } + + pub(crate) fn of(mut entries: Vec) -> Self { + entries.sort_by(|a, b| (&a.language, a.n).cmp(&(&b.language, b.n))); + Self { entries } + } + + pub fn entries(&self) -> &[OntologyEntry] { + &self.entries + } +} + +/// The entries of exactly `language` whose every condition holds against the +/// view's stance and discourse features, in `n` order. An absent feature meets +/// no condition. Nothing else of the view is read. +pub fn select<'a>( + o: &'a Ontology, + language: &str, + input: &LoweringInput, +) -> Vec<&'a OntologyEntry> { + o.entries + .iter() + .filter(|e| e.language == language) + .filter(|e| { + e.when.iter().all(|c| match c.slot { + Slot::Stance => c.holds(&input.stance().features), + Slot::Discourse => c.holds(&input.discourse().features), + _ => false, + }) + }) + .collect() +} diff --git a/crates/weksa/src/run.rs b/crates/weksa/src/run.rs index a1b879d..0e63af4 100644 --- a/crates/weksa/src/run.rs +++ b/crates/weksa/src/run.rs @@ -47,7 +47,8 @@ use crate::packet::{Packet, Stance}; use crate::score::{CHRF_VERSION, chrf, Embedder, ItemScore, ScoreInput, Scorer, SplitMean, aggregate}; use crate::split::{Split, SplitScheme, fnv1a64, fnv1a64_of, hex16}; use crate::store::{ - CorpusStore, EntityStore, InventoryStore, PacketStore, StoreError, open_cache_over, + CorpusStore, EntityStore, InventoryStore, OntologyStore, PacketStore, StoreError, + check_ontology_entry, open_cache_over, }; use crate::validate::LoweringInput; @@ -55,7 +56,9 @@ use crate::validate::LoweringInput; /// whose scheme and digest function decide which lines the prompt holds as /// Train and name every prompt, then `lower.rs`, whose `EntityForms` port and /// `entity()` the lowering prompt reads, then `packet.rs`, whose serde -/// shapes the lowering prompt prints as the packet. Each file enters the digest +/// shapes the lowering prompt prints as the packet, then `ontology.rs`, whose +/// entry shape and `select` decide which ontology lines the lowering prompt +/// prints. Each file enters the digest /// behind its length, so the parts cannot be re-cut into other parts with the /// same digest. Any edit to any of them, comments included, ends a run; code /// outside those files is not covered. @@ -64,6 +67,7 @@ pub const PROMPT_SOURCE_DIGEST: u64 = fnv1a64_of(&[ include_bytes!("split.rs"), include_bytes!("lower.rs"), include_bytes!("packet.rs"), + include_bytes!("ontology.rs"), ]); /// The least composite gain an edit must show over item noise to be kept, and @@ -125,6 +129,13 @@ pub struct RunRecord { /// language is never offered, minted from, probed or scored. #[cultcache(key = 14)] pub panel: Vec, + /// Canonical absolute path of the ontology store: read-only for the run, + /// pinned by `ontology_digest`. + #[cultcache(key = 15)] + pub ontology: String, + /// 16 hex of the ontology file's bytes. + #[cultcache(key = 16)] + pub ontology_digest: String, } /// How a run's lowering prompts reach the model that answers them (rulings @@ -429,6 +440,7 @@ impl RoundRecord { pub enum DriftOf { Corpus, Entities, + Ontology, Prompts, Model, Embedder, @@ -464,6 +476,9 @@ pub enum RunError { /// The panel is empty, repeats or misspells a language, or names one with no /// live Train or Validation item in the pinned corpus. Panel, + /// An ontology entry of a panel language does not read against the run's + /// head inventory at its revision. + Ontology, } impl fmt::Display for RunError { @@ -473,7 +488,7 @@ impl fmt::Display for RunError { RunError::NoRun => f.write_str("the root holds no run"), RunError::Malformed(what) => write!(f, "malformed {what}"), RunError::Drift(DriftOf::Prompts) => f.write_str( - "drift in Prompts (the prompt source digest covers context.rs, split.rs, lower.rs and packet.rs)", + "drift in Prompts (the prompt source digest covers context.rs, split.rs, lower.rs, packet.rs and ontology.rs)", ), RunError::Drift(of) => write!(f, "drift in {of:?}"), RunError::NoInventory => f.write_str("the inventory holds no revision"), @@ -485,6 +500,9 @@ impl fmt::Display for RunError { 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"), + RunError::Ontology => f.write_str( + "an ontology entry of a panel language does not read against the run's inventory", + ), RunError::Panel => f.write_str( "the panel is empty, repeats or misspells a language, or names one with no live Train or Validation item", ), @@ -500,12 +518,13 @@ impl fmt::Debug for RunError { impl std::error::Error for RunError {} -/// The three stores a run pins. +/// The four stores a run pins. #[derive(Clone, Copy)] pub struct RunPaths<'a> { pub corpus: &'a Path, pub inventory: &'a Path, pub entities: &'a Path, + pub ontology: &'a Path, } /// A run's open stores, reopened only from its record. The one public producer @@ -517,6 +536,7 @@ pub struct RunStores { corpus: CorpusStore, inventory: InventoryStore, entities: EntityStore, + ontology: OntologyStore, } /// The run's own copy of the inventory, made at `create`. @@ -530,6 +550,9 @@ fn check_pins(cache: &CultCache, root: &Path, record: &RunRecord) -> Result<(), if file_digest(&record.entities).as_ref() != Some(&record.entity_digest) { return Err(RunError::Drift(DriftOf::Entities)); } + if file_digest(&record.ontology).as_ref() != Some(&record.ontology_digest) { + return Err(RunError::Drift(DriftOf::Ontology)); + } let (path, digest, _) = head_of(cache, root, record)?; if file_digest_at(&path).as_ref() != Some(&digest) { return Err(RunError::Drift(DriftOf::Inventory)); @@ -663,6 +686,8 @@ impl RunStores { corpus: canonical(paths.corpus)?, inventory: canonical(paths.inventory)?, entities: canonical(paths.entities)?, + ontology: canonical(paths.ontology)?, + ontology_digest: String::new(), corpus_digest: String::new(), entity_digest: String::new(), prompt_digest: hex16(PROMPT_SOURCE_DIGEST), @@ -684,11 +709,13 @@ impl RunStores { corpus_digest: file_digest(&record.corpus).ok_or(RunError::Store)?, entity_digest: file_digest(&record.entities).ok_or(RunError::Store)?, inventory_digest: file_digest_at(&head).ok_or(RunError::Store)?, + ontology_digest: file_digest(&record.ontology).ok_or(RunError::Store)?, ..record }; between(); let mut run = Self::with(root, cache, record)?; run.check_panel()?; + run.check_ontology()?; // The stores were read between the digests: unless they still match // the pins, what was opened is not what was pinned. Nothing is // recorded for a run that did not pin. @@ -739,6 +766,7 @@ impl RunStores { corpus: CorpusStore::open(Path::new(&record.corpus)).map_err(store)?, inventory: InventoryStore::open(&head).map_err(store)?, entities: EntityStore::open(Path::new(&record.entities)).map_err(store)?, + ontology: OntologyStore::open(Path::new(&record.ontology)).map_err(store)?, cache, record, }) @@ -748,6 +776,18 @@ impl RunStores { &self.record } + /// Every ontology entry of a panel language reads against the run's head + /// inventory at its own revision: the check the store applied at admission, + /// applied again to this inventory. + fn check_ontology(&self) -> Result<(), RunError> { + let inventory = self.inventory.inventory().map_err(|_| RunError::Store)?; + let entries = self.ontology.all().map_err(|_| RunError::Store)?; + entries + .iter() + .filter(|e| self.record.panel.contains(&e.language)) + .try_for_each(|e| check_ontology_entry(e, &inventory).map_err(|_| RunError::Ontology)) + } + /// Every panel language holds a live Train and a live Validation item. fn check_panel(&self) -> Result<(), RunError> { let items = self.corpus.all().map_err(|_| RunError::Store)?; @@ -1171,7 +1211,9 @@ impl RunStores { /// Train and Validation packet of plain round `n`, per panel language, asks the lowerer again /// (`model`, the replay), with the packet's stance emptied (drop) and with /// the next item's stance in its split (permute), and reads how far the - /// lowering moves against the round's own answer (`recorded`). Test and + /// lowering moves against the round's own answer (`recorded`). The variant + /// stance also changes which ontology entries are selected, so the figure is + /// the stance's whole effect on the lowering, packet and ontology together. Test and /// withdrawn items are never asked. Records nothing and writes nothing in /// `round-`; the variant stores are rebuilt each call. An answer that /// is not a usable lowering drops its pair and is counted in `unusable`. @@ -1190,6 +1232,7 @@ impl RunStores { .find(|r| r.n() == n && r.cycle().is_none()) .ok_or(RunError::Malformed("round"))?; let inventory = self.inventory.inventory().map_err(store)?; + let ontology = self.ontology.ontology().map_err(store)?; let dir = self.ablation_dir(n); std::fs::create_dir_all(&dir).map_err(|e| RunError::Io(e.kind()))?; @@ -1242,7 +1285,14 @@ impl RunStores { let view = stores[slot] .admit(packet, &self.inventory, &self.corpus, &self.entities) .map_err(|_| RunError::Store)?; - Prompt::lower(&view, &packet_item, &item.language, &inventory, &self.entities) + Prompt::lower( + &view, + &packet_item, + &item.language, + &inventory, + &self.entities, + &ontology, + ) .map_err(|_| RunError::Store) }; let base = prompt_of(0, packet.clone())?; @@ -1444,6 +1494,7 @@ fn score_round( ) -> Result { let store = |_| RunError::Store; let inventory = inventory_store.inventory().map_err(store)?; + let ontology = run.ontology.ontology().map_err(store)?; let rev = inventory.latest().ok_or(RunError::NoInventory)?.n; let train = run.train().map_err(store)?; @@ -1524,7 +1575,7 @@ fn score_round( // Each item is lowered in its own language: the only reference the // scorer has is the item's own text. let language = &items[*at].language; - let Ok(prompt) = Prompt::lower(view, id, language, &inventory, &run.entities) else { + let Ok(prompt) = Prompt::lower(view, id, language, &inventory, &run.entities, &ontology) else { fates[*at] = Fate::Refused(Stage::Lower, Some(packet_key.clone())); continue; }; @@ -2725,6 +2776,8 @@ mod tests { lowerer_reach: LowererReach::ToolLessRelay, answerer_family: ModelFamily::Unrecorded, panel: vec!["en-US".into()], + ontology: String::new(), + ontology_digest: String::new(), } } @@ -2915,6 +2968,8 @@ mod tests { copy("inventory.cc", "i.cc"), copy("entity.cc", "e.cc"), ); + let ontology = dir.path().join("o.cc"); + fs::write(&ontology, [0x90]).unwrap(); let root = dir.path().join("run"); let mut run = RunStores::create( &root, @@ -2923,6 +2978,7 @@ mod tests { corpus: &corpus, inventory: &inventory, entities: &entities, + ontology: &ontology, }, "fake-model", "bag", diff --git a/crates/weksa/src/schema.rs b/crates/weksa/src/schema.rs index 21add8f..4fea40d 100644 --- a/crates/weksa/src/schema.rs +++ b/crates/weksa/src/schema.rs @@ -4,6 +4,7 @@ use crate::corpus::CorpusItem; use crate::entity::Entity; use crate::inventory::{InventoryEntry, InventoryRevision}; +use crate::ontology::OntologyEntry; use crate::packet::Packet; use crate::run::{Decision, RoundRecord, RunRecord}; use crate::speaker::{Scene, Speaker}; @@ -25,6 +26,7 @@ pub fn published() -> Vec<(String, String)> { published_for::(), published_for::(), published_for::(), + published_for::(), published_for::(), published_for::(), published_for::(), diff --git a/crates/weksa/src/store.rs b/crates/weksa/src/store.rs index 16b7ccd..9183f2f 100644 --- a/crates/weksa/src/store.rs +++ b/crates/weksa/src/store.rs @@ -19,7 +19,11 @@ use crate::form::{ use crate::inventory::{ Change, InvId, Inventory, InventoryEntry, InventoryRevision, Slot, revision_key, }; -use crate::packet::{EntityId, Packet}; +use crate::ontology::{ + MAX_CONDITIONS, MAX_CHOICE_BYTES, MAX_ENTRIES_PER_LANGUAGE, MAX_EXAMPLE_BYTES, MAX_EXAMPLES, + Ontology, OntologyEntry, Test, +}; +use crate::packet::{EntityId, FeatValue, Packet}; use crate::speaker::{Annotator, MAX_PARTICIPANTS, Party, Scene, Speaker, scene_key, speaker_key}; use crate::validate::{LoweringInput, Refusal, feature_refusals, validate}; @@ -1207,3 +1211,131 @@ fn check_next(key: &str, latest: u32, got: u32) -> Result<(), StoreError> { } Ok(()) } + +/// The language ontology: immutable entries admitted in all-or-nothing +/// batches. The only writer of `weksa.ontology_entry`. +pub struct OntologyStore { + cache: CultCache, +} + +impl OntologyStore { + pub fn open(path: &Path) -> anyhow::Result { + Ok(Self { + cache: open_cache(path, |c| c.register_entry_type::())?, + }) + } + + /// Every entry, by language then number. + pub fn all(&self) -> anyhow::Result> { + Ok(self.ontology()?.entries().to_vec()) + } + + pub fn ontology(&self) -> anyhow::Result { + Ok(Ontology::of(self.cache.get_all::()?)) + } + + /// Admits a batch whole or not at all; an identical replay of stored + /// entries is `Unchanged`. Per language the batch's numbers run the + /// language's latest plus one, consecutively, to at most + /// `MAX_ENTRIES_PER_LANGUAGE` entries in all. Every entry passes + /// [`check_ontology_entry`] against the inventory before any is put. No + /// message echoes an entry's text. + pub fn admit( + &mut self, + batch: Vec, + inventory: &InventoryStore, + ) -> Result { + let all = self.cache.get_all::()?; + if batch + .iter() + .all(|e| all.iter().any(|old| old == e)) + { + return Ok(AddOutcome::Unchanged); + } + let inv = inventory.inventory()?; + let mut counted: std::collections::BTreeMap<&str, u32> = std::collections::BTreeMap::new(); + for e in &batch { + let key = e.key(); + if !is_language_tag(&e.language) { + return Err(malformed(&key, "an ontology language is a language tag")); + } + let latest = match counted.get(e.language.as_str()) { + Some(n) => *n, + None => all + .iter() + .filter(|o| o.language == e.language) + .map(|o| o.n) + .max() + .unwrap_or(0), + }; + check_next(&key, latest, e.n)?; + if e.n as usize > MAX_ENTRIES_PER_LANGUAGE { + return Err(malformed(&key, "a language holds at most 64 entries")); + } + counted.insert(e.language.as_str(), e.n); + check_ontology_entry(e, &inv)?; + } + let mut staged = Vec::new(); + for e in &batch { + staged.push(self.cache.prepare_entry_named(e.key(), e)?.0); + } + self.cache.put_prepared_batch(staged)?; + Ok(AddOutcome::Added) + } +} + +/// The rules of one ontology entry against an inventory: the annotator, the +/// bounded and normalized text of the choice and examples, the condition count +/// and each condition's feature (slot `Stance` or `Discourse`, a grade feature +/// for `AtLeast` and `AtMost`, an option or flag value for `Is`) read at the +/// entry's inventory revision. The store applies it on admission and a run +/// applies it again against its own head inventory. +pub(crate) fn check_ontology_entry( + e: &OntologyEntry, + inventory: &Inventory, +) -> Result<(), StoreError> { + let key = e.key(); + check_annotator(&key, &e.annotator)?; + let text_ok = |t: &str, max: usize| { + (1..=max).contains(&t.len()) && !t.chars().any(char::is_control) && is_nfc(t) + }; + if !text_ok(&e.choice, MAX_CHOICE_BYTES) { + return Err(malformed( + &key, + "a choice is 1 to 200 normalized bytes with no control character", + )); + } + if e.examples.len() > MAX_EXAMPLES + || !e.examples.iter().all(|x| text_ok(x, MAX_EXAMPLE_BYTES)) + { + return Err(malformed( + &key, + "an entry has at most 3 examples of 1 to 120 normalized bytes with no control character", + )); + } + if e.when.len() > MAX_CONDITIONS { + return Err(malformed(&key, "an entry has at most 4 conditions")); + } + let mut out = Vec::new(); + for c in &e.when { + if !matches!(c.slot, Slot::Stance | Slot::Discourse) { + return Err(malformed(&key, "a condition reads slot Stance or Discourse")); + } + if matches!(c.test, Test::Is(FeatValue::Grade(_))) { + return Err(malformed(&key, "Is names an option or a flag")); + } + out.extend(feature_refusals( + inventory, + e.inventory_rev, + &[c.as_value()], + c.slot, + )); + } + if e.when.is_empty() && !inventory.has_revision(e.inventory_rev) { + out.extend(feature_refusals(inventory, e.inventory_rev, &[], Slot::Stance)); + } + if !out.is_empty() { + return Err(StoreError::Invalid(out)); + } + Ok(()) +} diff --git a/crates/weksa/tests/cli.rs b/crates/weksa/tests/cli.rs index 5f75500..605d6a7 100644 --- a/crates/weksa/tests/cli.rs +++ b/crates/weksa/tests/cli.rs @@ -12,6 +12,8 @@ fn weksa(dir: &std::path::Path, args: &[&str]) -> Output { "./i.cc", "--entities", "./e.cc", + "--ontology", + "./o.cc", ]) .args(args) .output() @@ -316,6 +318,7 @@ fn schema_writes_the_published_files() { "weksa.loop_decision.schema.json", "weksa.loop_round.schema.json", "weksa.loop_run.schema.json", + "weksa.ontology_entry.schema.json", "weksa.scene.schema.json", "weksa.speaker.schema.json" ] @@ -1337,6 +1340,7 @@ fn dao_stores(dir: &std::path::Path) { ] { std::fs::copy(src.join(from), dir.join(to)).unwrap(); } + std::fs::write(dir.join("o.cc"), [0x90]).unwrap(); } #[test] diff --git a/crates/weksa/tests/common/mod.rs b/crates/weksa/tests/common/mod.rs index b7b7c7e..8350428 100644 --- a/crates/weksa/tests/common/mod.rs +++ b/crates/weksa/tests/common/mod.rs @@ -114,6 +114,15 @@ pub fn entities_in(dir: &std::path::Path) -> EntityStore { store } +/// An empty ontology store at `/ontology.cc`, made if absent. +pub fn ontology_in(dir: &std::path::Path) -> std::path::PathBuf { + let path = dir.join("ontology.cc"); + if !path.exists() { + std::fs::write(&path, [0x90]).unwrap(); + } + path +} + /// A run over the stores `world()` and `corpus()` keep in `dir`: `c.cc`, /// `i.cc` and `entities.cc`. Read at the call, so create it after the items. /// The run's en-US panel needs a live Train and a live Validation item: a @@ -125,6 +134,7 @@ pub fn run_over(dir: &std::path::Path) -> weksa::run::RunStores { } } let entities = entities_in(dir); + ontology_in(dir); let mut corpus = CorpusStore::open(&dir.join("c.cc")).unwrap(); for (n, split) in [(1, weksa::Split::Train), (2, weksa::Split::Validation)] { let held = corpus @@ -147,6 +157,7 @@ pub fn run_over(dir: &std::path::Path) -> weksa::run::RunStores { corpus: &dir.join("c.cc"), inventory: &dir.join("i.cc"), entities: &dir.join("entities.cc"), + ontology: &dir.join("ontology.cc"), }, "fake-model", "bag", @@ -230,6 +241,7 @@ pub fn world() -> World { let dir = tempfile::tempdir().unwrap(); let mut corpus = CorpusStore::open(&dir.path().join("c.cc")).unwrap(); let entities = entities_in(dir.path()); + ontology_in(dir.path()); let train = group_in_bucket(10); let mut first = item_in("item:nibu:1", "Nibu says mind the hatch.", &train, cast()); first.names = vec![NameSpan { diff --git a/crates/weksa/tests/context.rs b/crates/weksa/tests/context.rs index 0103149..61e86f7 100644 --- a/crates/weksa/tests/context.rs +++ b/crates/weksa/tests/context.rs @@ -602,7 +602,7 @@ mod lowering { fn lower_prompt_names_its_language() { let (view, inv, entities, item) = dao(2); for tag in ["en-US", "ja-JP", "pt-BR"] { - let prompt = Prompt::lower(&view, &item, tag, &inv, &entities).unwrap(); + let prompt = Prompt::lower(&view, &item, tag, &inv, &entities, &weksa::Ontology::empty()).unwrap(); let want = format!("{LOWER}\n\nlanguage: {tag}\n\npacket: "); assert!(prompt.text().starts_with(&want), "{tag}"); } @@ -614,10 +614,10 @@ mod lowering { #[test] fn lower_prompt_text_is_pinned() { let (view, inv, entities, item) = dao(2); - let prompt = Prompt::lower(&view, &item, "en-US", &inv, &entities).unwrap(); + let prompt = Prompt::lower(&view, &item, "en-US", &inv, &entities, &weksa::Ontology::empty()).unwrap(); let (head, listing) = prompt.text().split_once("inventory rev:3\n").unwrap(); let expected = format!( - "{LOWER}\n\nlanguage: en-US\n\npacket: {}\n\nentities: {{}}\n\n", + "{LOWER}\n\nlanguage: en-US\n\npacket: {}\n\nentities: {{}}\n\nontology: none\n\n", concat!( r#"{"context":{"setting":null,"medium":null,"participants":[],"audience":[]},"#, r#""discourse":{"speech_act":"speech_act:1","addressee":null,"addressee_consent":null,"features":[]},"#, @@ -676,7 +676,7 @@ mod lowering { let mut packet = packets().remove(2); packet.stance = stance.clone(); let view = admitted(packet, &store, "daodejing/corpus.cc", &entities); - let prompt = Prompt::lower(&view, &item, "en-US", &inv, &entities).unwrap(); + let prompt = Prompt::lower(&view, &item, "en-US", &inv, &entities, &weksa::Ontology::empty()).unwrap(); (stance, prompt) }; let three = [prompt_of(own), prompt_of(angry), prompt_of(Stance::default())]; @@ -713,7 +713,7 @@ mod lowering { ("sa-Latn", &["Nibuwa"]), ("en-US", &["Nibu", "Nibu's"]), ])]); - let prompt = Prompt::lower(&view, &item, "en-US", &cast.inventory().unwrap(), &held).unwrap(); + let prompt = Prompt::lower(&view, &item, "en-US", &cast.inventory().unwrap(), &held, &weksa::Ontology::empty()).unwrap(); assert!( prompt .text() @@ -743,7 +743,7 @@ mod lowering { ), (Held(vec![]), LowerError::UnknownEntity { entity: id }), ] { - assert_eq!(Prompt::lower(&view, &item, "en-US", &inv, &held).err(), Some(want)); + assert_eq!(Prompt::lower(&view, &item, "en-US", &inv, &held, &weksa::Ontology::empty()).err(), Some(want)); } } } diff --git a/crates/weksa/tests/golf_loop.rs b/crates/weksa/tests/golf_loop.rs index 73f1df2..38ae231 100644 --- a/crates/weksa/tests/golf_loop.rs +++ b/crates/weksa/tests/golf_loop.rs @@ -24,8 +24,13 @@ fn rewrite_run(root: &Path, change: impl FnOnce(&mut RunRecord)) { cache.put(format!("run:{}", record.label), &record).unwrap(); } -fn paths(dir: &Path) -> (PathBuf, PathBuf, PathBuf) { - (dir.join("c.cc"), dir.join("i.cc"), dir.join("entities.cc")) +fn paths(dir: &Path) -> (PathBuf, PathBuf, PathBuf, PathBuf) { + ( + dir.join("c.cc"), + dir.join("i.cc"), + dir.join("entities.cc"), + common::ontology_in(dir), + ) } fn hex(path: &Path) -> String { @@ -37,7 +42,7 @@ fn a_run_pins_its_stores_and_refuses_drift() { let mut w = world(); let dir = w.dir.path().to_path_buf(); let root = dir.join("run"); - let (c, i, e) = paths(&dir); + let (c, i, e, o) = paths(&dir); let at = |label: &str, model: &str| { RunStores::create( &root, @@ -46,6 +51,7 @@ fn a_run_pins_its_stores_and_refuses_drift() { corpus: &c, inventory: &i, entities: &e, + ontology: &o, }, model, "bag", @@ -141,7 +147,7 @@ fn a_run_works_on_its_own_copy_of_the_inventory() { let w = world(); let dir = w.dir.path().to_path_buf(); let root = dir.join("run"); - let (c, i, e) = paths(&dir); + let (c, i, e, o) = paths(&dir); let source_bytes = std::fs::read(&i).unwrap(); let mut run = RunStores::create( &root, @@ -150,6 +156,7 @@ fn a_run_works_on_its_own_copy_of_the_inventory() { corpus: &c, inventory: &i, entities: &e, + ontology: &o, }, "fake-model", "bag", @@ -228,6 +235,7 @@ fn create_refuses_a_root_that_holds_an_inventory_and_never_truncates_it() { corpus: &dao.corpus, inventory, entities: &dao.entities, + ontology: &dao.ontology, }, "fake-model", "bag", @@ -276,6 +284,7 @@ fn a_create_that_fails_leaves_no_inventory_and_the_retry_succeeds() { corpus: &dao.corpus, inventory, entities, + ontology: &dao.ontology, }, "fake-model", "bag", @@ -388,10 +397,12 @@ fn a_store_changed_between_its_digest_and_its_open_is_drift() { assert!(dir.join(name).exists(), "{name}"); } let (c, i, e) = (dir.join("c.cc"), dir.join("i.cc"), dir.join("entities.cc")); + let o = dir.join("ontology.cc"); let paths = || weksa::run::RunPaths { corpus: &c, inventory: &i, entities: &e, + ontology: &o, }; assert_eq!( RunStores::create_between( @@ -440,10 +451,12 @@ fn window( let dir = w.dir.path().to_path_buf(); let root = dir.join("run"); let (c, i, e) = (dir.join("c.cc"), dir.join("i.cc"), dir.join("entities.cc")); + let o = dir.join("ontology.cc"); let paths = weksa::run::RunPaths { corpus: &c, inventory: &i, entities: &e, + ontology: &o, }; let created = RunStores::create_between( &root, @@ -501,12 +514,13 @@ fn source_digests_cover_their_files() { let digest = |name: &str| fnv1a64(&read(name)); // The prompt's partition and names come from split.rs, and the lowering // prompt reads lower.rs's target language and entity port and prints - // packet.rs's serde shapes: all four are covered. - let (context, split, lower, packet) = ( + // packet.rs's serde shapes and ontology.rs's selection: all five are covered. + let (context, split, lower, packet, ontology) = ( read("context.rs"), read("split.rs"), read("lower.rs"), read("packet.rs"), + read("ontology.rs"), ); // Each file enters behind its length, so the parts have one framing. let framed = [ @@ -518,12 +532,14 @@ fn source_digests_cover_their_files() { &lower, (packet.len() as u64).to_le_bytes().as_slice(), &packet, + (ontology.len() as u64).to_le_bytes().as_slice(), + &ontology, ] .concat(); assert_eq!(weksa::run::PROMPT_SOURCE_DIGEST, fnv1a64(&framed)); assert_ne!( weksa::run::PROMPT_SOURCE_DIGEST, - fnv1a64(&[context.clone(), split.clone(), lower.clone(), packet.clone()].concat()), + fnv1a64(&[context.clone(), split.clone(), lower.clone(), packet.clone(), ontology.clone()].concat()), "bare concatenation is not the digest" ); // Moving the boundary between the parts moves the digest. @@ -532,6 +548,7 @@ fn source_digests_cover_their_files() { weksa::split::fnv1a64_of(&[b"a", b"bc"]) ); assert_ne!(weksa::run::PROMPT_SOURCE_DIGEST, digest("context.rs")); + assert_ne!(weksa::run::PROMPT_SOURCE_DIGEST, digest("ontology.rs")); } /// The encode prompt of `item:nibu:1` over `world()` at revision 4. @@ -837,6 +854,7 @@ struct Dao { corpus: PathBuf, inventory: PathBuf, entities: PathBuf, + ontology: PathBuf, run: RunStores, } @@ -866,6 +884,7 @@ fn dao_panel(edit: impl FnOnce(&Path, &Path), panel: &[&str]) -> Dao { copy("entity.cc", "e.cc"), ); edit(&corpus, &entities); + let ontology = common::ontology_in(dir.path()); let root = dir.path().join("run"); let run = RunStores::create( &root, @@ -874,6 +893,7 @@ fn dao_panel(edit: impl FnOnce(&Path, &Path), panel: &[&str]) -> Dao { corpus: &corpus, inventory: &inventory, entities: &entities, + ontology: &ontology, }, "fake-model", "bag", @@ -888,6 +908,7 @@ fn dao_panel(edit: impl FnOnce(&Path, &Path), panel: &[&str]) -> Dao { corpus, inventory, entities, + ontology, run, } } @@ -1055,7 +1076,7 @@ fn lowering_prompts(dao: &Dao, inventory: &InventoryStore) -> Vec<(String, Promp let view = store .admit(packet, inventory, &corpus, dao.run.entities()) .unwrap(); - let prompt = Prompt::lower(&view, &key, "en-US", &inv, dao.run.entities()).unwrap(); + let prompt = Prompt::lower(&view, &key, "en-US", &inv, dao.run.entities(), &weksa::Ontology::empty()).unwrap(); (key.to_string(), prompt) }) .collect() @@ -1527,6 +1548,7 @@ fn errors_echo_no_input() { corpus: &missing, inventory: &missing, entities: &missing, + ontology: &missing, }; let e = RunStores::create( &root, @@ -1595,6 +1617,7 @@ fn errors_echo_no_input() { corpus: &dao.corpus, inventory: &dao.inventory, entities: &dao.entities, + ontology: &dao.ontology, }, "fake-model", "bag", @@ -2516,6 +2539,7 @@ fn a_changed_head_is_drift() { corpus: &dao.corpus, inventory: &dao.inventory, entities: &dao.entities, + ontology: &dao.ontology, }, "fake-model", "bag", @@ -2854,6 +2878,7 @@ fn a_summary_line_says_how_lowerings_were_answered() { corpus: &dao.corpus, inventory: &dao.inventory, entities: &dao.entities, + ontology: &dao.ontology, }; RunStores::create( &root, @@ -3577,6 +3602,7 @@ fn mixed_family_round(family: ModelFamily) -> u32 { corpus: &dir.join("c.cc"), inventory: &dir.join("i.cc"), entities: &dir.join("entities.cc"), + ontology: &dir.join("ontology.cc"), }, "not-a-draft", "bag", @@ -4363,7 +4389,7 @@ fn open_refuses_a_bad_panel() { let created = RunStores::create( &root, "p", - RunPaths { corpus, inventory, entities }, + RunPaths { corpus, inventory, entities, ontology: &dao.ontology }, "fake-model", "bag", weksa::run::LowererReach::ToolLessRelay, diff --git a/crates/weksa/tests/original_corpus.rs b/crates/weksa/tests/original_corpus.rs index 9213939..2194a28 100644 --- a/crates/weksa/tests/original_corpus.rs +++ b/crates/weksa/tests/original_corpus.rs @@ -274,6 +274,8 @@ fn the_recall_probe_covers_every_live_original_item_and_names_no_work() { tmp.path().join(f) }; let (c, i, e) = (path("corpus.cc"), path("inventory.cc"), path("entity.cc")); + let o = tmp.path().join("ontology.cc"); + std::fs::write(&o, [0x90]).unwrap(); let run = RunStores::create( &tmp.path().join("run"), "orig", @@ -281,6 +283,7 @@ fn the_recall_probe_covers_every_live_original_item_and_names_no_work() { corpus: &c, inventory: &i, entities: &e, + ontology: &o, }, "m", "bag", @@ -350,6 +353,7 @@ fn original_round(family: ModelFamily) -> (weksa::run::RunStores, weksa::run::Ro for f in ["corpus.cc", "entity.cc", "inventory.cc"] { std::fs::copy(src.join(f), tmp.join(f)).unwrap(); } + std::fs::write(tmp.join("ontology.cc"), [0x90]).unwrap(); let mut run = RunStores::create( &tmp.join("run"), "orig", @@ -357,6 +361,7 @@ fn original_round(family: ModelFamily) -> (weksa::run::RunStores, weksa::run::Ro corpus: &tmp.join("corpus.cc"), inventory: &tmp.join("inventory.cc"), entities: &tmp.join("entity.cc"), + ontology: &tmp.join("ontology.cc"), }, "nope", "bag", @@ -506,6 +511,7 @@ fn no_test_item_is_offered_to_a_round_or_recall_or_recorded() { for f in ["corpus.cc", "entity.cc", "inventory.cc"] { std::fs::copy(src.join(f), tmp.path().join(f)).unwrap(); } + std::fs::write(tmp.path().join("ontology.cc"), [0x90]).unwrap(); let p = |f: &str| tmp.path().join(f); let mut run = RunStores::create( &p("run"), @@ -514,6 +520,7 @@ fn no_test_item_is_offered_to_a_round_or_recall_or_recorded() { corpus: &p("corpus.cc"), inventory: &p("inventory.cc"), entities: &p("entity.cc"), + ontology: &p("ontology.cc"), }, "nope", "bag", diff --git a/schemas/cultnet/weksa.loop_run.schema.json b/schemas/cultnet/weksa.loop_run.schema.json index bb63827..e5b144b 100644 --- a/schemas/cultnet/weksa.loop_run.schema.json +++ b/schemas/cultnet/weksa.loop_run.schema.json @@ -49,6 +49,14 @@ "description": "The answering model.", "type": "string" }, + "ontology": { + "description": "Canonical absolute path of the ontology store: read-only for the run,\npinned by `ontology_digest`.", + "type": "string" + }, + "ontology_digest": { + "description": "16 hex of the ontology file's bytes.", + "type": "string" + }, "panel": { "description": "The languages the run offers, reads and decides on: BCP 47-form tags,\nsorted, unique, at least one, set once at open. An item of any other\nlanguage is never offered, minted from, probed or scored.", "type": "array", @@ -73,7 +81,9 @@ "chrf_version", "inventory_digest", "lowerer_reach", - "panel" + "panel", + "ontology", + "ontology_digest" ], "$defs": { "LowererReach": { diff --git a/schemas/cultnet/weksa.ontology_entry.schema.json b/schemas/cultnet/weksa.ontology_entry.schema.json new file mode 100644 index 0000000..99ba82d --- /dev/null +++ b/schemas/cultnet/weksa.ontology_entry.schema.json @@ -0,0 +1,264 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "title": "OntologyEntry", + "description": "One choice of one language. Key `onto::`.", + "type": "object", + "properties": { + "annotator": { + "$ref": "#/$defs/Annotator" + }, + "choice": { + "type": "string" + }, + "examples": { + "type": "array", + "items": { + "type": "string" + } + }, + "inventory_rev": { + "description": "The inventory revision the conditions read against.", + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "language": { + "type": "string" + }, + "layer": { + "$ref": "#/$defs/Layer" + }, + "n": { + "description": "The entry's number within its language, from 1.", + "type": "integer", + "format": "uint32", + "minimum": 0 + }, + "when": { + "description": "Every condition must hold; none means the entry always applies.", + "type": "array", + "items": { + "$ref": "#/$defs/Condition" + } + } + }, + "required": [ + "language", + "n", + "inventory_rev", + "layer", + "when", + "choice", + "examples", + "annotator" + ], + "$defs": { + "Annotator": { + "description": "Who annotated a document. A model's generator is an attestation string, held\nto the same form as every provenance string.", + "oneOf": [ + { + "type": "string", + "enum": [ + "Operator" + ] + }, + { + "type": "object", + "properties": { + "Model": { + "type": "object", + "properties": { + "family": { + "$ref": "#/$defs/ModelFamily" + }, + "generator": { + "type": "string" + } + }, + "required": [ + "family", + "generator" + ] + } + }, + "additionalProperties": false, + "required": [ + "Model" + ] + } + ] + }, + "Condition": { + "description": "One feature of one slot of the view, tested. Only `Stance` and `Discourse`\nreach a lowering view today.", + "type": "object", + "properties": { + "feature": { + "$ref": "#/$defs/InvId" + }, + "slot": { + "$ref": "#/$defs/Slot" + }, + "test": { + "$ref": "#/$defs/Test" + } + }, + "required": [ + "slot", + "feature", + "test" + ] + }, + "FeatValue": { + "oneOf": [ + { + "type": "object", + "properties": { + "Grade": { + "$ref": "#/$defs/Grade" + } + }, + "additionalProperties": false, + "required": [ + "Grade" + ] + }, + { + "description": "A label the feature's inventory entry declares.", + "type": "object", + "properties": { + "Option": { + "$ref": "#/$defs/OptionLabel" + } + }, + "additionalProperties": false, + "required": [ + "Option" + ] + }, + { + "type": "object", + "properties": { + "Flag": { + "type": "boolean" + } + }, + "additionalProperties": false, + "required": [ + "Flag" + ] + } + ] + }, + "Grade": { + "type": "integer", + "maximum": 1000, + "minimum": 0 + }, + "InvId": { + "type": "string", + "pattern": "^(concept|frame|role|relation|speech_act|feature|referent_kind|extension):[1-9][0-9]*$" + }, + "Layer": { + "description": "Which part of the language an entry shapes.", + "type": "string", + "enum": [ + "Lexicon", + "Grammar", + "Discourse", + "Phonology", + "Orthography" + ] + }, + "ModelFamily": { + "description": "The family of the model that wrote a line.", + "oneOf": [ + { + "type": "string", + "enum": [ + "Anthropic", + "OpenAi", + "Google", + "Alibaba", + "Meta", + "Mistral" + ] + }, + { + "description": "Nothing records which family wrote the line.", + "type": "string", + "const": "Unrecorded" + } + ] + }, + "OptionLabel": { + "type": "string", + "pattern": "^[a-z][a-z0-9_]{0,23}$" + }, + "Slot": { + "description": "Where a feature may sit in a packet.", + "oneOf": [ + { + "type": "string", + "enum": [ + "Discourse", + "Referent", + "Predication", + "Relation", + "Stance" + ] + }, + { + "description": "The speaker's relation to one party of the scene, held by `weksa.scene`\ndocuments; see `LoweringInput::with_scene`.", + "type": "string", + "const": "Scene" + }, + { + "description": "The speaker's stable axes, held by `weksa.speaker` documents.", + "type": "string", + "const": "Speaker" + } + ] + }, + "Test": { + "description": "What a feature's value must be for a condition to hold.", + "oneOf": [ + { + "type": "object", + "properties": { + "AtLeast": { + "$ref": "#/$defs/Grade" + } + }, + "additionalProperties": false, + "required": [ + "AtLeast" + ] + }, + { + "type": "object", + "properties": { + "AtMost": { + "$ref": "#/$defs/Grade" + } + }, + "additionalProperties": false, + "required": [ + "AtMost" + ] + }, + { + "type": "object", + "properties": { + "Is": { + "$ref": "#/$defs/FeatValue" + } + }, + "additionalProperties": false, + "required": [ + "Is" + ] + } + ] + } + } +}