subtract: delete dead Checkpoint / TestReadings door and parser test
Checkpoint and TestReadings had zero non-test production callers. Remove Checkpoint, TestReadings, EncoderOffer::for_checkpoint, OfferRefusal::OfferedAtCheckpoint, split/mutants.rs, and tests/checkpoint_door.rs while preserving SplitScheme Test exclusion in round/train/offers.
This commit is contained in:
parent
0fbfecde26
commit
2dbfd278e1
8 changed files with 19 additions and 493 deletions
|
|
@ -28,7 +28,6 @@
|
|||
//! process its forger controls can stop it.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::marker::PhantomData;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
|
|
@ -41,7 +40,7 @@ use crate::packet::{
|
|||
Context, Discourse, EntityId, Extension, FeatValue, Grade, Predication, Referent, Relation, Stance,
|
||||
};
|
||||
use crate::run::LADDER_STEP;
|
||||
use crate::split::{Checkpoint, Split, SplitScheme, fnv1a64, hex16};
|
||||
use crate::split::{Split, SplitScheme, fnv1a64, hex16};
|
||||
use crate::store::{CorpusStore, normalized};
|
||||
use crate::validate::{LoweringInput, SceneRead};
|
||||
|
||||
|
|
@ -179,71 +178,27 @@ pub enum OfferRefusal {
|
|||
Withdrawn,
|
||||
/// A model-written item of a Test group is in no split.
|
||||
NoSplit,
|
||||
/// A Test item is offered only under a [`Checkpoint`].
|
||||
TestBeforeCheckpoint,
|
||||
/// An item is offered at most once under one [`Checkpoint`].
|
||||
OfferedAtCheckpoint,
|
||||
/// A Test item is excluded from round offers.
|
||||
TestItem,
|
||||
}
|
||||
|
||||
/// One item the encoder may be shown, with the entities a packet for it may
|
||||
/// cite. Built per item, so a call sees one item and nothing of its group.
|
||||
///
|
||||
/// An offer made under a [`Checkpoint`] borrows it, so it is dead before
|
||||
/// `TestReadings::at_checkpoint` can spend the checkpoint, and a Test offer is
|
||||
/// never encoded after (or beside) the reading. A round offer borrows nothing.
|
||||
///
|
||||
/// ```
|
||||
/// use weksa::context::{EncoderOffer, TrainItems};
|
||||
/// use weksa::split::Checkpoint;
|
||||
/// use weksa::{CorpusItem, score::TestReadings};
|
||||
/// fn f(mut c: Checkpoint, i: &CorpusItem, t: &TrainItems, inv: &weksa::Inventory) {
|
||||
/// if let Ok(o) = EncoderOffer::for_checkpoint(i, &mut c) {
|
||||
/// let _ = weksa::context::Prompt::encode(&o, t, inv, 1);
|
||||
/// }
|
||||
/// let _ = TestReadings::at_checkpoint(c, &[], &[], &[]);
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// use weksa::context::{EncoderOffer, TrainItems};
|
||||
/// use weksa::split::Checkpoint;
|
||||
/// use weksa::{CorpusItem, score::TestReadings};
|
||||
/// fn f(mut c: Checkpoint, i: &CorpusItem, t: &TrainItems, inv: &weksa::Inventory) {
|
||||
/// let o = EncoderOffer::for_checkpoint(i, &mut c).unwrap();
|
||||
/// let _ = TestReadings::at_checkpoint(c, &[], &[], &[]);
|
||||
/// let _ = weksa::context::Prompt::encode(&o, t, inv, 1);
|
||||
/// }
|
||||
/// ```
|
||||
pub struct EncoderOffer<'cp> {
|
||||
pub struct EncoderOffer {
|
||||
item: CorpusItem,
|
||||
entities: Vec<EntityId>,
|
||||
_checkpoint: PhantomData<&'cp mut Checkpoint>,
|
||||
}
|
||||
|
||||
impl<'cp> EncoderOffer<'cp> {
|
||||
impl EncoderOffer {
|
||||
/// A round offers Train and Validation items. `RunStores::offer` and
|
||||
/// `RunStores::offers` are the public producers.
|
||||
pub(crate) fn for_round(item: &CorpusItem) -> Result<EncoderOffer<'static>, OfferRefusal> {
|
||||
pub(crate) fn for_round(item: &CorpusItem) -> Result<EncoderOffer, OfferRefusal> {
|
||||
match Self::gate(item)? {
|
||||
Split::Test => Err(OfferRefusal::TestBeforeCheckpoint),
|
||||
Split::Test => Err(OfferRefusal::TestItem),
|
||||
_ => Ok(Self::of(item)),
|
||||
}
|
||||
}
|
||||
|
||||
/// A convergence checkpoint offers any live item, Test included, each item
|
||||
/// at most once under one `Checkpoint`. The gate runs first, so a refused
|
||||
/// item records no key.
|
||||
pub fn for_checkpoint(
|
||||
item: &CorpusItem,
|
||||
checkpoint: &'cp mut Checkpoint,
|
||||
) -> Result<Self, OfferRefusal> {
|
||||
Self::gate(item)?;
|
||||
if !checkpoint.first_offer(&item.id) {
|
||||
return Err(OfferRefusal::OfferedAtCheckpoint);
|
||||
}
|
||||
Ok(Self::of(item))
|
||||
}
|
||||
|
||||
fn gate(item: &CorpusItem) -> Result<Split, OfferRefusal> {
|
||||
if item.withdrawn {
|
||||
return Err(OfferRefusal::Withdrawn);
|
||||
|
|
@ -251,14 +206,13 @@ impl<'cp> EncoderOffer<'cp> {
|
|||
SplitScheme::V1.live(item).ok_or(OfferRefusal::NoSplit)
|
||||
}
|
||||
|
||||
fn of<'a>(item: &CorpusItem) -> EncoderOffer<'a> {
|
||||
fn of(item: &CorpusItem) -> EncoderOffer {
|
||||
let mut entities: Vec<EntityId> = item.cited_entities().cloned().collect();
|
||||
entities.sort();
|
||||
entities.dedup();
|
||||
EncoderOffer {
|
||||
item: item.clone(),
|
||||
entities,
|
||||
_checkpoint: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -827,28 +781,6 @@ mod tests {
|
|||
assert!(prompt.item_keys().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkpoint_offer_gate() {
|
||||
// A fresh checkpoint per call: this test is the gate, not the once rule.
|
||||
let check =
|
||||
|i: &CorpusItem| EncoderOffer::for_checkpoint(i, &mut Checkpoint::for_test(1)).err();
|
||||
let train = item("item:a:1", "t", &group_in(Split::Train), false);
|
||||
let validation = item("item:b:1", "v", &group_in(Split::Validation), false);
|
||||
let test = item("item:c:1", "x", &group_in(Split::Test), false);
|
||||
let no_split = item("item:c:2", "m", &group_in(Split::Test), true);
|
||||
let mut withdrawn = item("item:a:2", "w", &group_in(Split::Train), false);
|
||||
withdrawn.withdrawn = true;
|
||||
assert_eq!(check(&train), None);
|
||||
assert_eq!(check(&validation), None);
|
||||
assert_eq!(check(&test), None);
|
||||
assert_eq!(check(&no_split), Some(OfferRefusal::NoSplit));
|
||||
assert_eq!(check(&withdrawn), Some(OfferRefusal::Withdrawn));
|
||||
// Withdrawn wins over NoSplit.
|
||||
let mut both = no_split.clone();
|
||||
both.withdrawn = true;
|
||||
assert_eq!(check(&both), Some(OfferRefusal::Withdrawn));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_offer_gate_precedence() {
|
||||
let round = |i: &CorpusItem| EncoderOffer::for_round(i).err();
|
||||
|
|
@ -856,9 +788,9 @@ mod tests {
|
|||
no_split.withdrawn = true;
|
||||
// Withdrawn wins over NoSplit.
|
||||
assert_eq!(round(&no_split), Some(OfferRefusal::Withdrawn));
|
||||
// A withdrawn Test item is Withdrawn, not TestBeforeCheckpoint.
|
||||
// A withdrawn Test item is Withdrawn, not TestItem.
|
||||
let mut test = item("item:c:1", "x", &group_in(Split::Test), false);
|
||||
assert_eq!(round(&test), Some(OfferRefusal::TestBeforeCheckpoint));
|
||||
assert_eq!(round(&test), Some(OfferRefusal::TestItem));
|
||||
test.withdrawn = true;
|
||||
assert_eq!(round(&test), Some(OfferRefusal::Withdrawn));
|
||||
}
|
||||
|
|
@ -977,52 +909,4 @@ mod tests {
|
|||
assert!(!out.chars().any(|c| is_sep(c) && c != '\n'), "{sep:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checkpoint_offers_each_item_once() {
|
||||
let mut cp = Checkpoint::for_test(1);
|
||||
let offer = |cp: &mut Checkpoint, i: &CorpusItem| EncoderOffer::for_checkpoint(i, cp).err();
|
||||
let a = item("item:c:1", "a", &group_in(Split::Test), false);
|
||||
let b = item("item:c:3", "b", &group_in(Split::Test), false);
|
||||
let v = item("item:b:1", "v", &group_in(Split::Validation), false);
|
||||
assert_eq!(offer(&mut cp, &a), None);
|
||||
assert_eq!(offer(&mut cp, &a), Some(OfferRefusal::OfferedAtCheckpoint));
|
||||
assert_eq!(offer(&mut cp, &b), None);
|
||||
assert_eq!(offer(&mut cp, &v), None);
|
||||
assert_eq!(offer(&mut cp, &v), Some(OfferRefusal::OfferedAtCheckpoint));
|
||||
|
||||
// The once rule is per key, not per text: a distinct key with the same
|
||||
// text is a different item.
|
||||
let twin = item("item:c:4", "a", &group_in(Split::Test), false);
|
||||
assert_eq!(offer(&mut cp, &twin), None);
|
||||
assert_eq!(offer(&mut cp, &twin), Some(OfferRefusal::OfferedAtCheckpoint));
|
||||
// Re-offers after others intervened are still refused: the set keeps
|
||||
// every key, not the last.
|
||||
assert_eq!(offer(&mut cp, &a), Some(OfferRefusal::OfferedAtCheckpoint));
|
||||
assert_eq!(offer(&mut cp, &b), Some(OfferRefusal::OfferedAtCheckpoint));
|
||||
// Keys are whole: ids longer than 8 bytes that share an 8-byte prefix.
|
||||
let l1 = item("item:long:1", "l1", &group_in(Split::Test), false);
|
||||
let l2 = item("item:long:2", "l2", &group_in(Split::Test), false);
|
||||
assert_eq!(offer(&mut cp, &l1), None);
|
||||
assert_eq!(offer(&mut cp, &l2), None);
|
||||
assert_eq!(offer(&mut cp, &l1), Some(OfferRefusal::OfferedAtCheckpoint));
|
||||
// The rule holds for Train too.
|
||||
let t = item("item:a:1", "t", &group_in(Split::Train), false);
|
||||
assert_eq!(offer(&mut cp, &t), None);
|
||||
assert_eq!(offer(&mut cp, &t), Some(OfferRefusal::OfferedAtCheckpoint));
|
||||
|
||||
// A refused item records no key: its refusal stays the gate's.
|
||||
let mut gone = item("item:c:2", "w", &group_in(Split::Test), false);
|
||||
gone.withdrawn = true;
|
||||
assert_eq!(offer(&mut cp, &gone), Some(OfferRefusal::Withdrawn));
|
||||
assert_eq!(offer(&mut cp, &gone), Some(OfferRefusal::Withdrawn));
|
||||
let mut live = gone.clone();
|
||||
live.withdrawn = false;
|
||||
assert_eq!(offer(&mut cp, &live), None, "the refusal recorded no key");
|
||||
|
||||
// The checkpoint is spent by its reading; a new one offers afresh.
|
||||
let _ = crate::score::TestReadings::at_checkpoint(cp, &[], &[], &[]);
|
||||
let mut fresh = Checkpoint::for_test(2);
|
||||
assert_eq!(offer(&mut fresh, &a), None);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -941,7 +941,7 @@ impl RunStores {
|
|||
pub fn offer(
|
||||
&self,
|
||||
key: &str,
|
||||
) -> anyhow::Result<Result<EncoderOffer<'static>, crate::context::OfferRefusal>> {
|
||||
) -> anyhow::Result<Result<EncoderOffer, crate::context::OfferRefusal>> {
|
||||
let item = self
|
||||
.corpus
|
||||
.get(key)?
|
||||
|
|
@ -953,7 +953,7 @@ impl RunStores {
|
|||
/// The live Train and Validation offers in a panel language, in key order.
|
||||
/// Items the gate refuses, and items of any other language, are skipped
|
||||
/// and read no further.
|
||||
pub fn offers(&self) -> anyhow::Result<Vec<EncoderOffer<'static>>> {
|
||||
pub fn offers(&self) -> anyhow::Result<Vec<EncoderOffer>> {
|
||||
Ok(self
|
||||
.corpus
|
||||
.all()?
|
||||
|
|
|
|||
|
|
@ -160,8 +160,7 @@ pub(super) fn held_out(minted: &[&str], items: &[CorpusItem], want: Split) -> Sp
|
|||
/// items (unigrams over all minted strings, longer grams within one string).
|
||||
/// Honest single-word glosses saturate n = 1, so the leak signature is pooled
|
||||
/// n >= 2 and the worst item at n >= 2. Train items are not measured; withdrawn
|
||||
/// items and items in no split are dropped. Test is read only through
|
||||
/// `TestReadings`.
|
||||
/// items and items in no split are dropped.
|
||||
pub fn leak_diagnostic(minted: &[&str], items: &[CorpusItem]) -> SplitLeak {
|
||||
held_out(minted, items, Split::Validation)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,8 +3,7 @@
|
|||
//! before either is read, and the scorer takes no input from a packet, so no
|
||||
//! text the output carries can raise a score except by resembling the
|
||||
//! reference. No door judges text; the diagnostics report. The round path
|
||||
//! (`aggregate`, `leak_diagnostic`) reads Train and Validation; Test is read
|
||||
//! only through `TestReadings::at_checkpoint` (convergence-test).
|
||||
//! (`aggregate`, `leak_diagnostic`) reads Train and Validation only.
|
||||
|
||||
mod chrf;
|
||||
mod diagnostics;
|
||||
|
|
@ -20,7 +19,7 @@ pub use diagnostics::{OrderCoverage, PairChrf, SplitLeak, WorstItem, leak_diagno
|
|||
pub use embed::{Embedder, OllamaEmbedder, cosine};
|
||||
|
||||
use crate::corpus::CorpusItem;
|
||||
use crate::split::{Checkpoint, Split, SplitScheme};
|
||||
use crate::split::{Split, SplitScheme};
|
||||
|
||||
/// One reference/output pair; both are scored whole.
|
||||
pub struct ScoreInput<'a> {
|
||||
|
|
@ -168,82 +167,6 @@ pub fn validation_items(scored: &[(&CorpusItem, ItemScore)]) -> Vec<ItemScore> {
|
|||
scores_in(scored, Split::Validation).into_iter().cloned().collect()
|
||||
}
|
||||
|
||||
/// The Test split's readings, scalars only: no item key, no minted string, no
|
||||
/// pair. The checkpoint decision (convergence-test) needs numbers; a key beside
|
||||
/// a minted string is the handle an edit step would act on. The only producer
|
||||
/// is `at_checkpoint`, which consumes a `Checkpoint`; only the lib can make one.
|
||||
///
|
||||
/// ```
|
||||
/// use weksa::score::TestReadings;
|
||||
/// fn f(t: TestReadings) -> usize { t.count() }
|
||||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// use weksa::score::TestReadings;
|
||||
/// fn f(t: TestReadings) { let _u = t.clone(); }
|
||||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// use weksa::score::TestReadings;
|
||||
/// fn f(t: TestReadings) { let _ = format!("{t:?}"); }
|
||||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// use weksa::score::TestReadings;
|
||||
/// fn s<T: serde::Serialize>(_: &T) {}
|
||||
/// fn f(t: TestReadings) { s(&t); }
|
||||
/// ```
|
||||
pub struct TestReadings {
|
||||
mean: SplitMean,
|
||||
leak: SplitLeak,
|
||||
}
|
||||
|
||||
impl TestReadings {
|
||||
/// Reads the live Test items against the scores and the minted strings,
|
||||
/// by the same `split_leak` method the Validation reading uses. The
|
||||
/// checkpoint is spent.
|
||||
pub fn at_checkpoint(
|
||||
checkpoint: Checkpoint,
|
||||
scored: &[(&CorpusItem, ItemScore)],
|
||||
minted: &[&str],
|
||||
items: &[CorpusItem],
|
||||
) -> TestReadings {
|
||||
let _spent = checkpoint;
|
||||
TestReadings {
|
||||
mean: split_mean(scored, Split::Test),
|
||||
leak: diagnostics::held_out(minted, items, Split::Test),
|
||||
}
|
||||
}
|
||||
|
||||
/// Scored Test items.
|
||||
pub fn count(&self) -> usize {
|
||||
self.mean.count
|
||||
}
|
||||
|
||||
pub fn chrf(&self) -> Option<f64> {
|
||||
self.mean.chrf
|
||||
}
|
||||
|
||||
pub fn meaning(&self) -> Option<f64> {
|
||||
self.mean.meaning
|
||||
}
|
||||
|
||||
/// Test items in the leak reading.
|
||||
pub fn items(&self) -> usize {
|
||||
self.leak.items
|
||||
}
|
||||
|
||||
/// The highest chrF of any minted string against any Test item; the score
|
||||
/// only, never the pair.
|
||||
pub fn max_chrf(&self) -> Option<f64> {
|
||||
self.leak.max_chrf.as_ref().map(|p| p.chrf)
|
||||
}
|
||||
|
||||
pub fn coverage_by_n(&self) -> &[OrderCoverage] {
|
||||
&self.leak.coverage_by_n
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -284,80 +207,4 @@ mod tests {
|
|||
);
|
||||
assert_eq!(got.len(), aggregate(&scored).validation.count);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_readings_at_checkpoint() {
|
||||
let train_item = in_split("item:t:1", UNRELATED, Split::Train, false);
|
||||
let test = in_split("item:c:1", HELD_OUT, Split::Test, false);
|
||||
let test_model = in_split("item:c:2", "model words here", Split::Test, true);
|
||||
let mut gone = in_split("item:c:3", "withdrawn words", Split::Test, false);
|
||||
gone.withdrawn = true;
|
||||
let val = in_split(
|
||||
"item:v:1",
|
||||
"gardening is quiet work",
|
||||
Split::Validation,
|
||||
false,
|
||||
);
|
||||
let items = [
|
||||
train_item.clone(),
|
||||
test.clone(),
|
||||
test_model.clone(),
|
||||
gone.clone(),
|
||||
val.clone(),
|
||||
];
|
||||
let scored = [
|
||||
(&train_item, score(10.0, Some(0.5))),
|
||||
(&val, score(40.0, Some(0.8))),
|
||||
(&test, score(60.0, Some(0.6))),
|
||||
(&test_model, score(100.0, Some(1.0))),
|
||||
(&gone, score(90.0, Some(0.9))),
|
||||
];
|
||||
let t = TestReadings::at_checkpoint(Checkpoint::for_test(2), &scored, &[HELD_OUT], &items);
|
||||
assert_eq!(
|
||||
(t.count(), t.chrf(), t.meaning()),
|
||||
(1, Some(60.0), Some(0.6))
|
||||
);
|
||||
assert_eq!(
|
||||
t.items(),
|
||||
1,
|
||||
"model-written and withdrawn Test items are excluded"
|
||||
);
|
||||
assert!(t.max_chrf().unwrap() > 99.0);
|
||||
assert_eq!(t.coverage_by_n()[2].share, Some(1.0));
|
||||
|
||||
// A minted string that is not the Test text reads low.
|
||||
let t = TestReadings::at_checkpoint(Checkpoint::for_test(2), &scored, &["zzz"], &items);
|
||||
assert!(t.max_chrf().unwrap() < 20.0);
|
||||
assert_eq!(t.coverage_by_n()[2].share, Some(0.0));
|
||||
|
||||
let empty = TestReadings::at_checkpoint(Checkpoint::for_test(2), &[], &[HELD_OUT], &[]);
|
||||
assert_eq!(
|
||||
(empty.count(), empty.chrf(), empty.meaning()),
|
||||
(0, None, None)
|
||||
);
|
||||
assert_eq!((empty.items(), empty.max_chrf()), (0, None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validation_and_test_leak_agree_in_method() {
|
||||
// The same text and minted strings, once in Validation and once in
|
||||
// Test, read the same numbers.
|
||||
let words: Vec<&str> = HELD_OUT.split(' ').collect();
|
||||
let chunks: Vec<String> = words.chunks(3).map(|c| c.join(" ")).collect();
|
||||
let minted: Vec<&str> = chunks.iter().map(String::as_str).collect();
|
||||
let train_item = in_split("item:t:1", UNRELATED, Split::Train, false);
|
||||
let v = leak_diagnostic(
|
||||
&minted,
|
||||
&[
|
||||
in_split("item:v:1", HELD_OUT, Split::Validation, false),
|
||||
train_item.clone(),
|
||||
],
|
||||
);
|
||||
let test = in_split("item:c:1", HELD_OUT, Split::Test, false);
|
||||
let t =
|
||||
TestReadings::at_checkpoint(Checkpoint::for_test(1), &[], &minted, &[test, train_item]);
|
||||
assert_eq!(t.items(), v.items);
|
||||
assert_eq!(t.max_chrf(), v.max_chrf.as_ref().map(|p| p.chrf));
|
||||
assert_eq!(t.coverage_by_n(), v.coverage_by_n.as_slice());
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +1,9 @@
|
|||
//! The train/validation/test split is derived from an item's group and nothing
|
||||
//! else. No stored assignment exists, so no writer can reassign one. An item is
|
||||
//! read in its live split. The round path (round records, prompts, `aggregate`,
|
||||
//! `leak_diagnostic`) carries no Test reading; a typed `TestReadings` and a Test
|
||||
//! `EncoderOffer` need a Checkpoint, and only the lib can make one
|
||||
//! (convergence-freeze adds the door). Operator tools (`weksa corpus dump`,
|
||||
//! `weksa score`, `CorpusStore`) read corpus text of any split; that is not
|
||||
//! gated here.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
//! `leak_diagnostic`) reads Train and Validation and excludes Test. Operator
|
||||
//! tools (`weksa corpus dump`, `weksa score`, `CorpusStore`) read corpus text
|
||||
//! of any split; that is not gated here.
|
||||
|
||||
use crate::corpus::{CorpusItem, Source};
|
||||
|
||||
|
|
@ -93,88 +89,6 @@ impl SplitScheme {
|
|||
}
|
||||
}
|
||||
|
||||
/// Permission to read Test once, as typed `TestReadings` or as Test
|
||||
/// `EncoderOffer`s. Only the weksa lib can make one: there is no public
|
||||
/// constructor, so no code outside it can obtain those. This is not a seal on
|
||||
/// corpus text: operator tools and `CorpusStore` can read any item, and the
|
||||
/// guarded invariant is that the round path holds no Test reading. The one door
|
||||
/// is added by
|
||||
/// convergence-freeze, which builds a `Checkpoint` from the convergence window
|
||||
/// over the run's persisted round records (convergence-test).
|
||||
/// `TestReadings::at_checkpoint` consumes it, so one `Checkpoint` buys one Test
|
||||
/// reading. One `Checkpoint` also offers each item at most once
|
||||
/// (`EncoderOffer::for_checkpoint`), and an offer borrows its Checkpoint, so it
|
||||
/// cannot outlive the reading that spends it.
|
||||
///
|
||||
/// ```
|
||||
/// fn f(c: &weksa::split::Checkpoint) -> u32 { c.round() }
|
||||
/// ```
|
||||
///
|
||||
/// No public constructor:
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// let _ = weksa::split::Checkpoint::declare(1);
|
||||
/// ```
|
||||
///
|
||||
/// The test constructor is not exported (this doctest names it today; the
|
||||
/// line-based tripwire in `tests/checkpoint_door.rs` catches only common
|
||||
/// single-line forms of a new public constructor):
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// let _ = weksa::split::Checkpoint::for_test(1);
|
||||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// let _ = weksa::split::Checkpoint { round: 1, offered: Default::default() };
|
||||
/// ```
|
||||
///
|
||||
/// One reading per checkpoint:
|
||||
///
|
||||
/// ```
|
||||
/// use weksa::score::TestReadings;
|
||||
/// use weksa::split::Checkpoint;
|
||||
/// fn f(c: Checkpoint) { let _ = TestReadings::at_checkpoint(c, &[], &[], &[]); }
|
||||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// use weksa::score::TestReadings;
|
||||
/// use weksa::split::Checkpoint;
|
||||
/// fn f(c: Checkpoint) {
|
||||
/// let _ = TestReadings::at_checkpoint(c, &[], &[], &[]);
|
||||
/// let _ = TestReadings::at_checkpoint(c, &[], &[], &[]);
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ```compile_fail
|
||||
/// fn f(c: weksa::split::Checkpoint) { let _ = c.clone(); }
|
||||
/// ```
|
||||
pub struct Checkpoint {
|
||||
round: u32,
|
||||
offered: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl Checkpoint {
|
||||
#[cfg(test)]
|
||||
pub(crate) fn for_test(round: u32) -> Self {
|
||||
Self {
|
||||
round,
|
||||
offered: BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Records `key` as offered; false when it already was.
|
||||
pub(crate) fn first_offer(&mut self, key: &str) -> bool {
|
||||
self.offered.insert(key.to_string())
|
||||
}
|
||||
|
||||
pub fn round(&self) -> u32 {
|
||||
self.round
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod mutants;
|
||||
|
||||
/// Item builders for the unit tests that live in `src`: the twins of
|
||||
/// `tests/common`'s `group_in_bucket`, `item_in`, `cast` and `model`.
|
||||
#[cfg(test)]
|
||||
|
|
|
|||
|
|
@ -1,11 +0,0 @@
|
|||
//! Pins of private items of `split` found unpinned by mutation testing.
|
||||
|
||||
use super::Checkpoint;
|
||||
|
||||
/// A checkpoint reports the round it was declared at, whatever the round.
|
||||
#[test]
|
||||
fn a_checkpoint_reports_its_round() {
|
||||
assert_eq!(Checkpoint::for_test(7).round(), 7);
|
||||
assert_eq!(Checkpoint::for_test(0).round(), 0);
|
||||
assert_eq!(Checkpoint::for_test(1).round(), 1);
|
||||
}
|
||||
|
|
@ -1,107 +0,0 @@
|
|||
//! A line-based tripwire on the Checkpoint door, not a proof. The real defence
|
||||
//! is that `Checkpoint::for_test` is `cfg(test)`, pinned by the compile_fail
|
||||
//! doctest on its current name in `split.rs`. This scan reads `split.rs` line by
|
||||
//! line and catches the common single-line forms: a `pub fn` in `impl
|
||||
//! Checkpoint` whose signature line says `-> Self` or `-> Checkpoint` without
|
||||
//! `cfg(test)` above it, a trait impl for `Checkpoint`, a derive on it, a `pub`
|
||||
//! field in its braces, and a `-> Checkpoint` line in any other `src` file. It
|
||||
//! misses: signatures wrapped over several lines, `Option`, `Box`, `Result` or
|
||||
//! tuple returns from `split.rs`, tuple structs with `pub` fields, and
|
||||
//! constructors made by macros.
|
||||
|
||||
/// Why `src` lets code outside the lib make a `Checkpoint`, if it does.
|
||||
fn door_leaks(split_rs: &str) -> Vec<String> {
|
||||
let mut leaks = Vec::new();
|
||||
let lines: Vec<&str> = split_rs.lines().collect();
|
||||
let mut in_impl = false;
|
||||
let mut in_struct = false;
|
||||
for (n, line) in lines.iter().enumerate() {
|
||||
let t = line.trim();
|
||||
if t.starts_with("impl Checkpoint") {
|
||||
in_impl = true;
|
||||
} else if t.starts_with("impl") && t.contains("Checkpoint") {
|
||||
leaks.push(format!("{}: trait impl: {t}", n + 1));
|
||||
}
|
||||
if t.starts_with("pub struct Checkpoint") {
|
||||
let derived = lines[..n]
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|l| l.trim().starts_with("#[") || l.trim().starts_with("///"))
|
||||
.any(|l| l.contains("derive"));
|
||||
if derived {
|
||||
leaks.push(format!("{}: derive on Checkpoint", n + 1));
|
||||
}
|
||||
in_struct = true;
|
||||
continue;
|
||||
}
|
||||
if in_struct {
|
||||
if t.starts_with('}') {
|
||||
in_struct = false;
|
||||
} else if t.starts_with("pub ") {
|
||||
leaks.push(format!("{}: public field: {t}", n + 1));
|
||||
}
|
||||
}
|
||||
if in_impl && t.starts_with("pub ") && t.contains("fn ") {
|
||||
let mints = t.contains("-> Self") || t.contains("-> Checkpoint");
|
||||
let test_only = lines[..n]
|
||||
.iter()
|
||||
.rev()
|
||||
.take_while(|l| l.trim().starts_with("#["))
|
||||
.any(|l| l.contains("cfg(test)"));
|
||||
if mints && !test_only {
|
||||
leaks.push(format!("{}: pub constructor: {t}", n + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
leaks
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_public_item_mints_a_checkpoint() {
|
||||
let src =
|
||||
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/src/split.rs")).unwrap();
|
||||
assert_eq!(door_leaks(&src), Vec::<String>::new());
|
||||
// No other module returns one either.
|
||||
for entry in std::fs::read_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/src")).unwrap() {
|
||||
let path = entry.unwrap().path();
|
||||
if path.extension().is_some_and(|e| e == "rs") && !path.ends_with("split.rs") {
|
||||
let text = std::fs::read_to_string(&path).unwrap();
|
||||
let minting = text
|
||||
.lines()
|
||||
.filter(|l| l.contains("-> Checkpoint") || l.contains("-> Result<Checkpoint"))
|
||||
.count();
|
||||
assert_eq!(minting, 0, "{}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_scan_sees_each_way_to_open_the_door() {
|
||||
let good = "impl Checkpoint {\n #[cfg(test)]\n pub(crate) fn for_test(r: u32) -> Self { x }\n}\n";
|
||||
assert!(door_leaks(good).is_empty());
|
||||
// Test constructor made public, under its own name or another.
|
||||
let public = "impl Checkpoint {\n pub fn for_test(r: u32) -> Self { x }\n}\n";
|
||||
assert_eq!(door_leaks(public).len(), 1);
|
||||
let renamed = "impl Checkpoint {\n #[cfg(test)]\n #[allow(x)]\n pub fn new(r: u32) -> Checkpoint { x }\n}\n";
|
||||
assert!(
|
||||
door_leaks(renamed).is_empty(),
|
||||
"cfg(test) above another attribute counts"
|
||||
);
|
||||
let renamed = "impl Checkpoint {\n pub fn new(r: u32) -> Checkpoint { x }\n}\n";
|
||||
assert_eq!(door_leaks(renamed).len(), 1);
|
||||
// cfg(test) on the previous item does not cover this one.
|
||||
let stray =
|
||||
"impl Checkpoint {\n #[cfg(test)]\n fn a() {}\n pub fn b() -> Self { x }\n}\n";
|
||||
assert_eq!(door_leaks(stray).len(), 1);
|
||||
assert_eq!(door_leaks("impl Default for Checkpoint {}\n").len(), 1);
|
||||
assert_eq!(door_leaks("impl From<u32> for Checkpoint {}\n").len(), 1);
|
||||
assert_eq!(
|
||||
door_leaks("#[derive(Clone)]\npub struct Checkpoint {\n").len(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
door_leaks("pub struct Checkpoint {\n pub round: u32,\n}\n").len(),
|
||||
1
|
||||
);
|
||||
assert!(door_leaks("pub struct Checkpoint {\n round: u32,\n}\n").is_empty());
|
||||
}
|
||||
|
|
@ -177,7 +177,7 @@ fn encoder_offer_split_gate() {
|
|||
let round = |key: &str| c.run.offer(key).unwrap().err();
|
||||
assert_eq!(round("item:a:1"), None);
|
||||
assert_eq!(round("item:b:1"), None);
|
||||
assert_eq!(round("item:c:1"), Some(OfferRefusal::TestBeforeCheckpoint));
|
||||
assert_eq!(round("item:c:1"), Some(OfferRefusal::TestItem));
|
||||
assert_eq!(round("item:c:2"), Some(OfferRefusal::NoSplit));
|
||||
assert_eq!(round("item:a:2"), Some(OfferRefusal::Withdrawn));
|
||||
assert!(get(&c, "item:a:2").withdrawn);
|
||||
|
|
|
|||
Loading…
Reference in a new issue