Ontology fix pass s1: refuse format and separator characters, canonical-case language, entries on retired features; kill six surviving mutants; two-language round test
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
cd435e2a48
commit
602f7c2cd5
8 changed files with 169 additions and 28 deletions
|
|
@ -107,6 +107,25 @@ pub(crate) fn is_language_tag(s: &str) -> bool {
|
|||
.all(|t| (1..=8).contains(&t.len()) && t.bytes().all(|b| b.is_ascii_alphanumeric()))
|
||||
}
|
||||
|
||||
/// A language tag in its canonical case: lowercase language, two-letter region
|
||||
/// in capitals, four-letter script in title case, any other subtag lowercase.
|
||||
/// An ontology is selected by exact tag, so a case variant would be a dead
|
||||
/// language.
|
||||
pub(crate) fn is_canonical_language_tag(s: &str) -> bool {
|
||||
is_language_tag(s)
|
||||
&& s.split('-').enumerate().all(|(i, t)| {
|
||||
let upper = |c: char| c.is_ascii_uppercase();
|
||||
match (i, t.len()) {
|
||||
(0, _) => !t.chars().any(upper),
|
||||
(_, 2) if t.bytes().all(|b| b.is_ascii_alphabetic()) => t.chars().all(upper),
|
||||
(_, 4) if t.bytes().all(|b| b.is_ascii_alphabetic()) => {
|
||||
t.chars().next().is_some_and(upper) && !t.chars().skip(1).any(upper)
|
||||
}
|
||||
_ => !t.chars().any(upper),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// A slug: `[a-z0-9]` and inner `-`, 1 to 48 bytes, no edge `-`.
|
||||
pub(crate) fn is_slug(s: &str) -> bool {
|
||||
let b = s.as_bytes();
|
||||
|
|
|
|||
|
|
@ -86,6 +86,11 @@ impl Condition {
|
|||
}
|
||||
|
||||
/// One choice of one language. Key `onto:<language>:<n>`.
|
||||
///
|
||||
/// The store judges the form of an entry's text (bounds, normalization, no
|
||||
/// control or format character) and never its meaning: what may enter an entry
|
||||
/// is owned by the minting flow (Train-only assembly) and the scorer's leak
|
||||
/// diagnostic (ruling `leak-owned-by-flow-and-scorer-3`), not by a door here.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, JsonSchema, DatabaseEntry)]
|
||||
#[cultcache(type = "weksa.ontology_entry")]
|
||||
pub struct OntologyEntry {
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ use crate::corpus::{CorpusItem, CorpusItemId, ModelFamily, Source};
|
|||
use crate::encode::{EditDraft, LoweringDraft, PacketDraft, encoder_id};
|
||||
use crate::form::{is_attestation, is_slug};
|
||||
use crate::model::{ModelPort, PortError};
|
||||
use crate::ontology::OntologyEntry;
|
||||
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};
|
||||
|
|
@ -782,10 +783,21 @@ impl RunStores {
|
|||
fn check_ontology(&self) -> Result<(), RunError> {
|
||||
let inventory = self.inventory.inventory().map_err(|_| RunError::Store)?;
|
||||
let entries = self.ontology.all().map_err(|_| RunError::Store)?;
|
||||
let head = inventory.latest().map(|r| r.n);
|
||||
entries
|
||||
.iter()
|
||||
.filter(|e| self.record.panel.contains(&e.language))
|
||||
.try_for_each(|e| check_ontology_entry(e, &inventory).map_err(|_| RunError::Ontology))
|
||||
.try_for_each(|e| {
|
||||
// At its own revision, and again at the head: an entry on a
|
||||
// feature the head retired could never select.
|
||||
let at_head = OntologyEntry {
|
||||
inventory_rev: head.ok_or(RunError::Ontology)?,
|
||||
..e.clone()
|
||||
};
|
||||
check_ontology_entry(e, &inventory)
|
||||
.and_then(|()| check_ontology_entry(&at_head, &inventory))
|
||||
.map_err(|_| RunError::Ontology)
|
||||
})
|
||||
}
|
||||
|
||||
/// Every panel language holds a live Train and a live Validation item.
|
||||
|
|
|
|||
|
|
@ -14,7 +14,8 @@ use unicode_segmentation::UnicodeSegmentation;
|
|||
use crate::corpus::{CorpusItem, CorpusItemId, Source, item_key, key_slug};
|
||||
use crate::entity::{Entity, EntityOrigin, Pronunciation};
|
||||
use crate::form::{
|
||||
is_attestation, is_calendar_date, is_joining_only, is_language_tag, is_refused_format, is_slug,
|
||||
is_attestation, is_calendar_date, is_canonical_language_tag, is_joining_only, is_language_tag,
|
||||
is_refused_format, is_slug,
|
||||
};
|
||||
use crate::inventory::{
|
||||
Change, InvId, Inventory, InventoryEntry, InventoryRevision, Slot, revision_key,
|
||||
|
|
@ -1256,8 +1257,11 @@ impl OntologyStore {
|
|||
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"));
|
||||
if !is_canonical_language_tag(&e.language) {
|
||||
return Err(malformed(
|
||||
&key,
|
||||
"an ontology language is a language tag in canonical case",
|
||||
));
|
||||
}
|
||||
let latest = match counted.get(e.language.as_str()) {
|
||||
Some(n) => *n,
|
||||
|
|
@ -1297,12 +1301,14 @@ pub(crate) fn check_ontology_entry(
|
|||
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)
|
||||
(1..=max).contains(&t.len())
|
||||
&& !t.chars().any(|c| c.is_control() || is_refused_format(c))
|
||||
&& 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",
|
||||
"a choice is 1 to 200 normalized bytes with no control or format character",
|
||||
));
|
||||
}
|
||||
if e.examples.len() > MAX_EXAMPLES
|
||||
|
|
@ -1310,7 +1316,7 @@ pub(crate) fn check_ontology_entry(
|
|||
{
|
||||
return Err(malformed(
|
||||
&key,
|
||||
"an entry has at most 3 examples of 1 to 120 normalized bytes with no control character",
|
||||
"an entry has at most 3 examples of 1 to 120 normalized bytes with no control or format character",
|
||||
));
|
||||
}
|
||||
if e.when.len() > MAX_CONDITIONS {
|
||||
|
|
|
|||
|
|
@ -847,6 +847,11 @@ mod lowering {
|
|||
assert_eq!(keys(&both, "en-US"), ["onto:en-US:1"]);
|
||||
let low = view_of(Some(200), Some(false), &cast, &entities);
|
||||
assert_eq!(keys(&low, "ja-JP"), ["onto:ja-JP:2", "onto:ja-JP:4"]);
|
||||
// A grade equal to the bound meets AtLeast and AtMost alike.
|
||||
let edge = view_of(Some(600), None, &cast, &entities);
|
||||
assert_eq!(keys(&edge, "ja-JP"), ["onto:ja-JP:1", "onto:ja-JP:4"]);
|
||||
let edge = view_of(Some(300), None, &cast, &entities);
|
||||
assert_eq!(keys(&edge, "ja-JP"), ["onto:ja-JP:2", "onto:ja-JP:4"]);
|
||||
// An absent feature meets no condition, however lax.
|
||||
let bare = view_of(None, None, &cast, &entities);
|
||||
assert_eq!(keys(&bare, "ja-JP"), ["onto:ja-JP:4"]);
|
||||
|
|
|
|||
|
|
@ -4596,8 +4596,9 @@ fn ablation_reads_each_language_apart() {
|
|||
);
|
||||
}
|
||||
|
||||
/// An en-US Dao ontology: entry 1 for a stance with affection, entry 2 for one
|
||||
/// with almost no restraint (which no Dao packet has).
|
||||
/// A Dao ontology for en-US and ja-JP: entry 1 of each for a stance with
|
||||
/// affection, and a ja-JP entry 2 for almost no restraint (which no Dao packet
|
||||
/// has).
|
||||
fn dao_ontology(path: &Path, inventory: &Path) {
|
||||
use weksa::packet::Grade;
|
||||
use weksa::{Condition, Layer, OntologyEntry, OntologyStore, Slot, Test};
|
||||
|
|
@ -4610,8 +4611,8 @@ fn dao_ontology(path: &Path, inventory: &Path) {
|
|||
.unwrap()
|
||||
.id
|
||||
};
|
||||
let entry = |n, gloss: &str, test, choice: &str| OntologyEntry {
|
||||
language: "en-US".into(),
|
||||
let entry = |language: &str, n, gloss: &str, test, choice: &str| OntologyEntry {
|
||||
language: language.into(),
|
||||
n,
|
||||
inventory_rev: 1,
|
||||
layer: Layer::Discourse,
|
||||
|
|
@ -4624,14 +4625,22 @@ fn dao_ontology(path: &Path, inventory: &Path) {
|
|||
examples: vec![],
|
||||
annotator: weksa::Annotator::Operator,
|
||||
};
|
||||
let affection = || Test::AtLeast(Grade::new(200).unwrap());
|
||||
OntologyStore::open(path)
|
||||
.unwrap()
|
||||
.admit(
|
||||
vec![
|
||||
entry(1, "affection", Test::AtLeast(Grade::new(200).unwrap()), "warm"),
|
||||
entry(2, "restraint", Test::AtMost(Grade::new(100).unwrap()), "blunt"),
|
||||
entry("en-US", 1, "affection", affection(), "ENWARM"),
|
||||
entry("ja-JP", 1, "affection", affection(), "JAWARM"),
|
||||
entry(
|
||||
"ja-JP",
|
||||
2,
|
||||
"restraint",
|
||||
Test::AtMost(Grade::new(100).unwrap()),
|
||||
"JABLUNT",
|
||||
),
|
||||
],
|
||||
&inv_store(inventory),
|
||||
&inv,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
|
@ -4653,7 +4662,7 @@ fn a_run_pins_its_ontology_and_refuses_drift() {
|
|||
let mut store = weksa::OntologyStore::open(&dao.ontology).unwrap();
|
||||
store
|
||||
.admit(
|
||||
vec![weksa::OntologyEntry { n: 3, ..entry }],
|
||||
vec![weksa::OntologyEntry { n: 2, ..entry }],
|
||||
&inv_store(&dao.inventory),
|
||||
)
|
||||
.unwrap();
|
||||
|
|
@ -4671,7 +4680,7 @@ fn create_refuses_an_entry_its_inventory_cannot_read() {
|
|||
// another file where that feature is retired or absent, so the entry is
|
||||
// admitted against a richer inventory and refused against the run's.
|
||||
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../data/daodejing");
|
||||
let make = |language: &str, dir: &Path| {
|
||||
let make = |language: &str, dir: &Path, retire: bool| {
|
||||
for (from, to) in [("corpus.cc", "c.cc"), ("inventory.cc", "i.cc"), ("entity.cc", "e.cc")] {
|
||||
std::fs::copy(src.join(from), dir.join(to)).unwrap();
|
||||
}
|
||||
|
|
@ -4726,6 +4735,21 @@ fn create_refuses_an_entry_its_inventory_cannot_read() {
|
|||
&store,
|
||||
)
|
||||
.unwrap();
|
||||
if retire {
|
||||
// The run's head inventory retires the feature after the entry's revision.
|
||||
store
|
||||
.admit_revision(
|
||||
weksa::InventoryRevision {
|
||||
n: n + 1,
|
||||
parent: Some(n),
|
||||
changes: vec![weksa::Change::Retire(id)],
|
||||
frozen: false,
|
||||
},
|
||||
vec![],
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::copy(&rich, dir.join("i.cc")).unwrap();
|
||||
}
|
||||
ontology
|
||||
};
|
||||
let create = |dir: &Path, ontology: &Path| {
|
||||
|
|
@ -4746,35 +4770,49 @@ fn create_refuses_an_entry_its_inventory_cannot_read() {
|
|||
)
|
||||
};
|
||||
let panel_dir = tempfile::tempdir().unwrap();
|
||||
let o = make("en-US", panel_dir.path());
|
||||
let o = make("en-US", panel_dir.path(), false);
|
||||
assert_eq!(create(panel_dir.path(), &o).err(), Some(RunError::Ontology));
|
||||
assert!(!panel_dir.path().join("run/run.cc").exists());
|
||||
assert!(!panel_dir.path().join("run/inventory.cc").exists());
|
||||
// The same entry under a language outside the panel does not refuse.
|
||||
let other_dir = tempfile::tempdir().unwrap();
|
||||
let o = make("ja-JP", other_dir.path());
|
||||
let o = make("ja-JP", other_dir.path(), false);
|
||||
assert!(create(other_dir.path(), &o).is_ok());
|
||||
// An entry on a feature the head inventory has retired can never select.
|
||||
let retired_dir = tempfile::tempdir().unwrap();
|
||||
let o = make("en-US", retired_dir.path(), true);
|
||||
assert_eq!(create(retired_dir.path(), &o).err(), Some(RunError::Ontology));
|
||||
assert!(!retired_dir.path().join("run/run.cc").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_lowering_prompts_carry_selected_entries() {
|
||||
let mut dao = dao_build(|_, _| {}, &["en-US"], dao_ontology);
|
||||
let mut model = fake(&good_answers());
|
||||
let mut dao = dao_build(
|
||||
|corpus, entities| add_languages(corpus, entities, LAOZI_JA),
|
||||
&["ja-JP", "en-US"],
|
||||
dao_ontology,
|
||||
);
|
||||
let mut model = bilingual_fake();
|
||||
let r = recorded(round(&mut dao.run, &mut model, &Scorer::new(Bag)).unwrap());
|
||||
let mut lowerings = 0;
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
for ((_, text), call) in model.seen.iter().zip(r.calls()) {
|
||||
if !text.starts_with(LOWER_INSTRUCTIONS) {
|
||||
continue;
|
||||
}
|
||||
lowerings += 1;
|
||||
let item = call.items[0].as_str();
|
||||
// Only the third Dao packet carries affection.
|
||||
if item == "item:daodejing:3" {
|
||||
assert!(text.contains("\nonto:en-US:1 [discourse] warm\n"), "{text}");
|
||||
let (language, warm, other) = if text.contains("\n\nlanguage: ja-JP\n\n") {
|
||||
("ja-JP", "JAWARM", "ENWARM")
|
||||
} else {
|
||||
("en-US", "ENWARM", "JAWARM")
|
||||
};
|
||||
// Only the third packet of each language carries affection.
|
||||
if item.ends_with(":3") || item.ends_with(":13") {
|
||||
assert!(text.contains(&format!("\nonto:{language}:1 [discourse] {warm}\n")), "{text}");
|
||||
} else {
|
||||
assert!(text.contains("\n\nontology: none\n\n"), "{item}: {text}");
|
||||
}
|
||||
assert!(!text.contains("onto:en-US:2") && !text.contains("blunt"));
|
||||
assert!(!text.contains(other) && !text.contains("JABLUNT"), "{item}: {text}");
|
||||
seen.insert(item.to_string());
|
||||
}
|
||||
assert_eq!(lowerings, 3);
|
||||
assert_eq!(seen.len(), 6, "three items in each language");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1673,6 +1673,7 @@ mod ontology {
|
|||
}
|
||||
|
||||
#[test]
|
||||
#[allow(clippy::vec_init_then_push)]
|
||||
fn ontology_admit_refuses_each_rule() {
|
||||
let d = dir();
|
||||
let w = world();
|
||||
|
|
@ -1681,6 +1682,40 @@ mod ontology {
|
|||
let mut cases: Vec<(&str, Vec<OntologyEntry>)> = Vec::new();
|
||||
cases.push(("non-tag language", vec![entry("not a tag", 1)]));
|
||||
cases.push(("n not latest+1", vec![entry("ja-JP", 2)]));
|
||||
cases.push(("case-variant language", vec![entry("ja-jp", 1)]));
|
||||
cases.push((
|
||||
"decomposed choice",
|
||||
vec![OntologyEntry { choice: "e\u{301}".into(), ..entry("ja-JP", 1) }],
|
||||
));
|
||||
cases.push((
|
||||
"decomposed example",
|
||||
vec![OntologyEntry { examples: vec!["e\u{301}".into()], ..entry("ja-JP", 1) }],
|
||||
));
|
||||
for sep in ["\u{2028}", "\u{2029}", "\u{202e}", "\u{200b}"] {
|
||||
cases.push((
|
||||
"line separator or format character in a choice",
|
||||
vec![OntologyEntry { choice: format!("a{sep}b"), ..entry("ja-JP", 1) }],
|
||||
));
|
||||
cases.push((
|
||||
"line separator or format character in an example",
|
||||
vec![OntologyEntry { examples: vec![format!("a{sep}b")], ..entry("ja-JP", 1) }],
|
||||
));
|
||||
}
|
||||
cases.push((
|
||||
"unconditioned entry at an unknown revision",
|
||||
vec![OntologyEntry { when: vec![], inventory_rev: 99, ..entry("ja-JP", 1) }],
|
||||
));
|
||||
cases.push((
|
||||
"Predication slot on a feature that sits there",
|
||||
vec![OntologyEntry {
|
||||
when: vec![when(
|
||||
Slot::Predication,
|
||||
"modality",
|
||||
Test::Is(FeatValue::Option(lab("actual"))),
|
||||
)],
|
||||
..entry("ja-JP", 1)
|
||||
}],
|
||||
));
|
||||
cases.push((
|
||||
"65th entry",
|
||||
(1..=65).map(|n| entry("ja-JP", n)).collect(),
|
||||
|
|
@ -1766,6 +1801,23 @@ mod ontology {
|
|||
assert!(!shown.contains("SECRETCHOICE"), "{shown}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ontology_admit_accepts_the_bounds_and_joiners() {
|
||||
let d = dir();
|
||||
let w = world();
|
||||
let mut s = store(&d);
|
||||
// Exactly 64 entries in one language; exactly the byte bounds; a ZWNJ.
|
||||
let mut batch: Vec<OntologyEntry> = (1..=64).map(|n| entry("ja-JP", n)).collect();
|
||||
batch[0].choice = "x".repeat(200);
|
||||
batch[0].examples = vec!["y".repeat(120); 3];
|
||||
batch[1].choice = "a\u{200c}b".into();
|
||||
batch[2].when = (0..4)
|
||||
.map(|_| when(Slot::Stance, "restraint", Test::AtMost(Grade::new(1000).unwrap())))
|
||||
.collect();
|
||||
assert_eq!(s.admit(batch, &w.inventory).unwrap(), AddOutcome::Added);
|
||||
assert_eq!(s.all().unwrap().len(), 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ontology_admit_is_all_or_nothing() {
|
||||
let d = dir();
|
||||
|
|
@ -1781,6 +1833,10 @@ mod ontology {
|
|||
// An identical replay, from a reopened store, changes nothing.
|
||||
let mut again = store(&d);
|
||||
assert_eq!(again.admit(batch, &w.inventory).unwrap(), AddOutcome::Unchanged);
|
||||
// A batch of one stored entry and one new one is not a replay.
|
||||
let mixed = vec![entry("ja-JP", 1), entry("ja-JP", 5)];
|
||||
assert!(again.admit(mixed, &w.inventory).is_err());
|
||||
assert_eq!(again.all().unwrap().len(), 4);
|
||||
// Each language numbers from its own latest.
|
||||
assert_eq!(
|
||||
again
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
||||
"title": "OntologyEntry",
|
||||
"description": "One choice of one language. Key `onto:<language>:<n>`.",
|
||||
"description": "One choice of one language. Key `onto:<language>:<n>`.\n\nThe store judges the form of an entry's text (bounds, normalization, no\ncontrol or format character) and never its meaning: what may enter an entry\nis owned by the minting flow (Train-only assembly) and the scorer's leak\ndiagnostic (ruling `leak-owned-by-flow-and-scorer-3`), not by a door here.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"annotator": {
|
||||
|
|
|
|||
Loading…
Reference in a new issue