RS fix batch: read-side density, the smallest seal, R5's two shapes, stale prose

F1: AdmissionIndex::build now calls receipt::head before copying any
ordinal, so query and view refuse a receipt chain that is not exactly
{1..=N} (duplicate, gap, zero, or above-N) instead of trusting a stored
ordinal unchecked. New test query::tests::query_and_view_refuse_a_receipt_chain_that_is_not_dense
pins it behaviourally: it plants each broken chain directly (bypassing
admission) and asserts query and view both refuse. The schema's ordinal
gets minimum: 1 (was 0), matched by #[schemars(range(min = 1))] on
AdmissionFacts::ordinal. head's doc now says AdmissionIndex::build asks
it too.

F2: Mind::open_with is renamed to an internal open_checked, and a
test-only Mind::open_with is gated behind cfg(test) or the test-support
feature, exactly like store_path_for. Production reaches open_checked
only through Mind::open, which takes the store's per-path lock first.
mind::tests::a_mind_has_one_owner_at_a_time (pre-existing) still pins
that a second Mind::open on the same path is refused. The full store
seal against a second in-process owner over an arbitrary MindStore stays
a recorded follow-up. lib.rs's crate doc now names Mind::open as the
owner of "may this store be this instance's mind".

F3: R5 is not binary. Two loosenings are pinned as R5b and R5c in
mind.rs, with behavioural fixtures: a foreign type with no epoch record
at all still refuses MissingIdentity, not ForeignStore (R5b); an epoch
record at the current key with a foreign value, beside a foreign type,
still refuses ForeignEpoch, not ForeignStore (R5c).

F5: gate step numbering in mind.rs's doc comment and its test comments
now read 2 (epoch), 3 (type), matching the code's actual order. docs.rs
no longer credits resolutions_of/assignments_of with reading history,
which RS-2 deleted. The two-door test in query.rs is renamed from
a_ref_whose_kind_and_id_disagree_is_refused_by_both_doors to
..._by_view, since view is the only door left.

Per the operator's ruling retiring the anchor-based mutation harness,
this batch carries no .psd1 changes; the cut9/cut10/readside mutation
files have uncommitted edits from the earlier pass (stale references to
the old test names, and R3L's target) left for a later pass to fold in
or drop.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-09-22 18:34:47 +02:00
commit 056db28792
6 changed files with 141 additions and 34 deletions

View file

@ -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<Item = (&str, &PipelineResolution)> {
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<Item = (&str, &PipelineStewardship)> {
self.stewardships().filter(move |(_, stewardship)| stewardship.instance == *mind && stewardship.repo == *repo)
}

View file

@ -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

View file

@ -136,11 +136,24 @@ impl Mind<OwnedRedbMessagePackBackingStore> {
unavailable(error)
}
})?;
Self::open_with(store, instance)
Self::open_checked(store, instance)
}
}
impl<S: MindStore> Mind<S> {
/// 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, MindRefusal> {
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<S: MindStore> Mind<S> {
/// 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<Self, MindRefusal> {
/// 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<Self, MindRefusal> {
require_grammatical_slug("instance", instance)?;
let raw = store.pull_all().map_err(unavailable)?;
refuse_foreign_epoch(&raw)?;
@ -234,7 +249,7 @@ impl<S: MindStore> Mind<S> {
}
}
/// 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<CultCacheEnvelope>, 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.

View file

@ -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<S: MindStore>(mind: &Mind<S>) -> Result<Self, MindRefusal> {
// 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();

View file

@ -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<S: MindStore>(mind: &Mind<S>) -> Result<u64, MindRefusal> {
let mut ordinals = mind.receipts()?.into_iter().map(|receipt| receipt.ordinal).collect::<Vec<_>>();
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);

View file

@ -82,7 +82,7 @@
"ordinal": {
"type": "integer",
"format": "uint64",
"minimum": 0
"minimum": 1
},
"provenance": {
"$ref": "#/$defs/PipelineProvenance"