diff --git a/pkgs/id/crates/id-events/src/event_store/ingest.rs b/pkgs/id/crates/id-events/src/event_store/ingest.rs index 84b244d9f5..230e1b3006 100644 --- a/pkgs/id/crates/id-events/src/event_store/ingest.rs +++ b/pkgs/id/crates/id-events/src/event_store/ingest.rs @@ -7,8 +7,11 @@ //! rules. Anything that fails is refused as [`Refusal::Malformed`]. //! 2. **Duplicate.** An event whose ID is stored, or is one of its author's fork proof //! headers, changes nothing. -//! 3. **Frozen.** An event above its author's fork point is refused as -//! [`Refusal::Frozen`]. +//! 3. **Fork point.** If the author has a fork proof at the event's own sequence number, +//! the proof keeps the two lowest IDs there: an event that joins them replaces the +//! proof (step 4), and one that displaces neither header is refused as +//! [`Refusal::Frozen`]. An event above the fork point is not refused for sitting +//! there: it goes on to the steps below, and is kept as voided evidence when it links. //! 4. **Fork.** If the author has another event at the same sequence number, stored or //! held, the two are a fork, whatever their backlinks and dependencies. The proof for that //! sequence number holds the two lowest IDs there, and the proofs at higher points stay. The @@ -79,12 +82,16 @@ //! the refused rival is sent again, while the other event is still held. The behaviour is //! pinned by `test_a_rival_refused_by_the_cap_is_seen_only_when_sent_again`. //! -//! # Known limit: a rival refused as frozen +//! # Events above a fork point are kept as evidence //! -//! An event above its author's fork point is refused as frozen when it arrives after the fork. -//! When it arrives before, it is kept as voided. So an `after` hash that names such an event is -//! present in some arrival orders and not in others. The batch property names rivals, but it -//! compares the batch path with per-event ingest in one arrival order, so it holds either way. +//! An event above its author's fork point is decided on its own conflicts, backlink, and +//! dependencies, like any other event. When it links, it is stored as voided evidence: the +//! resolution never applies it, but it is present, so an `after` hash that names it is +//! satisfied in every arrival order — the same state as when it arrived before the fork and +//! the fork voided it. One whose backlink can never link is parked, and one that waits is +//! held, as below the fork point. Only an event at a fork proof's own sequence number that +//! displaces neither of the proof's two headers is refused as frozen: the position holds +//! one event, and the headers are the events present there. //! //! The property tests in `tests/event_store_properties.rs` check the applied state against //! this definition, for every arrival order. @@ -100,7 +107,7 @@ use super::waiting_rows::{Hold, Mirror}; use super::{ ACTIONS, APPLIED, CHAINS, Chain, DEVICE_OPS, EVENTS, EventStore, FORKS, ForkProof, HASHES, PROOF_HEADERS, PROOF_IDS, StoreError, corrupt, decode_stored, lowest_proof, position_key, - store_body, store_chain, store_event, store_fork, + proof_at, store_body, store_chain, store_event, store_fork, }; use super::{Ingest, Refusal}; use id_core::membership::AuthId; @@ -962,26 +969,29 @@ fn decide_in( if let Some(stored) = stored_at(txn, &author, seq)? { conflicts.push(stored); } - if let Some(proof) = read_proof(txn, &author)? { - if seq > proof.seq { + // A proof at the event's own sequence number governs it, wherever that point sits: + // the proof keeps the two lowest IDs there, and an arrival that displaces neither + // header is refused as frozen. It cannot be kept as evidence instead: the position + // holds one event, and the two headers are the events present there. + if let Some(proof) = read_proof_at(txn, &author, seq)? { + conflicts.extend([proof.first.clone(), proof.second.clone(), event.clone()]); + let (first, second) = two_lowest(conflicts)?; + if first.id == proof.first.id && second.id == proof.second.id { return Ok(Decision::Refuse(Refusal::Frozen)); } - if seq == proof.seq { - // Another event at the fork point. The proof keeps the two lowest IDs there. - conflicts.extend([proof.first.clone(), proof.second.clone(), event.clone()]); - let (first, second) = two_lowest(conflicts)?; - if first.id == proof.first.id && second.id == proof.second.id { - return Ok(Decision::Refuse(Refusal::Frozen)); - } - store_fork(txn, &author, seq, &first, &second)?; - return Ok(Decision::Fork { - seq, - proof: [first.id, second.id], - }); - } + store_fork(txn, &author, seq, &first, &second)?; + return Ok(Decision::Fork { + seq, + proof: [first.id, second.id], + }); } + // Above the author's fork point the event is not refused for sitting there. It is + // decided on its own conflicts, backlink, and dependencies below, and kept as voided + // evidence when it links, so an `after` hash that names it is present in every + // arrival order — the state it would be in had it arrived before the fork. The + // resolution never applies it: it sits at or above the fork point. if !conflicts.is_empty() { - // The first conflict at this sequence number, or one below the fork point. + // The first conflict at this sequence number, at any point of the chain. conflicts.push(event.clone()); let (first, second) = two_lowest(conflicts)?; store_fork(txn, &author, seq, &first, &second)?; @@ -1226,6 +1236,15 @@ fn read_proof(txn: &WriteTransaction, author: &AuthorKey) -> Result Result, StoreError> { + proof_at(&txn.open_table(FORKS)?, author, seq) +} + /// The stored event at `author`'s `seq`, applied or voided, if there is one. fn stored_at( txn: &WriteTransaction, @@ -1915,7 +1934,7 @@ mod tests { } #[test] - fn test_a_frozen_chain_refuses_its_later_events_and_changes_nothing() { + fn test_a_frozen_chain_keeps_its_later_events_as_voided_evidence() { let (_dir, mut store) = open(); let signer = key(4); let who = author(&signer); @@ -1927,11 +1946,16 @@ mod tests { Ingest::Fork { seq: 1, .. } )); let before = store.chain(&who).unwrap(); + // The later event arrives after the fork. It is kept as voided evidence: stored, + // never applied, and the chain row is unchanged. assert_eq!( ingest(&mut store, &events[2]), - Ingest::Refused(Refusal::Frozen) + Ingest::Voided { + id: events[2].id, + released: vec![], + } ); - assert!(store.event(&who, 2).unwrap().is_none()); + assert_eq!(store.event(&who, 2).unwrap(), Some(events[2].clone())); assert_eq!(store.chain(&who).unwrap(), before); store.check_invariants().unwrap(); } @@ -2298,6 +2322,100 @@ mod tests { assert_eq!(store.chain(&author(&y)).unwrap().unwrap().next_seq, 1); } + #[test] + fn test_a_dependent_on_a_post_fork_event_resolves_in_either_arrival_order() { + // The order matrix of #12050: one signed event set — a chain through sequence 2, + // a rival at sequence 1, and another author's event whose `after` names sequence + // 2 — delivered fork-last and fork-first, per event and as a batch. The dependent + // event's disposition and the presence of the event it names must not depend on + // the order: the sequence-2 event is present in both orders and applied in + // neither final state, and the dependent applies in both. + let x = key(51); + let y = key(52); + let x_events = chain_of(&x, 3); + let rival = event(&x, 1, Some(x_events[0].id), Vec::new(), "rival"); + let dependent = event(&y, 0, None, vec![x_events[2].id], "y"); + + let assert_final_state = |store: &EventStore| { + assert_eq!( + store.event(&author(&x), 2).unwrap(), + Some(x_events[2].clone()), + "the sequence-2 event is present" + ); + assert_eq!( + store.chain(&author(&x)).unwrap(), + Some(Chain { + next_seq: 1, + head: Some(x_events[0].id), + frozen: true, + }) + ); + assert_eq!(store.chain(&author(&y)).unwrap().unwrap().next_seq, 1); + store.check_invariants().unwrap(); + }; + + // Fork last, per event: the sequence-2 event applies, then the fork voids it. + { + let (_dir, mut store) = open(); + ingest_all(&mut store, &x_events); + assert!(matches!( + ingest(&mut store, &rival), + Ingest::Fork { seq: 1, .. } + )); + assert_eq!( + ingest(&mut store, &dependent), + Ingest::Accepted { + id: dependent.id, + released: vec![], + } + ); + assert_final_state(&store); + } + // Fork first, per event: the sequence-2 event arrives above the fork point and + // is kept as voided evidence, so the dependent still applies. + { + let (_dir, mut store) = open(); + ingest_all(&mut store, &x_events[..2]); + assert!(matches!( + ingest(&mut store, &rival), + Ingest::Fork { seq: 1, .. } + )); + assert_eq!( + ingest(&mut store, &x_events[2]), + Ingest::Voided { + id: x_events[2].id, + released: vec![], + } + ); + assert_eq!( + ingest(&mut store, &dependent), + Ingest::Accepted { + id: dependent.id, + released: vec![], + } + ); + assert_final_state(&store); + } + // Both orders again, as one batch each. + for order in [ + vec![&x_events[0], &x_events[1], &x_events[2], &rival, &dependent], + vec![&x_events[0], &x_events[1], &rival, &x_events[2], &dependent], + ] { + let (_dir, mut store) = open(); + let batch: Vec> = order.iter().map(|event| event.bytes.clone()).collect(); + let outcomes = store.ingest_batch(&batch, 0).unwrap(); + assert_eq!( + outcomes.last(), + Some(&Ingest::Accepted { + id: dependent.id, + released: vec![], + }), + "the dependent applies in the batch order {outcomes:?}" + ); + assert_final_state(&store); + } + } + #[test] fn test_a_backlink_that_is_not_the_applied_head_is_parked_and_not_stored() { let (_dir, mut store) = open(); @@ -2327,8 +2445,8 @@ mod tests { // applied H1 by the first author, so its arrival forks that chain, and H2 becomes a proof // header: present, but never stored. R is released by that. It cannot link to H2, so it // must park. Holding it to wait for H2 would wait on a dependency that is already present. - // R is not the forking author's event: an event above the fork point is refused as frozen - // before the backlink is read, so only another author's backlink reaches this path. + // The forking author's own event above the fork point reaches this path too: it is + // decided on its backlink, not refused for sitting above the point. let (_dir, mut store) = open(); let forker = key(15); let other = key(16); @@ -2374,18 +2492,32 @@ mod tests { #[test] fn test_a_frozen_refusal_gives_the_frozen_reason() { + // The frozen refusal is now only for an event at the fork point itself that + // displaces neither of the proof's two headers: the position holds one event, + // and the headers are the events present there. Three events at sequence 1, + // taken in ID order: the first is stored, the second forks the chain and the + // proof holds the two of them, and the third displaces neither. let (_dir, mut store) = open(); let signer = key(4); - let events = chain_of(&signer, 3); - ingest_all(&mut store, &events[..2]); - let rival = event(&signer, 1, Some(events[0].id), Vec::new(), "rival"); + let events = chain_of(&signer, 1); + ingest_all(&mut store, &events); + let mut at_point: Vec = ["one", "two", "three"] + .into_iter() + .map(|kind| event(&signer, 1, Some(events[0].id), Vec::new(), kind)) + .collect(); + at_point.sort_by(|a, b| a.id.as_bytes().cmp(b.id.as_bytes())); assert!(matches!( - ingest(&mut store, &rival), + ingest(&mut store, &at_point[0]), + Ingest::Accepted { .. } + )); + assert!(matches!( + ingest(&mut store, &at_point[1]), Ingest::Fork { seq: 1, .. } )); - let result = ingest(&mut store, &events[2]); + let result = ingest(&mut store, &at_point[2]); assert_eq!(result, Ingest::Refused(Refusal::Frozen)); assert_eq!(result.reason(), Some(Reason::Frozen)); + store.check_invariants().unwrap(); } #[test] @@ -3784,7 +3916,9 @@ mod tests { store.is_waiting(&waits.id), "the event waits across the restart" ); - // Its dependency arrives, so it is released. Its chain is frozen at 1, so it is refused. + // Its dependency arrives, so it is released. Its chain is frozen at 1, so it is + // kept as voided evidence rather than refused: its waiting row goes, and the + // event itself is stored, unapplied. assert_eq!( ingest(&mut store, &y0), Ingest::Accepted { @@ -3794,6 +3928,15 @@ mod tests { ); assert!(!store.is_waiting(&waits.id)); assert!(store.waiting_ids().unwrap().is_empty()); + assert_eq!(store.event(&author(&x), 2).unwrap(), Some(waits.clone())); + assert_eq!( + store.chain(&author(&x)).unwrap(), + Some(Chain { + next_seq: 1, + head: Some(x_events[0].id), + frozen: true, + }) + ); store.check_invariants().unwrap(); } diff --git a/pkgs/id/crates/id-events/src/event_store/mod.rs b/pkgs/id/crates/id-events/src/event_store/mod.rs index b6ed534d06..99d9f7cf27 100644 --- a/pkgs/id/crates/id-events/src/event_store/mod.rs +++ b/pkgs/id/crates/id-events/src/event_store/mod.rs @@ -1489,6 +1489,17 @@ pub(crate) fn store_fork( Ok(()) } +/// The fork proof at `author`'s `seq`, if the author has forked there. A proof above the +/// lowest point still governs its own sequence number: it keeps the two lowest IDs there. +pub(super) fn proof_at( + forks: &impl ReadableTable<&'static [u8], &'static [u8]>, + author: &AuthorKey, + seq: SeqNum, +) -> Result, StoreError> { + let row = forks.get(position_key(author, seq).as_slice())?; + row.map(|row| decode_proof(row.value())).transpose() +} + /// The fork proof at `author`'s lowest fork point, if the author has forked. That point freezes /// the chain. The rows are keyed by position, so the first row of the author's range is the lowest. pub(super) fn lowest_proof( diff --git a/pkgs/id/crates/id-events/src/event_store/sync.rs b/pkgs/id/crates/id-events/src/event_store/sync.rs index f139592992..fdd6f20b69 100644 --- a/pkgs/id/crates/id-events/src/event_store/sync.rs +++ b/pkgs/id/crates/id-events/src/event_store/sync.rs @@ -1374,11 +1374,11 @@ mod tests { /// not store (Codex finding on PR 2214: the tally had a voided count the outcome dropped). /// /// The shape matters. An event above its author's fork point that arrives *after* the - /// fork is refused as frozen (`ingest.rs`, "Known limit: a rival refused as frozen"), so - /// it is counted as refused, and the voided count stays zero: voided labels an event the - /// store keeps without applying, not an arrival it turns away. + /// fork is kept as voided evidence (#12050; `ingest.rs`, "Events above a fork point are + /// kept as evidence"), so it is counted as voided, and the refused count stays zero: + /// voided labels an event the store keeps without applying. #[tokio::test(flavor = "multi_thread")] - async fn test_a_range_session_counts_frozen_arrivals_as_refused() { + async fn test_a_range_session_counts_post_fork_arrivals_as_voided() { let (_da, mut a) = open(); let (_db, mut b) = open(); let events = chain_of(1, 5, b"x"); @@ -1422,16 +1422,21 @@ mod tests { assert_eq!(da.sent, 2, "events 4 and 5 are missing on B's side"); assert_eq!( db.received, 2, - "both above the fork point are received and turned away: {db:?}" + "both above the fork point are received and kept: {db:?}" ); assert_eq!( - db.refused, 2, - "events 4 and 5 arrive above the fork point, so they are frozen: {db:?}" + db.refused, 0, + "no arrival is refused: the fork no longer turns its later events away: {db:?}" ); - assert_eq!(db.accepted, 0, "a frozen arrival is not accepted: {db:?}"); + assert_eq!(db.accepted, 0, "a post-fork arrival is not applied: {db:?}"); assert_eq!( - db.voided, 0, - "voided counts stored-but-unapplied events, not refused arrivals: {db:?}" + db.voided, 2, + "events 4 and 5 arrive above the fork point, so they are kept as voided evidence: {db:?}" + ); + assert!( + b.event_by_id(&events[3].id).unwrap().is_some() + && !b.event_applied(&events[3].id).unwrap(), + "the kept arrival is present on B but does not apply" ); } @@ -1440,9 +1445,9 @@ mod tests { /// that names a voided group operation in its `after` set: the membership /// layer voids an event that names a voided event when its author is not a /// member of the group at that position (resolve rule 3), so the receiver - /// keeps the event without applying it. This is the stored-but-unapplied - /// shape the frozen-arrival test above cannot reach: a frozen arrival is - /// turned away, while this one is kept. + /// keeps the event without applying it. This is a second stored-but-unapplied + /// shape, beside the post-fork one above: there the fork voids the arrival, + /// here the membership layer does. #[tokio::test(flavor = "multi_thread")] async fn test_a_range_session_counts_a_stored_but_unapplied_arrival_as_voided() { use id_core::membership::AuthId; diff --git a/pkgs/id/tests/crash/store.rs b/pkgs/id/tests/crash/store.rs index faedb138dd..4cb367d14e 100644 --- a/pkgs/id/tests/crash/store.rs +++ b/pkgs/id/tests/crash/store.rs @@ -19,7 +19,7 @@ use std::io; use std::sync::{Arc, Mutex, MutexGuard}; use id::chain::{self, ChainExt, sign}; -use id::event_store::{EventStore, FILE_NAME, Ingest, Refusal, Storage}; +use id::event_store::{EventStore, FILE_NAME, Ingest, Storage}; use id::waiting::WaitingLimits; use p2panda_core::{Hash, SigningKey}; use redb::{Database, DatabaseError, StorageBackend, StorageError, TableDefinition}; @@ -420,8 +420,9 @@ fn creation_in_place_control_fails_at_some_crash_point() { } /// The deliveries the ingest sweep makes after creation: a wait that a later event releases, an -/// after hash on another author's event, a fork, an event refused as frozen, two repeats, and the -/// waiting events that stay held to the end: a fork between two held events, and a parked event. +/// after hash on another author's event, a fork, an event kept as voided evidence above the fork +/// point, two repeats, and the waiting events that stay held to the end: a fork between two held +/// events, and a parked event. fn workload() -> Vec> { let author = SigningKey::from_bytes(&[21; 32]); let other = SigningKey::from_bytes(&[22; 32]); @@ -611,8 +612,8 @@ fn clean_ingest_run_has_every_outcome_and_survives_its_reopen() { "a2 forks" ); assert!( - matches!(outcomes[5], Ingest::Refused(Refusal::Frozen)), - "a3 is refused after the fork" + matches!(outcomes[5], Ingest::Voided { .. }), + "a3 is kept as voided evidence after the fork" ); assert!( matches!(outcomes[6], Ingest::Duplicate { .. }), diff --git a/pkgs/id/tests/event_store_properties.rs b/pkgs/id/tests/event_store_properties.rs index a7cbcf8b25..35cfd40d83 100644 --- a/pkgs/id/tests/event_store_properties.rs +++ b/pkgs/id/tests/event_store_properties.rs @@ -165,7 +165,8 @@ type ForkPlan = BTreeMap; /// The events a later event may name: those that are present in every delivery order. An /// author with a fork is referable up to its fork point. At the fork point it is referable only /// when there are two events there, which the fork proof holds. Above the fork point, an event -/// is refused as frozen in some orders and kept in others, so no event names it. +/// is kept as voided evidence when it links, but one whose backlink names a proof header is +/// parked instead, so it is not present in every order and no event names it. fn referable(events: &[Event], plan: &ForkPlan) -> Vec { events .iter()