diff --git a/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md b/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md index 13962df8fd..5a19657bc6 100644 --- a/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md +++ b/doc/2026-10-12T14-33-36Z_phase_4_groups_encryption/2026-10-12T14-33-36Z_phase_4_groups_encryption.md @@ -7,21 +7,21 @@ ## Steps -| Step | Track | Status | Commits | Tests | Notes | -| ------------------------------------- | ------- | ------ | ------------------ | ------------------------------------- | ----------------------------------------- | -| P4.1 DataScheme adapter | adapter | done | a630a440 | | blocks the rest | -| P4.2 Our DGM and the from_join fork | adapter | done | e57c1223 | | | -| P4.3 from_join withholding rule | adapter | done | daa4f200 | | | -| P4.4 Scheme v1 | scheme | done | d22f6987, 3b671bb4 | | | -| P4.5 recent:N and full | history | done | 6b2a9005, 67207add | | | -| P4.6 Lazy full history | history | done | 25d7d814 | | | -| P4.7 Heads rule | heads | done | 6001cfdd, e1fee2ce | 8 new (4 heads, 4 concurrency) | cap 32, refusal not merge; open epoch gap | -| P4.8 Rotation policy and PCS recovery | warn | done | 205a5483 | 4 rotation and recovery tests | `Session::recover`; no CLI command yet | -| P4.9 Warnings | warn | done | 4b82eff2 | 11 warning tests (9 unit, 2 property) | pure evaluator; not yet wired into serve | -| P4.10 scheme none notice | warn | done | a95c52ae | 4 notice tests | function only; no UI yet | -| P4.11 DataScheme cost measurement | warn | done | 2a3de9a9 | 1 smoke test; benchmark ignored | numbers below | -| P4.12 Welcome chunking | history | done | c38e6a39 | | | -| P4.13 Roster follows the group fold | scheme | done | a39cc834 | 11 scheme tests (incl. fold property) | mismatch poisons the session | +| Step | Track | Status | Commits | Tests | Notes | +| ------------------------------------- | ------- | ------ | ------------------ | ------------------------------------- | -------------------------------------------------- | +| P4.1 DataScheme adapter | adapter | done | a630a440 | | blocks the rest | +| P4.2 Our DGM and the from_join fork | adapter | done | e57c1223 | | | +| P4.3 from_join withholding rule | adapter | done | daa4f200 | | | +| P4.4 Scheme v1 | scheme | done | d22f6987, 3b671bb4 | | | +| P4.5 recent:N and full | history | done | 6b2a9005, 67207add | | | +| P4.6 Lazy full history | history | done | 25d7d814 | | | +| P4.7 Heads rule | heads | done | 6001cfdd, e1fee2ce | 8 new (4 heads, 4 concurrency) | cap 32, merge above the cap (2979); open epoch gap | +| P4.8 Rotation policy and PCS recovery | warn | done | 205a5483 | 4 rotation and recovery tests | `Session::recover`; no CLI command yet | +| P4.9 Warnings | warn | done | 4b82eff2 | 11 warning tests (9 unit, 2 property) | pure evaluator; not yet wired into serve | +| P4.10 scheme none notice | warn | done | a95c52ae | 4 notice tests | function only; no UI yet | +| P4.11 DataScheme cost measurement | warn | done | 2a3de9a9 | 1 smoke test; benchmark ignored | numbers below | +| P4.12 Welcome chunking | history | done | c38e6a39 | | | +| P4.13 Roster follows the group fold | scheme | done | a39cc834 | 11 scheme tests (incl. fold property) | mismatch poisons the session | ## Decisions @@ -86,25 +86,25 @@ Commits on `p4-heads` (not pushed): - A control message names the heads: the delivered or published control messages that no delivered or published control message names. It also names its author's own latest control message, even when a later message covers it. Application messages name the same list. - At most 32 parents, own latest included. A publish that would name more is refused with `SchemeError::TooManyParents { count, cap }`. The check runs before the crate call, for update, send, add, remove and recovery. A refusal leaves the epoch and the roster as they were, and nothing is dropped from the parents. -- The merge in the plan (P4.7: merge when the heads would exceed the cap) is not built. A group with more than 32 heads cannot publish until a member sees fewer of them. This is open. +- The merge in the plan (P4.7: merge when the heads would exceed the cap) is built (queue task 2979). While a change's parents would exceed 32, the session first publishes update merges: each is an update naming up to 32 heads, own latest first, and the heads it leaves stay heads. Each merge turns 32 parents into one, so the count falls by at least 31 and the loop ends. The change that follows names at most the cap, including the last merge and the heads the merge left. Every `Session` change that can merge returns all the messages to broadcast, merges first: a member without the merge cannot deliver the change that names it. `TooManyParents` remains as the orderer's guard for a publish that skipped the merge; it is not reachable through the `Session` API. - The rule it replaces named the latest control message of each author. That list grew with the number of authors. At 33 authors it went past 32 with no check, and it named messages that a later head already covered. ### Findings - The red test (`test_two_concurrent_adds_converge_for_a_third_member`) had two admins add members 4 and 5 from the same view, and member 1 ordered the two adds in either order. It failed before the fix. A joiner that received the other admin's add before its own welcome applied that add to an empty roster, and its roster lacked a member. The orderer now delivers the welcome after its own past and before any other pending message. A welcome that is not yet ready holds delivery. -- Open: an update made without knowing a concurrent add never reaches the joiner. The joiner then holds one epoch fewer than the members, and messages under that epoch are withheld from it. `test_open_a_joiner_misses_an_update_made_without_knowing_it` pins this. The heads rule does not fix it, since the update names nothing about the add. The options are a refusal, or a fetch of the missing secret through lazy history (P4.6). This needs a decision. +- Resolved: an update made without knowing a concurrent add never reaches the joiner by delivery. The joiner then holds one epoch fewer than the members, and messages under that epoch are withheld from it. `test_open_a_joiner_misses_an_update_made_without_knowing_it` pins this. The heads rule does not fix it, since the update names nothing about the add. The decision (issue #189) is lazy history (P4.6): the joiner fetches the missing epoch through `Session::fetch_history`. That fetch runs only when a caller supplies a transport -- inside `pkgs/id` the only call sites are the history tests -- so a caller that receives `Received::Withheld` must drive it; nothing in this crate fetches on its own. - In the two-add case, every member agrees on the latest epoch and on the epoch set. ### Properties and tests - `test_concurrent_updates_and_sends_converge` and `test_a_concurrent_add_and_sends_converge`, 16 cases each. Two or three admins each make one change from the group as it was: an update, a send, or the add of member 4. Each member then hears the changes it did not make, one at a time, in its own shuffled order, with the members taking turns. At the end every member has the same roster and the same epoch set, and reads every send by another member. A local run at 128 cases passed. - A property that mixed updates, sends and an add found the open gap above. The add and the updates are therefore in separate properties. -- Heads: `test_a_message_names_the_heads_and_not_every_authors_latest` (red before the change), `test_an_author_names_its_own_latest_even_when_a_later_message_covers_it`, `test_a_message_may_name_32_parents`, and `test_a_message_naming_33_parents_is_refused_and_the_state_is_kept` (red before the change). The last one checks that an update and a send are both refused at 33 parents, and that the epoch and the roster are unchanged. -- Results: the encryption module has 73 passed and 1 ignored (the P4.11 benchmark). The full `cargo test --lib` has 1172 passed, 0 failed and 4 ignored. Clippy reports nothing in `src/encryption`. +- Heads: `test_a_message_names_the_heads_and_not_every_authors_latest` (red before the change), `test_an_author_names_its_own_latest_even_when_a_later_message_covers_it`, `test_a_message_may_name_32_parents`, and `test_a_group_above_32_heads_merges_and_publishes_again`. The last one was the refusal test at 33 parents; it now checks the merge: a publish above the cap returns a merge naming 32 of the 33 parents and the change that follows, the left head and the merge are both named by that change, and every member of the 33 ends on the same roster and epoch set and reads a message sent after the merge. +- A change refused above the cap lost its merges (found in review of this change): `add_with_history`, `add_from_join` and `remove` merged the heads before the change step checked the view policy, so a policy refusal dropped merge envelopes the session had already absorbed, and a later publish named a merge nobody received. The policy is now checked before the merge in all three. `test_a_refused_change_above_the_cap_loses_no_merge` pins it: red without the reorder, green with it. +- Results after the merge (queue task 2979): the encryption module has 72 passed and 1 ignored (the P4.11 benchmark). The count fell by one because the 33-parent refusal test became the merge test, then rose by one for the refusal-above-the-cap test below. The full `cargo test --lib` has 1172 passed, 0 failed and 4 ignored. Clippy reports nothing in `src/encryption`. ### Open -- The merge rule for more than 32 heads (above). - The open epoch gap for a concurrent update and add (above). - The S10 scenarios at 40 members are not reproduced. Concurrency is tested with 2 or 3 admins, and 33 members only for the cap. Storms and partitions at scale are open. - Concurrent removals, and a removal concurrent with an update, are not in the properties. @@ -122,4 +122,4 @@ Commits on `p4-heads` (not pushed): - The failure is `serve_tests::test_world_module_shared_over_iroh_and_web_presentations`: the server stalls after `world: records document ready` and never prints `node:`. It fails the same way on the phase-3 tip (3a51589d), so phase 4 did not cause it. Issue #190. - One earlier run failed `test_an_interrupted_session_restarts_without_duplicates` under load and passed alone three times. Issue #188. - Not run in this pass: `just crash-gate` and the nix checks. -- Open from the tracks: the heads merge for groups above 32 heads (issue #189), the joiner that misses an update made without knowing a concurrent add (issue #189), the held-message cap (issue #186), and stalled delivery on missing pre-join controls (issue #187). +- Open from the tracks: the joiner that misses an update made without knowing a concurrent add (issue #189, resolved by lazy history in P4.6), the held-message cap (issue #186), and stalled delivery on missing pre-join controls (issue #187). diff --git a/pkgs/id/src/encryption/ordering.rs b/pkgs/id/src/encryption/ordering.rs index 955ba1da35..70858a3170 100644 --- a/pkgs/id/src/encryption/ordering.rs +++ b/pkgs/id/src/encryption/ordering.rs @@ -3,9 +3,11 @@ //! The crate's orderer (`MessageOrderer`) is test-only, so the adapter brings its own with the same //! rules. A message names the heads it can see: the latest control messages of the concurrent //! branches. It always names its author's own latest control message, and it names at most -//! [`MAX_PARENTS`]. A publish that would name more is refused (P4.7). A message is delivered once -//! every message it names is delivered. Nothing is delivered before the device is welcomed: a create -//! or a welcome opens delivery, and earlier messages wait in the queue. +//! [`MAX_PARENTS`]. A publish that would name more is refused, unless the session asked for a merge: +//! then the list is cut to [`MAX_PARENTS`], own latest kept, so a group above the cap can publish +//! again (P4.7). A message is delivered once every message it names is delivered. Nothing is +//! delivered before the device is welcomed: a create or a welcome opens delivery, and earlier +//! messages wait in the queue. //! //! Application messages are never named by other messages, so the adapter may leave one out //! without stalling anything. [`super::scheme`] does that for messages whose group secret the @@ -25,7 +27,8 @@ use thiserror::Error; use super::roster::Roster; /// The most parents a message may name (P4.7, N22). A publish that would name more is refused, and -/// nothing is dropped from the list. +/// nothing is dropped from the list, unless it is a merge: then up to this many are named and the +/// rest stay heads for a later merge. pub const MAX_PARENTS: usize = 32; /// One published group message: a control message with its direct messages, or an application @@ -182,6 +185,7 @@ impl Orderer { deliverable: VecDeque::new(), welcomed: false, welcome: None, + merge_next: false, } } } @@ -212,9 +216,19 @@ pub struct OrdererState { /// The create or welcome that opened delivery. It is delivered before any pending message that /// is not in its own past (P4.7). welcome: Option, + /// Set by the session just before a merge update, so that publish cuts the parent list to + /// [`MAX_PARENTS`] instead of refusing (P4.7). + #[serde(default)] + merge_next: bool, } impl OrdererState { + /// Asks the next publish to be a merge: it names up to [`MAX_PARENTS`] of the heads instead of + /// all of them, so the ones it leaves stay heads and the count falls (P4.7). + pub fn begin_merge(&mut self) { + self.merge_next = true; + } + /// The parents a message published now names: our own latest control message, then the heads. pub fn parent_list(&self) -> Vec { let mut parents: Vec = self.own.into_iter().collect(); @@ -259,14 +273,20 @@ impl OrdererState { } /// Publishes our own message. It names the parents, and it is ready. A message whose parents - /// would be more than [`MAX_PARENTS`] is refused, and no sequence number is used. + /// would be more than [`MAX_PARENTS`] is refused and no sequence number is used, unless it is a + /// merge: then it names the first [`MAX_PARENTS`] (own latest first) and the rest stay heads + /// (P4.7). fn publish(&mut self, content: Content) -> Result { - let parents = self.parent_list(); + let merge = std::mem::take(&mut self.merge_next); + let mut parents = self.parent_list(); if parents.len() > MAX_PARENTS { - return Err(OrdererError::TooManyParents { - count: parents.len(), - cap: MAX_PARENTS, - }); + if !merge { + return Err(OrdererError::TooManyParents { + count: parents.len(), + cap: MAX_PARENTS, + }); + } + parents.truncate(MAX_PARENTS); } let seq = self.next_seq; self.next_seq += 1; diff --git a/pkgs/id/src/encryption/scheme.rs b/pkgs/id/src/encryption/scheme.rs index 9634350a4f..8e898d771a 100644 --- a/pkgs/id/src/encryption/scheme.rs +++ b/pkgs/id/src/encryption/scheme.rs @@ -91,8 +91,9 @@ pub enum Received { /// What the recovery procedure (N8) did. The CLI prints [`RECOVERY_STEPS`] next to it. #[derive(Clone, Debug)] pub struct Recovery { - /// The removal. It rotates the epoch, so the device no longer holds the new secrets. - pub removal: Envelope, + /// The removal, after any merge updates the heads needed first. It rotates the epoch, so the + /// device no longer holds the new secrets. + pub removal: Vec, /// The re-add: the welcome and the immediate update, in delivery order (P4.3). pub readd: Vec, /// The epoch before the procedure. @@ -272,7 +273,7 @@ impl Session { view: &GroupView, added: Key, rng: &Rng, - ) -> Result { + ) -> Result, SchemeError> { self.add_with_history(view, added, HistoryMode::Full, rng) } @@ -281,36 +282,45 @@ impl Session { /// /// The bundle is cut here, before `Dcgka::add`, so the crate never sees a secret outside the /// window. The joiner then holds exactly the window and refuses older messages. + /// + /// Returns every message to broadcast: any merge updates first, then the add (P4.7). pub fn add_with_history( &mut self, view: &GroupView, added: Key, mode: HistoryMode, rng: &Rng, - ) -> Result { + ) -> Result, SchemeError> { self.ensure_welcomed()?; if !view.members.contains_key(&added) { return Err(SchemeError::NotInModel(short(added))); } let added_key = member_of(added)?; + // The policy is checked before the merge, not only inside the change step: a refusal after + // the merge would drop merge envelopes the session has already absorbed, and a later + // publish would name a merge nobody received (P4.7). + self.check_policy(view)?; + let mut messages = self.merge_heads(rng)?; // The bundle is cut from the state before the change takes it, so the welcome carries the // window the mode allows and the roster check still runs on the fold's view. let bundle = { let y = self.state.as_ref().ok_or(SchemeError::Poisoned)?; mode.welcome_bundle(&y.secrets) }; - self.change(view, |mut y| { + messages.push(self.change(view, |mut y| { let (dcgka, output) = Dcgka::add(y.dcgka, added_key, &bundle, rng)?; y.dcgka = dcgka; publish(y, output) - }) + })?); + Ok(messages) } /// Adds `added` by a join: a welcome that carries no earlier secret, then an immediate update. /// /// The joiner learns nothing the group had before the add, so it cannot read messages sent /// before its join. The update gives the group a secret the joiner does learn, and it must be - /// delivered too. Returns the add and the update, in the order they are delivered. + /// delivered too. Returns the add and the update, in the order they are delivered, after any + /// merge updates the heads needed first (P4.7). pub fn add_from_join( &mut self, view: &GroupView, @@ -322,31 +332,46 @@ impl Session { return Err(SchemeError::NotInModel(short(added))); } let added_key = member_of(added)?; - let add = self.change(view, |y| EncryptionGroup::add_from_join(y, added_key, rng))?; - let update = self.change(view, |y| EncryptionGroup::update(y, rng))?; - Ok(vec![add, update]) + // The policy is checked before the merge, not only inside the change step: a refusal after + // the merge would drop merge envelopes the session has already absorbed, and a later + // publish would name a merge nobody received (P4.7). + self.check_policy(view)?; + let mut messages = self.merge_heads(rng)?; + messages.push(self.change(view, |y| EncryptionGroup::add_from_join(y, added_key, rng))?); + messages.push(self.change(view, |y| EncryptionGroup::update(y, rng))?); + Ok(messages) } /// Removes `removed`, which `view` must no longer list. The removal rotates the epoch. + /// + /// Returns every message to broadcast: any merge updates first, then the removal (P4.7). pub fn remove( &mut self, view: &GroupView, removed: Key, rng: &Rng, - ) -> Result { + ) -> Result, SchemeError> { self.ensure_welcomed()?; if view.members.contains_key(&removed) { return Err(SchemeError::StillInModel(short(removed))); } let removed_key = member_of(removed)?; - self.change(view, |y| EncryptionGroup::remove(y, removed_key, rng)) + // The policy is checked before the merge, for the reason the add paths give (P4.7). + self.check_policy(view)?; + let mut messages = self.merge_heads(rng)?; + messages.push(self.change(view, |y| EncryptionGroup::remove(y, removed_key, rng))?); + Ok(messages) } /// Rotates the epoch by giving every current member a new secret. - pub fn update(&mut self, rng: &Rng) -> Result { + /// + /// Returns every message to broadcast: the merge updates the heads needed first, if any, then + /// the update itself (P4.7). + pub fn update(&mut self, rng: &Rng) -> Result, SchemeError> { self.ensure_welcomed()?; - self.ensure_parents_fit()?; - self.step(|y| EncryptionGroup::update(y, rng)) + let mut messages = self.merge_heads(rng)?; + messages.push(self.step(|y| EncryptionGroup::update(y, rng))?); + Ok(messages) } /// Recovers a device whose key is suspect: removes `removed`, then adds `added` back by a join. @@ -378,10 +403,14 @@ impl Session { } /// Encrypts `plaintext` under the current epoch. - pub fn send(&mut self, plaintext: &[u8], rng: &Rng) -> Result { + /// + /// Returns every message to broadcast, in order: the merge updates the heads needed first, if + /// any, then the application message (P4.7). + pub fn send(&mut self, plaintext: &[u8], rng: &Rng) -> Result, SchemeError> { self.ensure_welcomed()?; - self.ensure_parents_fit()?; - self.step(|y| EncryptionGroup::send(y, plaintext, rng)) + let mut messages = self.merge_heads(rng)?; + messages.push(self.step(|y| EncryptionGroup::send(y, plaintext, rng))?); + Ok(messages) } /// Handles a message from the group. @@ -555,9 +584,34 @@ impl Session { .collect()) } - /// Refuses a publish that would name more than [`MAX_PARENTS`] parents (P4.7). It runs before the - /// crate call, since a call that fails inside the orderer consumes the state and poisons the - /// session. Nothing is dropped from the parents: the change is refused. + /// Publishes the merge updates the heads need before a change can name them all (P4.7). + /// + /// A merge is an update that names up to [`MAX_PARENTS`] heads, so the heads it leaves stay + /// heads and the parent count falls by at least 31. A count above the cap therefore comes down + /// in a bounded number of merges, and the change that follows names at most the cap. Nothing is + /// merged while the device is not welcomed, since there is no head to merge, and nothing is + /// merged when the heads already fit. + /// + /// The returned messages must reach the group before the change that follows: the change names + /// the last merge as its author's latest, so a member that lacks it cannot deliver the change. + fn merge_heads(&mut self, rng: &Rng) -> Result, SchemeError> { + let mut merged = Vec::new(); + loop { + let y = self.state.as_ref().ok_or(SchemeError::Poisoned)?; + if !y.is_welcomed || y.orderer.parent_count() <= MAX_PARENTS { + return Ok(merged); + } + let message = self.step(|mut y| { + y.orderer.begin_merge(); + EncryptionGroup::update(y, rng) + })?; + merged.push(message); + } + } + + /// Refuses a change whose parents still exceed [`MAX_PARENTS`] after the merges (P4.7). It runs + /// before the crate call, since a call that fails inside the orderer consumes the state and + /// poisons the session. Nothing is dropped from the parents: the change is refused. fn ensure_parents_fit(&self) -> Result<(), SchemeError> { let y = self.state.as_ref().ok_or(SchemeError::Poisoned)?; let count = y.orderer.parent_count(); diff --git a/pkgs/id/src/encryption/tests.rs b/pkgs/id/src/encryption/tests.rs index f95ea7ef9d..2fb844393a 100644 --- a/pkgs/id/src/encryption/tests.rs +++ b/pkgs/id/src/encryption/tests.rs @@ -20,6 +20,7 @@ use proptest::prelude::*; use proptest::test_runner::TestCaseResult; use super::history::{HISTORY_WAIT, HistoryAnswer, HistoryError, ask_member}; +use super::ordering::MAX_PARENTS; use super::welcome::{CHUNK_HEADER_BYTES, Reassembly, WelcomeError, split}; use super::*; use crate::groups::{ @@ -193,6 +194,13 @@ impl Cast { .expect("create") } + /// The only message a change returns, when it needed no merge. A change that needed a merge + /// returns the merges too, and a test that expects them reads the session directly (P4.7). + fn alone(mut messages: Vec) -> Envelope { + assert_eq!(messages.len(), 1, "the change needed no merge"); + messages.pop().expect("a message") + } + fn add(&mut self, by: u8, who: u8) -> Envelope { let view = self.log( by, @@ -201,11 +209,13 @@ impl Cast { role: Role::Admin, }), ); - self.sessions + let messages = self + .sessions .get_mut(&id(by)) .expect("session") .add(&view, id(who), &self.rng) - .expect("add") + .expect("add"); + Self::alone(messages) } fn remove(&mut self, by: u8, who: u8) -> Envelope { @@ -216,11 +226,13 @@ impl Cast { successor: None, }), ); - self.sessions + let messages = self + .sessions .get_mut(&id(by)) .expect("session") .remove(&view, id(who), &self.rng) - .expect("remove") + .expect("remove"); + Self::alone(messages) } /// An add that welcomes the joiner with the secrets `mode` allows. @@ -232,11 +244,13 @@ impl Cast { role: Role::Admin, }), ); - self.sessions + let messages = self + .sessions .get_mut(&id(by)) .expect("session") .add_with_history(&view, id(who), mode, &self.rng) - .expect("add_with_history") + .expect("add_with_history"); + Self::alone(messages) } /// A join through `add_from_join`: the add, then the immediate update. @@ -256,19 +270,23 @@ impl Cast { } fn update(&mut self, by: u8) -> Envelope { - self.sessions + let messages = self + .sessions .get_mut(&id(by)) .expect("session") .update(&self.rng) - .expect("update") + .expect("update"); + Self::alone(messages) } fn send(&mut self, by: u8, message: &str) -> Envelope { - self.sessions + let messages = self + .sessions .get_mut(&id(by)) .expect("session") .send(message.as_bytes(), &self.rng) - .expect("send") + .expect("send"); + Self::alone(messages) } /// Hands `message` to each of `to`, in order, and returns what each one read. @@ -1139,7 +1157,9 @@ fn test_recovery_puts_the_device_back_and_its_compromised_copy_cannot_read() { let fresh = cast.reinstall(3); cast.sessions.insert(id(3), fresh); cast.deliver(&create, &[3]); - cast.deliver(&recovery.removal, &[2, 3]); + for message in &recovery.removal { + cast.deliver(message, &[2, 3]); + } cast.deliver(&recovery.readd[0], &[2, 3]); cast.deliver(&recovery.readd[1], &[2, 3]); assert!( @@ -1297,7 +1317,9 @@ fn test_fork_recovery_removes_the_forked_key_and_reenrols_a_new_one() { // The new key takes the removal and the welcome, in delivery order. cast.deliver(&create, &[4]); - cast.deliver(&recovery.removal, &[2, 4]); + for message in &recovery.removal { + cast.deliver(message, &[2, 4]); + } cast.deliver(&recovery.readd[0], &[2, 4]); cast.deliver(&recovery.readd[1], &[2, 4]); assert!(cast.session(4).is_welcomed(), "the new key is welcomed"); @@ -1907,9 +1929,11 @@ proptest! { fn concurrent_add(cast: &mut Cast, by: u8, who: u8, members: &[u8]) -> Envelope { let members: BTreeSet = members.iter().map(|seed| id(*seed)).collect(); let rng = Rng::default(); - cast.session_mut(by) + let messages = cast + .session_mut(by) .add(&view_of(&members), id(who), &rng) - .expect("concurrent add") + .expect("concurrent add"); + Cast::alone(messages) } #[test] @@ -2003,8 +2027,8 @@ fn test_an_author_names_its_own_latest_even_when_a_later_message_covers_it() { } /// A group of 33 members. Members 2 to 33 each update from the create, so no update names another. -/// Member 1 has heard the first `heard` of them. Returns the group and the create. -fn concurrent_updates(heard: usize) -> (Cast, Envelope) { +/// Member 1 has heard the first `heard` of them. Returns the group, the create and every update. +fn concurrent_updates(heard: usize) -> (Cast, Envelope, Vec) { let seeds: Vec = (1..=33).collect(); let mut cast = Cast::new(&seeds); let create = cast.create(1, &seeds); @@ -2014,12 +2038,12 @@ fn concurrent_updates(heard: usize) -> (Cast, Envelope) { for update in updates.iter().take(heard) { cast.deliver(update, &[1]); } - (cast, create) + (cast, create, updates) } #[test] fn test_a_message_may_name_32_parents() { - let (mut cast, create) = concurrent_updates(31); + let (mut cast, create, _) = concurrent_updates(31); // The 31 updates member 1 has heard are its heads, and its own create is named too. let message = cast.update(1); assert_eq!(message.parents().len(), 32, "the cap is 32, and it is met"); @@ -2030,34 +2054,111 @@ fn test_a_message_may_name_32_parents() { } #[test] -fn test_a_message_naming_33_parents_is_refused_and_the_state_is_kept() { - let (mut cast, _) = concurrent_updates(32); - let epoch = cast.epoch(1); - let members = cast.members_of(1); +fn test_a_group_above_32_heads_merges_and_publishes_again() { + // Everyone hears all 32 concurrent updates, so the storm's heads are 32 updates. Member 1 never + // updated, so its own create is still named too: 33 parents, one above the cap (P4.7). + let (mut cast, create, updates) = concurrent_updates(32); + for (author, update) in (2..=33u8).zip(&updates) { + let rest: Vec = (1..=33).filter(|seed| *seed != author).collect(); + cast.deliver(update, &rest); + } + let epoch = cast.epoch_set(1); + let roster = cast.members_of(1); let rng = Rng::default(); - let update = cast.session_mut(1).update(&rng); + // A publish above the cap merges first: an update naming 32 of the 33 parents, own latest kept. + let published = cast + .session_mut(1) + .update(&rng) + .expect("a merge, then the update"); + assert_eq!(published.len(), 2, "one merge and the requested update"); + let (merge, update) = (&published[0], &published[1]); + assert_eq!( + merge.parents().len(), + MAX_PARENTS, + "the merge names the cap and no more" + ); assert!( - matches!( - update, - Err(SchemeError::TooManyParents { count: 33, cap: 32 }) - ), - "{update:?}" + merge.parents().contains(&create.id()), + "the merge still names the author's own latest" ); - let send = cast.session_mut(1).send(b"refused", &rng); + // The one head the merge left is named by the update that follows, so the merge dropped nothing + // from the causal past: the group ends with every parent named by the merge or the update. + let leftover: Vec = updates + .iter() + .map(Envelope::id) + .filter(|id| !merge.parents().contains(id)) + .collect(); + assert_eq!(leftover.len(), 1, "32 of the 33 heads were merged"); assert!( - matches!( - send, - Err(SchemeError::TooManyParents { count: 33, cap: 32 }) - ), - "{send:?}" + update.parents().contains(&leftover[0]) && update.parents().contains(&merge.id()), + "the update names the left head and the merge" ); - assert_eq!( - cast.epoch(1), - epoch, - "the refused change left the epoch as it was" + assert!( + update.parents().len() <= MAX_PARENTS, + "the update fits the cap" ); - assert_eq!(cast.members_of(1), members, "and the roster"); + + // The group takes the merge and then the update, and every member ends on the same roster and + // the same epochs, so the group published again rather than staying deadlocked. + for member in &published { + let rest: Vec = (2..=33).collect(); + cast.deliver(member, &rest); + } + for who in 1..=33 { + assert_eq!(cast.members_of(who), roster, "member {who} roster"); + assert_eq!( + cast.epoch_set(who), + cast.epoch_set(1), + "member {who} epochs" + ); + } + assert!( + cast.epoch_set(1).len() > epoch.len(), + "the merge rotated the epoch" + ); + + // And the group publishes application messages again. + let message = cast.send(1, "after the merge"); + for read in cast.deliver(&message, &(2..=33).collect::>()) { + assert_eq!(read, vec![text("after the merge")]); + } +} + +#[test] +fn test_a_refused_change_above_the_cap_loses_no_merge() { + // Everyone hears all 32 concurrent updates, so member 1 sits on 33 parents, one above the + // cap: its next publish has to merge first (P4.7). + let (mut cast, _create, updates) = concurrent_updates(32); + for (author, update) in (2..=33u8).zip(&updates) { + let rest: Vec = (1..=33).filter(|seed| *seed != author).collect(); + cast.deliver(update, &rest); + } + let rng = Rng::default(); + + // A removal whose view names no scheme is refused by the policy check. The refusal must + // come before any merge: a merge absorbed by the session but never broadcast would leave + // the group waiting on a parent it never received. + let mut view = cast.view(); + view.members.remove(&id(33)); + view.policy = Policy::default(); + let result = cast.session_mut(1).remove(&view, id(33), &rng); + assert!(matches!(result, Err(SchemeError::NoScheme)), "{result:?}"); + + // The merge is still member 1's to publish: its next update returns the merge and then the + // update, the group takes both, and it publishes application messages again. + let published = cast + .session_mut(1) + .update(&rng) + .expect("a merge, then the update"); + assert_eq!(published.len(), 2, "the refusal lost no merge"); + for member in &published { + cast.deliver(member, &(2..=33).collect::>()); + } + let message = cast.send(1, "after the refused change"); + for read in cast.deliver(&message, &(2..=33).collect::>()) { + assert_eq!(read, vec![text("after the refused change")]); + } } /// A seeded shuffle, so a proptest case replays one delivery order. @@ -2354,7 +2455,7 @@ fn measure_update_cost(members: usize, updates: usize) -> UpdateCost { let mut sent = Vec::with_capacity(updates); let started = Instant::now(); for _ in 0..updates { - sent.push(session.update(&rng).expect("update")); + sent.extend(session.update(&rng).expect("update")); } let count = f64::from(u32::try_from(updates).expect("a few updates")); let update_ms = started.elapsed().as_secs_f64() * 1_000.0 / count;