diff --git a/crates/huginn-mind/src/docs.rs b/crates/huginn-mind/src/docs.rs index 5ac02ab..8a21b2c 100644 --- a/crates/huginn-mind/src/docs.rs +++ b/crates/huginn-mind/src/docs.rs @@ -93,14 +93,13 @@ impl Docs { } /// Every resolution of one subject, in image and batch: the scope a - /// subject's sequence counts in and the scope its history is read from. + /// subject's sequence counts in. pub(crate) fn resolutions_of(&self, subject: &PipelineRef) -> impl Iterator { self.resolutions().filter(move |(_, resolution)| resolution.subject == *subject) } /// Every assignment of one repo to one mind, in image and batch, in force - /// or not: the scope a stewardship's sequence counts in and the scope its - /// history is read from. + /// or not: the scope a stewardship's sequence counts in. pub(crate) fn assignments_of(&self, mind: &Slug, repo: &OrgRepo) -> impl Iterator { self.stewardships().filter(move |(_, stewardship)| stewardship.instance == *mind && stewardship.repo == *repo) } diff --git a/crates/huginn-mind/src/lib.rs b/crates/huginn-mind/src/lib.rs index 8ca4f1e..6c73109 100644 --- a/crates/huginn-mind/src/lib.rs +++ b/crates/huginn-mind/src/lib.rs @@ -1,9 +1,9 @@ //! `huginn-mind`: one instance's mind as typed CultCache state. //! -//! The crate owns three decisions and nothing else. `Mind::open_with` owns -//! "may this store be this instance's mind": the opener refuses a foreign -//! type, a foreign epoch, a missing identity or a foreign identity before it -//! attaches anything. `receipt::commit` owns "did a batch enter, whole, with a +//! The crate owns three decisions and nothing else. `Mind::open` owns "may +//! this store be this instance's mind": the opener refuses a foreign type, a +//! foreign epoch, a missing identity or a foreign identity before it attaches +//! anything, and takes the store's per-path lock first. `receipt::commit` owns "did a batch enter, whole, with a //! receipt": one compare-and-swap over the store, a receipt naming the exact //! bytes read and written, and a typed conflict when the swap loses. //! `Mind::admit_prepared` owns "may this batch enter": every cross-field and diff --git a/crates/huginn-mind/src/mind.rs b/crates/huginn-mind/src/mind.rs index c5eb1c5..3fb2442 100644 --- a/crates/huginn-mind/src/mind.rs +++ b/crates/huginn-mind/src/mind.rs @@ -136,11 +136,24 @@ impl Mind { unavailable(error) } })?; - Self::open_with(store, instance) + Self::open_checked(store, instance) } } impl Mind { + /// Test-only door onto the same fail-closed sequence `open` runs, for a + /// store already in hand (planted directly, or opened by a test through + /// `store_path_for`). Gated exactly like `store_path_for`: it compiles + /// only under `cfg(test)` in this crate or for a dependent's own tests + /// via the `test-support` feature, never into a release binary. A second + /// in-process owner of one store is not yet sealed for every `MindStore` + /// impl (F2's recorded follow-up); production reaches this sequence only + /// through `Mind::open`, which takes the per-path redb lock first. + #[cfg(any(test, feature = "test-support"))] + pub fn open_with(store: S, instance: &Slug) -> Result { + Self::open_checked(store, instance) + } + /// Fail-closed, in this order, nothing attached until every step passes: /// pull the raw envelopes; if anything is stored, exactly one epoch /// record at the current epoch; every type is one of the fifteen; and @@ -149,8 +162,10 @@ impl Mind { /// written at a foreign epoch is refused as `ForeignEpoch`, never as /// `ForeignStore`: a real epoch bump always moves every type id, so the /// type gate would otherwise fire first and the epoch gate would never - /// be reached for the one case it exists for (F5). - pub fn open_with(store: S, instance: &Slug) -> Result { + /// be reached for the one case it exists for (F5). This is the one + /// construction site of a `Mind`; `open` and the test-only `open_with` + /// both call it and neither reimplements it. + fn open_checked(store: S, instance: &Slug) -> Result { require_grammatical_slug("instance", instance)?; let raw = store.pull_all().map_err(unavailable)?; refuse_foreign_epoch(&raw)?; @@ -234,7 +249,7 @@ impl Mind { } } -/// Step 2: a runtime store, a Mind store or any other file passed by mistake +/// Step 3: a runtime store, a Mind store or any other file passed by mistake /// dies on its first foreign type. fn refuse_foreign_types(raw: &[CultCacheEnvelope]) -> Result<(), MindRefusal> { if let Some(foreign) = raw.iter().find(|envelope| !is_known_type(&envelope.r#type)) { @@ -243,7 +258,7 @@ fn refuse_foreign_types(raw: &[CultCacheEnvelope]) -> Result<(), MindRefusal> { Ok(()) } -/// Step 3: a non-empty store carries exactly one epoch record, keyed by the +/// Step 2: a non-empty store carries exactly one epoch record, keyed by the /// epoch it names, at the epoch this binary writes. A store with no epoch /// record at all is `MissingIdentity`; every other defect is `ForeignEpoch`, /// whose `found` names the defect: the stored epoch when the value is @@ -350,35 +365,36 @@ mod tests { fn the_opener_refuses_foreign_epoch_missing_identity_and_foreign_type_before_attaching() { let yggdrasil = slug(INSTANCE); let cases: Vec<(Vec, MindRefusal)> = vec![ - // Step 2 before everything: a runtime store passed by mistake. + // Step 3, reached because the epoch record here is current: a + // runtime store passed by mistake. ( vec![foreign("epiphany.runtime_spine.v47"), epoch(), prepare(&instance(INSTANCE))], MindRefusal::ForeignStore { r#type: "epiphany.runtime_spine.v47".into() }, ), - // Step 3 before step 4: a foreign epoch with no identity at all. + // Step 2 before step 4: a foreign epoch with no identity at all. // Its key is foreign too, which is what refuses it here. ( vec![foreign_epoch()], MindRefusal::ForeignEpoch { found: FOREIGN_EPOCH.into(), expected: PIPELINE_SCHEMA_EPOCH.into() }, ), - // Step 3: the value, under the one key the record may have. + // Step 2: the value, under the one key the record may have. ( vec![epoch_record(PIPELINE_SCHEMA_EPOCH, FOREIGN_EPOCH), prepare(&instance(INSTANCE))], MindRefusal::ForeignEpoch { found: FOREIGN_EPOCH.into(), expected: PIPELINE_SCHEMA_EPOCH.into() }, ), - // Step 3: the current epoch under any other key is not the epoch + // Step 2: the current epoch under any other key is not the epoch // record, whatever it says about itself. ( vec![epoch_record("not-the-epoch", PIPELINE_SCHEMA_EPOCH), prepare(&instance(INSTANCE))], MindRefusal::ForeignEpoch { found: "not-the-epoch".into(), expected: PIPELINE_SCHEMA_EPOCH.into() }, ), - // Step 3: two records are no record, counted before either value + // Step 2: two records are no record, counted before either value // is read. ( vec![epoch(), epoch_record("second", PIPELINE_SCHEMA_EPOCH), prepare(&instance(INSTANCE))], MindRefusal::ForeignEpoch { found: "2 records".into(), expected: PIPELINE_SCHEMA_EPOCH.into() }, ), - // Step 3: an identity without an epoch record. + // Step 2: an identity without an epoch record. (vec![prepare(&instance(INSTANCE))], MindRefusal::MissingIdentity), // Step 4: an epoch record without an identity. (vec![epoch()], MindRefusal::MissingIdentity), @@ -444,6 +460,34 @@ mod tests { ); } + /// F3 (RS fix batch), R5b: a foreign store with no epoch record at all + /// still refuses `MissingIdentity`, the epoch-first order's own answer + /// (F5, read-side cut) -- not `ForeignStore`, which is what a mutant that + /// only reorders the gates when there *is* some epoch record present + /// would answer, by running the type gate first over a store that has + /// no epoch record to look at. + #[test] + fn a_foreign_type_with_no_epoch_record_is_missing_identity_not_foreign_store() { + let store = planted(vec![foreign("epiphany.pipeline.campaign.v1")]); + assert_eq!(Mind::open_with(store, &slug(INSTANCE)).err(), Some(MindRefusal::MissingIdentity)); + } + + /// F3 (RS fix batch), R5c: an epoch record at the current key, but a + /// foreign value, beside a foreign type, still refuses `ForeignEpoch` -- + /// the epoch gate reads the record's *value* before the type gate ever + /// runs, not only when the record's *key* is itself foreign. A mutant + /// that reorders the gates only on a foreign key would answer + /// `ForeignStore` here instead, since this record sits at the correct + /// key. + #[test] + fn a_foreign_epoch_value_at_the_current_key_beside_a_foreign_type_is_foreign_epoch() { + let store = planted(vec![epoch_record(PIPELINE_SCHEMA_EPOCH, FOREIGN_EPOCH), foreign("epiphany.pipeline.campaign.v1")]); + assert_eq!( + Mind::open_with(store, &slug(INSTANCE)).err(), + Some(MindRefusal::ForeignEpoch { found: FOREIGN_EPOCH.into(), expected: PIPELINE_SCHEMA_EPOCH.into() }) + ); + } + #[test] fn the_instance_document_is_the_identity_not_the_path() { // The same bytes opened under another name are refused. diff --git a/crates/huginn-mind/src/query.rs b/crates/huginn-mind/src/query.rs index 0ae7e2e..f9ada57 100644 --- a/crates/huginn-mind/src/query.rs +++ b/crates/huginn-mind/src/query.rs @@ -23,7 +23,7 @@ use serde::{Deserialize, Serialize}; use crate::docs::{Docs, Held}; use crate::mind::Mind; -use crate::receipt::{Faculty, PipelineProvenance}; +use crate::receipt::{self, Faculty, PipelineProvenance}; use crate::refusal::MindRefusal; use crate::store::MindStore; @@ -40,6 +40,7 @@ pub struct AdmissionFacts { pub receipt_id: String, pub admitted_at: String, pub provenance: PipelineProvenance, + #[schemars(range(min = 1))] pub ordinal: u64, } @@ -111,6 +112,11 @@ pub(crate) struct AdmissionIndex(BTreeMap<(String, String), AdmissionFacts>); impl AdmissionIndex { pub(crate) fn build(mind: &Mind) -> Result { + // Every reader of the ordinal asks the same density check admission + // does, through `head`: a chain that is not exactly `{1..=N}` refuses + // here before a single ordinal is copied out, not only when admission + // happens to be the caller. + receipt::head(mind)?; let mut facts = BTreeMap::new(); for receipt in mind.receipts()? { for write in receipt.writes.iter() { @@ -403,12 +409,12 @@ mod tests { assert_eq!(view(&mind, K::Verdict, &id("verdict", "cut-1.s1")).status, PipelineStatus::InForce); } - /// Ruling 1's read half: the grammar lives in the leaf, and both doors - /// that take a ref ask it before they look. A ref that is no ref is - /// refused; a ref that is well formed and names nothing is still the - /// empty answer, so the door refuses malformation and not absence. + /// Ruling 1's read half: the grammar lives in the leaf, and `view`, the + /// one door that takes a ref, asks it before it looks. A ref that is no + /// ref is refused; a ref that is well formed and names nothing is still + /// the empty answer, so the door refuses malformation and not absence. #[test] - fn a_ref_whose_kind_and_id_disagree_is_refused_by_both_doors() { + fn a_ref_whose_kind_and_id_disagree_is_refused_by_view() { let mut mind = seeded(); let q1 = id("question", "Q1"); committed(admit(&mut mind, vec![question("Q1", &["A", "B"], "A")])); @@ -432,6 +438,59 @@ mod tests { assert_eq!(mind.view(&r(K::Question, &absent)), Ok(None)); } + /// F1 (RS fix batch): the read side never got to answer over an + /// undense ordinal chain, because `AdmissionIndex::build` copied + /// `receipt.ordinal` straight off the receipts without asking `head`. + /// `query` and `view` now go through the same density check admission + /// does, so a store planted directly (bypassing admission entirely) with + /// a duplicate, a gap, a zero, or an ordinal above `N` refuses both doors + /// alike, never answering as though the chain were dense. + #[test] + fn query_and_view_refuse_a_receipt_chain_that_is_not_dense() { + let base = MemoryStore::new(); + let mut mind = opened(base.clone(), INSTANCE); + seed(&mut mind); + committed(admit(&mut mind, vec![question("Q1", &["A", "B"], "A")])); + // The seed and Q1's batch: two receipts, ordinals {1, 2}. + + let cache = schema_cache().unwrap(); + let plant_at = |ordinal: u64, label: &str| { + let broken = MemoryStore::new(); + for row in base.rows() { + broken.plant(row); + } + let extra = receipt::candidate( + &slug(INSTANCE), + provenance(Faculty::Hands), + &[], + &[prepare(&question(label, &["A", "B"], "A"))], + ordinal, + now(), + ) + .unwrap(); + broken.plant(cache.prepare_entry_named(&extra.receipt_id, &extra).unwrap().0); + broken + }; + + let q1 = id("question", "Q1"); + let refuses = |store: MemoryStore, label: &str| { + let broken_mind = opened(store, INSTANCE); + assert!( + matches!(broken_mind.query(&PipelineQuery::default()), Err(MindRefusal::Unavailable { .. })), + "{label}: query must refuse an undense chain" + ); + assert!( + matches!(broken_mind.view(&r(K::Question, &q1)), Err(MindRefusal::Unavailable { .. })), + "{label}: view must refuse an undense chain" + ); + }; + + refuses(plant_at(2, "Q2"), "duplicate [1,2,2]"); + refuses(plant_at(4, "Q2"), "gap [1,2,4]"); + refuses(plant_at(0, "Q2"), "zero [0,1,2]"); + refuses(plant_at(99, "Q2"), "above N [1,2,99]"); + } + /// D3: the facts come from the one receipt that wrote the document, from /// `writes` alone, and a row no receipt wrote refuses rather than showing. #[test] @@ -487,7 +546,7 @@ mod tests { provenance(Faculty::Soul), &[], &[prepare(&question("Q1", &["A", "B"], "A")), prepare(&question("Q8", &["A", "B"], "A"))], - 999, + 4, // head + 1: dense, so this plants only the duplicate identity, not an F1 density fault too. now(), ) .unwrap(); @@ -737,7 +796,7 @@ mod tests { provenance(Faculty::Soul), &[], &[prepare(&question("Q1", &["A", "B"], "A")), prepare(&question("Q8", &["A", "B"], "A"))], - 999, + 3, // head + 1: dense, so this plants only the duplicate identity, not an F1 density fault too. now(), ) .unwrap(); diff --git a/crates/huginn-mind/src/receipt.rs b/crates/huginn-mind/src/receipt.rs index b9b7f63..e175b40 100644 --- a/crates/huginn-mind/src/receipt.rs +++ b/crates/huginn-mind/src/receipt.rs @@ -191,8 +191,11 @@ pub(crate) fn candidate( /// This mind's admission order: `N`, the count of receipts, when their /// ordinals are exactly `{1..=N}`. Every reader of the ordinal asks here, /// never by counting receipts itself: admission takes `head(self)? + 1` for -/// the next one, and a read takes `head` as its current `asOf`. A chain that -/// is not dense refuses rather than guessing, on both sides alike. +/// the next one, and `AdmissionIndex::build` (`query.rs`) calls it too, so +/// `query` and `view` carry the same density check rather than trusting a +/// stored ordinal unchecked. `ordinal` stays display-only on the read side +/// until RS-3 makes it the order. A chain that is not dense refuses rather +/// than guessing, on both sides alike. pub(crate) fn head(mind: &Mind) -> Result { let mut ordinals = mind.receipts()?.into_iter().map(|receipt| receipt.ordinal).collect::>(); ordinals.sort_unstable(); @@ -365,12 +368,14 @@ mod tests { assert!(landed.contains(&(HuginnCommitReceipt::TYPE.to_string(), receipt_id)), "{landed:?}"); } - /// RS-1: `head` requires the stored ordinals to be exactly `{1..=N}`, and - /// both admission and a read ask it. A duplicate and a gap are planted - /// directly, bypassing the commit path, and both `head` itself and a - /// fresh admission over the same store must refuse. + /// RS-1: `head` requires the stored ordinals to be exactly `{1..=N}`. + /// A duplicate and a gap are planted directly, bypassing the commit path, + /// and both `head` itself and a fresh admission over the same store must + /// refuse. `query.rs`'s + /// `query_and_view_refuse_a_receipt_chain_that_is_not_dense` pins the + /// same check on the read side. #[test] - fn a_chain_that_is_not_dense_refuses_admission_and_reads_alike() { + fn a_chain_that_is_not_dense_refuses_head_and_admission() { let base = MemoryStore::new(); let mut mind = opened(base.clone(), INSTANCE); seed(&mut mind); diff --git a/schemas/cultnet/huginn.mind_response.v1.schema.json b/schemas/cultnet/huginn.mind_response.v1.schema.json index dcf48d0..e22e14b 100644 --- a/schemas/cultnet/huginn.mind_response.v1.schema.json +++ b/schemas/cultnet/huginn.mind_response.v1.schema.json @@ -82,7 +82,7 @@ "ordinal": { "type": "integer", "format": "uint64", - "minimum": 0 + "minimum": 1 }, "provenance": { "$ref": "#/$defs/PipelineProvenance"