From b58ad8cf7d4af70928f14d8eba7183f49e51cd2b Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:38:49 -0600 Subject: [PATCH 1/4] feat(id): add pure writer-set view projection and expansion semantics - Add pkgs/id/src/idset/view.rs: pure projection/discovery expansion over an explicitly pinned snapshot; no store wiring yet. - Add pkgs/id/tests/writer_set_projection.rs: targeted acceptance tests for expansion semantics and edge cases. Refs #5545 --- pkgs/id/src/idset.rs | 3 + pkgs/id/src/idset/view.rs | 299 +++++++++++++++++++++++++ pkgs/id/tests/writer_set_projection.rs | 141 ++++++++++++ 3 files changed, 443 insertions(+) create mode 100644 pkgs/id/src/idset/view.rs create mode 100644 pkgs/id/tests/writer_set_projection.rs diff --git a/pkgs/id/src/idset.rs b/pkgs/id/src/idset.rs index 71136b8fac..d1c11268e8 100644 --- a/pkgs/id/src/idset.rs +++ b/pkgs/id/src/idset.rs @@ -61,6 +61,9 @@ use unicode_normalization::is_nfc; use crate::groups::Role; use crate::waiting::AuthorKey; +/// View projection and discovery over an explicitly pinned snapshot. +pub mod view; + /// The kind of a writer-set event, as the header's `kind` names it. pub const WRITER_KIND: &str = "idset.writer"; diff --git a/pkgs/id/src/idset/view.rs b/pkgs/id/src/idset/view.rs new file mode 100644 index 0000000000..058aa4a643 --- /dev/null +++ b/pkgs/id/src/idset/view.rs @@ -0,0 +1,299 @@ +//! Pure writer-set projection and subject discovery (§§4–5 of the writer-set +//! design). The caller supplies the immutable event and membership snapshot; +//! this module never consults live store state. + +use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet}; +use std::ops::Bound::{Excluded, Unbounded}; + +use p2panda_core::Hash; + +use crate::groups::Role; +use crate::waiting::AuthorKey; + +use super::{Entry, Excludes, Rescind, WriterSet}; + +/// One-level, frontier-pinned direct membership for a group. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct GroupMembers { + /// The group being expanded. + pub group: Hash, + /// The publishing event's signed causal frontier. + pub frontier: Vec, + /// The resolution snapshot under which membership was resolved. + pub resolution: Hash, + /// Direct key members and their resolved roles. Group-valued members are + /// deliberately not represented: writer-set expansion does not recurse. + pub members: BTreeMap, +} + +impl GroupMembers { + /// A membership result for one `(group, frontier, resolution)` tuple. + #[must_use] + pub fn new( + group: Hash, + frontier: Vec, + resolution: Hash, + members: BTreeMap, + ) -> Self { + Self { + group, + frontier, + resolution, + members, + } + } +} + +/// An expanded entry set. A public admission is represented without +/// materializing every known author; exclusions always take precedence. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ExpandedWriters { + public: bool, + authors: BTreeSet, + excludes_public: bool, + excluded_authors: BTreeSet, +} + +impl ExpandedWriters { + /// Whether `author` is admitted after exclusions are applied. + #[must_use] + pub fn contains(&self, author: &AuthorKey) -> bool { + !self.excludes_public + && (self.public || self.authors.contains(author)) + && !self.excluded_authors.contains(author) + } + + /// Whether this expansion admits every author before exclusions. + #[must_use] + pub const fn is_public(&self) -> bool { + self.public + } + + /// Explicitly named authors. A public expansion still requires an + /// all-authors index lookup by its caller. + #[must_use] + pub fn explicit_authors(&self) -> &BTreeSet { + &self.authors + } +} + +/// A projection or discovery input cannot be evaluated as specified. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub enum ProjectionError { + /// A referenced event or causal dependency is absent from the snapshot. + #[error("the pinned snapshot is missing event {0}")] + MissingEvent(Hash), + /// No resolved one-level membership was supplied for this tuple. + #[error("the pinned snapshot is missing group {group} at its frontier under resolution {resolution}")] + MissingGroupMembers { + /// The group whose expansion is missing. + group: Hash, + /// The resolution snapshot required by the view. + resolution: Hash, + }, + /// Two events in the input use the same ID. + #[error("the pinned snapshot contains duplicate event {0}")] + DuplicateEvent(Hash), + /// A selected view or writer-set input does not pass its pinned validity gate. + #[error("the selected {0} configuration event is not applied under the pinned resolution")] + Undefined(&'static str), + /// The event metadata does not agree with the writer-set object it carries. + #[error("writer-set event {0} does not match its signed author, sequence, or selected set")] + InvalidWriterSet(Hash), + /// A set event has the wrong body shape for its event kind. + #[error("event {0} has a writer-set kind but no matching decoded object")] + MissingWriterSet(Hash), + /// A continuation cursor belongs to another snapshot or query. + #[error("the discovery cursor does not belong to this snapshot and query")] + StaleCursor, + /// The discovery budget cannot make progress or is invalid. + #[error("the discovery budget must allow at least one indexed row")] + InvalidBudget, + /// The first row to scan is larger than the byte budget. + #[error("the next indexed row is larger than the discovery byte budget")] + BudgetTooSmall, +} + +/// The least role a group member must hold, in the project's role order. +fn role_at_least(actual: Role, minimum: Role) -> bool { + actual >= minimum +} + +/// Expands a writer-set's entries at their publishing frontier. +/// +/// For `retro`, only admission entries with `include_history` contribute; all +/// exclusions still apply. Group snapshots are direct-member snapshots and are +/// selected by the complete `(group, frontier, resolution)` tuple. +/// +/// # Errors +/// +/// Returns [`ProjectionError::MissingGroupMembers`] when a group entry has no +/// matching pinned membership snapshot. +pub fn expand_set( + set: &WriterSet, + frontier: &[Hash], + resolution: &Hash, + groups: &[GroupMembers], + retro: bool, +) -> Result { + let mut expanded = ExpandedWriters::default(); + add_entries( + &mut expanded, + &set.entries, + frontier, + resolution, + groups, + retro, + false, + )?; + add_entries( + &mut expanded, + &set.excludes, + frontier, + resolution, + groups, + false, + true, + )?; + Ok(expanded) +} + +fn add_entries( + expanded: &mut ExpandedWriters, + entries: &[Entry], + frontier: &[Hash], + resolution: &Hash, + groups: &[GroupMembers], + history_only: bool, + exclusion: bool, +) -> Result<(), ProjectionError> { + for entry in entries { + if history_only && !entry.include_history() { + continue; + } + match entry { + Entry::Key { author, .. } => { + if exclusion { + expanded.excluded_authors.insert(*author); + } else { + expanded.authors.insert(*author); + } + } + Entry::Group { + id, role_min, .. + } => { + let members = groups + .iter() + .find(|snapshot| { + snapshot.group == *id + && snapshot.frontier == frontier + && snapshot.resolution == *resolution + }) + .ok_or(ProjectionError::MissingGroupMembers { + group: *id, + resolution: *resolution, + })?; + for (author, role) in &members.members { + if role_at_least(*role, *role_min) { + if exclusion { + expanded.excluded_authors.insert(*author); + } else { + expanded.authors.insert(*author); + } + } + } + } + Entry::Public { .. } => { + if exclusion { + expanded.excludes_public = true; + } else { + expanded.public = true; + } + } + } + } + Ok(()) +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used)] +mod tests { + use super::*; + use crate::idset::{Entry, Excludes, WriterSet}; + + fn author(n: u8) -> AuthorKey { + [n; 32] + } + + fn hash(n: u8) -> Hash { + Hash::new([n; 32]) + } + + fn set(entries: Vec, excludes: Vec) -> WriterSet { + WriterSet { + set_id: hash(90), + version: 3, + owner: author(1), + scope: Some("test".to_owned()), + entries, + excludes: Excludes(excludes), + } + } + + #[test] + fn test_retro_expansion_uses_only_history_marked_entries_and_exclusions_win() { + let group = hash(10); + let frontier = vec![hash(11)]; + let resolution = hash(12); + let members = GroupMembers::new( + group, + frontier.clone(), + resolution, + BTreeMap::from([(author(2), Role::Read), (author(3), Role::Write)]), + ); + let set = set( + vec![ + Entry::Key { + author: author(2), + include_history: true, + }, + Entry::Key { + author: author(4), + include_history: false, + }, + Entry::Group { + id: group, + role_min: Role::Write, + include_history: true, + }, + ], + vec![Entry::Key { + author: author(3), + include_history: false, + }], + ); + + let expanded = expand_set(&set, &frontier, &resolution, &[members], true).unwrap(); + + assert!(expanded.contains(&author(2))); + assert!(!expanded.contains(&author(3))); + assert!(!expanded.contains(&author(4))); + } + + #[test] + fn test_public_exclusion_admits_nobody() { + let set = set( + vec![Entry::Public { + include_history: true, + }], + vec![Entry::Public { + include_history: false, + }], + ); + + let expanded = expand_set(&set, &[], &hash(12), &[], false).unwrap(); + + assert!(expanded.is_public()); + assert!(!expanded.contains(&author(2))); + } +} diff --git a/pkgs/id/tests/writer_set_projection.rs b/pkgs/id/tests/writer_set_projection.rs new file mode 100644 index 0000000000..9d810308ba --- /dev/null +++ b/pkgs/id/tests/writer_set_projection.rs @@ -0,0 +1,141 @@ +//! Writer-set view projection and discovery over an explicitly pinned snapshot. +//! Tests the acceptance points of the writer-set design (§§4–5). + +use id::idset::view::{expand_set, GroupMembers}; +use id::groups::Role; +use id::idset::{Entry, Excludes, WriterSet}; +use p2panda_core::Hash; + +fn author(n: u8) -> [u8; 32] { + [n; 32] +} + +fn hash(n: u8) -> Hash { + Hash::new([n; 32]) +} + +#[test] +fn test_expansion_public_exclusion_admits_nobody() { + let set = WriterSet { + set_id: hash(90), + version: 3, + owner: author(1), + scope: Some("test".to_owned()), + entries: vec![Entry::Public { + include_history: true, + }], + excludes: Excludes(vec![Entry::Public { + include_history: false, + }]), + }; + + let expanded = expand_set(&set, &[], &hash(12), &[], false).unwrap(); + + assert!(expanded.is_public()); + assert!(!expanded.contains(&author(2))); +} + +#[test] +fn test_expansion_key_exclusion_wins() { + let set = WriterSet { + set_id: hash(90), + version: 3, + owner: author(1), + scope: Some("test".to_owned()), + entries: vec![Entry::Key { + author: author(2), + include_history: true, + }], + excludes: Excludes(vec![Entry::Key { + author: author(2), + include_history: false, + }]), + }; + + let expanded = expand_set(&set, &[], &hash(12), &[], false).unwrap(); + + assert!(expanded.contains(&author(2))); + assert!(!expanded.contains(&author(3))); +} + +#[test] +fn test_expansion_group_one_level_frontier_pinned() { + let group = hash(10); + let frontier = vec![hash(11)]; + let resolution = hash(12); + let members = GroupMembers::new( + group, + frontier.clone(), + resolution, + std::collections::BTreeMap::from([ + (author(2), Role::Read), + (author(3), Role::Write), + ]), + ); + + let set = WriterSet { + set_id: hash(90), + version: 3, + owner: author(1), + scope: Some("test".to_owned()), + entries: vec![Entry::Group { + id: group, + role_min: Role::Read, + include_history: false, + }], + excludes: Excludes(vec![]), + }; + + let expanded = expand_set(&set, &frontier, &resolution, &[members], false).unwrap(); + + assert!(expanded.contains(&author(2))); + assert!(expanded.contains(&author(3))); +} + +#[test] +fn test_expansion_retro_only_history_marked_entries() { + let group = hash(10); + let frontier = vec![hash(11)]; + let resolution = hash(12); + let members = GroupMembers::new( + group, + frontier.clone(), + resolution, + std::collections::BTreeMap::from([ + (author(2), Role::Read), + (author(3), Role::Write), + ]), + ); + + let set = WriterSet { + set_id: hash(90), + version: 3, + owner: author(1), + scope: Some("test".to_owned()), + entries: vec![ + Entry::Key { + author: author(2), + include_history: true, + }, + Entry::Key { + author: author(4), + include_history: false, + }, + Entry::Group { + id: group, + role_min: Role::Write, + include_history: true, + }, + ], + excludes: Excludes(vec![Entry::Key { + author: author(3), + include_history: false, + }]), + }; + + let expanded = expand_set(&set, &frontier, &resolution, &[members], true).unwrap(); + + assert!(expanded.contains(&author(2))); + assert!(!expanded.contains(&author(3))); + assert!(!expanded.contains(&author(4))); +} From 31100ce9e321e19216c6e06e24c9a6fb24939bdc Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 19:55:58 -0600 Subject: [PATCH 2/4] fix(id): apply writer-set exclusions --- pkgs/id/src/idset/view.rs | 10 +++++----- pkgs/id/tests/writer_set_projection.rs | 14 ++++---------- 2 files changed, 9 insertions(+), 15 deletions(-) diff --git a/pkgs/id/src/idset/view.rs b/pkgs/id/src/idset/view.rs index 058aa4a643..3555988e17 100644 --- a/pkgs/id/src/idset/view.rs +++ b/pkgs/id/src/idset/view.rs @@ -84,7 +84,9 @@ pub enum ProjectionError { #[error("the pinned snapshot is missing event {0}")] MissingEvent(Hash), /// No resolved one-level membership was supplied for this tuple. - #[error("the pinned snapshot is missing group {group} at its frontier under resolution {resolution}")] + #[error( + "the pinned snapshot is missing group {group} at its frontier under resolution {resolution}" + )] MissingGroupMembers { /// The group whose expansion is missing. group: Hash, @@ -148,7 +150,7 @@ pub fn expand_set( )?; add_entries( &mut expanded, - &set.excludes, + &set.excludes.0, frontier, resolution, groups, @@ -179,9 +181,7 @@ fn add_entries( expanded.authors.insert(*author); } } - Entry::Group { - id, role_min, .. - } => { + Entry::Group { id, role_min, .. } => { let members = groups .iter() .find(|snapshot| { diff --git a/pkgs/id/tests/writer_set_projection.rs b/pkgs/id/tests/writer_set_projection.rs index 9d810308ba..0ffca09495 100644 --- a/pkgs/id/tests/writer_set_projection.rs +++ b/pkgs/id/tests/writer_set_projection.rs @@ -1,8 +1,8 @@ //! Writer-set view projection and discovery over an explicitly pinned snapshot. //! Tests the acceptance points of the writer-set design (§§4–5). -use id::idset::view::{expand_set, GroupMembers}; use id::groups::Role; +use id::idset::view::{GroupMembers, expand_set}; use id::idset::{Entry, Excludes, WriterSet}; use p2panda_core::Hash; @@ -54,7 +54,7 @@ fn test_expansion_key_exclusion_wins() { let expanded = expand_set(&set, &[], &hash(12), &[], false).unwrap(); - assert!(expanded.contains(&author(2))); + assert!(!expanded.contains(&author(2))); assert!(!expanded.contains(&author(3))); } @@ -67,10 +67,7 @@ fn test_expansion_group_one_level_frontier_pinned() { group, frontier.clone(), resolution, - std::collections::BTreeMap::from([ - (author(2), Role::Read), - (author(3), Role::Write), - ]), + std::collections::BTreeMap::from([(author(2), Role::Read), (author(3), Role::Write)]), ); let set = WriterSet { @@ -101,10 +98,7 @@ fn test_expansion_retro_only_history_marked_entries() { group, frontier.clone(), resolution, - std::collections::BTreeMap::from([ - (author(2), Role::Read), - (author(3), Role::Write), - ]), + std::collections::BTreeMap::from([(author(2), Role::Read), (author(3), Role::Write)]), ); let set = WriterSet { From f53a5d5bd55e6a00db5677672da18b95109f9730 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:00:20 -0600 Subject: [PATCH 3/4] fix(id): construct test hashes with supported API --- pkgs/id/src/idset/view.rs | 2 +- pkgs/id/tests/writer_set_projection.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pkgs/id/src/idset/view.rs b/pkgs/id/src/idset/view.rs index 3555988e17..8d272fe333 100644 --- a/pkgs/id/src/idset/view.rs +++ b/pkgs/id/src/idset/view.rs @@ -226,7 +226,7 @@ mod tests { } fn hash(n: u8) -> Hash { - Hash::new([n; 32]) + Hash::from([n; 32]) } fn set(entries: Vec, excludes: Vec) -> WriterSet { diff --git a/pkgs/id/tests/writer_set_projection.rs b/pkgs/id/tests/writer_set_projection.rs index 0ffca09495..515d80f656 100644 --- a/pkgs/id/tests/writer_set_projection.rs +++ b/pkgs/id/tests/writer_set_projection.rs @@ -11,7 +11,7 @@ fn author(n: u8) -> [u8; 32] { } fn hash(n: u8) -> Hash { - Hash::new([n; 32]) + Hash::from([n; 32]) } #[test] From 9f2bb4f218902f2ffda8606343ba9aef9a7feab1 Mon Sep 17 00:00:00 2001 From: "developing-today[bot]" <5454422+developing-today[bot]@users.noreply.github.com> Date: Fri, 6 Nov 2026 20:14:08 -0600 Subject: [PATCH 4/4] chore(id): restore world_records from origin/main --- pkgs/id/src/world_records.rs | 38 ++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/pkgs/id/src/world_records.rs b/pkgs/id/src/world_records.rs index 783674b854..cc1a88b0e2 100644 --- a/pkgs/id/src/world_records.rs +++ b/pkgs/id/src/world_records.rs @@ -266,8 +266,13 @@ pub async fn read_records(doc: &Doc, blobs: &Store) -> Result { .get_bytes(entry.content_hash()) .await .with_context(|| format!("content of record {key:?} is not available yet"))?; - let value: serde_json::Value = - serde_json::from_slice(&bytes).with_context(|| format!("record {key:?}"))?; + // A duplicate key is a parse error (#6520, #6634): the cap below + // must see the value as written, never a last-wins collapse of it — + // a duplicate could hide an over-cap value behind a small second + // entry. The publish path (parse_records) refuses the same shape. + let text = std::str::from_utf8(&bytes).with_context(|| format!("record {key:?}"))?; + let value = id_core::json_unique::parse_json_without_duplicate_keys(text) + .with_context(|| format!("record {key:?}"))?; let size = serde_json::to_vec(&value).map_or(usize::MAX, |v| v.len()); ensure!( size <= MAX_RECORD_VALUE_BYTES, @@ -657,6 +662,35 @@ mod tests { host.shutdown().await; } + #[tokio::test] + async fn read_records_refuses_a_duplicate_key_hiding_an_oversized_value() { + let host = Node::spawn().await; + let store = RecordsStore::open(&host.docs, None).await.unwrap(); + // As written this value is over the cap; collapsed last-wins it is + // {"k":"small"} and would pass — the #6634 receipt bypass. + let raw = format!( + "{{\"k\":\"{}\",\"k\":\"small\"}}", + "x".repeat(MAX_RECORD_VALUE_BYTES + 100) + ); + assert!(raw.len() > MAX_RECORD_VALUE_BYTES); + write_raw(&store, "dup", raw.into_bytes()).await; + let err = read_err(&store, &host.blobs).await; + assert!(err.contains("dup"), "{err}"); + host.shutdown().await; + } + + #[tokio::test] + async fn read_records_refuses_a_small_nested_duplicate_key() { + let host = Node::spawn().await; + let store = RecordsStore::open(&host.docs, None).await.unwrap(); + // Well under every cap, raw and collapsed: only the duplicate-key + // refusal can reject this value. + write_raw(&store, "nested", br#"{"a":{"b":1,"b":2}}"#.to_vec()).await; + let err = read_err(&store, &host.blobs).await; + assert!(err.contains("nested"), "{err}"); + host.shutdown().await; + } + #[tokio::test] async fn read_records_refuses_an_over_long_key() { let host = Node::spawn().await;