From fb05c800c5911d6453b686823a2437ce06128976 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Mon, 9 Nov 2026 21:37:28 -0600 Subject: [PATCH] id: wire writer-set view projection into EventStore + CLI (#6690) Follow-up to #5545 (projection module landed in PR #6672). The pure projection in idset::view ran only over caller-built snapshots; nothing in the store could feed it. EventStore wiring (new event_store::writer_set module): writer-set and rescind bodies verified against the header payload commitment at ingest are retained in a new additive writer_set_bodies table; stored_writer_set/stored_rescind read them back cross-checked against the stored header (kind, owner, version=seq, payload hash); group_members_snapshot builds the one-level GroupMembers from the store resolved group fold (same load+resolve path as roster) pinned under the caller (frontier, resolution) tuple; expand_stored_writer_set expands a stored set at its own publishing frontier; discover_writer_sets is the subject-first discovery query over stored sets (scope filter), each hit carrying the set and its expansion. CLI: id writer-sets show|expand|discover over the --event-store store, following the claim/doc command patterns; registered in the cli.rs doc list and README table. Snapshot limit, stated in the module doc: the store snapshot is its resolved state (fold of all applied group events it holds); frontier-historical resolution remains the membership layer pinned expander (idset::expand). --- pkgs/id/README.md | 1 + pkgs/id/src/cli.rs | 66 ++++++ pkgs/id/src/commands/mod.rs | 2 + pkgs/id/src/commands/writer_set.rs | 150 +++++++++++++ pkgs/id/src/event_store/ingest.rs | 18 +- pkgs/id/src/event_store/mod.rs | 17 +- pkgs/id/src/event_store/writer_set.rs | 308 ++++++++++++++++++++++++++ pkgs/id/src/main.rs | 3 + pkgs/id/tests/writer_set_store.rs | 290 ++++++++++++++++++++++++ 9 files changed, 851 insertions(+), 4 deletions(-) create mode 100644 pkgs/id/src/commands/writer_set.rs create mode 100644 pkgs/id/src/event_store/writer_set.rs create mode 100644 pkgs/id/tests/writer_set_store.rs diff --git a/pkgs/id/README.md b/pkgs/id/README.md index 8bc57ad61a..5460dfd399 100644 --- a/pkgs/id/README.md +++ b/pkgs/id/README.md @@ -161,6 +161,7 @@ it is — a valid world capability, minted by the host's admin with | `revoke` | | Revoke a delegation by its grant event ID | | `doc` | | Publish documents; list events/frontier/history | | `claim` | | Tag claims on any subject (set, clear, search) | +| `writer-sets` | | Writer sets in the event store (show, expand, discover) | ### Tag Subcommands diff --git a/pkgs/id/src/cli.rs b/pkgs/id/src/cli.rs index 30c457a776..7b6b599261 100644 --- a/pkgs/id/src/cli.rs +++ b/pkgs/id/src/cli.rs @@ -33,6 +33,7 @@ //! revoke Revoke a delegation by its grant's event ID //! doc Documents: publish a file; list events, frontier, history //! claim Tag claims on any subject (set, clear, list, search) +//! writer-sets Writer sets in the event store (show, expand, discover) //! migrate-tags Migrate existing files to name/file auto-tags (alias: migrate) //! ``` //! @@ -1326,6 +1327,32 @@ pub enum Command { #[command(subcommand)] command: ClaimCommand, }, + /// Writer sets stored in the event store: show one, expand it, or discover + /// sets by scope (writer-set spec §§4–5; issue #6690). + /// + /// A writer set is a signed `idset.writer` event whose body the store + /// retains at ingest. `show` prints the stored object, `expand` runs the + /// view projection over the store's resolved group state at the set's own + /// publishing frontier, and `discover` lists every stored set for a scope + /// with the writers each expands to. `--resolution` names the resolution + /// snapshot the projection is pinned under; without one, the zero hash + /// names the store's current resolved state. + /// + /// # Examples + /// + /// ```bash + /// id writer-sets discover --scope metrics + /// id writer-sets expand EVENT --json + /// id writer-sets show EVENT + /// ``` + WriterSets { + /// Print JSON instead of lines (one array for `discover`). + #[arg(long, global = true)] + json: bool, + /// The writer-set action to run. + #[command(subcommand)] + command: WriterSetCommand, + }, /// Migrate existing files to have name/file auto-tags. /// /// Scans all blob tags in the store and adds `name` and `file` @@ -2646,6 +2673,45 @@ pub enum DocCommand { }, } +/// The actions of `id writer-sets` (writer-set spec §§4–5; issue #6690). +#[derive(Subcommand, Debug, Clone, PartialEq, Eq)] +pub enum WriterSetCommand { + /// Show one stored writer set: its ID, version, owner, scope, and the + /// counts of its admission entries and exclusions. + Show { + /// The publishing event's ID. + event: String, + }, + /// Expand one stored writer set at its publishing frontier: whether the + /// expansion is public, and the explicit authors it admits after + /// exclusions. + Expand { + /// The publishing event's ID. + event: String, + /// The resolution snapshot to pin the projection under, as hex. + /// Without one, the zero hash names the store's current resolved + /// state. + #[arg(long)] + resolution: Option, + /// Expand retroactively: only entries marked include-history + /// contribute (exclusions always apply). + #[arg(long)] + retro: bool, + }, + /// Discover stored writer sets by scope: one row per set, with the + /// writers it expands to. Without `--scope`, every stored set matches. + Discover { + /// The scope (subject) to match, exactly. + #[arg(long)] + scope: Option, + /// The resolution snapshot to pin each expansion under, as hex. + /// Without one, the zero hash names the store's current resolved + /// state. + #[arg(long)] + resolution: Option, + }, +} + /// Subcommands for `id claim`. A claim is the event that sets a tag on a subject. #[derive(Subcommand, Debug)] pub enum ClaimCommand { diff --git a/pkgs/id/src/commands/mod.rs b/pkgs/id/src/commands/mod.rs index cee12f7c36..aac1b53756 100644 --- a/pkgs/id/src/commands/mod.rs +++ b/pkgs/id/src/commands/mod.rs @@ -74,6 +74,7 @@ pub mod tag; pub mod text; #[cfg(feature = "world")] pub mod world; +pub mod writer_set; pub use claim::cmd_claim; pub use client::create_local_client_endpoint; @@ -101,3 +102,4 @@ pub use serve::{ pub use tag::{cmd_migrate_tags, cmd_tag}; #[cfg(feature = "world")] pub use world::cmd_world; +pub use writer_set::cmd_writer_sets; diff --git a/pkgs/id/src/commands/writer_set.rs b/pkgs/id/src/commands/writer_set.rs new file mode 100644 index 0000000000..98f2dfab02 --- /dev/null +++ b/pkgs/id/src/commands/writer_set.rs @@ -0,0 +1,150 @@ +//! `id writer-sets`: show, expand, and discover the writer sets stored in +//! the event store (writer-set spec §§4–5; issue #6690). +//! +//! This module parses the arguments, acts on the event store, and prints. +//! The rules are the library's ([`crate::event_store`]): a stored set is read +//! back from its retained body and checked against its publishing header, +//! the projection is [`crate::idset::view::expand_set`] over snapshots the +//! store builds from its resolved group state, and discovery is +//! subject-first — filter by the set's scope, each hit carrying the set and +//! the writers it expands to. +//! +//! # Output +//! +//! `show` prints `show event= set= version= owner= +//! [scope=] entries= excludes=`. `expand` prints `expand +//! event= public= authors= retro=`. `discover` +//! prints one row per stored set, `event= set= version= [scope=] public= +//! authors=`, or one JSON array with `--json`. + +use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; + +use anyhow::{Result, bail}; +use p2panda_core::Hash; +use serde_json::{Value, json}; + +use crate::cli::WriterSetCommand; +use crate::commands::doc::{print_action, print_rows}; +use crate::commands::group::hex; +use crate::event_store::{DiscoveredWriterSet, EventStore}; +use crate::groups::log::hash_from_hex; +use crate::idset::WriterSet; +use crate::idset::view::ExpandedWriters; +use crate::local_events::DIR_NAME; +use crate::waiting::WaitingLimits; + +/// Opens the event store the command reads, at `path` or the default +/// events directory. +fn open_store(path: Option) -> Result { + let dir = path.unwrap_or_else(|| PathBuf::from(DIR_NAME)); + std::fs::create_dir_all(&dir) + .map_err(|err| anyhow::anyhow!("create {}: {err}", dir.display()))?; + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX)) + .unwrap_or(0); + Ok(EventStore::open(&dir, WaitingLimits::default(), now_ms)?) +} + +/// The resolution snapshot a query pins: the `--resolution` hash when one is +/// given, else the zero hash, which names the store's current resolved +/// state. +fn resolution(pin: Option) -> Result { + match pin { + Some(text) => hash_from_hex(&text), + None => Ok(Hash::from([0; 32])), + } +} + +/// The author keys an expansion admits explicitly, as hex, in key order. +fn author_values(expanded: &ExpandedWriters) -> Value { + json!( + expanded + .explicit_authors() + .iter() + .map(|author| hex(author)) + .collect::>() + ) +} + +/// The fields of one stored set, as `show` prints them. +fn set_fields(event: Hash, set: &WriterSet) -> Vec<(&'static str, Value)> { + let mut fields = vec![ + ("event", json!(event.to_hex())), + ("set", json!(set.set_id.to_hex())), + ("version", json!(set.version)), + ("owner", json!(hex(&set.owner))), + ]; + if let Some(scope) = &set.scope { + fields.push(("scope", json!(scope))); + } + fields.push(("entries", json!(set.entries.len()))); + fields.push(("excludes", json!(set.excludes.0.len()))); + fields +} + +/// The fields of one discovery hit, as `discover` rows print them. +fn hit_fields(hit: &DiscoveredWriterSet) -> Vec<(&'static str, Value)> { + let mut fields = vec![ + ("event", json!(hit.event_id.to_hex())), + ("set", json!(hit.set.set_id.to_hex())), + ("version", json!(hit.set.version)), + ]; + if let Some(scope) = &hit.set.scope { + fields.push(("scope", json!(scope))); + } + fields.push(("public", json!(hit.expanded.is_public()))); + fields.push(("authors", author_values(&hit.expanded))); + fields +} + +/// Runs an `id writer-sets` command. +/// +/// # Errors +/// +/// Fails if an argument is malformed, the store cannot be opened or read, +/// or the named event is not a stored writer set. +pub async fn cmd_writer_sets( + path: Option, + json: bool, + command: WriterSetCommand, +) -> Result<()> { + let store = open_store(path)?; + match command { + WriterSetCommand::Show { event } => { + let event = hash_from_hex(&event)?; + let Some(set) = store.stored_writer_set(&event)? else { + bail!("no stored writer set for event {event}"); + }; + print_action(json, "show", set_fields(event, &set)); + } + WriterSetCommand::Expand { + event, + resolution: pin, + retro, + } => { + let event = hash_from_hex(&event)?; + let expanded = store.expand_stored_writer_set(&event, &resolution(pin)?, retro)?; + print_action( + json, + "expand", + vec![ + ("event", json!(event.to_hex())), + ("public", json!(expanded.is_public())), + ("authors", author_values(&expanded)), + ("retro", json!(retro)), + ], + ); + } + WriterSetCommand::Discover { + scope, + resolution: pin, + } => { + let hits = store.discover_writer_sets(scope.as_deref(), &resolution(pin)?)?; + let rows: Vec> = hits.iter().map(hit_fields).collect(); + print_rows(json, &rows); + } + } + Ok(()) +} diff --git a/pkgs/id/src/event_store/ingest.rs b/pkgs/id/src/event_store/ingest.rs index fe619da5e5..62bbb92e7c 100644 --- a/pkgs/id/src/event_store/ingest.rs +++ b/pkgs/id/src/event_store/ingest.rs @@ -236,6 +236,9 @@ impl EventStore { /// - A body that is not a group operation, or no body at all, makes the event content. /// - A body that claims to be a group operation decodes to its action, or it is refused. /// - A body that is not the one the header commits to, by BLAKE3 hash and size, is refused. + /// - A writer-set or rescind event's verified body is retained with the store + /// (`writer_set_bodies`), so the stored object can be read back and projected + /// (issue #6690; see the `writer_set` submodule). /// - A tag event (kind `tag.set` or `tag.clear`) takes no body. Its operation is in its /// header (#182), so a payload on a tag event is refused. Its tag takes no membership /// action, and the fold reads it from the stored header (see `claims`). @@ -258,6 +261,13 @@ impl EventStore { Err(err) => return Ok(Ingest::Refused(Refusal::Malformed(err.to_string()))), }; let kind = &event.header.extensions.kind; + // A writer-set or rescind body is retained with its event (issue + // #6690): the header commits to it by hash, and `body_action` below + // has already refused a body that is not the committed one, so what + // is retained here is the object the signer published. + let retain_body = body + .filter(|_| crate::idset::is_writer_kind(kind) || crate::idset::is_rescind_kind(kind)); + let event_id = event.id; let action = if is_tag_kind(kind) || is_document_kind(kind) || is_removal_kind(kind) { if body.is_some() { return Ok(Ingest::Refused(Refusal::Malformed( @@ -272,7 +282,13 @@ impl EventStore { Err(refusal) => return Ok(Ingest::Refused(refusal)), } }; - self.ingest_event(event, action.as_ref(), now_ms) + let result = self.ingest_event(event, action.as_ref(), now_ms)?; + if let Some(body) = retain_body + && !matches!(result, Ingest::Refused(_)) + { + self.record_writer_body(&event_id, body)?; + } + Ok(result) } /// Verifies one received event, which may be a group operation, and applies what it allows. diff --git a/pkgs/id/src/event_store/mod.rs b/pkgs/id/src/event_store/mod.rs index 9d250cce13..5aede500d1 100644 --- a/pkgs/id/src/event_store/mod.rs +++ b/pkgs/id/src/event_store/mod.rs @@ -70,11 +70,13 @@ pub mod range; mod resolve; pub mod sync; mod waiting_rows; +mod writer_set; use crate::waiting::{AuthorKey, WaitRefusal, WaitingLimits, WaitingPool}; pub use ingest::{Ingest, Refusal}; use ingest::{is_present, is_proof_header, present_in}; use waiting_rows::{Mirror, Row}; +pub use writer_set::{DiscoveredWriterSet, WriterSetStoreError}; /// The store's file name in its directory. pub const FILE_NAME: &str = "events.redb"; @@ -109,6 +111,14 @@ const WAITING_BY_DEP: MultimapTableDefinition<'static, &'static [u8], &'static [ const META: TableDefinition<'static, &'static [u8], &'static [u8]> = TableDefinition::new("meta"); const BLOCKS: TableDefinition<'static, &'static [u8], &'static [u8]> = TableDefinition::new("blocks"); +/// Each writer-set or rescind event's retained body, by event ID (writer-set +/// spec §§4–5; issue #6690). Headers commit to bodies by hash but are stored +/// without them; this table is the one place a body is kept, so a stored +/// writer-set object can be read back and checked against its header. Written +/// only from the ingest path, after the body has been verified against the +/// header's payload commitment. +const WRITER_SET_BODIES: TableDefinition<'static, &'static [u8], &'static [u8]> = + TableDefinition::new("writer_set_bodies"); /// Each group operation's encoded action, by event ID. Written when the event arrives, held or /// stored, so a release reads it back without the caller. The resolution reads it again. const ACTIONS: TableDefinition<'static, &'static [u8], &'static [u8]> = @@ -647,12 +657,13 @@ impl EventStore { create_fresh(storage)? }; verify_schema(&db)?; - // The blocks table is additive: stores created before it gain it here, - // on the write every open already performs, instead of a format change - // that would refuse them. + // The blocks and writer-set-bodies tables are additive: stores created + // before them gain them here, on the write every open already + // performs, instead of a format change that would refuse them. { let txn = db.begin_write()?; txn.open_table(BLOCKS)?; + txn.open_table(WRITER_SET_BODIES)?; txn.commit()?; } let mut store = Self { diff --git a/pkgs/id/src/event_store/writer_set.rs b/pkgs/id/src/event_store/writer_set.rs new file mode 100644 index 0000000000..cbd9dc2a9f --- /dev/null +++ b/pkgs/id/src/event_store/writer_set.rs @@ -0,0 +1,308 @@ +//! Writer-set objects in the store (writer-set spec §§4–5; issue #6690, +//! follow-up to #5545). +//! +//! The pure projection lives in [`crate::idset::view`]: it runs over a pinned +//! snapshot and never consults live store state. This module is the wiring +//! that lets it run against what a store actually holds: +//! +//! - **Body retention.** Event headers commit to a body by hash but the store +//! otherwise keeps no bodies. When a writer-set or rescind event is ingested +//! with its body ([`EventStore::ingest_with_body`]) and the body is the one +//! the header commits to, the body is retained here, keyed by event ID, so +//! the object can be read back and checked against its header. +//! - **Reads.** [`EventStore::stored_writer_set`] and +//! [`EventStore::stored_rescind`] decode a retained body and cross-check it +//! against the stored header: kind, author/owner, sequence/version, and the +//! payload hash commitment. A body that disagrees with its header is +//! corruption, never a usable object. +//! - **Snapshots.** [`EventStore::group_members_snapshot`] builds the +//! one-level [`GroupMembers`] a projection needs from the store's resolved +//! group state (the same load + resolve path as [`EventStore::roster`]), +//! pinned under the caller's `(frontier, resolution)` tuple. +//! - **Projection + discovery.** [`EventStore::expand_stored_writer_set`] +//! expands one stored set at its own publishing frontier, and +//! [`EventStore::discover_writer_sets`] is the subject-first discovery +//! query over every stored set: filter by scope (the set's subject), each +//! hit carrying the set and its expanded writers — both sides of the set, +//! not the set alone. +//! +//! The snapshot a store can offer today is its *resolved* state: the fold of +//! every applied group event it holds. Frontier-historical resolution — +//! membership as of an older causal position — stays with the membership +//! layer's pinned expander ([`crate::idset::expand`]); the tuple recorded on +//! the snapshot names the caller's pin so a result is never presented as +//! resolved under a different snapshot than it was. + +use std::collections::BTreeMap; + +use p2panda_core::Hash; +use redb::{ReadableDatabase, ReadableTable}; + +use crate::groups::Role; +use crate::idset::view::{ExpandedWriters, GroupMembers, ProjectionError, expand_set}; +use crate::idset::{IdsetError, Rescind, WriterSet, decode_rescind_body, decode_writer_body}; +use crate::waiting::AuthorKey; + +use super::{EventStore, StoreError, WRITER_SET_BODIES, resolve}; + +/// Why a stored writer-set object cannot be read or expanded. +#[derive(Debug, thiserror::Error)] +pub enum WriterSetStoreError { + /// The underlying store read or write failed. + #[error(transparent)] + Store(#[from] StoreError), + /// The retained body is not a valid object of its kind. + #[error(transparent)] + Body(#[from] IdsetError), + /// No applied writer-set event has this ID. + #[error("no stored writer-set event {0}")] + NoSuchSet(Hash), + /// The stored event or its retained body disagrees with the other: the + /// event is not of the expected kind, its author is not the object's + /// owner, its sequence is not the object's version, or its payload hash + /// does not commit to the body. + #[error("stored writer-set event {0} does not match its body")] + Mismatch(Hash), + /// The projection could not be evaluated over the store's snapshot. + #[error(transparent)] + Projection(#[from] ProjectionError), +} + +/// One discovery hit: a stored writer set and the writers it expands to +/// under the query's resolution snapshot. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DiscoveredWriterSet { + /// The event that published this version of the set. + pub event_id: Hash, + /// The set object, as decoded from its retained body. + pub set: WriterSet, + /// The set expanded at its publishing frontier under the query's + /// resolution: who the set admits, after exclusions. + pub expanded: ExpandedWriters, +} + +impl EventStore { + /// Retains the body of a writer-set or rescind event, keyed by the + /// event's ID. Called from the ingest path once the body has been + /// verified against the header's payload commitment; a body retained for + /// an event that is later superseded by a fork proof is harmless, as + /// every read cross-checks the body against the stored header and the + /// applied state. + /// + /// # Errors + /// + /// Returns a redb error if the write fails. + pub(super) fn record_writer_body(&self, id: &Hash, body: &[u8]) -> Result<(), StoreError> { + let txn = self.db.begin_write()?; + { + let mut bodies = txn.open_table(WRITER_SET_BODIES)?; + bodies.insert(id.as_bytes().as_slice(), body)?; + } + txn.commit()?; + Ok(()) + } + + /// The retained body of the event with this ID, when one was ingested + /// with the event. Only writer-set and rescind events retain bodies. + /// + /// # Errors + /// + /// Returns a redb error if the read fails. + pub fn writer_set_body(&self, id: &Hash) -> Result>, StoreError> { + let txn = self.db.begin_read()?; + let bodies = txn.open_table(WRITER_SET_BODIES)?; + let row = bodies.get(id.as_bytes().as_slice())?; + Ok(row.map(|body| body.value().to_vec())) + } + + /// The stored writer set published by the event with this ID. + /// + /// Returns `None` when the event is not an applied writer-set event or + /// no body was retained for it. A retained body that disagrees with its + /// header — kind, owner, version, or the payload hash commitment — is an + /// error, not an absent set. + /// + /// # Errors + /// + /// Returns [`WriterSetStoreError::Mismatch`] when the body and the header + /// disagree, [`WriterSetStoreError::Body`] when the body does not decode, + /// or a store error when a read fails. + pub fn stored_writer_set(&self, id: &Hash) -> Result, WriterSetStoreError> { + let Some((event, body)) = self.writer_object_parts(id, crate::idset::WRITER_KIND)? else { + return Ok(None); + }; + let set = decode_writer_body(&body)?; + let author = resolve::author_of(&event); + if set.owner != author || set.version != u64::from(event.header.seq_num) { + return Err(WriterSetStoreError::Mismatch(*id)); + } + Ok(Some(set)) + } + + /// The stored rescind published by the event with this ID, under the same + /// rules as [`EventStore::stored_writer_set`]. A rescind carries no owner + /// or version of its own — its set is named in the body — so the check is + /// kind plus the payload hash commitment. + /// + /// # Errors + /// + /// The same errors as [`EventStore::stored_writer_set`]. + pub fn stored_rescind(&self, id: &Hash) -> Result, WriterSetStoreError> { + let Some((_event, body)) = self.writer_object_parts(id, crate::idset::RESCIND_KIND)? else { + return Ok(None); + }; + Ok(Some(decode_rescind_body(&body)?)) + } + + /// The event and retained body behind a writer-object read: the event + /// must be stored, applied, and of `kind`, the body must be retained, and + /// the header must commit to the body by payload hash. + fn writer_object_parts( + &self, + id: &Hash, + kind: &str, + ) -> Result)>, WriterSetStoreError> { + let Some(event) = self.event_by_id(id)? else { + return Ok(None); + }; + if event.header.extensions.kind != kind || !self.event_applied(id)? { + return Ok(None); + } + let Some(body) = self.writer_set_body(id)? else { + return Ok(None); + }; + if event.header.payload_hash != Some(Hash::digest(&body)) { + return Err(WriterSetStoreError::Mismatch(*id)); + } + Ok(Some((event, body))) + } + + /// The one-level membership snapshot of `group` from the store's + /// resolved state, pinned under `(frontier, resolution)`. + /// + /// Members and roles come from the group fold over every applied group + /// event the store holds — the same resolution [`EventStore::roster`] + /// reports, with roles kept. A group the store does not know resolves to + /// an empty snapshot: the projection then admits nobody through that + /// group entry, rather than failing the whole expansion. + /// + /// # Errors + /// + /// Returns a store error when the resolution cannot be loaded. + pub fn group_members_snapshot( + &self, + group: &Hash, + frontier: Vec, + resolution: &Hash, + ) -> Result { + let txn = self.db.begin_read()?; + let (stored, forks, headers) = { + let events = txn.open_table(super::EVENTS)?; + let actions = txn.open_table(super::ACTIONS)?; + let forks = txn.open_table(super::FORKS)?; + let proof_headers = txn.open_table(super::PROOF_HEADERS)?; + resolve::load(&events, &actions, &forks, &proof_headers)? + }; + let resolved = resolve::resolve(&stored, &forks, &headers)?; + let members: BTreeMap = resolved + .projection + .as_ref() + .and_then(|projection| projection.group(group)) + .map(|view| view.members.clone()) + .unwrap_or_default(); + Ok(GroupMembers::new(*group, frontier, *resolution, members)) + } + + /// Expands the stored writer set published by `id` at the set event's + /// own publishing frontier (its signed `after` dependencies and + /// backlink), under `resolution`. + /// + /// With `retro`, only entries marked `include_history` contribute, per + /// the projection's retro rule; exclusions always apply. + /// + /// # Errors + /// + /// Returns [`WriterSetStoreError::NoSuchSet`] when no applied writer set + /// has this ID, or the read/projection error that stopped the expansion. + pub fn expand_stored_writer_set( + &self, + id: &Hash, + resolution: &Hash, + retro: bool, + ) -> Result { + let Some(set) = self.stored_writer_set(id)? else { + return Err(WriterSetStoreError::NoSuchSet(*id)); + }; + let event = self + .event_by_id(id)? + .ok_or(WriterSetStoreError::NoSuchSet(*id))?; + let mut frontier: Vec = event.header.extensions.after.clone(); + if let Some(backlink) = event.header.backlink + && !frontier.contains(&backlink) + { + frontier.push(backlink); + } + let mut groups = Vec::new(); + let mut seen = Vec::new(); + for entry in set.entries.iter().chain(set.excludes.0.iter()) { + if let crate::idset::Entry::Group { id: group, .. } = entry + && !seen.contains(group) + { + seen.push(*group); + groups.push(self.group_members_snapshot(group, frontier.clone(), resolution)?); + } + } + Ok(expand_set(&set, &frontier, resolution, &groups, retro)?) + } + + /// The discovery query (spec §5): every stored writer set whose scope is + /// `scope` — or every stored set when `scope` is `None` — each expanded + /// at its publishing frontier under `resolution`. Hits are ordered by + /// publishing event ID, so the result is deterministic for a given store + /// state. + /// + /// A stored set whose expansion fails is reported as the error that + /// stopped it: discovery surfaces its hits whole or says why it cannot, + /// it never silently drops a set. + /// + /// # Errors + /// + /// Returns the first read or projection error that stops the scan. + pub fn discover_writer_sets( + &self, + scope: Option<&str>, + resolution: &Hash, + ) -> Result, WriterSetStoreError> { + let mut ids = Vec::new(); + { + let txn = self.db.begin_read().map_err(StoreError::from)?; + let bodies = txn + .open_table(WRITER_SET_BODIES) + .map_err(StoreError::from)?; + for row in bodies.iter().map_err(StoreError::from)? { + let (key, _body) = row.map_err(StoreError::from)?; + let bytes: [u8; 32] = key.value().try_into().map_err(|_| { + StoreError::Corrupt("a writer-set body key is not a hash".to_owned()) + })?; + ids.push(Hash::from(bytes)); + } + } + ids.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + let mut hits = Vec::new(); + for id in ids { + let Some(set) = self.stored_writer_set(&id)? else { + continue; + }; + if scope.is_some() && set.scope.as_deref() != scope { + continue; + } + let expanded = self.expand_stored_writer_set(&id, resolution, false)?; + hits.push(DiscoveredWriterSet { + event_id: id, + set, + expanded, + }); + } + Ok(hits) + } +} diff --git a/pkgs/id/src/main.rs b/pkgs/id/src/main.rs index 3c0a2c8a02..dd15416dc6 100644 --- a/pkgs/id/src/main.rs +++ b/pkgs/id/src/main.rs @@ -434,6 +434,9 @@ async fn main() -> Result<()> { Some(Command::Claim { json, command }) => { id::commands::cmd_claim(cli.event_store, json, command).await } + Some(Command::WriterSets { json, command }) => { + id::commands::cmd_writer_sets(cli.event_store, json, command).await + } #[cfg(feature = "sandbox")] Some(Command::MatchAudit(command)) => id::commands::cmd_match_audit(command), #[cfg(feature = "world")] diff --git a/pkgs/id/tests/writer_set_store.rs b/pkgs/id/tests/writer_set_store.rs new file mode 100644 index 0000000000..1e59929658 --- /dev/null +++ b/pkgs/id/tests/writer_set_store.rs @@ -0,0 +1,290 @@ +//! Store-backed writer-set wiring (writer-set spec §§4–5; issue #6690, +//! follow-up to #5545): a writer-set event ingested with its body is +//! retained by the store, reads back checked against its header, expands +//! over the store's resolved group state, and is found by the discovery +//! query. The oracle is the pure projection itself +//! ([`id::idset::view::expand_set`]) fed the same set: the store path must +//! agree with it, and a body that disagrees with its header must never +//! become a usable object. + +#![allow(clippy::unwrap_used, clippy::expect_used)] + +use id::chain::{ChainExt, sign}; +use id::event_store::{EventStore, Ingest, WriterSetStoreError}; +use id::idset::view::expand_set; +use id::idset::{ + Entry, Excludes, RESCIND_KIND, Rescind, WRITER_KIND, WriterSet, encode_rescind_body, + encode_writer_body, +}; +use id::waiting::{AuthorKey, WaitingLimits}; +use p2panda_core::{Hash, SigningKey}; + +fn author_of(key: &SigningKey) -> AuthorKey { + *key.verifying_key().as_bytes() +} + +fn ext(kind: &str) -> ChainExt { + ChainExt { + kind: kind.to_owned(), + group: None, + after: vec![], + tag: None, + document: None, + removes: None, + note: None, + link: None, + checkpoint: None, + rotation: None, + chat: None, + } +} + +fn store() -> (tempfile::TempDir, EventStore) { + let dir = tempfile::tempdir().unwrap(); + let store = EventStore::open(dir.path(), WaitingLimits::default(), 0).unwrap(); + (dir, store) +} + +const ALICE: u8 = 21; +const BOB: u8 = 22; +const CAROL: u8 = 23; + +fn key_author(n: u8) -> AuthorKey { + [n; 32] +} + +/// A set for scope `metrics`: Alice and Bob admitted, Bob excluded again — +/// exclusions win, so the expansion admits Alice only. +fn metrics_set(owner: AuthorKey, version: u64) -> WriterSet { + WriterSet { + set_id: WriterSet::derive_set_id(&owner, "metrics"), + version, + owner, + scope: Some("metrics".to_owned()), + entries: vec![ + Entry::Key { + author: key_author(ALICE), + include_history: true, + }, + Entry::Key { + author: key_author(BOB), + include_history: false, + }, + ], + excludes: Excludes(vec![Entry::Key { + author: key_author(BOB), + include_history: false, + }]), + } +} + +/// Signs `set` at its own version on `owner`'s chain and ingests it with its +/// body. Returns the publishing event's ID. +fn publish( + store: &mut EventStore, + key: &SigningKey, + set: &WriterSet, + backlink: Option, +) -> Hash { + let body = encode_writer_body(set).unwrap(); + let event = sign( + key, + u32::try_from(set.version).unwrap(), + backlink, + Some(&body), + ext(WRITER_KIND), + ) + .unwrap(); + let result = store + .ingest_with_body(&event.bytes, Some(&body), 0) + .unwrap(); + assert!( + matches!(result, Ingest::Accepted { .. }), + "writer-set event was not accepted: {result:?}" + ); + event.id +} + +#[test] +fn test_stored_writer_set_reads_back_and_expands_like_the_pure_projection() { + let (_dir, mut store) = store(); + let key = SigningKey::from_bytes(&[7; 32]); + let owner = author_of(&key); + let set = metrics_set(owner, 0); + let id = publish(&mut store, &key, &set, None); + + // The retained body reads back as the published object. + assert_eq!(store.stored_writer_set(&id).unwrap(), Some(set.clone())); + assert_eq!( + store.writer_set_body(&id).unwrap(), + Some(encode_writer_body(&set).unwrap()) + ); + + // The store expansion agrees with the pure projection over an empty + // group snapshot set (the set names no groups). + let resolution = Hash::from([9; 32]); + let expanded = store + .expand_stored_writer_set(&id, &resolution, false) + .unwrap(); + let oracle = expand_set(&set, &[], &resolution, &[], false).unwrap(); + assert_eq!(expanded, oracle); + assert!(expanded.contains(&key_author(ALICE))); + assert!(!expanded.contains(&key_author(BOB))); + assert!(!expanded.contains(&key_author(CAROL))); + assert!(!expanded.is_public()); + + // Retro expansion: only Alice's entry is marked include-history, and + // she is admitted either way; Bob stays excluded. + let retro = store + .expand_stored_writer_set(&id, &resolution, true) + .unwrap(); + assert!(retro.contains(&key_author(ALICE))); + assert!(!retro.contains(&key_author(BOB))); +} + +#[test] +fn test_writer_set_without_body_is_not_a_stored_object() { + let (_dir, mut store) = store(); + let key = SigningKey::from_bytes(&[8; 32]); + let owner = author_of(&key); + let set = metrics_set(owner, 0); + let body = encode_writer_body(&set).unwrap(); + let event = sign(&key, 0, None, Some(&body), ext(WRITER_KIND)).unwrap(); + + // Ingested through the header-only path, the event is stored and + // applied, but no body was retained, so there is no object to read. + let result = store.ingest(&event.bytes, 0).unwrap(); + assert!(matches!(result, Ingest::Accepted { .. })); + assert_eq!(store.stored_writer_set(&event.id).unwrap(), None); + assert!(matches!( + store.expand_stored_writer_set(&event.id, &Hash::from([9; 32]), false), + Err(WriterSetStoreError::NoSuchSet(_)) + )); +} + +#[test] +fn test_discovery_finds_sets_by_scope_with_their_expansions() { + let (_dir, mut store) = store(); + let key = SigningKey::from_bytes(&[7; 32]); + let owner = author_of(&key); + + let metrics = metrics_set(owner, 0); + let metrics_id = publish(&mut store, &key, &metrics, None); + + // A second version of an unrelated set on the same chain. + let other = WriterSet { + set_id: WriterSet::derive_set_id(&owner, "other"), + version: 1, + owner, + scope: Some("other".to_owned()), + entries: vec![Entry::Public { + include_history: false, + }], + excludes: Excludes(vec![]), + }; + let body = encode_writer_body(&other).unwrap(); + let other_event = sign(&key, 1, Some(metrics_id), Some(&body), ext(WRITER_KIND)).unwrap(); + let result = store + .ingest_with_body(&other_event.bytes, Some(&body), 0) + .unwrap(); + assert!(matches!(result, Ingest::Accepted { .. })); + + let resolution = Hash::from([9; 32]); + let hits = store + .discover_writer_sets(Some("metrics"), &resolution) + .unwrap(); + assert_eq!(hits.len(), 1); + assert_eq!(hits[0].event_id, metrics_id); + assert_eq!(hits[0].set, metrics); + assert!(hits[0].expanded.contains(&key_author(ALICE))); + assert!(!hits[0].expanded.contains(&key_author(BOB))); + + // Unscoped discovery returns both sets, in event-ID order. + let all = store.discover_writer_sets(None, &resolution).unwrap(); + assert_eq!(all.len(), 2); + assert!(all[0].event_id.as_bytes() <= all[1].event_id.as_bytes()); + let public_hit = all + .iter() + .find(|hit| hit.event_id == other_event.id) + .unwrap(); + assert!(public_hit.expanded.is_public()); + assert!(public_hit.expanded.contains(&key_author(CAROL))); + + // A scope nothing published matches nothing. + assert!( + store + .discover_writer_sets(Some("nope"), &resolution) + .unwrap() + .is_empty() + ); +} + +#[test] +fn test_group_entry_expands_over_the_store_snapshot() { + let (_dir, mut store) = store(); + let key = SigningKey::from_bytes(&[7; 32]); + let owner = author_of(&key); + let unknown_group = Hash::digest(b"no such group in this store"); + + // The snapshot of a group the store does not know is empty, pinned + // under the caller's tuple. + let resolution = Hash::from([9; 32]); + let snapshot = store + .group_members_snapshot(&unknown_group, vec![], &resolution) + .unwrap(); + assert_eq!(snapshot.group, unknown_group); + assert_eq!(snapshot.resolution, resolution); + assert!(snapshot.members.is_empty()); + + // A set whose only entry is that group admits nobody through the store + // path — the snapshot exists, so the projection runs and finds no + // members, instead of failing for a missing snapshot. + let set = WriterSet { + set_id: WriterSet::derive_set_id(&owner, "grouped"), + version: 0, + owner, + scope: Some("grouped".to_owned()), + entries: vec![Entry::Group { + id: unknown_group, + role_min: id::groups::Role::Read, + include_history: false, + }], + excludes: Excludes(vec![]), + }; + let id = publish(&mut store, &key, &set, None); + let expanded = store + .expand_stored_writer_set(&id, &resolution, false) + .unwrap(); + assert!(!expanded.contains(&key_author(ALICE))); + assert!(!expanded.is_public()); +} + +#[test] +fn test_stored_rescind_reads_back() { + let (_dir, mut store) = store(); + let key = SigningKey::from_bytes(&[7; 32]); + let owner = author_of(&key); + let set = metrics_set(owner, 0); + let set_id = publish(&mut store, &key, &set, None); + + let rescind = Rescind { + set_id: set.set_id, + from_version: 0, + target: Entry::Key { + author: key_author(ALICE), + include_history: false, + }, + through: None, + }; + let body = encode_rescind_body(&rescind).unwrap(); + let event = sign(&key, 1, Some(set_id), Some(&body), ext(RESCIND_KIND)).unwrap(); + let result = store + .ingest_with_body(&event.bytes, Some(&body), 0) + .unwrap(); + assert!(matches!(result, Ingest::Accepted { .. })); + + assert_eq!(store.stored_rescind(&event.id).unwrap(), Some(rescind)); + // Kinds do not cross: the rescind is not a set, the set is not a rescind. + assert_eq!(store.stored_writer_set(&event.id).unwrap(), None); + assert_eq!(store.stored_rescind(&set_id).unwrap(), None); +}