From 0d6f9a60d75ab47d5065686705020290ee7114f7 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Tue, 22 Sep 2026 11:56:04 +0200 Subject: [PATCH] Cut RS-1: the receipt ordinal, receipt v2, and the epoch-first opener Per eureka-read-side-cut.md. The receipt goes to v2 (type id and schema version both huginn.mind_commit_receipt.v2) and gains ordinal: u64 at key 7. candidate takes the ordinal; digest stays unchanged, so an exact replay keeps the ordinal its first admission assigned. validate refuses ordinal == 0. New receipt::head(mind) decodes the receipts and requires their ordinals to be exactly {1..=N}, refusing Unavailable otherwise; admission is the only caller, passing head(self)? + 1, and no other code computes an ordinal. AdmissionFacts gains ordinal, filled by AdmissionIndex::build; the order query.rs sorts by is unchanged (RS-3 deletes it, not this cut). mind.rs's opener now calls refuse_foreign_epoch before refuse_foreign_types, so a store written at a foreign epoch is refused as ForeignEpoch rather than 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. The doc comment is updated to match. Regenerated both published wire schemas. New tools/eureka-readside-mutations.psd1 (R1-R5, R1 and R3 with L variants, R1 also with an off-by-one-head R1L2; R2 and R5 documented as having no loosening, on the same grounds cut10's D9 and D12 give). Five new tests carry them: ordinals_are_admission_order_not_clock_or_id_order and an_exact_replay_keeps_its_ordinal in admission.rs, a_chain_that_is_not_dense_refuses_admission_and_reads_alike in receipt.rs, and a_v1_receipt_store_is_refused_at_open plus a_store_written_at_the_previous_epoch_is_refused_by_the_epoch_gate in mind.rs. cut8's H6 is re-anchored on the new gate order (its own rule, every gate before attach, is unchanged); cut8 (67), cut9 (27) and cut10 (65) all rerun clean, because candidate's signature and the opener's order both changed. Co-Authored-By: Claude Sonnet 5 --- crates/huginn-mind/src/admission.rs | 60 +++++- crates/huginn-mind/src/mind.rs | 43 ++++- crates/huginn-mind/src/query.rs | 8 +- crates/huginn-mind/src/receipt.rs | 91 ++++++++- .../huginn.mind_response.v1.schema.json | 10 +- tools/eureka-cut8-mutations.psd1 | 6 +- tools/eureka-readside-mutations.psd1 | 179 ++++++++++++++++++ 7 files changed, 378 insertions(+), 19 deletions(-) create mode 100644 tools/eureka-readside-mutations.psd1 diff --git a/crates/huginn-mind/src/admission.rs b/crates/huginn-mind/src/admission.rs index 3bcef73..7fed0b3 100644 --- a/crates/huginn-mind/src/admission.rs +++ b/crates/huginn-mind/src/admission.rs @@ -146,7 +146,7 @@ impl Mind { if carries_instance { writes.push(HuginnMindEpoch::envelope(self.cache())?); } - let candidate = receipt::candidate(&mind, provenance, &strong_reads, &writes, now)?; + let candidate = receipt::candidate(&mind, provenance, &strong_reads, &writes, receipt::head(self)? + 1, now)?; // A8 for staged in &docs.batch { check(&docs, staged, &mind)?; @@ -865,6 +865,60 @@ mod tests { assert_eq!(receipt_count(&mind), receipts + 1); } + /// RS-1: the ordinal is `head + 1` at admission, not a rank derived from + /// the clock or the receipt id. Three batches land at one `now`, so a + /// mutant that ranked by `(committed_at, receipt_id)` would fall back to + /// id order among them; the ids are checked not to already sort in + /// admission order, so that fallback provably disagrees with the truth. + #[test] + fn ordinals_are_admission_order_not_clock_or_id_order() { + let mut mind = seeded(); + assert_eq!(receipt::head(&mind).unwrap(), 1, "the seed batch is ordinal 1"); + let same_time = now(); + let (id1, _) = committed(admit_at(&mut mind, vec![question_n(1)], same_time)); + let (id2, _) = committed(admit_at(&mut mind, vec![question_n(2)], same_time)); + let (id3, _) = committed(admit_at(&mut mind, vec![question_n(3)], same_time)); + + let mut by_id = [id1.clone(), id2.clone(), id3.clone()]; + by_id.sort(); + assert_ne!( + by_id, + [id1.clone(), id2.clone(), id3.clone()], + "the fixture needs receipt ids that do not already sort in admission order" + ); + + let receipts = mind.receipts().unwrap(); + let ordinal_of = |id: &str| receipts.iter().find(|receipt| receipt.receipt_id == id).unwrap().ordinal; + assert_eq!(ordinal_of(&id1), 2); + assert_eq!(ordinal_of(&id2), 3); + assert_eq!(ordinal_of(&id3), 4); + assert_eq!(receipt::head(&mind).unwrap(), 4); + } + + /// RS-1, A9: the ordinal is not digested, so an exact replay finds the + /// receipt it first landed with and keeps that receipt's ordinal, even + /// when the head has moved since and a fresh candidate would be assigned + /// a different one. + #[test] + fn an_exact_replay_keeps_its_ordinal() { + let mut mind = seeded(); + let (first_id, _) = committed(admit(&mut mind, vec![question("Q1", &["A", "B"], "A")])); + let first_ordinal = + mind.receipts().unwrap().into_iter().find(|receipt| receipt.receipt_id == first_id).unwrap().ordinal; + + // Move the head, so a replay's own candidate would carry a different + // ordinal than the one already on the stored receipt. + committed(admit(&mut mind, vec![question("Q2", &["A", "B"], "A")])); + + let outcome = admit(&mut mind, vec![question("Q1", &["A", "B"], "A")]); + assert_eq!(outcome, PipelineAdmissionOutcome::AlreadyAdmitted { receipt_id: first_id.clone() }); + + let receipts = mind.receipts().unwrap(); + assert_eq!(receipts.iter().filter(|receipt| receipt.receipt_id == first_id).count(), 1, "no second receipt lands"); + let stored = receipts.iter().find(|receipt| receipt.receipt_id == first_id).unwrap(); + assert_eq!(stored.ordinal, first_ordinal, "the replay does not overwrite the ordinal"); + } + /// A batch that derives a write replays like any other: the second /// admission re-derives the record the first one landed, sequence and /// all, so A9 recognises the digest and answers with the first receipt @@ -1912,7 +1966,9 @@ mod tests { let mut mind = opened(store.clone(), INSTANCE); seed(&mut mind); let envelopes = vec![prepare(&question("Q1", &["A", "B"], "A"))]; - let candidate = receipt::candidate(&slug(INSTANCE), provenance(Faculty::Hands), &[], &envelopes, now()).unwrap(); + let ordinal = receipt::head(&mind).unwrap() + 1; + let candidate = + receipt::candidate(&slug(INSTANCE), provenance(Faculty::Hands), &[], &envelopes, ordinal, now()).unwrap(); let mut planted = HuginnCommitReceipt { writes: vec![], ..candidate.clone() }; planted.writes = candidate.strong_reads.clone(); planted.receipt_id = candidate.receipt_id.clone(); diff --git a/crates/huginn-mind/src/mind.rs b/crates/huginn-mind/src/mind.rs index 84f1228..c5eb1c5 100644 --- a/crates/huginn-mind/src/mind.rs +++ b/crates/huginn-mind/src/mind.rs @@ -142,15 +142,19 @@ impl Mind { impl Mind { /// Fail-closed, in this order, nothing attached until every step passes: - /// pull the raw envelopes; every type is one of the fifteen; if anything - /// is stored, exactly one epoch record at the current epoch and exactly - /// one `instance` document naming the declared instance; then register, - /// attach and pull. + /// pull the raw envelopes; if anything is stored, exactly one epoch + /// record at the current epoch; every type is one of the fifteen; and + /// exactly one `instance` document naming the declared instance; then + /// register, attach and pull. The epoch gate runs first so a store + /// 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 { require_grammatical_slug("instance", instance)?; let raw = store.pull_all().map_err(unavailable)?; - refuse_foreign_types(&raw)?; refuse_foreign_epoch(&raw)?; + refuse_foreign_types(&raw)?; refuse_foreign_identity(&raw, instance)?; let (cache, image) = attach(store.clone())?; Ok(Self { instance: instance.clone(), store, cache, image }) @@ -411,6 +415,35 @@ mod tests { assert!(Mind::open_with(empty, &yggdrasil).unwrap().is_empty()); } + /// RS-1: receipt v2 is a new type id, so a store carrying an old, + /// v1-shaped receipt is refused at the type gate, before anything tries + /// to decode its 7-slot payload as the 8-slot v2 shape (F3: with + /// `#[serde(default)]` that decode would succeed and silently misread + /// every old receipt's ordinal as 0). + #[test] + fn a_v1_receipt_store_is_refused_at_open() { + let store = + planted(vec![epoch(), prepare(&instance(INSTANCE)), foreign("huginn.mind_commit_receipt.v1")]); + assert_eq!( + Mind::open_with(store, &slug(INSTANCE)).err(), + Some(MindRefusal::ForeignStore { r#type: "huginn.mind_commit_receipt.v1".into() }) + ); + } + + /// RS-1, F5: a real epoch bump always moves every type id (F4), so a + /// store written at a foreign epoch also carries at least one foreign + /// type. The epoch gate must run first, or the type gate fires instead + /// and the epoch gate is never reached for the one case it exists for. + /// The eight cases of the opener test above are unchanged by the swap. + #[test] + fn a_store_written_at_the_previous_epoch_is_refused_by_the_epoch_gate() { + let raw = vec![foreign_epoch(), foreign("epiphany.pipeline.campaign.v0")]; + assert_eq!( + Mind::open_with(planted(raw), &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 271be19..0ae7e2e 100644 --- a/crates/huginn-mind/src/query.rs +++ b/crates/huginn-mind/src/query.rs @@ -32,12 +32,15 @@ use crate::store::MindStore; pub const QUERY_LIMIT_MAX: usize = 200; /// What admission recorded about a document when it landed: the receipt that -/// wrote it, the `now` that receipt was taken at, and who asked. +/// wrote it, the `now` that receipt was taken at, who asked, and the +/// receipt's ordinal. `ordinal` is display-only here until RS-3 makes it the +/// read side's order. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, JsonSchema)] pub struct AdmissionFacts { pub receipt_id: String, pub admitted_at: String, pub provenance: PipelineProvenance, + pub ordinal: u64, } /// Whether a document still stands, and if not, what closed it. Derived at @@ -116,6 +119,7 @@ impl AdmissionIndex { receipt_id: receipt.receipt_id.clone(), admitted_at: receipt.committed_at.clone(), provenance: receipt.provenance.clone(), + ordinal: receipt.ordinal, }; if facts.insert(identity, landed).is_some() { return Err(integrity(&write.document_type, &write.document_key, "is written by two receipts")); @@ -483,6 +487,7 @@ mod tests { provenance(Faculty::Soul), &[], &[prepare(&question("Q1", &["A", "B"], "A")), prepare(&question("Q8", &["A", "B"], "A"))], + 999, now(), ) .unwrap(); @@ -732,6 +737,7 @@ mod tests { provenance(Faculty::Soul), &[], &[prepare(&question("Q1", &["A", "B"], "A")), prepare(&question("Q8", &["A", "B"], "A"))], + 999, now(), ) .unwrap(); diff --git a/crates/huginn-mind/src/receipt.rs b/crates/huginn-mind/src/receipt.rs index a2e8066..b9b7f63 100644 --- a/crates/huginn-mind/src/receipt.rs +++ b/crates/huginn-mind/src/receipt.rs @@ -10,8 +10,9 @@ //! Digest: `receipt_id = "mind-commit-" + hex(sha256(msgpack_named((instance, //! strong_reads, writes))))`, where each list is `DocumentVersion`s in //! `(document_type, document_key)` order and a version carries the exact -//! payload bytes and their SHA-256. `committed_at` and `provenance` are not -//! digested. +//! payload bytes and their SHA-256. `committed_at`, `provenance` and +//! `ordinal` are not digested: an exact replay keeps the ordinal its first +//! admission assigned. use chrono::{DateTime, SecondsFormat, Utc}; use cultcache_rs::{CultCacheEnvelope, DatabaseEntry}; @@ -24,7 +25,7 @@ use crate::mind::{Mind, unavailable}; use crate::refusal::MindRefusal; use crate::store::MindStore; -pub const RECEIPT_SCHEMA_VERSION: &str = "huginn.mind_commit_receipt.v1"; +pub const RECEIPT_SCHEMA_VERSION: &str = "huginn.mind_commit_receipt.v2"; /// Which faculty a batch was admitted as. Attribution, not authority /// (ruling 18): no admission rule trusts it, and Cut 9's views read it back @@ -92,7 +93,7 @@ impl DocumentVersion { /// The receipt of one admitted batch, stored beside the documents it names /// and keyed by its id. #[derive(Clone, Debug, PartialEq, Eq, DatabaseEntry)] -#[cultcache(type = "huginn.mind_commit_receipt.v1", schema = "HuginnCommitReceipt")] +#[cultcache(type = "huginn.mind_commit_receipt.v2", schema = "HuginnCommitReceipt")] pub struct HuginnCommitReceipt { #[cultcache(key = 0)] pub schema_version: String, @@ -108,6 +109,11 @@ pub struct HuginnCommitReceipt { pub writes: Vec, #[cultcache(key = 6)] pub committed_at: String, + /// This mind's admission order: dense from 1, never reused, never + /// digested. `head` reads it back; `candidate` is the one place it is + /// assigned, as `head + 1`. + #[cultcache(key = 7)] + pub ordinal: u64, } impl HuginnCommitReceipt { @@ -135,6 +141,9 @@ impl HuginnCommitReceipt { if !unique_identities(&self.strong_reads) || !unique_identities(&self.writes) { return Err(integrity("receipt names an identity twice")); } + if self.ordinal == 0 { + return Err(integrity("receipt ordinal is 0")); + } if self.receipt_id != self.digest()? { return Err(integrity(&format!("receipt {} does not match its digest", self.receipt_id))); } @@ -162,6 +171,7 @@ pub(crate) fn candidate( provenance: PipelineProvenance, strong_reads: &[CultCacheEnvelope], writes: &[CultCacheEnvelope], + ordinal: u64, now: DateTime, ) -> Result { let mut receipt = HuginnCommitReceipt { @@ -172,11 +182,28 @@ pub(crate) fn candidate( strong_reads: versions(strong_reads), writes: versions(writes), committed_at: now.to_rfc3339_opts(SecondsFormat::Secs, true), + ordinal, }; receipt.receipt_id = receipt.digest()?; Ok(receipt) } +/// 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. +pub(crate) fn head(mind: &Mind) -> Result { + let mut ordinals = mind.receipts()?.into_iter().map(|receipt| receipt.ordinal).collect::>(); + ordinals.sort_unstable(); + let n = ordinals.len() as u64; + if ordinals.into_iter().eq(1..=n) { + Ok(n) + } else { + Err(MindRefusal::Unavailable { detail: "receipt ordinals are not 1..=N: found a duplicate or a gap".into() }) + } +} + /// The versions of a set of envelopes in identity order, so the digest does /// not depend on the order a batch was assembled in. fn versions(envelopes: &[CultCacheEnvelope]) -> Vec { @@ -262,7 +289,8 @@ mod tests { use std::sync::{Arc, Mutex}; use super::*; - use crate::fixtures::{INSTANCE, admit, committed, id, instance, opened, prepare, question, seed}; + use crate::fixtures::{INSTANCE, admit, committed, id, instance, now, opened, prepare, provenance, question, refusal, seed, slug}; + use crate::mind::schema_cache; use crate::store::test_stores::MemoryStore; use cultcache_rs::{CacheBackingStore, PushAllOptions}; use epiphany_pipeline::{PipelineDocument, PipelineKind, PipelineRefusal}; @@ -337,6 +365,57 @@ 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. + #[test] + fn a_chain_that_is_not_dense_refuses_admission_and_reads_alike() { + let base = MemoryStore::new(); + let mut mind = opened(base.clone(), INSTANCE); + seed(&mut mind); + committed(admit(&mut mind, vec![question("Q1", &["A", "B"], "A")])); + assert_eq!(head(&mind).unwrap(), 2, "the seed and Q1's batch"); + + 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 = 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 + }; + + // A duplicate: a third receipt at ordinal 2, which the store already + // carries. + let duplicated = plant_at(2, "Q2"); + assert!(matches!(head(&opened(duplicated.clone(), INSTANCE)), Err(MindRefusal::Unavailable { .. }))); + let mut duplicated_mind = opened(duplicated, INSTANCE); + assert!(matches!( + refusal(admit(&mut duplicated_mind, vec![question("Q3", &["A", "B"], "A")])), + MindRefusal::Unavailable { .. } + )); + + // A gap: a third receipt at ordinal 4, skipping 3. + let gapped = plant_at(4, "Q2"); + assert!(matches!(head(&opened(gapped.clone(), INSTANCE)), Err(MindRefusal::Unavailable { .. }))); + let mut gapped_mind = opened(gapped, INSTANCE); + assert!(matches!( + refusal(admit(&mut gapped_mind, vec![question("Q3", &["A", "B"], "A")])), + MindRefusal::Unavailable { .. } + )); + } + /// S5 closed against the real type: the organ's own receipt in a mind's /// store is never decoded as a pipeline document. #[test] @@ -345,7 +424,7 @@ mod tests { envelope.r#type = HuginnCommitReceipt::TYPE.into(); assert_eq!( PipelineDocument::decode(&envelope), - Err(PipelineRefusal::ForeignStore { r#type: "huginn.mind_commit_receipt.v1".into() }) + Err(PipelineRefusal::ForeignStore { r#type: "huginn.mind_commit_receipt.v2".into() }) ); } } diff --git a/schemas/cultnet/huginn.mind_response.v1.schema.json b/schemas/cultnet/huginn.mind_response.v1.schema.json index b489747..dcf48d0 100644 --- a/schemas/cultnet/huginn.mind_response.v1.schema.json +++ b/schemas/cultnet/huginn.mind_response.v1.schema.json @@ -73,12 +73,17 @@ ], "$defs": { "AdmissionFacts": { - "description": "What admission recorded about a document when it landed: the receipt that\nwrote it, the `now` that receipt was taken at, and who asked.", + "description": "What admission recorded about a document when it landed: the receipt that\nwrote it, the `now` that receipt was taken at, who asked, and the\nreceipt's ordinal. `ordinal` is display-only here until RS-3 makes it the\nread side's order.", "type": "object", "properties": { "admitted_at": { "type": "string" }, + "ordinal": { + "type": "integer", + "format": "uint64", + "minimum": 0 + }, "provenance": { "$ref": "#/$defs/PipelineProvenance" }, @@ -89,7 +94,8 @@ "required": [ "receipt_id", "admitted_at", - "provenance" + "provenance", + "ordinal" ] }, "AuthorityMap": { diff --git a/tools/eureka-cut8-mutations.psd1 b/tools/eureka-cut8-mutations.psd1 index 51fd7b5..9ac7e73 100644 --- a/tools/eureka-cut8-mutations.psd1 +++ b/tools/eureka-cut8-mutations.psd1 @@ -125,19 +125,19 @@ impl MindStore for OwnedRedbMessagePackBackingStore { } @{ Id = 'H6' - Rule = 'Ruling 20: the opener attaches nothing until every gate passes.' + Rule = 'Ruling 20: the opener attaches nothing until every gate passes. Re-anchored by RS-1, which swapped the epoch and type gates'' order; the rule -- every gate before attach -- is unchanged.' Test = 'mind::tests::the_opener_refuses_foreign_epoch_missing_identity_and_foreign_type_before_attaching' File = 'crates/huginn-mind/src/mind.rs' Old = @' - refuse_foreign_types(&raw)?; refuse_foreign_epoch(&raw)?; + refuse_foreign_types(&raw)?; refuse_foreign_identity(&raw, instance)?; let (cache, image) = attach(store.clone())?; '@ New = @' let (cache, image) = attach(store.clone())?; - refuse_foreign_types(&raw)?; refuse_foreign_epoch(&raw)?; + refuse_foreign_types(&raw)?; refuse_foreign_identity(&raw, instance)?; '@ } diff --git a/tools/eureka-readside-mutations.psd1 b/tools/eureka-readside-mutations.psd1 new file mode 100644 index 0000000..26383d2 --- /dev/null +++ b/tools/eureka-readside-mutations.psd1 @@ -0,0 +1,179 @@ +# RS-1 mutations, R1-R5: the receipt ordinal, receipt v2, and the epoch-first +# opener. Each rule has a revert, `Rn`, and (where a distinct weaker shape +# exists) a loosening, `RnL`. Every entry names the test that must fail while +# it is applied. Run through the Eureka skill's harness from this repo: +# +# $env:CARGO_TARGET_DIR = 'C:\Users\Meta\.cargo-target-codex' +# powershell -File C:\Users\Meta\.claude\skills\eureka\tools\eureka-mutations.ps1 -Repo F:\Projects\Huginn ` +# -Entries tools/eureka-readside-mutations.psd1 ` +# -Target crates/huginn-mind/src/receipt.rs,crates/huginn-mind/src/admission.rs,crates/huginn-mind/src/mind.rs ` +# -Test 'cargo test -p huginn-mind --lib' +# +# `M0` is the harness's own no-op control and is not listed here. +# +# R2 has no loosening and says so rather than carrying a weak entry: "the +# ordinal is not digested" has one natural mutant, putting it back in the +# digest. There is no partial shape of "digested a little" to weaken it into. +# +# R5 has no loosening for the same reason D9 and D12 in cut10 give: the rule +# is an order between two calls, and the only two orders are the order and +# its reverse. Swapping the gates back is the revert and the whole space of +# wrong orders at once. +@{ + Mutations = @( + @{ + Id = 'R1' + Rule = 'The ordinal is head + 1 at admission, assigned nowhere else.' + Test = 'admission::tests::ordinals_are_admission_order_not_clock_or_id_order' + File = 'crates/huginn-mind/src/admission.rs' + Old = ' let candidate = receipt::candidate(&mind, provenance, &strong_reads, &writes, receipt::head(self)? + 1, now)?;' + New = ' let candidate = receipt::candidate(&mind, provenance, &strong_reads, &writes, 1, now)?;' + } + @{ + Id = 'R1L' + Rule = 'The ordinal is admission order, not a function of the clock or the receipt id: a same-second batch of three must not fall back to ranking by (committed_at, receipt_id).' + Test = 'admission::tests::ordinals_are_admission_order_not_clock_or_id_order' + File = 'crates/huginn-mind/src/admission.rs' + Old = ' let candidate = receipt::candidate(&mind, provenance, &strong_reads, &writes, receipt::head(self)? + 1, now)?;' + New = @' + let provisional = receipt::candidate(&mind, provenance.clone(), &strong_reads, &writes, 0, now)?; + let mut order = self.receipts()?.into_iter().map(|r| (r.committed_at, r.receipt_id)).collect::>(); + order.push((provisional.committed_at.clone(), provisional.receipt_id.clone())); + order.sort(); + let ordinal = (order + .iter() + .position(|entry| entry == &(provisional.committed_at.clone(), provisional.receipt_id.clone())) + .unwrap() + + 1) as u64; + let candidate = receipt::candidate(&mind, provenance, &strong_reads, &writes, ordinal, now)?; +'@ + } + @{ + Id = 'R1L2' + Rule = 'head is exactly N, not N off by one.' + Test = 'admission::tests::ordinals_are_admission_order_not_clock_or_id_order' + File = 'crates/huginn-mind/src/receipt.rs' + Old = ' Ok(n)' + New = ' Ok(n.saturating_sub(1))' + } + @{ + Id = 'R2' + Rule = 'The ordinal is not digested (A9): an exact replay keeps the ordinal its first admission assigned, whatever the head has moved to since.' + Test = 'admission::tests::an_exact_replay_keeps_its_ordinal' + File = 'crates/huginn-mind/src/receipt.rs' + Old = ' let bytes = rmp_serde::to_vec_named(&(&self.instance, &self.strong_reads, &self.writes))' + New = ' let bytes = rmp_serde::to_vec_named(&(&self.instance, &self.strong_reads, &self.writes, self.ordinal))' + } + @{ + Id = 'R3' + Rule = 'head requires the ordinals to be exactly {1..=N}; a chain that is not dense refuses rather than answering a number.' + Test = 'receipt::tests::a_chain_that_is_not_dense_refuses_admission_and_reads_alike' + File = 'crates/huginn-mind/src/receipt.rs' + Old = @' + let mut ordinals = mind.receipts()?.into_iter().map(|receipt| receipt.ordinal).collect::>(); + ordinals.sort_unstable(); + let n = ordinals.len() as u64; + if ordinals.into_iter().eq(1..=n) { + Ok(n) + } else { + Err(MindRefusal::Unavailable { detail: "receipt ordinals are not 1..=N: found a duplicate or a gap".into() }) + } +'@ + New = @' + Ok(mind.receipts()?.len() as u64) +'@ + } + @{ + Id = 'R3L' + Rule = 'Density is validated wherever the ordinal is read, in the one shared head, not only along the one path a caller happens to exercise it from.' + Test = 'receipt::tests::a_chain_that_is_not_dense_refuses_admission_and_reads_alike' + Edits = @( + @{ + File = 'crates/huginn-mind/src/receipt.rs' + Old = @' + let mut ordinals = mind.receipts()?.into_iter().map(|receipt| receipt.ordinal).collect::>(); + ordinals.sort_unstable(); + let n = ordinals.len() as u64; + if ordinals.into_iter().eq(1..=n) { + Ok(n) + } else { + Err(MindRefusal::Unavailable { detail: "receipt ordinals are not 1..=N: found a duplicate or a gap".into() }) + } +'@ + New = @' + Ok(mind.receipts()?.len() as u64) +'@ + } + @{ + File = 'crates/huginn-mind/src/admission.rs' + Old = ' let candidate = receipt::candidate(&mind, provenance, &strong_reads, &writes, receipt::head(self)? + 1, now)?;' + New = @' + { + let mut ordinals = self.receipts()?.into_iter().map(|r| r.ordinal).collect::>(); + ordinals.sort_unstable(); + let n = ordinals.len() as u64; + if !ordinals.into_iter().eq(1..=n) { + return Err(MindRefusal::Unavailable { + detail: "receipt ordinals are not 1..=N: found a duplicate or a gap".into(), + }); + } + } + let candidate = receipt::candidate(&mind, provenance, &strong_reads, &writes, receipt::head(self)? + 1, now)?; +'@ + } + ) + } + @{ + Id = 'R4' + Rule = 'Receipt v2 is a new type id, not the old id with an added field: a store carrying a v1-shaped receipt is refused at the type gate.' + Test = 'mind::tests::a_v1_receipt_store_is_refused_at_open' + Edits = @( + @{ + File = 'crates/huginn-mind/src/receipt.rs' + Old = 'pub const RECEIPT_SCHEMA_VERSION: &str = "huginn.mind_commit_receipt.v2";' + New = 'pub const RECEIPT_SCHEMA_VERSION: &str = "huginn.mind_commit_receipt.v1";' + } + @{ + File = 'crates/huginn-mind/src/receipt.rs' + Old = '#[cultcache(type = "huginn.mind_commit_receipt.v2", schema = "HuginnCommitReceipt")]' + New = '#[cultcache(type = "huginn.mind_commit_receipt.v1", schema = "HuginnCommitReceipt")]' + } + ) + } + @{ + Id = 'R4L' + Rule = 'The type gate knows only the current id, not the old one kept beside it for compatibility: a widened opener that still recognises huginn.mind_commit_receipt.v1 as known is the shape F3 warns against (a silent misread of every old receipt''s ordinal as 0), one step short of a full revert.' + Test = 'mind::tests::a_v1_receipt_store_is_refused_at_open' + File = 'crates/huginn-mind/src/mind.rs' + Old = @' +fn is_known_type(type_id: &str) -> bool { + type_id == HuginnMindEpoch::TYPE + || type_id == HuginnCommitReceipt::TYPE + || PipelineKind::ALL.iter().any(|kind| kind.type_id() == type_id) +} +'@ + New = @' +fn is_known_type(type_id: &str) -> bool { + type_id == HuginnMindEpoch::TYPE + || type_id == HuginnCommitReceipt::TYPE + || type_id == "huginn.mind_commit_receipt.v1" + || PipelineKind::ALL.iter().any(|kind| kind.type_id() == type_id) +} +'@ + } + @{ + Id = 'R5' + Rule = 'The epoch gate runs before the type gate, so a store written at a foreign epoch is refused as ForeignEpoch and not 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.' + Test = 'mind::tests::a_store_written_at_the_previous_epoch_is_refused_by_the_epoch_gate' + File = 'crates/huginn-mind/src/mind.rs' + Old = @' + refuse_foreign_epoch(&raw)?; + refuse_foreign_types(&raw)?; +'@ + New = @' + refuse_foreign_types(&raw)?; + refuse_foreign_epoch(&raw)?; +'@ + } + ) +}