From d19a9021ca34046eff25b9c80ece75eb91740561 Mon Sep 17 00:00:00 2001 From: repo-worker-code-g Date: Fri, 6 Nov 2026 22:52:39 -0600 Subject: [PATCH 1/2] =?UTF-8?q?feat(id):=20store-wired=20writer-set=20expa?= =?UTF-8?q?nsion=20=E2=80=94=20expand/expand=5Fretro=20over=20the=20member?= =?UTF-8?q?ship=20layer=20(#4998)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Spec §9 item 2 (slice 2 of #3789). Adds Membership::members_at_position(+_shared) in id-core — the frontier-pinned enumeration counterpart of access_at_position, key members only (one-level flattening, §D4) — and idset::expand::Expander, which resolves each referenced group at the set version's pinned frontier under its resolution state R, caches it under the §4.5 key (group, frontier, R), and delegates entry semantics to view::expand_set. expand/expand_retro return authors only; exclusions are applied by filtering the admitted set through ExpandedWriters::contains (the raw explicit_authors set does not subtract exclusions). A public admission cannot be materialized as a set of authors and is refused with ExpandError::PublicEntry. The idset module doc no longer states expansion is absent. Tests: pkgs/id/tests/writer_set_expansion.rs carries spec tests 1-7 (order-independence, frontier-pinning, reproducibility against a later membership event, retro subset + empty-without-history, fork-invalidated grant + cache key on R, role_min at the frontier, exclusion wins + never-admitted no-op) plus the public refusal. cargo test -p id -p id-core: 3179 passed, 0 failed. --- .../id/crates/id-core/src/membership/layer.rs | 58 +++ pkgs/id/src/idset.rs | 10 +- pkgs/id/src/idset/expand.rs | 246 ++++++++++ pkgs/id/tests/writer_set_expansion.rs | 446 ++++++++++++++++++ 4 files changed, 757 insertions(+), 3 deletions(-) create mode 100644 pkgs/id/src/idset/expand.rs create mode 100644 pkgs/id/tests/writer_set_expansion.rs diff --git a/pkgs/id/crates/id-core/src/membership/layer.rs b/pkgs/id/crates/id-core/src/membership/layer.rs index a267ac5906..440ebeed7c 100644 --- a/pkgs/id/crates/id-core/src/membership/layer.rs +++ b/pkgs/id/crates/id-core/src/membership/layer.rs @@ -500,6 +500,44 @@ impl Membership { Ok(managers) } + /// The key members of `group` and their access at the causal position that `after` + /// names, sorted by key. Group-valued members are not returned: a caller expanding a + /// group reference one level (writer-set spec §D4) must not follow a nested group + /// reference, and key members are the only ones that can be admitted by it. This is + /// the enumeration counterpart of [`Membership::access_at_position`]: the answer is + /// pinned to the position `after` names, never the live roster [`Membership::members`] + /// reports. + /// + /// # Errors + /// + /// Returns [`MembershipError`] when an `after` hash is not indexed. + pub fn members_at_position( + &mut self, + after: &[Hash], + group: Hash, + ) -> Result)>, MembershipError> { + let heads: HashSet = self.index.frontier(after, group)?.into_iter().collect(); + Ok(key_members_at(&self.state, heads, group)) + } + + /// The same as [`Membership::members_at_position`], borrowing the layer immutably. A + /// caller that holds the state can ask about a position this way; it copies the + /// frontier index rather than memoising into it, so prefer the mutable method on a + /// hot path. + /// + /// # Errors + /// + /// Returns [`MembershipError`] when an `after` hash is not indexed. + pub fn members_at_position_shared( + &self, + after: &[Hash], + group: Hash, + ) -> Result)>, MembershipError> { + let mut index = self.index.clone(); + let heads: HashSet = index.frontier(after, group)?.into_iter().collect(); + Ok(key_members_at(&self.state, heads, group)) + } + /// Whether a create has been decided for `group`. pub fn has_group(&self, group: Hash) -> bool { self.state.has_group(AuthId::Group(group)) @@ -587,6 +625,26 @@ fn canonical_feed_order(events: &[CausalEvent]) -> Vec { order } +/// The key members of `group` at the auth frontier `heads`, sorted by key. Group-valued +/// members are skipped (one-level expansion, writer-set spec §D4). +fn key_members_at( + state: &GroupState, + heads: HashSet, + group: Hash, +) -> Vec<([u8; 32], Access<()>)> { + let mut members: Vec<([u8; 32], Access<()>)> = + Graph::members_at(state, heads, AuthId::Group(group)) + .unwrap_or_default() + .into_iter() + .filter_map(|(id, access)| match id { + AuthId::Key(key) => Some((key, access)), + AuthId::Group(_) => None, + }) + .collect(); + members.sort_unstable_by_key(|(key, _)| *key); + members +} + /// Replays `accepted` on a fresh graph. fn rebuild(accepted: &[AuthOperation]) -> Result { accepted.iter().try_fold(Graph::init(), |state, op| { diff --git a/pkgs/id/src/idset.rs b/pkgs/id/src/idset.rs index f5bd670860..eb1f123a3c 100644 --- a/pkgs/id/src/idset.rs +++ b/pkgs/id/src/idset.rs @@ -56,9 +56,10 @@ //! from, so its `set_id` is an owner-chosen opaque value, unverifiable by //! design. //! -//! This module is types and encoding only. Expansion, projection, and -//! counting are later slices of the spec's routing (§9 items 2–4) and are -//! deliberately absent here. +//! This module is the types and encoding. Expansion now lives beside the +//! types: [`expand`] wires [`view`]'s pure projection to the membership +//! layer (spec §9 item 2). Counting is a later slice of the spec's routing +//! (§9 item 4) and is deliberately absent here. use cbor_core::{DecodeOptions, Strictness, Value}; use p2panda_core::Hash; @@ -67,6 +68,9 @@ use unicode_normalization::is_nfc; use crate::groups::Role; use crate::waiting::AuthorKey; +/// Store-wired expansion over the membership layer (spec §9 item 2). +pub mod expand; + /// View projection and discovery over an explicitly pinned snapshot. pub mod view; diff --git a/pkgs/id/src/idset/expand.rs b/pkgs/id/src/idset/expand.rs new file mode 100644 index 0000000000..a82fb14920 --- /dev/null +++ b/pkgs/id/src/idset/expand.rs @@ -0,0 +1,246 @@ +//! Store-wired writer-set expansion: `expand` / `expand_retro` over the +//! membership layer (writer-set spec §9 item 2; issue #4998, origin #3789). +//! +//! [`super::view::expand_set`] is the pure projection: the caller supplies a +//! pinned membership snapshot and it evaluates the entry logic. This module +//! is the wiring that produces that snapshot from the store's membership +//! layer, pinned to the set version's own frontier: +//! +//! - Group entries resolve through +//! [`Membership::members_at_position`] — the enumeration counterpart of +//! `is_member_at` / `access_at_position` — at the set version's pinned +//! frontier, **never** through the live `Membership::members` roster +//! (spec §4.5). A membership change after the pinned frontier therefore +//! cannot change a set version's expansion (spec §D4). +//! - Group-valued members are not followed: expansion flattens exactly one +//! level (spec §D3/D4), because `members_at_position` returns key members +//! only. +//! - A member's role is their access at that frontier, mapped the way the +//! groups fold maps it (`access_role` in `crate::groups::fold`): the +//! membership layer records Admin as Manage, so a `role_min` of +//! [`Role::Admin`] is answered by Manage-or-above at the frontier — the +//! same answer every other frontier-aware caller gets. +//! - Resolved groups are cached under the §4.5 key `(group, frontier, R)`, +//! where `R` is the caller's resolution-state identity +//! ([`SetVersion::resolution`]). Within one resolution state an expansion +//! is immutable and cacheable forever; across resolution states — a fork +//! proof invalidating a grant is exactly such a move — the cached entry +//! is not served and the group is resolved again. +//! +//! The result is authors only: no counting path is enabled here (counting +//! is spec §9 item 4). A set carrying a `Public` entry cannot be +//! materialized as a set of authors — every author is admitted — so it is +//! refused with [`ExpandError::PublicEntry`] rather than silently +//! returning only the explicitly named authors; callers that need the +//! public shape use [`ExpandedWriters`] from [`super::view`] directly. + +use std::collections::{BTreeMap, BTreeSet, HashMap}; + +use p2panda_auth::Access; +use p2panda_core::Hash; + +use crate::groups::Role; +use crate::membership::{Membership, MembershipError}; +use crate::waiting::AuthorKey; + +use super::view::{GroupMembers, ProjectionError, expand_set}; +use super::{Entry, WriterSet}; + +/// One set version, pinned for expansion: the set object, the causal +/// frontier its publishing event was expanded at (spec §D4), and the +/// resolution state `R` the expansion is evaluated under (spec §4.5). +#[derive(Clone, Debug)] +pub struct SetVersion<'a> { + /// The writer set at this version. + pub set: &'a WriterSet, + /// The publishing event's signed causal frontier: the `after` hashes + /// group membership is judged at. + pub frontier: Vec, + /// The resolution state's identity. Two expansions that differ only in + /// this value are different evaluations and are cached apart. + pub resolution: Hash, +} + +/// Why a store-wired expansion could not be evaluated. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum ExpandError { + /// The membership layer refused a frontier lookup. + #[error(transparent)] + Membership(#[from] MembershipError), + /// The pure projection refused the pinned snapshot. + #[error(transparent)] + Projection(#[from] ProjectionError), + /// The set admits the public, which no `BTreeSet` can + /// materialize. Use `view::expand_set`'s [`ExpandedWriters`] instead. + /// + /// [`ExpandedWriters`]: super::view::ExpandedWriters + #[error( + "the set has a public entry, so its expansion is every author and cannot be materialized as a set of authors" + )] + PublicEntry, +} + +/// The §4.5 cache key: `(group, frontier, R)`. The frontier is stored +/// sorted, so two spellings of the same causal position share one entry. +type CacheKey = (Hash, Vec, Hash); + +/// Expands set versions against one membership layer, caching each group's +/// frontier-pinned resolution under its §4.5 key for the expander's life. +/// One expander serves one resolution epoch of one store: when the store's +/// resolution state moves (a fork proof lands), build a fresh expander +/// over the rebuilt layer and name the new `R` in each [`SetVersion`]. +pub struct Expander<'a> { + membership: &'a mut Membership, + cache: HashMap>, +} + +impl<'a> Expander<'a> { + /// An expander over `membership` with an empty cache. + pub fn new(membership: &'a mut Membership) -> Self { + Self { + membership, + cache: HashMap::new(), + } + } + + /// The number of `(group, frontier, R)` resolutions currently cached. + /// Exposed so tests and metrics can pin the §4.5 key's behaviour: a + /// repeat expansion under the same key adds nothing, and the same + /// `(group, frontier)` under a new `R` adds a second entry instead of + /// serving the stale one. + #[must_use] + pub fn cache_entries(&self) -> usize { + self.cache.len() + } + + /// `expand(set_version) -> BTreeSet` (spec §3.1): every + /// author this set version admits, exclusions applied (spec §D6). + /// + /// # Errors + /// + /// Returns [`ExpandError::Membership`] when the layer cannot judge the + /// pinned frontier, [`ExpandError::Projection`] when the pinned + /// snapshot is incomplete, and [`ExpandError::PublicEntry`] when the + /// set admits the public. + pub fn expand(&mut self, version: &SetVersion<'_>) -> Result, ExpandError> { + self.expand_narrowed(version, false) + } + + /// `expand_retro(set_version)`: the same expansion narrowed to the + /// entries carrying `include_history` (spec §3.1/§4.1). The narrowing + /// is per entry, so one flagged entry never imports another entry's + /// backlog, and `expand_retro(v) ⊆ expand(v)` always holds. + /// + /// # Errors + /// + /// The same failures as [`Expander::expand`], except that a public + /// entry carrying no `include_history` does not contribute to the + /// retro expansion and so does not refuse it. + pub fn expand_retro( + &mut self, + version: &SetVersion<'_>, + ) -> Result, ExpandError> { + self.expand_narrowed(version, true) + } + + fn expand_narrowed( + &mut self, + version: &SetVersion<'_>, + retro: bool, + ) -> Result, ExpandError> { + let set = version.set; + if admits_public(set, retro) { + return Err(ExpandError::PublicEntry); + } + let mut groups = Vec::new(); + for group in referenced_groups(set) { + let members = self.group_members(group, version)?; + groups.push(GroupMembers::new( + group, + version.frontier.clone(), + version.resolution, + members, + )); + } + let expanded = expand_set( + set, + &version.frontier, + &version.resolution, + &groups, + retro, + )?; + // `ExpandedWriters` keeps exclusions apart from the admitted set — + // only `contains` applies them — so the materialized expansion is + // the admitted authors that survive exclusion (spec §D6), not the + // raw admitted set. + Ok(expanded + .explicit_authors() + .iter() + .copied() + .filter(|author| expanded.contains(author)) + .collect()) + } + + /// The frontier-pinned direct members of `group` under the version's + /// resolution state, from the cache when this exact §4.5 key was + /// already resolved. + fn group_members( + &mut self, + group: Hash, + version: &SetVersion<'_>, + ) -> Result, ExpandError> { + let mut frontier = version.frontier.clone(); + frontier.sort_unstable(); + let key = (group, frontier, version.resolution); + if let Some(members) = self.cache.get(&key) { + return Ok(members.clone()); + } + let members: BTreeMap = self + .membership + .members_at_position(&version.frontier, group)? + .into_iter() + .map(|(author, access)| (author, access_role(&access))) + .collect(); + self.cache.insert(key, members.clone()); + Ok(members) + } +} + +/// Whether the set's admissions (narrowed to history-carrying entries when +/// `retro`) include a public entry. Exclusions never admit, so a public +/// exclusion does not count. +fn admits_public(set: &WriterSet, retro: bool) -> bool { + set.entries.iter().any(|entry| { + matches!(entry, Entry::Public { .. }) && (!retro || entry.include_history()) + }) +} + +/// Every group named by an admission or an exclusion entry, in first-use +/// order. Both lists can carry group entries, and the projection needs a +/// pinned snapshot for each one it evaluates. +fn referenced_groups(set: &WriterSet) -> Vec { + let mut groups = Vec::new(); + for entry in set.entries.iter().chain(set.excludes.0.iter()) { + if let Entry::Group { id, .. } = entry { + if !groups.contains(id) { + groups.push(*id); + } + } + } + groups +} + +/// A member's role as their membership access gives it. Mirrors the groups +/// fold's `access_role`: Admin is recorded apart from the access level and +/// shows as Manage here. +fn access_role(access: &Access<()>) -> Role { + if access.is_manage() { + Role::Manage + } else if access.is_write() { + Role::Write + } else if access.is_read() { + Role::Read + } else { + Role::Pull + } +} diff --git a/pkgs/id/tests/writer_set_expansion.rs b/pkgs/id/tests/writer_set_expansion.rs new file mode 100644 index 0000000000..909279e40b --- /dev/null +++ b/pkgs/id/tests/writer_set_expansion.rs @@ -0,0 +1,446 @@ +//! Store-wired writer-set expansion (writer-set spec §9 item 2; issue +//! #4998): `expand` / `expand_retro` over the membership layer, pinned to +//! the set version's frontier. These are the seven spec tests, in order, +//! plus the public-entry refusal that keeps `expand` honest about +//! returning authors only. +//! +//! The oracle for every test is the membership layer itself, fed a known +//! causal history: the expected expansion is read off the history at the +//! pinned frontier by hand, and a later event's effect (or non-effect) is +//! checked against the layer's live roster to prove the pin did the work. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use std::collections::BTreeSet; + +use id::groups::Role; +use id::idset::expand::{ExpandError, Expander, SetVersion}; +use id::idset::{Entry, Excludes, WriterSet}; +use id::membership::{AuthId, CausalEvent, Membership, Outcome, Role as MembershipRole}; +use p2panda_auth::Access; +use p2panda_auth::group::{GroupAction, GroupMember}; +use p2panda_core::Hash; + +fn author(n: u8) -> [u8; 32] { + [n; 32] +} + +fn hash(n: u8) -> Hash { + Hash::from([n; 32]) +} + +const ALICE: u8 = 1; +const BOB: u8 = 2; +const CAROL: u8 = 3; +const DAVE: u8 = 4; +const ERIN: u8 = 5; +const FRANK: u8 = 6; +const MALLORY: u8 = 99; + +/// The group: its create event's ID, as in the membership scenarios. +fn group() -> Hash { + hash(10) +} + +fn individual(key: [u8; 32]) -> GroupMember { + GroupMember::Individual(AuthId::Key(key)) +} + +fn feed(membership: &mut Membership, id: Hash, after: Vec, role: MembershipRole) { + let outcomes = membership.receive(CausalEvent { id, after, role }).unwrap(); + assert!( + outcomes + .iter() + .any(|(event, outcome)| *event == id && *outcome == Outcome::Applied), + "event {id} was not applied: {outcomes:?}" + ); +} + +fn feed_auth( + membership: &mut Membership, + id: Hash, + after: Vec, + author: [u8; 32], + group: Option, + action: GroupAction, +) { + feed( + membership, + id, + after, + MembershipRole::Auth { + author, + group, + action, + }, + ); +} + +/// A group created by Alice: Alice manages, Bob reads, Carol writes. The +/// create event is the frontier a first set version pins. +fn base_layer() -> Membership { + let mut membership = Membership::new(); + feed_auth( + &mut membership, + group(), + vec![], + author(ALICE), + None, + GroupAction::Create { + initial_members: vec![ + (individual(author(ALICE)), Access::manage()), + (individual(author(BOB)), Access::read()), + (individual(author(CAROL)), Access::write()), + ], + }, + ); + membership +} + +fn set(entries: Vec, excludes: Vec) -> WriterSet { + WriterSet { + set_id: hash(90), + version: 3, + owner: author(ALICE), + scope: None, + entries, + excludes: Excludes(excludes), + } +} + +fn group_entry(role_min: Role, include_history: bool) -> Entry { + Entry::Group { + id: group(), + role_min, + include_history, + } +} + +fn key_entry(key: u8, include_history: bool) -> Entry { + Entry::Key { + author: author(key), + include_history, + } +} + +fn expand(membership: &mut Membership, set: &WriterSet, frontier: Vec) -> BTreeSet<[u8; 32]> { + Expander::new(membership) + .expand(&SetVersion { + set, + frontier, + resolution: hash(80), + }) + .unwrap() +} + +/// Spec test 1: expansion is order-independent — the same set with its +/// entries permuted yields the same set of authors. +#[test] +fn test_expand_is_order_independent() { + let mut membership = base_layer(); + let forward = set( + vec![ + key_entry(ERIN, false), + group_entry(Role::Read, false), + key_entry(FRANK, true), + ], + vec![key_entry(BOB, false)], + ); + let permuted = set( + vec![ + group_entry(Role::Read, false), + key_entry(FRANK, true), + key_entry(ERIN, false), + ], + vec![key_entry(BOB, false)], + ); + + let expected: BTreeSet<[u8; 32]> = [ALICE, CAROL, ERIN, FRANK] + .into_iter() + .map(author) + .collect(); + assert_eq!(expand(&mut membership, &forward, vec![group()]), expected); + assert_eq!(expand(&mut membership, &permuted, vec![group()]), expected); +} + +/// Spec test 2: expansion is frontier-pinned — a membership change after +/// the set version does not change `expand(v)`. +#[test] +fn test_expand_is_frontier_pinned() { + let mut membership = base_layer(); + let set = set(vec![group_entry(Role::Read, false)], vec![]); + let pinned: BTreeSet<[u8; 32]> = [ALICE, BOB, CAROL].into_iter().map(author).collect(); + assert_eq!(expand(&mut membership, &set, vec![group()]), pinned); + + // After the pin: Dave is added and Bob is removed. Neither may move + // the pinned expansion. + let add = hash(11); + feed_auth( + &mut membership, + add, + vec![group()], + author(ALICE), + Some(group()), + GroupAction::Add { + member: individual(author(DAVE)), + access: Access::write(), + }, + ); + let remove = hash(12); + feed_auth( + &mut membership, + remove, + vec![add], + author(ALICE), + Some(group()), + GroupAction::Remove { + member: individual(author(BOB)), + }, + ); + + assert_eq!(expand(&mut membership, &set, vec![group()]), pinned); + // The pin did the work, not a frozen layer: judged at the later + // frontier, the same set expands to the new roster. + let later: BTreeSet<[u8; 32]> = [ALICE, CAROL, DAVE].into_iter().map(author).collect(); + assert_eq!(expand(&mut membership, &set, vec![remove]), later); +} + +/// Spec test 3: expansion is unchanged by a later group-membership event — +/// the reproducibility guarantee, with the event written after the pin and +/// the expansion recomputed from scratch (fresh expander, empty cache). +#[test] +fn test_expand_unchanged_by_later_group_membership_event() { + let mut membership = base_layer(); + let set = set(vec![group_entry(Role::Write, false)], vec![]); + let before = expand(&mut membership, &set, vec![group()]); + + let add = hash(11); + feed_auth( + &mut membership, + add, + vec![group()], + author(ALICE), + Some(group()), + GroupAction::Add { + member: individual(author(DAVE)), + access: Access::write(), + }, + ); + // The live roster really did change. + assert!( + membership + .members(group()) + .iter() + .any(|(id, _)| *id == AuthId::Key(author(DAVE))) + ); + + let after = expand(&mut membership, &set, vec![group()]); + assert_eq!(before, after); + assert!(!after.contains(&author(DAVE))); +} + +/// Spec test 4: `expand_retro(v) ⊆ expand(v)`, per entry — one entry's +/// `include_history` never imports another entry's backlog — and a set +/// with no `include_history` entries has an empty retro expansion while +/// its plain expansion is not empty. +#[test] +fn test_expand_retro_subset_and_empty_without_history_entries() { + let mut membership = base_layer(); + let flagged = set( + vec![ + key_entry(ERIN, true), + key_entry(FRANK, false), + group_entry(Role::Write, true), + ], + vec![], + ); + let version = SetVersion { + set: &flagged, + frontier: vec![group()], + resolution: hash(80), + }; + let mut expander = Expander::new(&mut membership); + let full = expander.expand(&version).unwrap(); + let retro = expander.expand_retro(&version).unwrap(); + + let expected_full: BTreeSet<[u8; 32]> = [ALICE, CAROL, ERIN, FRANK] + .into_iter() + .map(author) + .collect(); + let expected_retro: BTreeSet<[u8; 32]> = [ALICE, CAROL, ERIN].into_iter().map(author).collect(); + assert_eq!(full, expected_full); + assert_eq!(retro, expected_retro); + assert!(retro.is_subset(&full)); + // Frank's unflagged key entry and Bob's unflagged-at-Write standing + // contribute nothing retroactively. + assert!(!retro.contains(&author(FRANK))); + assert!(!retro.contains(&author(BOB))); + + let no_history = set( + vec![key_entry(ERIN, false), group_entry(Role::Read, false)], + vec![], + ); + let version = SetVersion { + set: &no_history, + frontier: vec![group()], + resolution: hash(80), + }; + assert!(!expander.expand(&version).unwrap().is_empty()); + assert!(expander.expand_retro(&version).unwrap().is_empty()); +} + +/// Spec test 5: a fork proof that invalidates a group grant changes the +/// expansion, and the cache does not serve the stale one — the cache key +/// is `(group, frontier, R)`, so the same frontier under a new resolution +/// state recomputes instead of reusing the pre-proof entry. +#[test] +fn test_expand_fork_invalidated_grant_changes_expansion_and_cache_keys_on_resolution() { + let grant = hash(11); + let add_dave = |membership: &mut Membership, as_action: bool| { + let role = if as_action { + MembershipRole::Auth { + author: author(ALICE), + group: Some(group()), + action: GroupAction::Add { + member: individual(author(DAVE)), + access: Access::write(), + }, + } + } else { + // Exactly what the resolver feeds the layer for a fork-excluded + // action (event_store/resolve.rs): the event stays in the + // index, its membership effect is dropped. + MembershipRole::Other + }; + feed(membership, grant, vec![group()], role); + }; + + let set = set(vec![group_entry(Role::Write, false)], vec![]); + let frontier = vec![grant]; + + // The grant stands: Dave is in the expansion under R1. + let mut membership = base_layer(); + add_dave(&mut membership, true); + let mut expander = Expander::new(&mut membership); + let under_r1 = expander + .expand(&SetVersion { + set: &set, + frontier: frontier.clone(), + resolution: hash(80), + }) + .unwrap(); + assert!(under_r1.contains(&author(DAVE))); + assert_eq!(expander.cache_entries(), 1); + // A repeat under the same (group, frontier, R) key is served by the + // cache: no new entry. + expander + .expand(&SetVersion { + set: &set, + frontier: frontier.clone(), + resolution: hash(80), + }) + .unwrap(); + assert_eq!(expander.cache_entries(), 1); + // The same (group, frontier) under a new resolution state is a new + // cache entry, not the stale one. + expander + .expand(&SetVersion { + set: &set, + frontier: frontier.clone(), + resolution: hash(81), + }) + .unwrap(); + assert_eq!(expander.cache_entries(), 2); + + // The fork proof lands: under the new resolution state the grant is + // excluded before the layer sees it, and the same set version at the + // same frontier no longer expands to Dave. + let mut forked = base_layer(); + add_dave(&mut forked, false); + let under_r2 = Expander::new(&mut forked) + .expand(&SetVersion { + set: &set, + frontier, + resolution: hash(81), + }) + .unwrap(); + assert!(!under_r2.contains(&author(DAVE))); + assert!(under_r2.contains(&author(CAROL))); +} + +/// Spec test 6: `role_min` filters at the frontier — a member who holds +/// the role only later is not admitted by an earlier version. +#[test] +fn test_expand_role_min_filters_at_the_frontier() { + let mut membership = base_layer(); + let set = set(vec![group_entry(Role::Write, false)], vec![]); + + // At the create frontier Bob only reads: the Write threshold omits him. + let at_create = expand(&mut membership, &set, vec![group()]); + assert!(!at_create.contains(&author(BOB))); + assert!(at_create.contains(&author(CAROL))); + + // Alice promotes Bob to Write after the pin. + let promote = hash(11); + feed_auth( + &mut membership, + promote, + vec![group()], + author(ALICE), + Some(group()), + GroupAction::Promote { + member: individual(author(BOB)), + access: Access::write(), + }, + ); + + // The earlier version still does not admit him; the version pinned at + // the promotion does. + assert!(!expand(&mut membership, &set, vec![group()]).contains(&author(BOB))); + assert!(expand(&mut membership, &set, vec![promote]).contains(&author(BOB))); +} + +/// Spec test 7: an exclusion removes an admitted writer, and an exclusion +/// of someone never admitted is a no-op rather than an error. +#[test] +fn test_expand_exclusion_removes_admitted_and_ignores_never_admitted() { + let mut membership = base_layer(); + let admitted = set(vec![group_entry(Role::Read, false)], vec![]); + let baseline = expand(&mut membership, &admitted, vec![group()]); + assert!(baseline.contains(&author(BOB))); + + let excluding = set( + vec![group_entry(Role::Read, false)], + vec![key_entry(BOB, false), key_entry(MALLORY, false)], + ); + let expanded = expand(&mut membership, &excluding, vec![group()]); + assert!(!expanded.contains(&author(BOB))); + assert!(expanded.contains(&author(CAROL))); + assert_eq!(expanded.len(), baseline.len() - 1); +} + +/// A public entry admits every author, so `expand` cannot materialize it +/// as a set of authors: it refuses instead of silently returning only the +/// named authors. A public entry without `include_history` contributes +/// nothing to the retro expansion and does not refuse it. +#[test] +fn test_expand_public_entry_refused_not_materialized() { + let mut membership = base_layer(); + let public = set( + vec![ + Entry::Public { + include_history: false, + }, + key_entry(ERIN, false), + ], + vec![], + ); + let version = SetVersion { + set: &public, + frontier: vec![group()], + resolution: hash(80), + }; + let mut expander = Expander::new(&mut membership); + assert_eq!(expander.expand(&version), Err(ExpandError::PublicEntry)); + assert_eq!(expander.expand_retro(&version).unwrap(), BTreeSet::new()); +} From 9e0e5f43fc1caa3117013564f32eaa0cff3182a3 Mon Sep 17 00:00:00 2001 From: repo-worker-code-g Date: Fri, 6 Nov 2026 23:14:12 -0600 Subject: [PATCH 2/2] =?UTF-8?q?fix(id):=20address=20Codex=20review=20on=20?= =?UTF-8?q?#6787=20=E2=80=94=20property=20tests,=20public-exclusion=20empt?= =?UTF-8?q?y=20set,=20Admin=20threshold=20at=20Manage?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P1: proptest property suite for the expansion invariants (order-independence over generated entry/exclusion permutations, expand_retro subset, frontier-pinning under generated add/remove/promote histories), each with its oracle stated. P2a: a public exclusion (the §D6 emergency stop) now yields the finite empty set instead of ExpandError::PublicEntry. P2b: role_min Admin is evaluated at Manage — the membership layer records Admin as Manage, so admins are admitted instead of nobody; the approximation (non-admin managers also pass an Admin threshold) is documented in the module doc and pinned by test_expand_role_min_admin_is_answered_at_manage_the_layers_top_role. Targeted: writer_set_expansion 13/13, writer_set_projection 4/4. --- pkgs/id/src/idset/expand.rs | 102 ++++++++++-- pkgs/id/tests/writer_set_expansion.rs | 219 +++++++++++++++++++++++++- 2 files changed, 297 insertions(+), 24 deletions(-) diff --git a/pkgs/id/src/idset/expand.rs b/pkgs/id/src/idset/expand.rs index a82fb14920..380398c6ef 100644 --- a/pkgs/id/src/idset/expand.rs +++ b/pkgs/id/src/idset/expand.rs @@ -16,10 +16,17 @@ //! level (spec §D3/D4), because `members_at_position` returns key members //! only. //! - A member's role is their access at that frontier, mapped the way the -//! groups fold maps it (`access_role` in `crate::groups::fold`): the -//! membership layer records Admin as Manage, so a `role_min` of -//! [`Role::Admin`] is answered by Manage-or-above at the frontier — the -//! same answer every other frontier-aware caller gets. +//! groups fold maps it (`access_role` in `crate::groups::fold`). The +//! membership layer records Admin as Manage — Admin is a policy role the +//! groups fold tracks apart from access — so it cannot distinguish an +//! admin from any other manager at a frontier. A `role_min` of +//! [`Role::Admin`] is therefore evaluated at [`Role::Manage`], the +//! highest role the layer can answer for: admins are admitted (they are +//! managers in the layer), and so are non-admin managers. Answering +//! Admin exactly needs the fold's admin-at-frontier state plumbed into +//! expansion, which no caller can supply yet; the limitation is pinned +//! by a named test beside the spec tests (`test_expand_role_min_admin_*` +//! in `tests/writer_set_expansion.rs`). //! - Resolved groups are cached under the §4.5 key `(group, frontier, R)`, //! where `R` is the caller's resolution-state identity //! ([`SetVersion::resolution`]). Within one resolution state an expansion @@ -43,7 +50,7 @@ use crate::groups::Role; use crate::membership::{Membership, MembershipError}; use crate::waiting::AuthorKey; -use super::view::{GroupMembers, ProjectionError, expand_set}; +use super::view::{expand_set, GroupMembers, ProjectionError}; use super::{Entry, WriterSet}; /// One set version, pinned for expansion: the set object, the causal @@ -148,10 +155,30 @@ impl<'a> Expander<'a> { version: &SetVersion<'_>, retro: bool, ) -> Result, ExpandError> { - let set = version.set; - if admits_public(set, retro) { + // A public exclusion admits nobody (spec §D6, the emergency + // stop): the expansion is the finite empty set even when the + // admissions are public, so the public-admission refusal below + // must not fire for that configuration. + let public_excluded = version + .set + .excludes + .0 + .iter() + .any(|entry| matches!(entry, Entry::Public { .. })); + if admits_public(version.set, retro) && !public_excluded { return Err(ExpandError::PublicEntry); } + // The membership layer's highest distinguishable role is Manage + // (Admin is recorded as Manage there), so an Admin threshold is + // evaluated at Manage for the layer-backed snapshot; see the + // module doc for the limitation and its follow-up. + let effective; + let set = if has_admin_threshold(version.set) { + effective = clamp_admin_thresholds(version.set); + &effective + } else { + version.set + }; let mut groups = Vec::new(); for group in referenced_groups(set) { let members = self.group_members(group, version)?; @@ -162,13 +189,7 @@ impl<'a> Expander<'a> { members, )); } - let expanded = expand_set( - set, - &version.frontier, - &version.resolution, - &groups, - retro, - )?; + let expanded = expand_set(set, &version.frontier, &version.resolution, &groups, retro)?; // `ExpandedWriters` keeps exclusions apart from the admitted set — // only `contains` applies them — so the materialized expansion is // the admitted authors that survive exclusion (spec §D6), not the @@ -210,9 +231,9 @@ impl<'a> Expander<'a> { /// `retro`) include a public entry. Exclusions never admit, so a public /// exclusion does not count. fn admits_public(set: &WriterSet, retro: bool) -> bool { - set.entries.iter().any(|entry| { - matches!(entry, Entry::Public { .. }) && (!retro || entry.include_history()) - }) + set.entries + .iter() + .any(|entry| matches!(entry, Entry::Public { .. }) && (!retro || entry.include_history())) } /// Every group named by an admission or an exclusion entry, in first-use @@ -244,3 +265,50 @@ fn access_role(access: &Access<()>) -> Role { Role::Pull } } + +/// Whether any group entry in the set (admissions or exclusions) carries +/// an Admin `role_min` threshold. +fn has_admin_threshold(set: &WriterSet) -> bool { + set.entries + .iter() + .chain(set.excludes.0.iter()) + .any(|entry| { + matches!( + entry, + Entry::Group { + role_min: Role::Admin, + .. + } + ) + }) +} + +/// A copy of `set` with every Admin `role_min` lowered to Manage, the +/// highest role the membership layer distinguishes at a frontier. +fn clamp_admin_thresholds(set: &WriterSet) -> WriterSet { + fn clamp(entries: &[Entry]) -> Vec { + entries + .iter() + .map(|entry| match entry { + Entry::Group { + id, + role_min: Role::Admin, + include_history, + } => Entry::Group { + id: *id, + role_min: Role::Manage, + include_history: *include_history, + }, + other => other.clone(), + }) + .collect() + } + WriterSet { + set_id: set.set_id, + version: set.version, + owner: set.owner, + scope: set.scope.clone(), + entries: clamp(&set.entries), + excludes: super::Excludes(clamp(&set.excludes.0)), + } +} diff --git a/pkgs/id/tests/writer_set_expansion.rs b/pkgs/id/tests/writer_set_expansion.rs index 909279e40b..d291a94089 100644 --- a/pkgs/id/tests/writer_set_expansion.rs +++ b/pkgs/id/tests/writer_set_expansion.rs @@ -17,8 +17,8 @@ use id::groups::Role; use id::idset::expand::{ExpandError, Expander, SetVersion}; use id::idset::{Entry, Excludes, WriterSet}; use id::membership::{AuthId, CausalEvent, Membership, Outcome, Role as MembershipRole}; -use p2panda_auth::Access; use p2panda_auth::group::{GroupAction, GroupMember}; +use p2panda_auth::Access; use p2panda_core::Hash; fn author(n: u8) -> [u8; 32] { @@ -227,12 +227,10 @@ fn test_expand_unchanged_by_later_group_membership_event() { }, ); // The live roster really did change. - assert!( - membership - .members(group()) - .iter() - .any(|(id, _)| *id == AuthId::Key(author(DAVE))) - ); + assert!(membership + .members(group()) + .iter() + .any(|(id, _)| *id == AuthId::Key(author(DAVE)))); let after = expand(&mut membership, &set, vec![group()]); assert_eq!(before, after); @@ -444,3 +442,210 @@ fn test_expand_public_entry_refused_not_materialized() { assert_eq!(expander.expand(&version), Err(ExpandError::PublicEntry)); assert_eq!(expander.expand_retro(&version).unwrap(), BTreeSet::new()); } + +/// Codex P2 on PR #6787: a public exclusion is the §D6 emergency stop — +/// the expansion is the finite empty set, so `expand` must return it +/// instead of refusing the public admission it nullifies. +#[test] +fn test_expand_public_exclusion_admits_nobody_not_refused() { + let mut membership = base_layer(); + let stopped = set( + vec![Entry::Public { + include_history: true, + }], + vec![Entry::Public { + include_history: false, + }], + ); + let version = SetVersion { + set: &stopped, + frontier: vec![group()], + resolution: hash(80), + }; + let mut expander = Expander::new(&mut membership); + assert_eq!(expander.expand(&version).unwrap(), BTreeSet::new()); + assert_eq!(expander.expand_retro(&version).unwrap(), BTreeSet::new()); + + // The stop nullifies named admissions too. + let named = set( + vec![key_entry(ERIN, false)], + vec![Entry::Public { + include_history: false, + }], + ); + assert_eq!( + expand(&mut membership, &named, vec![group()]), + BTreeSet::new() + ); +} + +/// Codex P2 on PR #6787: the membership layer records Admin as Manage, so +/// an Admin `role_min` is answered at Manage, the layer's top role — +/// admins (managers in the layer) are admitted rather than nobody, and +/// the approximation is pinned here until admin-at-frontier plumbing +/// exists. Bob (Read) and Carol (Write) stay below the threshold. +#[test] +fn test_expand_role_min_admin_is_answered_at_manage_the_layers_top_role() { + let mut membership = base_layer(); + let set = set(vec![group_entry(Role::Admin, false)], vec![]); + let expanded = expand(&mut membership, &set, vec![group()]); + assert!(expanded.contains(&author(ALICE))); + assert!(!expanded.contains(&author(BOB))); + assert!(!expanded.contains(&author(CAROL))); +} + +// --------------------------------------------------------------------------- +// Property tests (Codex P1 on PR #6787; testing doctrine: invariants with +// a generator, not examples only). The oracle for each property is stated +// in its comment: permutation/subset properties are self-oracles over the +// generated input, and the pinning property's oracle is the expansion +// evaluated before the generated history is appended — any later event +// that moved the pinned answer is a counterexample. +// --------------------------------------------------------------------------- + +use proptest::prelude::*; + +fn role_strategy() -> impl Strategy { + prop_oneof![ + Just(Role::Pull), + Just(Role::Read), + Just(Role::Write), + Just(Role::Manage), + Just(Role::Admin), + ] +} + +fn entry_strategy() -> impl Strategy { + prop_oneof![ + (2..8u8, any::()).prop_map(|(n, include_history)| Entry::Key { + author: author(n), + include_history, + }), + (role_strategy(), any::()).prop_map(|(role_min, include_history)| Entry::Group { + id: group(), + role_min, + include_history, + }), + any::().prop_map(|include_history| Entry::Public { include_history }), + ] +} + +fn permute(entries: &[Entry], seed: usize) -> Vec { + let mut out = entries.to_vec(); + out.reverse(); + let len = out.len(); + if len > 0 { + out.rotate_left(seed % len); + } + out +} + +proptest! { + #![proptest_config(ProptestConfig::with_cases(128))] + + /// Invariant: expansion is a function of the entry *set*, not its + /// spelling — any permutation of entries and excludes expands the + /// same (including refusing the same). + #[test] + fn prop_expand_is_order_independent( + entries in proptest::collection::vec(entry_strategy(), 0..6), + excludes in proptest::collection::vec(entry_strategy(), 0..3), + seed in 0..720usize, + ) { + let mut membership = base_layer(); + let plain = set(entries.clone(), excludes.clone()); + let shuffled = set(permute(&entries, seed), permute(&excludes, seed + 1)); + let a = Expander::new(&mut membership).expand(&SetVersion { + set: &plain, + frontier: vec![group()], + resolution: hash(80), + }); + let b = Expander::new(&mut membership).expand(&SetVersion { + set: &shuffled, + frontier: vec![group()], + resolution: hash(80), + }); + prop_assert_eq!(a, b); + } + + /// Invariant: `expand_retro(v) ⊆ expand(v)` for every generated set. + /// When `expand` succeeds the retro expansion must also succeed (it + /// narrows the same admissions) and be a subset. + #[test] + fn prop_expand_retro_is_subset_of_expand( + entries in proptest::collection::vec(entry_strategy(), 0..6), + excludes in proptest::collection::vec(entry_strategy(), 0..3), + ) { + let mut membership = base_layer(); + let set = set(entries, excludes); + let version = SetVersion { + set: &set, + frontier: vec![group()], + resolution: hash(80), + }; + let mut expander = Expander::new(&mut membership); + if let Ok(full) = expander.expand(&version) { + let retro = expander.expand_retro(&version).unwrap(); + prop_assert!(retro.is_subset(&full), "retro {retro:?} not a subset of {full:?}"); + } + } + + /// Invariant: a set version's expansion is pinned to its frontier — + /// appending a generated membership history (adds, removes, promotes + /// by the group's manager, chained after the pin) never changes it. + /// Oracle: the expansion evaluated before the history is appended. + #[test] + fn prop_expand_is_frontier_pinned_under_generated_history( + entries in proptest::collection::vec(entry_strategy(), 0..5), + ops in proptest::collection::vec((2..8u8, 0..3u8, 0..4u8), 0..8), + ) { + let mut membership = base_layer(); + let set = set(entries, vec![]); + let version = SetVersion { + set: &set, + frontier: vec![group()], + resolution: hash(80), + }; + let before = Expander::new(&mut membership).expand(&version); + + let mut after = vec![group()]; + for (i, (who, kind, level)) in ops.iter().enumerate() { + let access = match level { + 0 => Access::pull(), + 1 => Access::read(), + 2 => Access::write(), + _ => Access::manage(), + }; + let action = match kind { + 0 => GroupAction::Add { + member: individual(author(*who)), + access, + }, + 1 => GroupAction::Remove { + member: individual(author(*who)), + }, + _ => GroupAction::Promote { + member: individual(author(*who)), + access, + }, + }; + let id = hash(20 + i as u8); + // Generated ops may be refused by the gate (removing a + // non-member, re-adding a member); a refusal is a no-op in + // the layer, which is fine — the pin must hold either way. + let _ = membership.receive(CausalEvent { + id, + after: after.clone(), + role: MembershipRole::Auth { + author: author(ALICE), + group: Some(group()), + action, + }, + }); + after = vec![id]; + } + + let after_expand = Expander::new(&mut membership).expand(&version); + prop_assert_eq!(before, after_expand); + } +}