From dde5570e80b0584a19f92011780e202db4924a74 Mon Sep 17 00:00:00 2001 From: tv Date: Sun, 29 Nov 2026 14:05:32 +0000 Subject: federation: a set keeps its names as it changes, in runs with their sums A set built the names it gives to others anew for every message, and a range's fingerprint cost its names. Now ranges::Names holds names in order in runs of up to 512, each with what it adds up to, so a range's fingerprint costs its ends and a sum per run between; and a set keeps one, adding and taking out as its store takes and lets go, entries come and go, and what it holds beside goes. In tests the names kept are compared with those read anew. A node splits a range where a number of its own says (ranges::answer's salt, from the system's randomness in store::passing), so that nobody knows beforehand which ranges it compares. Who is a member, which is the fold's to say of the store's state, a set asks only where its store changed, and once for the events of one message (Set::offer_all): asked for every event offered, it was what made catching up slow. A set's store has no more than 1024 events wait. --- src/document/ranges.rs | 532 ++++++++++++++++++++++++++++++++++++------------- 1 file changed, 398 insertions(+), 134 deletions(-) (limited to 'src/document/ranges.rs') diff --git a/src/document/ranges.rs b/src/document/ranges.rs index b142f90..d206280 100644 --- a/src/document/ranges.rs +++ b/src/document/ranges.rs @@ -13,16 +13,17 @@ //! knows it lacks it. //! //! A fingerprint is the names added up as numbers modulo 2^256, with how many they are, -//! hashed: sums combine, so a range's comes from its parts'. Someone who chooses names -//! can make two sets collide with about a day of work; a kind whose names anyone mints -//! has another way to tell that two nodes hold the same, and falls back on it. - -// Used by the kinds to come: by tests alone so far. +//! hashed: sums combine, so a range's comes from its parts'. A node keeps its names +//! (`Names`) in runs, each with its sum, so that a range's fingerprint costs its ends +//! and a sum per run between, not its names. Someone who chooses names can make two +//! sets collide with about a day of work: a node splits a range where a number of its +//! own says (`answer`'s `salt`), so that nobody knows beforehand which ranges it +//! compares; and a kind whose names anyone mints has another way to tell that two +//! nodes hold the same, and falls back on it. + +// Used by the kinds to come, behind `federation` so far. #![allow(dead_code)] -use std::collections::BTreeSet; -use std::ops::Bound; - use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; @@ -35,13 +36,16 @@ const PARTS: usize = 16; /// A range holding no more names than this is answered with the names themselves. const FEW: usize = 2 * PARTS; +/// The most names of a run; one that would hold more is split in two. +const RUN: usize = 512; + /// What stands for the names of a range: the same for the same names, and, but for /// names made to collide, for no others. #[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize, Deserialize)] pub(crate) struct Fingerprint(pub(crate) [u8; 16]); -/// The names of a range added up, and how many. -#[derive(Clone, Copy, Default)] +/// Names added up, and how many. +#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)] struct Sum { sum: [u8; 32], count: u64, @@ -49,13 +53,29 @@ struct Sum { impl Sum { fn add(&mut self, name: &Name) { + self.join(&Sum { + sum: *name, + count: 1, + }); + } + + /// Adds what `other` adds up. + fn join(&mut self, other: &Sum) { let mut carry = 0u16; - for (digit, other) in self.sum.iter_mut().zip(name) { + for (digit, other) in self.sum.iter_mut().zip(&other.sum) { let total = u16::from(*digit) + u16::from(*other) + carry; *digit = total as u8; carry = total >> 8; } - self.count += 1; + self.count += other.count; + } + + fn of<'a>(names: impl IntoIterator) -> Self { + let mut sum = Sum::default(); + for name in names { + sum.add(name); + } + sum } fn fingerprint(&self) -> Fingerprint { @@ -71,11 +91,191 @@ impl Sum { /// The fingerprint of `names`. pub(crate) fn fingerprint<'a>(names: impl IntoIterator) -> Fingerprint { - let mut sum = Sum::default(); - for name in names { - sum.add(name); + Sum::of(names).fingerprint() +} + +/// Names in order, in runs of no more than `RUN`, each with what it adds up to. +#[derive(Clone, Default, Debug)] +pub(crate) struct Names { + runs: Vec, + all: Sum, +} + +#[derive(Clone, Debug)] +struct Run { + names: Vec, + sum: Sum, +} + +impl Names { + pub(crate) fn new() -> Self { + Self::default() + } + + pub(crate) fn len(&self) -> usize { + self.all.count as usize + } + + pub(crate) fn is_empty(&self) -> bool { + self.all.count == 0 + } + + /// The fingerprint of them all. + pub(crate) fn fingerprint(&self) -> Fingerprint { + self.all.fingerprint() + } + + /// The run `name` is in, or would be: the last that begins no later than it. + fn run_of(&self, name: &Name) -> usize { + self.runs + .partition_point(|run| run.names[0] <= *name) + .saturating_sub(1) + } + + pub(crate) fn contains(&self, name: &Name) -> bool { + !self.runs.is_empty() + && self.runs[self.run_of(name)] + .names + .binary_search(name) + .is_ok() + } + + /// Adds `name`; whether it wasn't there. + pub(crate) fn insert(&mut self, name: Name) -> bool { + if self.runs.is_empty() { + self.runs.push(Run { + names: vec![name], + sum: Sum::of([&name]), + }); + self.all.add(&name); + return true; + } + let at = self.run_of(&name); + let run = &mut self.runs[at]; + let Err(place) = run.names.binary_search(&name) else { + return false; + }; + run.names.insert(place, name); + run.sum.add(&name); + self.all.add(&name); + if run.names.len() > RUN { + let upper = run.names.split_off(RUN / 2); + run.sum = Sum::of(&run.names); + let sum = Sum::of(&upper); + self.runs.insert(at + 1, Run { names: upper, sum }); + } + true + } + + /// Takes `name` out; whether it was there. + pub(crate) fn remove(&mut self, name: &Name) -> bool { + if self.runs.is_empty() { + return false; + } + let at = self.run_of(name); + let run = &mut self.runs[at]; + let Ok(place) = run.names.binary_search(name) else { + return false; + }; + run.names.remove(place); + if run.names.is_empty() { + self.runs.remove(at); + } else { + run.sum = Sum::of(&run.names); + } + // What is left adds up to the runs' sums: taking a name out of a sum would need + // subtraction, and a sum of sums is as cheap. + self.all = Sum::default(); + for run in &self.runs { + self.all.join(&run.sum); + } + true + } + + /// The names in order. + pub(crate) fn iter(&self) -> impl Iterator { + self.runs.iter().flat_map(|run| run.names.iter()) + } + + /// How many names come before `upper`: all, where it is after every name. + fn rank(&self, upper: &Upper) -> usize { + let Some(upper) = upper else { + return self.len(); + }; + let mut before = 0; + for run in &self.runs { + if run.names[run.names.len() - 1] < *upper { + before += run.names.len(); + } else { + return before + run.names.partition_point(|name| name < upper); + } + } + before + } + + /// What the names from the `from`th up to the `to`th add up to. + fn sum(&self, from: usize, to: usize) -> Sum { + let mut sum = Sum::default(); + let mut at = 0; + for run in &self.runs { + let end = at + run.names.len(); + if end > from && at < to { + if at >= from && end <= to { + sum.join(&run.sum); + } else { + let low = from.saturating_sub(at); + let high = run.names.len().min(to - at); + sum.join(&Sum::of(&run.names[low..high])); + } + } + if end >= to { + break; + } + at = end; + } + sum + } + + /// The names from the `from`th up to the `to`th. + fn between(&self, from: usize, to: usize) -> Vec { + let mut out = Vec::with_capacity(to.saturating_sub(from)); + let mut at = 0; + for run in &self.runs { + let end = at + run.names.len(); + if end > from && at < to { + let low = from.saturating_sub(at); + let high = run.names.len().min(to - at); + out.extend_from_slice(&run.names[low..high]); + } + if end >= to { + break; + } + at = end; + } + out + } + + /// The `at`th name. + fn at(&self, at: usize) -> Name { + let mut before = 0; + for run in &self.runs { + if at < before + run.names.len() { + return run.names[at - before]; + } + before += run.names.len(); + } + panic!("no {at}th name among {}", self.len()); + } +} + +impl FromIterator for Names { + fn from_iter>(names: T) -> Self { + let mut out = Names::new(); + for name in names { + out.insert(name); + } + out } - sum.fingerprint() } /// Where a part ends: before this name, or after every name. @@ -124,163 +324,155 @@ pub(crate) struct Answer { pub(crate) lacking: Vec, } -/// The names of `held` from `lower` (where the part before ended) up to `upper`. -fn within<'a>( - held: &'a BTreeSet, - lower: &Upper, - upper: &Upper, -) -> impl Iterator + Clone { - let from = match lower { - Some(name) => Bound::Included(*name), - None => Bound::Unbounded, - }; - let to = match upper { - Some(name) => Bound::Excluded(*name), - None => Bound::Unbounded, - }; - // A part ending no later than it begins holds nothing; `BTreeSet::range` panics on - // such bounds, which a peer may send. - let empty = matches!((lower, upper), (Some(from), Some(to)) if from >= to); - if empty { - held.range::((Bound::Excluded([0xff; 32]), Bound::Unbounded)) - } else { - held.range((from, to)) - } -} - /// The message that begins: this node's fingerprint of everything. -pub(crate) fn open(held: &BTreeSet) -> Message { +pub(crate) fn open(held: &Names) -> Message { Message(vec![Part::Fingerprint { upper: None, - fingerprint: fingerprint(held), + fingerprint: held.fingerprint(), }]) } +/// What is being answered with. +struct Reply<'a> { + held: &'a Names, + parts: Vec, + /// How many names it holds so far, and the most it may (0: any number). + sent: usize, + most: usize, + salt: u64, +} + /// Answers `message` by what this node holds, sending no more than `most` names (0: any /// number): ranges it would exceed that with are sent as their fingerprints, for the -/// peer to ask again. -pub(crate) fn answer(held: &BTreeSet, message: &Message, most: usize) -> Answer { +/// peer to ask again. Where it splits a range, `salt` says where: a number of the +/// node's own, another each time. +pub(crate) fn answer(held: &Names, message: &Message, most: usize, salt: u64) -> Answer { let mut out = Answer::default(); - let mut reply = Vec::new(); - let mut sent = 0; - // The first part begins before every name; `lower` is `None` only there. - let mut lower: Upper = None; - let mut first = true; + let mut reply = Reply { + held, + parts: Vec::new(), + sent: 0, + most, + salt, + }; + // Each part from where the one before ended; one ending before that holds nothing. + let mut from = 0; for part in &message.0 { let upper = part.upper(); - let from = if first { None } else { lower }; - // A part after one that ended after every name holds nothing. - let ours = if !first && lower.is_none() { - Vec::new() - } else { - within(held, &from, &upper).copied().collect::>() - }; + let to = held.rank(&upper).max(from); match part { - Part::Skip { .. } => reply.push(Part::Skip { upper }), + Part::Skip { .. } => reply.parts.push(Part::Skip { upper }), Part::Fingerprint { fingerprint: theirs, .. } => { - if fingerprint(&ours) == *theirs { - reply.push(Part::Skip { upper }); + if held.sum(from, to).fingerprint() == *theirs { + reply.parts.push(Part::Skip { upper }); } else if *theirs == fingerprint([]) { // The peer holds nothing here: all of ours is what it lacks. - send(&mut reply, &mut sent, most, upper, ours, false); - } else if ours.len() <= FEW { - send(&mut reply, &mut sent, most, upper, ours, true); + reply.send(upper, held.between(from, to), false); + } else if to - from <= FEW { + reply.send(upper, held.between(from, to), true); } else { - split(&mut reply, &mut sent, most, upper, &ours); + reply.split(upper, from, to); } } Part::Names { names, asking, .. } => { - let theirs: BTreeSet<&Name> = names.iter().collect(); out.lacking - .extend(names.iter().filter(|name| !held.contains(*name))); + .extend(names.iter().filter(|name| !held.contains(name))); if *asking { - let beside: Vec = ours + let theirs: std::collections::BTreeSet<&Name> = names.iter().collect(); + let beside: Vec = held + .between(from, to) .into_iter() .filter(|name| !theirs.contains(name)) .collect(); if beside.is_empty() { - reply.push(Part::Skip { upper }); + reply.parts.push(Part::Skip { upper }); } else { - send(&mut reply, &mut sent, most, upper, beside, false); + reply.send(upper, beside, false); } } else { - reply.push(Part::Skip { upper }); + reply.parts.push(Part::Skip { upper }); } } } - lower = upper; - first = false; + from = to; if upper.is_none() { break; } } - if reply.iter().any(|part| !matches!(part, Part::Skip { .. })) { - out.reply = Some(Message(merged(reply))); + if reply + .parts + .iter() + .any(|part| !matches!(part, Part::Skip { .. })) + { + out.reply = Some(Message(merged(reply.parts))); } out } -/// Adds `names` as a part ending at `upper`, or their fingerprint where that would be -/// more than `most` names in one message. -fn send( - reply: &mut Vec, - sent: &mut usize, - most: usize, - upper: Upper, - names: Vec, - asking: bool, -) { - if most != 0 && *sent + names.len() > most && *sent > 0 { - reply.push(Part::Fingerprint { +impl Reply<'_> { + /// Adds `names` as a part ending at `upper`, or their fingerprint where that would + /// be more than `most` names in one message. + fn send(&mut self, upper: Upper, names: Vec, asking: bool) { + let most = self.most; + if most != 0 && self.sent + names.len() > most && self.sent > 0 { + self.parts.push(Part::Fingerprint { + upper, + fingerprint: fingerprint(&names), + }); + return; + } + if most != 0 && names.len() > most { + // More than one message takes by itself: its first names, and the rest as + // a fingerprint, which the peer asks about again. + let (now, later) = names.split_at(most); + self.sent += now.len(); + self.parts.push(Part::Names { + upper: Some(later[0]), + names: now.to_vec(), + asking, + }); + self.parts.push(Part::Fingerprint { + upper, + fingerprint: fingerprint(later), + }); + return; + } + self.sent += names.len(); + self.parts.push(Part::Names { upper, - fingerprint: fingerprint(&names), - }); - return; - } - if most != 0 && names.len() > most { - // More than one message takes by itself: its first names, and the rest as a - // fingerprint, which the peer asks about again. - let (now, later) = names.split_at(most); - *sent += now.len(); - reply.push(Part::Names { - upper: Some(later[0]), - names: now.to_vec(), + names, asking, }); - reply.push(Part::Fingerprint { - upper, - fingerprint: fingerprint(later), - }); - return; - } - *sent += names.len(); - reply.push(Part::Names { - upper, - names, - asking, - }); -} + } -/// Adds `ours`, the names of a range ending at `upper`, in `PARTS` parts of about as -/// many names each: the names of a part where they are few, else its fingerprint. -fn split(reply: &mut Vec, sent: &mut usize, most: usize, upper: Upper, ours: &[Name]) { - let size = ours.len().div_ceil(PARTS); - let mut chunks = ours.chunks(size).peekable(); - while let Some(chunk) = chunks.next() { - let ends = match chunks.peek() { - Some(next) => Some(next[0]), - None => upper, - }; - if chunk.len() <= FEW / PARTS { - send(reply, sent, most, ends, chunk.to_vec(), true); - } else { - reply.push(Part::Fingerprint { - upper: ends, - fingerprint: fingerprint(chunk), - }); + /// Adds the names from the `from`th up to the `to`th, a range ending at `upper`, in + /// `PARTS` parts of about as many names each, the first shorter by what `salt` + /// says: the names of a part where they are few, else its fingerprint. + fn split(&mut self, upper: Upper, from: usize, to: usize) { + let size = (to - from).div_ceil(PARTS); + let mut start = from; + let mut end = from + 1 + (self.salt % size as u64) as usize; + while start < to { + let end_here = end.min(to); + let ends = if end_here == to { + upper + } else { + Some(self.held.at(end_here)) + }; + if end_here - start <= FEW / PARTS { + let names = self.held.between(start, end_here); + self.send(ends, names, true); + } else { + self.parts.push(Part::Fingerprint { + upper: ends, + fingerprint: self.held.sum(start, end_here).fingerprint(), + }); + } + start = end_here; + end = start + size; } } } @@ -300,8 +492,31 @@ fn merged(parts: Vec) -> Vec { #[cfg(test)] mod tests { use super::*; + use std::cell::Cell; + use std::collections::BTreeSet; + use crate::testrand::{Rng, for_seeds}; + fn of(names: &BTreeSet) -> Names { + names.iter().copied().collect() + } + + thread_local! { + static SALT: Cell = const { Cell::new(0) }; + } + + /// Another number each time. + fn salt() -> u64 { + SALT.with(|salt| { + salt.set( + salt.get() + .wrapping_mul(6364136223846793005) + .wrapping_add(1442695040888963407), + ); + salt.get() >> 33 + }) + } + /// Two nodes reconciling until neither has more to say: what each learned it /// lacks, and how many messages went. fn reconcile( @@ -310,7 +525,7 @@ mod tests { most: usize, ) -> (BTreeSet, BTreeSet, usize) { let (mut a_lacks, mut b_lacks) = (BTreeSet::new(), BTreeSet::new()); - let mut message = open(a); + let mut message = open(&of(a)); let mut messages = 1; // Whose turn it is to answer: b's first. let mut b_answers = true; @@ -320,7 +535,7 @@ mod tests { } else { (a, &mut a_lacks) }; - let answer = answer(held, &message, most); + let answer = answer(&of(held), &message, most, salt()); lacks.extend(answer.lacking); let Some(reply) = answer.reply else { return (a_lacks, b_lacks, messages); @@ -446,7 +661,7 @@ mod tests { b.extend(some(rng, 0, 300)); let most = rng.between(1, 50); let (mut a_lacks, mut b_lacks) = (BTreeSet::new(), BTreeSet::new()); - let mut message = open(&a); + let mut message = open(&of(&a)); let mut b_answers = true; for _ in 0..10_000 { let (held, lacks) = if b_answers { @@ -454,7 +669,7 @@ mod tests { } else { (&a, &mut a_lacks) }; - let answer = answer(held, &message, most); + let answer = answer(&of(held), &message, most, salt()); lacks.extend(answer.lacking); let Some(reply) = answer.reply else { let (expect_a, expect_b) = differences(&a, &b); @@ -489,7 +704,7 @@ mod tests { b.extend(names(rng, 20)); let (before_a, before_b) = (a.clone(), b.clone()); let (mut a_lacks, mut b_lacks) = (BTreeSet::new(), BTreeSet::new()); - let mut message = open(&a); + let mut message = open(&of(&a)); let mut b_answers = true; for _ in 0..10_000 { if rng.chance(0.5) { @@ -503,7 +718,7 @@ mod tests { } else { (&a, &mut a_lacks) }; - let answer = answer(held, &message, 0); + let answer = answer(&of(held), &message, 0, salt()); lacks.extend(answer.lacking); let Some(reply) = answer.reply else { let (expect_a, expect_b) = differences(&before_a, &before_b); @@ -547,8 +762,57 @@ mod tests { fingerprint: Fingerprint([3; 16]), }, ]); - let answer = answer(&held, &message, 0); + let answer = answer(&of(&held), &message, 0, 7); assert_eq!(answer.lacking, vec![[7; 32]]); assert!(answer.reply.is_some()); } + + #[test] + fn names_kept_in_runs_are_the_names_put_and_taken() { + for_seeds(40, |rng| { + let mut kept = Names::new(); + let mut plain = BTreeSet::new(); + let mut pool: Vec = (0..rng.between(1, 3000)).map(|_| rng.bytes32()).collect(); + pool.push([0; 32]); + pool.push([0xff; 32]); + for _ in 0..rng.between(0, 6000) { + let name = *rng.pick(&pool); + if rng.chance(0.7) { + assert_eq!(kept.insert(name), plain.insert(name)); + } else { + assert_eq!(kept.remove(&name), plain.remove(&name)); + } + } + assert_eq!(kept.len(), plain.len()); + assert_eq!(kept.is_empty(), plain.is_empty()); + assert!(kept.iter().eq(plain.iter())); + assert_eq!(kept.fingerprint(), fingerprint(&plain)); + assert!( + kept.runs + .iter() + .all(|run| !run.names.is_empty() && run.names.len() <= RUN) + ); + for name in pool.iter().take(50) { + assert_eq!(kept.contains(name), plain.contains(name)); + } + // Ranges by rank: what they add up to, hold, and where a name comes. + let all: Vec = plain.iter().copied().collect(); + for _ in 0..20 { + let from = rng.between(0, all.len()); + let to = rng.between(from, all.len()); + assert_eq!(kept.sum(from, to), Sum::of(&all[from..to])); + assert_eq!(kept.between(from, to), all[from..to]); + if from < all.len() { + assert_eq!(kept.at(from), all[from]); + assert_eq!(kept.rank(&Some(all[from])), from); + } + let bound = rng.bytes32(); + assert_eq!( + kept.rank(&Some(bound)), + all.iter().filter(|name| **name < bound).count() + ); + } + assert_eq!(kept.rank(&None), all.len()); + }); + } } -- cgit v1.3.1