diff --git a/pkgs/id/crates/id-sync/src/federation/slices/b07_conflict_report.rs b/pkgs/id/crates/id-sync/src/federation/slices/b07_conflict_report.rs index 47d8e39739..e36e913d32 100644 --- a/pkgs/id/crates/id-sync/src/federation/slices/b07_conflict_report.rs +++ b/pkgs/id/crates/id-sync/src/federation/slices/b07_conflict_report.rs @@ -19,10 +19,15 @@ //! it has an open report, and that report names exactly its heads. //! 2. **No silent resolution.** A version that joins two or more of a //! conflicted object's heads is a resolution. It is refused unless -//! it names the object's open report in its signed header; a header -//! that names any other report, or names one without joining heads, -//! is refused too. Resolution is therefore always a new signed -//! event that comes after the report it resolves. +//! its signed header names the conflict it resolves: the +//! [`ConflictKey`] of exactly the heads it joins. A header that names +//! any other key, or names one without joining heads, is refused too. +//! The key depends only on the conflicting versions, never on when or +//! from where a replica saw them, so one signed resolution means the +//! same thing on every replica that holds the same versions, while +//! each replica's report stays its own durable record. Because two +//! heads always come with an open report, a resolution is always a +//! new signed event that comes after a report covering what it joins. //! 3. **Reports are immutable.** When a conflicted object's heads //! change but stay plural, a new report supersedes the old one, //! whose status becomes `Superseded`; when they collapse to one, the @@ -45,7 +50,7 @@ //! ```text //! "id-sync/b07-version/v1" //! object_id 32 bytes -//! resolves 0x00, or 0x01 followed by a 32-byte report id +//! resolves 0x00, or 0x01 followed by a 32-byte conflict key //! parent_count u32, big-endian //! parents parent_count x 32 bytes, strictly ascending //! body the remaining bytes @@ -73,6 +78,9 @@ use super::b32_ingest_gate::{ pub type ObjectId = [u8; 32]; /// The address of a conflict report: SHA-256 of its canonical bytes. pub type ReportId = [u8; 32]; +/// The identity of a set of conflicting versions: what a resolution +/// names. See [`conflict_key`]. +pub type ConflictKey = [u8; 32]; /// A SHA-256 digest. pub type Digest32 = [u8; 32]; @@ -80,6 +88,7 @@ pub type Digest32 = [u8; 32]; pub const VERSION_DOMAIN: &[u8] = b"id-sync/b07-version/v1"; const REPORT_DOMAIN: &[u8] = b"id-sync/b07-conflict-report/v1"; const POLICY_DOMAIN: &[u8] = b"id-sync/b07-store-policy/v1"; +const CONFLICT_KEY_DOMAIN: &[u8] = b"id-sync/b07-conflict-key/v1"; fn sha256(bytes: &[u8]) -> Digest32 { let mut hasher = Sha256::new(); @@ -124,8 +133,8 @@ const fn path_tag(path: IngressPath) -> u8 { pub struct VersionHeader { /// The object this version belongs to. pub object_id: ObjectId, - /// The open report this version resolves, if it is a resolution. - pub resolves: Option, + /// The conflict this version resolves, if it is a resolution. + pub resolves: Option, /// The versions this one follows, strictly ascending. pub parents: Vec, /// The version's data. @@ -202,8 +211,8 @@ pub struct VersionRef { pub object_id: ObjectId, /// Its parents, ascending. pub parents: Vec, - /// The report it names as resolved, if any. - pub resolves: Option, + /// The conflict it names as resolved, if any. + pub resolves: Option, /// The identity the gate bound the signing key to. pub signer: String, /// The key that signed it. @@ -287,12 +296,17 @@ impl ConflictReport { sha256(&self.canonical_bytes()) } - /// What a resolution must name as its parents: every conflicting - /// version. A resolution is a new signed version with these parents - /// whose header names this report. + /// What a full resolution names as its parents: every conflicting + /// version. pub fn resolution_parents(&self) -> Vec { self.versions.iter().map(|v| v.event_id).collect() } + + /// What a full resolution names in its header: the conflict key of + /// every conflicting version. + pub fn conflict_key(&self) -> ConflictKey { + conflict_key(&self.resolution_parents()) + } } /// Where a report stands. @@ -391,19 +405,34 @@ pub enum IngestError { /// A parent belongs to a different object. ForeignParent(EventId), /// The version joins heads of a conflicted object without naming - /// its open report. + /// the conflict it resolves. ResolutionRequired { - /// The report a resolution must name. + /// The object's open report. open: ReportId, + /// The key the version would have to name. + key: ConflictKey, }, - /// The version names a report it does not resolve: not the - /// object's open report, or named without joining its heads. + /// The version names a conflict it does not resolve: not the key of + /// exactly the heads it joins, or named without joining heads. NotAResolution { - /// The report the version named. - named: ReportId, + /// The key the version named. + named: ConflictKey, }, } +/// The key of a set of conflicting versions: SHA-256 of +/// `"id-sync/b07-conflict-key/v1"`, the count as u64 big-endian, then +/// the distinct event ids in ascending order. +pub fn conflict_key(versions: &[EventId]) -> ConflictKey { + let distinct: BTreeSet<&EventId> = versions.iter().collect(); + let mut out = CONFLICT_KEY_DOMAIN.to_vec(); + out.extend_from_slice(&(distinct.len() as u64).to_be_bytes()); + for id in distinct { + out.extend_from_slice(id); + } + sha256(&out) +} + /// How long closed reports keep their evidence. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct RetentionPolicy { @@ -613,15 +642,19 @@ impl ConflictStore { .get(&version.object_id) .cloned() .unwrap_or_default(); - let joined = version + let joined: Vec = version .parents .iter() .filter(|p| state.heads.contains(*p)) - .count(); + .copied() + .collect(); match (state.open, version.resolves) { - (Some(open), Some(named)) if named == open && joined >= 2 => {} - (Some(open), None) if joined >= 2 => { - return Err(IngestError::ResolutionRequired { open }); + (Some(_), Some(named)) if joined.len() >= 2 && named == conflict_key(&joined) => {} + (Some(open), None) if joined.len() >= 2 => { + return Err(IngestError::ResolutionRequired { + open, + key: conflict_key(&joined), + }); } (_, Some(named)) => return Err(IngestError::NotAResolution { named }), _ => {} diff --git a/pkgs/id/crates/id-sync/tests/federation_b07.rs b/pkgs/id/crates/id-sync/tests/federation_b07.rs index f412f74244..c20e7a6824 100644 --- a/pkgs/id/crates/id-sync/tests/federation_b07.rs +++ b/pkgs/id/crates/id-sync/tests/federation_b07.rs @@ -110,6 +110,17 @@ fn payload( out } +/// The conflict key from the slice contract, computed independently. +fn key_of(ids: &[EventId]) -> [u8; 32] { + let distinct: BTreeSet<&EventId> = ids.iter().collect(); + let mut out = b"id-sync/b07-conflict-key/v1".to_vec(); + out.extend_from_slice(&u64::try_from(distinct.len()).unwrap().to_be_bytes()); + for id in distinct { + out.extend_from_slice(id); + } + sha(&out) +} + fn envelope( signer: usize, event_id: EventId, @@ -248,8 +259,14 @@ fn run( _ => heads.iter().rev().take(2).copied().collect(), }; let open = store.open_report(&object_id); + let joined: Vec = parents + .iter() + .filter(|p| heads.contains(p)) + .copied() + .collect(); let resolves = match step.resolves { - 1 | 2 => open, + 1 => Some(key_of(&joined)), + 2 => Some(key_of(&heads)), 3 => Some([0x5A; 32]), _ => None, }; @@ -258,11 +275,13 @@ fn run( // Predict. let conflicted = heads.len() > 1; - let joined = parents.iter().filter(|p| heads.contains(p)).count(); let expect_err = match (open, resolves) { - (Some(o), Some(r)) if r == o && joined >= 2 => None, + (Some(_), Some(r)) if joined.len() >= 2 && r == key_of(&joined) => None, (_, Some(r)) => Some(IngestError::NotAResolution { named: r }), - (Some(o), None) if joined >= 2 => Some(IngestError::ResolutionRequired { open: o }), + (Some(o), None) if joined.len() >= 2 => Some(IngestError::ResolutionRequired { + open: o, + key: key_of(&joined), + }), _ => None, }; assert_eq!(conflicted, open.is_some(), "open report iff diverged"); @@ -391,15 +410,37 @@ fn check_audit_order(store: &ConflictStore) { } AuditEntry::Resolved { report_id, .. } => assert!(created.contains(report_id)), AuditEntry::Recorded { event_id, .. } => { - if let Some(named) = store.version(event_id).unwrap().resolves { - assert!(created.contains(&named), "resolution before its report"); - let next = audit.get(i + 1).copied(); - assert!(matches!( - next, - Some(AuditEntry::Resolved { report_id, .. } - | AuditEntry::ReportCreated { supersedes: Some(report_id), .. }) - if report_id == named - )); + let version = store.version(event_id).unwrap(); + if let Some(named) = version.resolves { + // The next entry closes a report that was created + // earlier and that holds exactly what was resolved. + let closed = match audit.get(i + 1).copied() { + Some( + AuditEntry::Resolved { report_id, .. } + | AuditEntry::ReportCreated { + supersedes: Some(report_id), + .. + }, + ) => report_id, + other => panic!("resolution followed by {other:?}"), + }; + assert!(created.contains(&closed), "resolution before its report"); + let covered: BTreeSet = store + .report(&closed) + .unwrap() + .report + .versions + .iter() + .map(|v| v.event_id) + .collect(); + let joined: Vec = version + .parents + .iter() + .filter(|p| covered.contains(*p)) + .copied() + .collect(); + assert!(joined.len() >= 2); + assert_eq!(key_of(&joined), named); } } AuditEntry::Held { .. } | AuditEntry::Refused { .. } => {} @@ -468,12 +509,14 @@ fn divergence_reports_versions_signers_sources_and_disputed_data() { ] ); - // A merge that does not name the report is refused, and so is one - // that names some other report. + // A merge that does not name the conflict is refused, and so is one + // that names some other conflict. + let key = store.report(&id).unwrap().report.conflict_key(); + assert_eq!(key, key_of(&[event(3), event(2)])); let silent = envelope(2, event(4), doc, None, &[event(2), event(3)], b"merged"); assert_eq!( store.ingest(IngressPath::Remote, &silent, "peer-c", NOW), - Err(IngestError::ResolutionRequired { open: id }) + Err(IngestError::ResolutionRequired { open: id, key }) ); let wrong = envelope( 2, @@ -489,7 +532,14 @@ fn divergence_reports_versions_signers_sources_and_disputed_data() { ); assert_eq!(store.open_report(&doc), Some(id)); - let resolution = envelope(2, event(6), doc, Some(id), &[event(2), event(3)], b"merged"); + let resolution = envelope( + 2, + event(6), + doc, + Some(key), + &[event(2), event(3)], + b"merged", + ); assert_eq!( store.ingest(IngressPath::Remote, &resolution, "peer-c", NOW), Ok(IngestOutcome::Resolved(id)) @@ -669,7 +719,7 @@ fn retention_drops_only_closed_reports_after_expiry() { 2, event(9), a, - Some(open_ids[0]), + Some(store.report(&open_ids[0]).unwrap().report.conflict_key()), &[event(1), event(2)], b"m", ); @@ -688,3 +738,39 @@ fn retention_drops_only_closed_reports_after_expiry() { ); assert_eq!(store.expire(u64::MAX), 0, "open reports never expire"); } + +#[test] +fn one_signed_resolution_resolves_the_same_conflict_on_every_replica() { + let doc = object(4); + let root = envelope(0, event(1), doc, None, &[], b"v0"); + let left = envelope(0, event(2), doc, None, &[event(1)], b"left"); + let right = envelope(1, event(3), doc, None, &[event(1)], b"right"); + let key = key_of(&[event(2), event(3)]); + let resolution = envelope(2, event(4), doc, Some(key), &[event(2), event(3)], b"m"); + + // Two replicas see the same versions in a different order, by + // different paths and from different peers. + let mut a = store(); + let mut b = store(); + for env in [&root, &left, &right] { + a.ingest(IngressPath::Local, env, "self", NOW).unwrap(); + } + for env in [&right, &root, &left] { + b.ingest(IngressPath::Remote, env, "peer-a", NOW + 5) + .unwrap(); + } + let (ra, rb) = (a.open_report(&doc).unwrap(), b.open_report(&doc).unwrap()); + assert_ne!(ra, rb, "each replica keeps its own record"); + assert_eq!(a.report(&ra).unwrap().report.conflict_key(), key); + assert_eq!(b.report(&rb).unwrap().report.conflict_key(), key); + + assert_eq!( + a.ingest(IngressPath::Local, &resolution, "self", NOW), + Ok(IngestOutcome::Resolved(ra)) + ); + assert_eq!( + b.ingest(IngressPath::Remote, &resolution, "peer-a", NOW + 5), + Ok(IngestOutcome::Resolved(rb)) + ); + assert_eq!(a.heads(&doc), b.heads(&doc)); +}