diff --git a/pkgs/id/crates/id-sync/src/federation/mod.rs b/pkgs/id/crates/id-sync/src/federation/mod.rs index 493b11551e..ee2a1bbd71 100644 --- a/pkgs/id/crates/id-sync/src/federation/mod.rs +++ b/pkgs/id/crates/id-sync/src/federation/mod.rs @@ -5,5 +5,6 @@ //! consumers do not edit this root. The root records the slice //! registry only — see [`slices::B_SLICE_REGISTRY`]. +pub mod net_exchange; pub mod record_join; pub mod slices; diff --git a/pkgs/id/crates/id-sync/src/federation/net_exchange.rs b/pkgs/id/crates/id-sync/src/federation/net_exchange.rs new file mode 100644 index 0000000000..4a4c70ddb5 --- /dev/null +++ b/pkgs/id/crates/id-sync/src/federation/net_exchange.rs @@ -0,0 +1,597 @@ +//! B2(c) for #12232: the B09 exchange, carried over the existing +//! transport between two processes. +//! +//! [`super::slices::b09_anti_entropy::reconcile`] runs two replicas in +//! one process: it compares inventories, computes each side's offer +//! with [`Replica::offer`], and moves the missing signed versions +//! through [`Replica::receive`]. This module runs the same exchange +//! with the second replica in another process, over the crate's iroh +//! transport — the same framing ([`id_core::frames`]) and connect +//! path ([`id_core::connectivity::connect`]) as +//! [`crate::envelope_net`]. Nothing here admits, merges or invents a +//! version: the wire carries inventories, offers and the original +//! signed envelopes, and every version that arrives is admitted by +//! the receiving replica's own B07 store and B32 gate, exactly as in +//! process. +//! +//! The exchange is initiator-driven, in the order B09 prescribes: +//! +//! 1. **Summaries first.** The initiator sends its inventory summary; +//! the responder answers with its own. Digests are what replicas +//! exchange first ([`Inventory::summary`]); if no object diverged, +//! the exchange is already quiet and nothing else is sent. +//! 2. **Sets for the exchange.** Both sides send their full version +//! sets and refused sets. The responder computes its offer toward +//! the initiator from them and holds it; the initiator computes +//! the divergence and its own offer the same way. (The in-process +//! exchange holds both full inventories too; the digest step is +//! the early exit, not a different algorithm.) +//! 3. **Delivery.** The initiator sends the versions its offer names; +//! the responder admits each through `receive` and reports the +//! outcome of each. +//! 4. **Fetch.** The initiator asks for the responder's held offer; +//! the responder sends those versions and the initiator admits +//! each through its own `receive`. +//! +//! Both offers are computed from the inventories as they stood before +//! anything moved, as in [`reconcile`]. The initiator supplies the +//! logical time; both sides admit at that time. +//! +//! Outcomes cross the wire as [`NetOutcome`]: the store's own +//! outcomes keep their identity (a report id survives the trip), and +//! a refusal keeps its reason as text, because the gate's error type +//! is richer than the wire needs and is not reconstructed from it. +//! +//! Rollback is not starting the exchange: replicas keep their +//! versions, reports and refusals either way. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use iroh::endpoint::Connection; +use iroh::protocol::{AcceptError, ProtocolHandler}; +use iroh::{Endpoint, EndpointAddr}; +use serde::{Deserialize, Serialize}; +use tokio::sync::Mutex; + +use super::slices::b07_conflict_report::{IngestError, IngestOutcome}; +use super::slices::b08_sync_scope::SyncScopeConfig; +use super::slices::b09_anti_entropy::{ + Inventory, ObjectDivergence, Offer, Replica, divergence, diverged_objects, +}; +use super::slices::b32_ingest_gate::{Envelope, EventId, IngressPath, LogicalTime}; +use crate::hex::{hex_encode, hex_to_array}; + +/// ALPN for the federation sync exchange. Within version 1 fields may +/// be added; removing or changing one needs `/id-federation-sync/2`. +pub const FEDERATION_SYNC_ALPN: &[u8] = b"/id-federation-sync/1"; + +/// Bound on one whole exchange, matching `envelope_net`'s delivery +/// bound. +const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(30); + +/// The protocol's error conversion, as in `crate::artifact`: +/// `AcceptError` takes a boxed standard error; `anyhow` errors and +/// the concrete errors of the frame and serde calls all convert into +/// one. +fn accept_error>>(error: E) -> AcceptError { + AcceptError::from_boxed(error.into()) +} + +// --------------------------------------------------------------------- +// Wire forms + +fn hex_bytes(bytes: &[u8]) -> String { + hex_encode(bytes) +} + +fn unhex_bytes(text: &str) -> Result> { + if text.len() % 2 != 0 || !text.bytes().all(|b| b.is_ascii_hexdigit()) { + bail!("not lower-case hex of even length: {text:?}"); + } + let mut out = Vec::with_capacity(text.len() / 2); + for index in 0..text.len() / 2 { + out.push(u8::from_str_radix(&text[index * 2..index * 2 + 2], 16)?); + } + Ok(out) +} + +fn unhex32(text: &str) -> Result<[u8; 32]> { + hex_to_array(text).context("expected 64 hex characters") +} + +fn unhex64(text: &str) -> Result<[u8; 64]> { + hex_to_array(text).context("expected 128 hex characters") +} + +/// A B32 gate envelope as it crosses the wire: every field of +/// [`Envelope`], byte fields in hex. The envelope's signature covers +/// its preimage, not this encoding, so the encoding only has to be +/// faithful, and `into_envelope` checks every length it relies on. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +struct WireEnvelope { + signer: String, + verifying_key: String, + signature: Option, + scope: String, + payload: String, + payload_digest: String, + event_id: String, + issued_at: LogicalTime, +} + +impl WireEnvelope { + fn of(envelope: &Envelope) -> Self { + Self { + signer: envelope.signer.clone(), + verifying_key: hex_bytes(&envelope.verifying_key), + signature: envelope.signature.as_ref().map(|sig| hex_bytes(sig)), + scope: envelope.scope.clone(), + payload: hex_bytes(&envelope.payload), + payload_digest: hex_bytes(&envelope.payload_digest), + event_id: hex_bytes(&envelope.event_id), + issued_at: envelope.issued_at, + } + } + + fn into_envelope(self) -> Result { + Ok(Envelope { + signer: self.signer, + verifying_key: unhex32(&self.verifying_key)?, + signature: self.signature.as_deref().map(unhex64).transpose()?, + scope: self.scope, + payload: unhex_bytes(&self.payload)?, + payload_digest: unhex32(&self.payload_digest)?, + event_id: unhex32(&self.event_id)?, + issued_at: self.issued_at, + }) + } +} + +/// One side's offer, as reported over the wire. Withheld versions +/// carry their B08 exclusion by name; the initiator's own offer is +/// computed locally and converted through the same shape so both +/// directions report identically. +#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct NetOffer { + /// Versions to send, ascending, as event-id hex. + pub send: Vec, + /// Versions withheld by the link's bounds, with the exclusion. + pub withheld: Vec<(String, String)>, + /// Versions not sent because the remote refused them before. + pub refused_by_remote: Vec, +} + +impl NetOffer { + fn of(offer: &Offer) -> Self { + Self { + send: offer.send.iter().map(|id| hex_bytes(id)).collect(), + withheld: offer + .withheld + .iter() + .map(|(id, why)| (hex_bytes(id), format!("{why:?}"))) + .collect(), + refused_by_remote: offer + .refused_by_remote + .iter() + .map(|id| hex_bytes(id)) + .collect(), + } + } +} + +/// What one sent version came to at the receiver. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum NetOutcome { + /// Applied; the object has one head and no open report. + Applied, + /// Applied, and the object is diverged: this report (id, hex). + Conflict(String), + /// Applied as the resolution of this report (id, hex). + Resolved(String), + /// Admitted and held until its parents are stored. + Held, + /// Refused, with the receiver's reason. + Refused(String), +} + +fn net_outcome(result: &Result) -> NetOutcome { + match result { + Ok(IngestOutcome::Applied) => NetOutcome::Applied, + Ok(IngestOutcome::Conflict(id)) => NetOutcome::Conflict(hex_bytes(id)), + Ok(IngestOutcome::Resolved(id)) => NetOutcome::Resolved(hex_bytes(id)), + Ok(IngestOutcome::Held) => NetOutcome::Held, + Err(error) => NetOutcome::Refused(format!("{error:?}")), + } +} + +/// One direction of a carried exchange. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct NetTransfer { + /// The offer this direction made. + pub offer: NetOffer, + /// The receiver's outcome for each sent version, in send order. + pub outcomes: Vec<(EventId, NetOutcome)>, +} + +/// The result of one carried exchange: the shape of +/// [`super::slices::b09_anti_entropy::Exchange`], with wire outcomes. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct NetExchange { + /// The divergence detected before anything moved, from the + /// initiator's side. + pub divergence: Vec, + /// From the initiator to the responder. + pub forward: NetTransfer, + /// From the responder to the initiator. + pub backward: NetTransfer, +} + +impl NetExchange { + /// Whether nothing was sent either way. + pub fn is_quiet(&self) -> bool { + self.forward.offer.send.is_empty() && self.backward.offer.send.is_empty() + } +} + +type SummaryWire = Vec<(String, String)>; // (object id hex, digest hex) +type SetsWire = Vec<(String, Vec)>; // (object id hex, event id hexes) + +fn summary_wire(summary: &BTreeMap<[u8; 32], [u8; 32]>) -> SummaryWire { + summary + .iter() + .map(|(object, digest)| (hex_bytes(object), hex_bytes(digest))) + .collect() +} + +fn summary_from(wire: &SummaryWire) -> Result> { + wire.iter() + .map(|(object, digest)| Ok((unhex32(object)?, unhex32(digest)?))) + .collect() +} + +fn sets_wire(inventory: &Inventory) -> SetsWire { + inventory + .objects() + .map(|object| { + ( + hex_bytes(object), + inventory + .versions(object) + .map(|ids| ids.iter().map(|id| hex_bytes(id)).collect()) + .unwrap_or_default(), + ) + }) + .collect() +} + +fn inventory_from(wire: &SetsWire) -> Result { + let mut objects: BTreeMap<[u8; 32], BTreeSet> = BTreeMap::new(); + for (object, ids) in wire { + let mut set = BTreeSet::new(); + for id in ids { + set.insert(unhex32(id)?); + } + objects.insert(unhex32(object)?, set); + } + Ok(Inventory::from_objects(objects)) +} + +fn refused_wire(replica: &Replica) -> Vec { + replica.refused().keys().map(|id| hex_bytes(id)).collect() +} + +fn refused_from(wire: &[String]) -> Result> { + wire.iter().map(|id| unhex32(id)).collect() +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "msg", rename_all = "snake_case")] +enum Request { + Hello { + from: String, + now: LogicalTime, + summary: SummaryWire, + }, + Sets { + versions: SetsWire, + refused: Vec, + }, + Deliver { + versions: Vec, + }, + Fetch, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "msg", rename_all = "snake_case")] +enum Response { + Hello { + from: String, + summary: SummaryWire, + }, + Sets { + versions: SetsWire, + refused: Vec, + backward_offer: NetOffer, + }, + Delivered { + outcomes: Vec<(String, NetOutcome)>, + }, + Fetch { + versions: Vec, + }, +} + +// --------------------------------------------------------------------- +// Responder + +/// What one link's current exchange has established so far, on the +/// responder's side. +#[derive(Debug, Default)] +struct LinkState { + peer_name: String, + now: LogicalTime, + backward_offer: Option, +} + +/// Serves the federation sync exchange for one replica. Register with +/// `Router::builder(..).accept(FEDERATION_SYNC_ALPN, +/// FederationSyncProtocol::new(replica, scope))`. +#[derive(Clone, Debug)] +pub struct FederationSyncProtocol { + replica: Arc>, + scope: SyncScopeConfig, + link: Arc>, +} + +impl FederationSyncProtocol { + /// Serve `replica`'s exchange over links scoped by `scope`. + pub fn new(replica: Replica, scope: SyncScopeConfig) -> Self { + Self { + replica: Arc::new(Mutex::new(replica)), + scope, + link: Arc::new(Mutex::new(LinkState::default())), + } + } + + /// The served replica, shared with the process that hosts it so + /// the host's local writes and reads go through the same lock as + /// the served exchange. + pub fn shared_replica(&self) -> Arc> { + Arc::clone(&self.replica) + } +} + +impl ProtocolHandler for FederationSyncProtocol { + async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { + loop { + let (mut send, mut recv) = match conn.accept_bi().await { + Ok(streams) => streams, + Err(_) => return Ok(()), + }; + let Some(frame) = id_core::frames::read_frame(&mut recv) + .await + .map_err(accept_error)? + else { + return Ok(()); + }; + let request: Request = crate::checked_json::from_slice_unique(&frame) + .map_err(accept_error)?; + let response = { + let mut replica = self.replica.lock().await; + let mut link = self.link.lock().await; + answer(&mut replica, &self.scope, &mut link, request) + .map_err(accept_error)? + }; + let json = serde_json::to_vec(&response).map_err(accept_error)?; + id_core::frames::write_frame(&mut send, &json) + .await + .map_err(accept_error)?; + send.finish().map_err(accept_error)?; + } + } +} + +fn answer( + replica: &mut Replica, + scope: &SyncScopeConfig, + link: &mut LinkState, + request: Request, +) -> Result { + match request { + Request::Hello { from, now, .. } => { + link.peer_name = from; + link.now = now; + Ok(Response::Hello { + from: replica.name().to_owned(), + summary: summary_wire(&replica.inventory().summary()), + }) + } + Request::Sets { versions, refused } => { + let peer_inventory = inventory_from(&versions)?; + let peer_refused = refused_from(&refused)?; + let offer = replica.offer(&peer_inventory, &peer_refused, scope, link.now); + let reply = Response::Sets { + versions: sets_wire(&replica.inventory()), + refused: refused_wire(replica), + backward_offer: NetOffer::of(&offer), + }; + link.backward_offer = Some(offer); + Ok(reply) + } + Request::Deliver { versions } => { + let peer_name = link.peer_name.clone(); + let mut outcomes = Vec::with_capacity(versions.len()); + for wire in versions { + let envelope = wire.into_envelope()?; + let event_id = envelope.event_id; + let result = replica.receive(IngressPath::Internal, &envelope, &peer_name, link.now); + outcomes.push((hex_bytes(&event_id), net_outcome(&result))); + } + Ok(Response::Delivered { outcomes }) + } + Request::Fetch => { + let offer = link + .backward_offer + .take() + .context("fetch before the sets step")?; + let versions = offer + .send + .iter() + .filter_map(|id| replica.envelope(id)) + .map(WireEnvelope::of) + .collect(); + Ok(Response::Fetch { versions }) + } + } +} + +// --------------------------------------------------------------------- +// Initiator + +async fn roundtrip(conn: &Connection, request: &Request) -> Result { + let (mut send, mut recv) = conn.open_bi().await.context("opening a stream")?; + let json = serde_json::to_vec(request)?; + id_core::frames::write_frame(&mut send, &json).await?; + send.finish().context("finishing the request")?; + let frame = id_core::frames::read_frame(&mut recv) + .await? + .context("no reply")?; + crate::checked_json::from_slice_unique(&frame).context("malformed reply") +} + +/// Reconcile `local` with the replica served at `target`, over one +/// link scoped by `config`, at logical time `now`: the carried form +/// of [`super::slices::b09_anti_entropy::reconcile`], with this +/// process as the first replica. +/// +/// # Errors +/// +/// Fails if the connection, a stream, or a message fails, or the +/// peer's messages do not decode. A version the peer refuses is not +/// an error; it is reported in the exchange's outcomes. +pub async fn exchange( + endpoint: &Endpoint, + target: impl Into, + local: &mut Replica, + config: &SyncScopeConfig, + now: LogicalTime, +) -> Result { + let work = exchange_inner(endpoint, target.into(), local, config, now); + tokio::time::timeout(EXCHANGE_TIMEOUT, work) + .await + .context("exchange timed out")? +} + +async fn exchange_inner( + endpoint: &Endpoint, + target: EndpointAddr, + local: &mut Replica, + config: &SyncScopeConfig, + now: LogicalTime, +) -> Result { + let conn = id_core::connectivity::connect(endpoint, target, FEDERATION_SYNC_ALPN).await?; + let local_inventory = local.inventory(); + let local_summary = local_inventory.summary(); + + // 1. Summaries first; no divergence means a quiet exchange. + let Response::Hello { + from: remote_name, + summary: remote_summary_wire, + } = roundtrip( + &conn, + &Request::Hello { + from: local.name().to_owned(), + now, + summary: summary_wire(&local_summary), + }, + ) + .await? + else { + bail!("peer answered the hello with a different message"); + }; + let remote_summary = summary_from(&remote_summary_wire)?; + if diverged_objects(&local_summary, &remote_summary).is_empty() { + conn.close(0_u32.into(), b"done"); + return Ok(NetExchange::default()); + } + + // 2. Sets: the responder computes and holds its offer; the + // initiator computes the divergence and its own offer, both from + // the inventories as they stood before anything moved. + let local_refused: BTreeSet = local.refused().keys().copied().collect(); + let Response::Sets { + versions: remote_sets, + refused: remote_refused_wire, + backward_offer, + } = roundtrip( + &conn, + &Request::Sets { + versions: sets_wire(&local_inventory), + refused: local_refused.iter().map(|id| hex_bytes(id)).collect(), + }, + ) + .await? + else { + bail!("peer answered the sets step with a different message"); + }; + let remote_inventory = inventory_from(&remote_sets)?; + let remote_refused = refused_from(&remote_refused_wire)?; + let detected = divergence(&local_inventory, &remote_inventory); + let forward_offer = local.offer(&remote_inventory, &remote_refused, config, now); + + // 3. Delivery: the responder admits each offered version through + // its own store and reports the outcomes. + let forward_versions: Vec = forward_offer + .send + .iter() + .filter_map(|id| local.envelope(id)) + .map(WireEnvelope::of) + .collect(); + let Response::Delivered { outcomes } = roundtrip( + &conn, + &Request::Deliver { + versions: forward_versions, + }, + ) + .await? + else { + bail!("peer answered the delivery with a different message"); + }; + let forward_outcomes = outcomes + .into_iter() + .map(|(id, outcome)| Ok((unhex32(&id)?, outcome))) + .collect::>>()?; + + // 4. Fetch: the initiator admits the responder's offered versions + // through its own store. + let Response::Fetch { + versions: fetched, + } = roundtrip(&conn, &Request::Fetch).await? + else { + bail!("peer answered the fetch with a different message"); + }; + let mut backward_outcomes = Vec::with_capacity(fetched.len()); + for wire in fetched { + let envelope = wire.into_envelope()?; + let event_id = envelope.event_id; + let result = local.receive(IngressPath::Internal, &envelope, &remote_name, now); + backward_outcomes.push((event_id, net_outcome(&result))); + } + conn.close(0_u32.into(), b"done"); + + Ok(NetExchange { + divergence: detected, + forward: NetTransfer { + offer: NetOffer::of(&forward_offer), + outcomes: forward_outcomes, + }, + backward: NetTransfer { + offer: backward_offer, + outcomes: backward_outcomes, + }, + }) +} diff --git a/pkgs/id/crates/id-sync/src/federation/slices/b09_anti_entropy.rs b/pkgs/id/crates/id-sync/src/federation/slices/b09_anti_entropy.rs index 385e095b5c..09c8bdb97c 100644 --- a/pkgs/id/crates/id-sync/src/federation/slices/b09_anti_entropy.rs +++ b/pkgs/id/crates/id-sync/src/federation/slices/b09_anti_entropy.rs @@ -95,6 +95,15 @@ pub struct Inventory { } impl Inventory { + /// An inventory built from a peer's report of what it holds, as + /// received over the wire (B2(c), #12232): the same sets + /// [`Replica::inventory`] builds locally, from the other side's + /// telling. Divergence and offers computed against it are the + /// in-process ones; only the source of the sets differs. + pub fn from_objects(objects: BTreeMap>) -> Self { + Self { objects } + } + /// The versions held for one object. pub fn versions(&self, object_id: &ObjectId) -> Option<&BTreeSet> { self.objects.get(object_id) diff --git a/pkgs/id/crates/id-sync/tests/substrate_sync_transport.rs b/pkgs/id/crates/id-sync/tests/substrate_sync_transport.rs new file mode 100644 index 0000000000..c8d9a512b8 --- /dev/null +++ b/pkgs/id/crates/id-sync/tests/substrate_sync_transport.rs @@ -0,0 +1,713 @@ +//! Third step of the #9106 walking skeleton (#12232, slice B2(c)): +//! the five steps of `substrate_sync_path`, with the exchange carried +//! over the existing transport between two processes. +//! +//! Node A runs in this process. Node B runs in a child process — this +//! same test binary, re-invoked as `node_b_entry` — serving the +//! federation sync protocol (`federation::net_exchange`) on one iroh +//! endpoint. The parent drives B's local writes and reads over a +//! test-only control protocol on a second ALPN of the same endpoint; +//! everything the two nodes *exchange* — inventories, offers, signed +//! versions — crosses on the sync protocol, through +//! `net_exchange::exchange` on A's side and the served +//! `FederationSyncProtocol` on B's, and is admitted on both sides by +//! the same B07 store and B32 gate as in process. +//! +//! Oracles, as in `substrate_sync_path`: differential (what B reads +//! from an address equals, byte for byte, what A signed; both nodes +//! report the same conflict key, versions and base), metamorphic +//! (repeating the exchange changes nothing), and a plain-set model of +//! the heads, checked on both processes. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] + +use std::collections::BTreeSet; +use std::process::{Child, Command, Stdio}; +use std::str::FromStr; +use std::sync::Arc; +use std::time::Duration; + +use ed25519_dalek::SigningKey; +use id_core::graph::record::{GraphRecord, OpenedRecord, open}; +use id_core::graph::term::{Term, Triple}; +use id_core::hash_profile::ProfileDispatch; +use id_core::id_shape::{ContentId, HashProfile}; +use id_core::id_uri_format::resolve_context; +use id_core::id_uri_parse::{IdUriV1, UriTarget}; +use id_core::signed_envelope::{Envelope as RecordEnvelope, LogicalGraphId}; +use id_sync::federation::net_exchange::{ + FEDERATION_SYNC_ALPN, FederationSyncProtocol, NetOutcome, exchange, +}; +use id_sync::federation::slices::b07_conflict_report::{ + ConflictStore, IngestOutcome, ObjectId, RetentionPolicy, VersionHeader, conflict_key, +}; +use id_sync::federation::slices::b08_sync_scope::SyncScopeConfig; +use id_sync::federation::slices::b09_anti_entropy::Replica; +use id_sync::federation::slices::b32_ingest_gate::{ + EventId, FreshnessWindow, SignerAuthorization, sign_envelope, +}; +use iroh::endpoint::{Connection, RelayMode, presets}; +use iroh::protocol::{AcceptError, ProtocolHandler, Router}; +use iroh::{Endpoint, EndpointAddr, EndpointId, TransportAddr}; +use serde::{Deserialize, Serialize}; +use tokio::sync::{Mutex, Notify}; + +const START: u64 = 10_000; +const SCOPE: &str = "notes"; +const TRUST_DOMAIN: &str = "home"; +const NAMESPACE: &str = "notes"; +const CONTEXT: &str = "namespace/notes"; +const GRAPH: [u8; 32] = [0x11; 32]; +const WRITERS: [(&str, u8); 2] = [("alice", 7), ("bob", 9)]; +const ALICE: usize = 0; +const BOB: usize = 1; + +const CONTROL_ALPN: &[u8] = b"/id-skeleton-control/1"; +const CHILD_ENV: &str = "ID_SKELETON_NODE_B"; +const BANNER_ENV: &str = "ID_SKELETON_BANNER"; + +fn accept_error>>(error: E) -> AcceptError { + AcceptError::from_boxed(error.into()) +} + +// --------------------------------------------------------------------- +// The scenario, shared by both processes (same code as +// substrate_sync_path, so the two files read as siblings). + +fn key(writer: usize) -> SigningKey { + SigningKey::from_bytes(&[WRITERS[writer].1; 32]) +} + +fn node(name: &str) -> Replica { + let signers = WRITERS + .iter() + .enumerate() + .map(|(writer, (identity, _))| SignerAuthorization { + identity: (*identity).to_owned(), + verifying_key: key(writer).verifying_key().to_bytes(), + scopes: [SCOPE.to_owned()].into_iter().collect(), + }) + .collect(); + let freshness = FreshnessWindow { + max_age: 1_000_000, + max_future_skew: 30, + }; + Replica::new( + name, + TRUST_DOMAIN, + ConflictStore::new(signers, freshness, RetentionPolicy { retain_for: 3_600 }), + ) +} + +fn link() -> SyncScopeConfig { + SyncScopeConfig::new(SCOPE, TRUST_DOMAIN) +} + +fn note(text: &[u8]) -> GraphRecord { + GraphRecord::new( + LogicalGraphId::new(GRAPH), + vec![Triple::new( + Term::typed(1, b"urn:note:1".to_vec()), + Term::typed(2, b"body".to_vec()), + Term::typed(3, text.to_vec()), + )], + ) +} + +struct Written { + signed: OpenedRecord, + event: EventId, +} + +impl Written { + fn address(&self, resolver: &str) -> String { + IdUriV1::new( + resolver, + NAMESPACE, + UriTarget::Content(*self.signed.id.content_id()), + ) + .unwrap() + .format() + } +} + +/// Sign `record`, wrap it as a version following `parents`, and +/// produce it on `node`. The join is decision D14, as in +/// `substrate_sync_path`. +fn publish( + node: &mut Replica, + writer: usize, + record: &GraphRecord, + parents: &[EventId], + now: u64, +) -> (Written, Result) { + let identity = WRITERS[writer].0; + let signed = record.sign(CONTEXT, identity, &key(writer)).unwrap(); + let event: EventId = *signed.id.content_id().digest(); + let object: ObjectId = *record.graph.as_bytes(); + let header = VersionHeader { + object_id: object, + resolves: (parents.len() >= 2).then(|| conflict_key(parents)), + parents: parents.to_vec(), + body: signed.envelope.canonical_bytes().unwrap(), + }; + let version = sign_envelope(&key(writer), identity, SCOPE, &header.encode(), event, now); + let outcome = node + .produce(&version, now) + .map_err(|error| format!("{error:?}")); + (Written { signed, event }, outcome) +} + +#[derive(Debug, PartialEq, Eq)] +enum Unreadable { + NotHeld, + BodyIsNotTheNamedBytes, + NotASignedRecord, + JoinBroken(&'static str), +} + +/// Read a record on `node` given only its address text: the same +/// checks, in the same order, as `substrate_sync_path`'s read. +fn read(node: &Replica, address: &str) -> Result { + let dispatch = ProfileDispatch::default(); + let uri = IdUriV1::parse(address).unwrap(); + resolve_context(uri.resolver_hint(), node.name()).unwrap(); + let UriTarget::Content(named) = uri.target() else { + panic!("{address} does not name a record"); + }; + let version = node.envelope(named.digest()).ok_or(Unreadable::NotHeld)?; + let header = VersionHeader::decode(&version.payload).unwrap(); + dispatch + .verify_bytes(named, &header.body) + .map_err(|_| Unreadable::BodyIsNotTheNamedBytes)?; + let envelope = + RecordEnvelope::decode(&header.body).map_err(|_| Unreadable::NotASignedRecord)?; + let opened = open(envelope, &dispatch).map_err(|_| Unreadable::NotASignedRecord)?; + if opened.id.content_id() != named { + return Err(Unreadable::JoinBroken("event id")); + } + if &header.object_id != opened.record.graph.as_bytes() { + return Err(Unreadable::JoinBroken("object")); + } + if version.verifying_key != opened.envelope.body.key { + return Err(Unreadable::JoinBroken("signer")); + } + Ok(opened) +} + +fn heads(node: &Replica) -> BTreeSet { + node.store().heads(&GRAPH).into_iter().collect() +} + +/// The address of the version `event` as a reader on `resolver` writes it. +fn address_of(event: &EventId, resolver: &str) -> String { + IdUriV1::new( + resolver, + NAMESPACE, + UriTarget::Content(ContentId::new(HashProfile::RawBlake3_256, *event)), + ) + .unwrap() + .format() +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|byte| format!("{byte:02x}")).collect() +} + +fn unhex(text: &str) -> Vec { + (0..text.len() / 2) + .map(|index| u8::from_str_radix(&text[index * 2..index * 2 + 2], 16).unwrap()) + .collect() +} + +fn unhex32(text: &str) -> EventId { + unhex(text).try_into().unwrap() +} + +// --------------------------------------------------------------------- +// The control protocol: test-only, drives node B's local side. Nothing +// the nodes exchange travels on it. + +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "op", rename_all = "snake_case")] +enum Control { + Produce { + writer: usize, + text: String, + parents: Vec, + now: u64, + }, + Heads, + Report, + Read { + address: String, + }, + Shutdown, +} + +#[derive(Debug, Serialize, Deserialize)] +#[serde(tag = "reply", rename_all = "snake_case")] +enum ControlReply { + Produced { + event: String, + outcome: String, + }, + Heads { + heads: Vec, + }, + Report { + open: bool, + id: Option, + key: Option, + base: Vec, + versions: Vec, + signers: Vec, + }, + Read { + result: Result, + }, + Bye, +} + +#[derive(Clone, Debug)] +struct ControlProtocol { + replica: Arc>, + shutdown: Arc, +} + +impl ProtocolHandler for ControlProtocol { + async fn accept(&self, conn: Connection) -> Result<(), AcceptError> { + loop { + let (mut send, mut recv) = match conn.accept_bi().await { + Ok(streams) => streams, + Err(_) => return Ok(()), + }; + let frame = id_core::frames::read_frame(&mut recv) + .await + .map_err(accept_error)?; + let Some(frame) = frame else { + return Ok(()); + }; + let control: Control = serde_json::from_slice(&frame).map_err(accept_error)?; + let (reply, stop) = { + let mut replica = self.replica.lock().await; + answer_control(&mut replica, control) + }; + let json = serde_json::to_vec(&reply).map_err(accept_error)?; + id_core::frames::write_frame(&mut send, &json) + .await + .map_err(accept_error)?; + send.finish().map_err(accept_error)?; + if stop { + self.shutdown.notify_one(); + // Do not return yet: a returning handler lets the + // router tear the connection down, which can discard + // the reply still in flight (the artifact handlers + // wait the same way). The parent closes its side once + // it has the reply, and that releases this wait. + conn.closed().await; + return Ok(()); + } + } + } +} + +fn answer_control(replica: &mut Replica, control: Control) -> (ControlReply, bool) { + match control { + Control::Produce { + writer, + text, + parents, + now, + } => { + let parents: Vec = parents.iter().map(|id| unhex32(id)).collect(); + let (written, outcome) = publish(replica, writer, ¬e(text.as_bytes()), &parents, now); + ( + ControlReply::Produced { + event: hex(&written.event), + outcome: format!("{outcome:?}"), + }, + false, + ) + } + Control::Heads => ( + ControlReply::Heads { + heads: heads(replica).iter().map(|id| hex(id)).collect(), + }, + false, + ), + Control::Report => { + let Some(id) = replica.store().open_report(&GRAPH) else { + return ( + ControlReply::Report { + open: false, + id: None, + key: None, + base: vec![], + versions: vec![], + signers: vec![], + }, + false, + ); + }; + let stored = replica.store().report(&id).unwrap(); + ( + ControlReply::Report { + open: true, + id: Some(hex(&id)), + key: Some(hex(&stored.report.conflict_key())), + base: stored.report.base.iter().map(|id| hex(id)).collect(), + versions: stored + .report + .versions + .iter() + .map(|version| hex(&version.event_id)) + .collect(), + signers: stored + .report + .versions + .iter() + .map(|version| version.signer.clone()) + .collect(), + }, + false, + ) + } + Control::Read { address } => { + let result = read(replica, &address) + .map(|opened| hex(&opened.envelope.canonical_bytes().unwrap())) + .map_err(|unreadable| format!("{unreadable:?}")); + (ControlReply::Read { result }, false) + } + Control::Shutdown => (ControlReply::Bye, true), + } +} + +/// Node B's process entry. In an ordinary test run (no env var) this +/// returns at once; the parent test spawns this binary with the env +/// var set and `--exact node_b_entry` to run it as the second node. +#[test] +fn node_b_entry() { + if std::env::var_os(CHILD_ENV).is_none() { + return; + } + let runtime = tokio::runtime::Runtime::new().unwrap(); + runtime.block_on(async { + let endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .bind() + .await + .unwrap(); + let sync = FederationSyncProtocol::new(node("node-b"), link()); + let control = ControlProtocol { + replica: sync.shared_replica(), + shutdown: Arc::new(Notify::new()), + }; + let shutdown = control.shutdown.clone(); + let router = Router::builder(endpoint.clone()) + .accept(FEDERATION_SYNC_ALPN, sync) + .accept(CONTROL_ALPN, control) + .spawn(); + let sockets = endpoint.bound_sockets(); + let port = sockets + .iter() + .find(|socket| socket.is_ipv4()) + .unwrap_or(&sockets[0]) + .port(); + // The banner goes to a file, not stdout: the harness owns + // the child's stdout, and a banner line through it proved + // unreliable in the runner. The parent polls for the file. + let banner = std::env::var(BANNER_ENV).unwrap(); + std::fs::write(&banner, format!("READY {} {port}\n", endpoint.id())).unwrap(); + shutdown.notified().await; + router.shutdown().await.unwrap(); + endpoint.close().await; + }); +} + +// --------------------------------------------------------------------- +// The parent: node A, in this process. + +struct NodeB { + child: Child, + target: EndpointAddr, + conn: Connection, +} + +impl NodeB { + async fn spawn(endpoint: &Endpoint) -> NodeB { + let exe = std::env::current_exe().unwrap(); + let banner = std::env::temp_dir().join(format!( + "id-skeleton-banner-{}", + std::process::id() + )); + let _ = std::fs::remove_file(&banner); + let mut child = Command::new(exe) + .args(["--exact", "node_b_entry", "--nocapture", "--test-threads=1"]) + .env(CHILD_ENV, "1") + .env(BANNER_ENV, &banner) + .stdout(Stdio::null()) + .stderr(Stdio::inherit()) + .spawn() + .unwrap(); + // The child writes its banner to the file once its router is + // up; poll for it (bounded), rather than parsing the harness's + // stdout stream. + let mut ready = String::new(); + for _ in 0..480 { + if let Ok(text) = std::fs::read_to_string(&banner) { + if text.ends_with('\n') { + ready = text.trim_end().to_string(); + break; + } + } + tokio::time::sleep(Duration::from_millis(250)).await; + } + assert!( + !ready.is_empty(), + "node B wrote no banner in 120s; its step markers are on stderr" + ); + let mut parts = ready.split_whitespace(); + assert_eq!(parts.next(), Some("READY"), "child banner: {ready}"); + let id = EndpointId::from_str(parts.next().unwrap()).unwrap(); + let port: u16 = parts.next().unwrap().parse().unwrap(); + let target = EndpointAddr::from_parts( + id, + [TransportAddr::Ip(std::net::SocketAddr::from(( + std::net::Ipv4Addr::LOCALHOST, + port, + )))], + ); + let conn = id_core::connectivity::connect(endpoint, target.clone(), CONTROL_ALPN) + .await + .unwrap(); + NodeB { child, target, conn } + } + + async fn control(&self, control: Control) -> ControlReply { + let (mut send, mut recv) = self.conn.open_bi().await.unwrap(); + let json = serde_json::to_vec(&control).unwrap(); + id_core::frames::write_frame(&mut send, &json).await.unwrap(); + send.finish().unwrap(); + let frame = id_core::frames::read_frame(&mut recv) + .await + .unwrap() + .unwrap(); + serde_json::from_slice(&frame).unwrap() + } + + async fn produce( + &self, + writer: usize, + text: &str, + parents: &[EventId], + now: u64, + ) -> (EventId, String) { + let ControlReply::Produced { event, outcome } = self + .control(Control::Produce { + writer, + text: text.to_owned(), + parents: parents.iter().map(|id| hex(id)).collect(), + now, + }) + .await + else { + panic!("produce answered with a different reply"); + }; + (unhex32(&event), outcome) + } + + async fn heads(&self) -> BTreeSet { + let ControlReply::Heads { heads } = self.control(Control::Heads).await else { + panic!("heads answered with a different reply"); + }; + heads.iter().map(|id| unhex32(id)).collect() + } + + async fn read(&self, address: &str) -> Result, String> { + let ControlReply::Read { result } = self + .control(Control::Read { + address: address.to_owned(), + }) + .await + else { + panic!("read answered with a different reply"); + }; + result.map(|bytes| unhex(&bytes)) + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn the_five_steps_run_between_two_processes_over_the_transport() { + let endpoint = Endpoint::builder(presets::Minimal) + .relay_mode(RelayMode::Disabled) + .bind() + .await + .unwrap(); + let b = NodeB::spawn(&endpoint).await; + let mut a = node("node-a"); + + // Step 1: Alice writes the base record on A. + let (base, outcome) = publish(&mut a, ALICE, ¬e(b"first draft"), &[], START); + assert_eq!(outcome, Ok(IngestOutcome::Applied)); + + // Before any exchange, B does not hold it. + assert_eq!( + b.read(&base.address("node-b")).await, + Err("NotHeld".to_owned()) + ); + + // Steps 2 and 3: it is stored on A and syncs to B over the wire. + let carried = exchange(&endpoint, b.target.clone(), &mut a, &link(), START + 1) + .await + .unwrap(); + assert_eq!(carried.forward.offer.send, vec![hex(&base.event)]); + assert_eq!( + carried.forward.outcomes, + vec![(base.event, NetOutcome::Applied)] + ); + assert!(carried.backward.offer.send.is_empty()); + assert_eq!(heads(&a), BTreeSet::from([base.event])); + assert_eq!(b.heads().await, BTreeSet::from([base.event])); + + // B reads exactly the bytes Alice signed, from the address alone. + assert_eq!( + b.read(&base.address("node-b")).await.unwrap(), + base.signed.envelope.canonical_bytes().unwrap() + ); + assert_eq!(read(&a, &base.address("node-a")).unwrap(), base.signed); + + // Repeating the exchange changes nothing. + let carried = exchange(&endpoint, b.target.clone(), &mut a, &link(), START + 2) + .await + .unwrap(); + assert!(carried.is_quiet()); + + // Step 4: each writer follows the base on their own node. + let (from_a, outcome) = publish(&mut a, ALICE, ¬e(b"alice's edit"), &[base.event], START + 3); + assert_eq!(outcome, Ok(IngestOutcome::Applied)); + let (from_b_event, outcome) = b.produce(BOB, "bob's edit", &[base.event], START + 3).await; + assert_eq!(outcome, "Ok(Applied)"); + assert_ne!(from_a.event, from_b_event); + + // The exchange reports the conflict on both nodes: each side's + // admission of the other's edit opens the report there. + let carried = exchange(&endpoint, b.target.clone(), &mut a, &link(), START + 4) + .await + .unwrap(); + assert_eq!(carried.forward.offer.send, vec![hex(&from_a.event)]); + let ControlReply::Report { + open: b_open, + id: b_report, + key: b_key, + base: b_base, + versions: b_versions, + signers: b_signers, + } = b.control(Control::Report).await + else { + panic!("report answered with a different reply"); + }; + assert!(b_open); + assert_eq!( + carried.forward.outcomes, + vec![(from_a.event, NetOutcome::Conflict(b_report.unwrap()))] + ); + assert_eq!(carried.backward.offer.send, vec![hex(&from_b_event)]); + let report_a = a.store().open_report(&GRAPH).unwrap(); + assert_eq!( + carried.backward.outcomes, + vec![(from_b_event, NetOutcome::Conflict(hex(&report_a)))] + ); + + // Step 5: both nodes report the same conflict — same key, same + // versions, same base — and nothing was merged or dropped. + let expected = BTreeSet::from([from_a.event, from_b_event]); + let key = conflict_key(&[from_a.event, from_b_event]); + assert_eq!(hex(&key), b_key.clone().unwrap()); + let stored_a = a.store().report(&report_a).unwrap(); + assert_eq!(stored_a.report.conflict_key(), key); + assert_eq!(stored_a.report.base, vec![base.event]); + assert_eq!(b_base, vec![hex(&base.event)]); + let named_b: BTreeSet = b_versions.iter().map(|id| unhex32(id)).collect(); + assert_eq!(named_b, expected); + let signers_b: BTreeSet<&str> = b_signers.iter().map(String::as_str).collect(); + assert_eq!(signers_b, BTreeSet::from(["alice", "bob"])); + assert_eq!(heads(&a), expected); + assert_eq!(b.heads().await, expected); + for (written, resolver) in [(&base, "node-a"), (&from_a, "node-a")] { + assert_eq!(read(&a, &written.address(resolver)).unwrap(), written.signed); + } + assert_eq!( + b.read(&from_a.address("node-b")).await.unwrap(), + from_a.signed.envelope.canonical_bytes().unwrap() + ); + assert_eq!( + b.read(&base.address("node-b")).await.unwrap(), + base.signed.envelope.canonical_bytes().unwrap() + ); + // Bob's edit, which A holds only from the exchange, reads the same + // on both nodes. + let bobs_on_a = read(&a, &address_of(&from_b_event, "node-a")).unwrap(); + assert_eq!( + b.read(&address_of(&from_b_event, "node-b")).await.unwrap(), + bobs_on_a.envelope.canonical_bytes().unwrap() + ); + + // Another exchange neither clears the report nor invents a merge. + let carried = exchange(&endpoint, b.target.clone(), &mut a, &link(), START + 5) + .await + .unwrap(); + assert!(carried.is_quiet()); + assert!(a.store().open_report(&GRAPH).is_some()); + + // Bob resolves it on B with a record following both edits; the + // next exchange closes the report on A too. + let (merged_event, outcome) = b + .produce( + BOB, + "both edits, merged by bob", + &[from_a.event, from_b_event], + START + 6, + ) + .await; + assert!(outcome.starts_with("Ok(Resolved"), "merge on B: {outcome}"); + let carried = exchange(&endpoint, b.target.clone(), &mut a, &link(), START + 7) + .await + .unwrap(); + assert_eq!( + carried.backward.outcomes, + vec![(merged_event, NetOutcome::Resolved(hex(&report_a)))] + ); + assert_eq!(heads(&a), BTreeSet::from([merged_event])); + assert_eq!(b.heads().await, BTreeSet::from([merged_event])); + assert!(a.store().open_report(&GRAPH).is_none()); + let ControlReply::Report { open, .. } = b.control(Control::Report).await else { + panic!("report answered with a different reply"); + }; + assert!(!open); + + // The merged record is readable from its address on both nodes. + assert!(b.read(&address_of(&merged_event, "node-b")).await.is_ok()); + assert!(read(&a, &address_of(&merged_event, "node-a")).is_ok()); + + // Shut B down and see it exit cleanly. + let ControlReply::Bye = b.control(Control::Shutdown).await else { + panic!("shutdown answered with a different reply"); + }; + b.conn.close(iroh::endpoint::VarInt::from_u32(0), b"shutdown"); + let mut b = b; + let status = tokio::task::spawn_blocking(move || { + for _ in 0..100 { + if let Some(status) = b.child.try_wait().unwrap() { + return Some(status); + } + std::thread::sleep(Duration::from_millis(100)); + } + let _ = b.child.kill(); + None + }) + .await + .unwrap(); + assert!(status.is_some_and(|status| status.success())); + endpoint.close().await; +} diff --git a/planning/plans/2026-11-21_results-first.md b/planning/plans/2026-11-21_results-first.md index bd178bd078..6e1ad6009a 100644 --- a/planning/plans/2026-11-21_results-first.md +++ b/planning/plans/2026-11-21_results-first.md @@ -234,7 +234,7 @@ Each step is one PR unless it says otherwise. 23. **B0. Sequence accepted.** The delivered 39-component sequence and its #9078 and #9091 dependencies stand as recorded. Done when: #9112 carries the decision record and no owner-wait label. 24. **B1. Walking-skeleton design.** Done in code rather than as a document (#12268): the path's modules are `id_core::{graph::record, signed_envelope, hash_profile, id_uri_parse, id_uri_format}` and `id_sync::federation::slices::{b32_ingest_gate, b07_conflict_report, b08_sync_scope, b09_anti_entropy}`, and the interface they share is decision D14. Every other row stays in its recorded slot. The row-level map — which of the 126 rows the path runs through, in order, with their shared interfaces — is recorded in `doc/2026-11-22T16-13-20Z_design_id-walking-skeleton/note.md` (#12232). -25. **B2. The path, in slices.** Write a signed record at an `id://` address on node A; store it; sync it to node B over the existing transport; write a conflicting record on B; get a conflict report on both. Each slice lands with its test registered. Done when: one integration test does all five and fails if any module on the path is stubbed. State: write, sync, conflict and report run between two in-process nodes (#12268); (a) refusing a broken join at admission landed with #12279. Next slices, in order: (b) keep versions and reports in a store on disk through `id_store::content_store`; (c) carry the exchange over the existing transport between two processes. +25. **B2. The path, in slices.** Write a signed record at an `id://` address on node A; store it; sync it to node B over the existing transport; write a conflicting record on B; get a conflict report on both. Each slice lands with its test registered. Done when: one integration test does all five and fails if any module on the path is stubbed. State: write, sync, conflict and report run between two in-process nodes (#12268); (a) refusing a broken join at admission landed with #12279; (c) carrying the exchange over the existing transport between two processes landed 2026-11-22 (#12232): `id_sync::federation::net_exchange` runs B09's reconcile over iroh, and `tests/substrate_sync_transport.rs` does all five steps across a process boundary. Remaining slice: (b) keep versions and reports in a store on disk through `id_store::content_store` (#12492, in flight as PR #12497). 26. **B3. Reach it from the CLI.** The smallest command surface that drives B2 by hand. Done when: a README section shows the five steps as commands and the nightly runs them. ## Designs to write