diff options
| author | tv <tv@krebsco.de> | 2026-11-25 12:50:37 +0000 |
|---|---|---|
| committer | tv <tv@krebsco.de> | 2026-11-25 12:50:37 +0000 |
| commit | 8a34ccaf072e9f91ea6103cb96926833ef0f57f9 (patch) | |
| tree | 043de7122643b2fa5f077db84b7d938ded244f32 /src | |
| parent | 055e09b3410040e4300238ac5d0a53fdc2726e40 (diff) | |
federation: a checkpoint proposed a random wait after it is due
Every node voting by itself proposed a checkpoint as soon as one was due,
after a version say, at the heads it held then, and backed its own.
Nodes whose heads differed at that moment made different proposals, each
party's one true on its own: nothing ended that but nays by hand from
more than a third. Chance did it in a busy store, and a party on
purpose, sending each node another fresh write with the passing vote.
Now a node acting by itself only notes a checkpoint to propose
(Holding::proposes), and its worker has it proposed a random wait later
(Holding::propose), a sixtieth to a sixth of the keepalive interval, as
it waits before merging: by then it holds another node's proposal, and
proposes none beside one it would back.
Diffstat (limited to 'src')
| -rw-r--r-- | src/federation/held.rs | 140 |
1 files changed, 131 insertions, 9 deletions
diff --git a/src/federation/held.rs b/src/federation/held.rs index 1e1e0d4..cf3cf04 100644 --- a/src/federation/held.rs +++ b/src/federation/held.rs @@ -146,6 +146,8 @@ struct Inner { /// Of those, the ones its store held when the node first read it, at its start: taken /// some time before, which no clock of this run says. from_start: HashSet<Id>, + /// Whether it had a checkpoint to propose as it last acted by itself (`proposes`). + proposing: bool, /// Whether the store was read once since the node started (`from_start`). started: bool, at_checkpoint: Option<(Id, Instant)>, @@ -701,7 +703,7 @@ impl Holding { /// hand (`hand`, `vote::by_hand`): recorded, the record written, and offered to the /// store; the events, to put into the document. By hand, why not where it isn't. /// Nothing while its store is stopped. - fn sign(&self, hand: Option<(Id, bool)>) -> Result<Vec<Vec<u8>>, String> { + fn sign(&self, hand: Option<(Id, bool)>, propose: bool) -> Result<Vec<Vec<u8>>, String> { let (Some(voter), Some(party)) = (&self.voter, &self.party) else { return Err("this node doesn't vote for its party".to_owned()); }; @@ -738,7 +740,16 @@ impl Holding { } None => vote::decide(&seen, &voter.rules, record), }; + // A checkpoint to propose, by itself: noted, and signed only when asked for. + let mut acts = acts; + let due = hand.is_none() && acts.iter().any(|act| matches!(act, Act::Propose(_))); + if !propose { + acts.retain(|act| !matches!(act, Act::Propose(_))); + } if acts.is_empty() { + if hand.is_none() { + inner.proposing = due; + } return Ok(Vec::new()); } let current = store.state().current().clone(); @@ -790,6 +801,9 @@ impl Holding { // Written before anything is sent. record.save(&voter.record)?; inner.record = Some(record); + if hand.is_none() { + inner.proposing = due && !propose; + } let store = inner.store.as_mut().expect("held above"); for bytes in &signed { store.offer(bytes.clone()); @@ -884,21 +898,41 @@ impl Holding { } /// What it signs now, voting by itself by its operator's rules: to put into the - /// document. + /// document. Its votes; a checkpoint it would propose it only notes (`proposes`). pub(crate) fn act(&self) -> Vec<Vec<u8>> { if self.voter.is_none() { return Vec::new(); } - self.sign(None).unwrap_or_else(|why| { + self.sign(None, false).unwrap_or_else(|why| { warn!(why = %why, "Couldn't vote by itself"); Vec::new() }) } + /// Whether it had a checkpoint to propose as it last acted (`act`). + pub(crate) fn proposes(&self) -> bool { + self.inner.lock_or_recover().proposing + } + + /// As `act`, with the checkpoint it would propose, where one is still due: a random + /// wait after one first was, so that of the nodes voting by themselves few propose at + /// once. Each names the heads it holds then and backs its own, so those proposing at + /// once, at different heads, each bind their party's one `true` to their own proposal; + /// one that waited holds the first proposal by then, and proposes none beside it. + pub(crate) fn propose(&self) -> Vec<Vec<u8>> { + if self.voter.is_none() { + return Vec::new(); + } + self.sign(None, true).unwrap_or_else(|why| { + warn!(why = %why, "Couldn't propose a checkpoint by itself"); + Vec::new() + }) + } + /// A vote by hand through this node, which votes for its party and keeps its one /// record: the event, to put into the document, or why not. pub(crate) fn vote_by_hand(&self, proposal: Id, yes: bool) -> Result<Vec<u8>, String> { - self.sign(Some((proposal, yes)))? + self.sign(Some((proposal, yes)), false)? .pop() .ok_or_else(|| "nothing to cast".to_owned()) } @@ -1021,11 +1055,13 @@ fn found(pin: &Id, root: &[u8], events: &BTreeMap<Id, Vec<u8>>) -> Option<Built> /// refused now and then; writes what passed and what it signs voting by itself; puts again /// what the document lacks, a random wait after it first lacked it; and merges the store's /// heads where they are more than an event may name, a random wait after they first were, +/// and proposes a checkpoint a random wait after one was first due, /// so that of the members few do at once. pub(crate) async fn run_worker(state: crate::state::AppState) { let mut changed = state.change_tx.subscribe(); let mut due: Option<tokio::time::Instant> = None; let mut merge_due: Option<tokio::time::Instant> = None; + let mut propose_due: Option<tokio::time::Instant> = None; // Whether this node is a member of its store, as last said. let mut listed: Option<bool> = None; let mut looks = tokio::time::interval(LOOK); @@ -1053,7 +1089,7 @@ pub(crate) async fn run_worker(state: crate::state::AppState) { let unread = { let replica = doc.blocking_read(); if !replica.writable { - return (false, false, Vec::new(), Vec::new()); + return (false, false, false, Vec::new(), Vec::new()); } holding.unread(&replica.doc, replica.epoch_seq) }; @@ -1066,13 +1102,14 @@ pub(crate) async fn run_worker(state: crate::state::AppState) { ( !holding.lacking(&doc.blocking_read().doc).is_empty(), key.is_some_and(|key| holding.apart(&key)), + holding.proposes(), signed, passed, ) }); - let (lacking, apart, signed, passed) = read.await.unwrap_or_else(|error| { + let (lacking, apart, proposing, signed, passed) = read.await.unwrap_or_else(|error| { error!(error = %error, "Reading the store from the document failed"); - (false, false, Vec::new(), Vec::new()) + (false, false, false, Vec::new(), Vec::new()) }); for bytes in signed { if let Err(error) = write(&state, None, bytes).await { @@ -1110,6 +1147,17 @@ pub(crate) async fn run_worker(state: crate::state::AppState) { Some(due) => Some(due), None => Some(tokio::time::Instant::now() + wait()), }; + // A checkpoint to propose: a random wait after one first was, a sixtieth to a + // sixth of the keepalive interval (1 to 10 s at a minute), in which another + // node's proposal comes, and this node proposes none beside it. + propose_due = match propose_due { + _ if !proposing => None, + Some(due) => Some(due), + None => { + let keepalive = state.timing.keepalive; + Some(tokio::time::Instant::now() + wait_within((keepalive / 60, keepalive / 6))) + } + }; tokio::select! { changed = changed.changed() => { if changed.is_err() { @@ -1134,6 +1182,18 @@ pub(crate) async fn run_worker(state: crate::state::AppState) { } } } + () = sleep_until(propose_due), if propose_due.is_some() => { + propose_due = None; + let holding = Arc::clone(&state.holding); + let proposed = tokio::task::spawn_blocking(move || holding.propose()) + .await + .unwrap_or_default(); + for bytes in proposed { + if let Err(error) = write(&state, None, bytes).await { + warn!(error = %error, "Couldn't put what it signed for its party: put again later"); + } + } + } _ = looks.tick() => look = true, } } @@ -1147,10 +1207,14 @@ async fn sleep_until(due: Option<tokio::time::Instant>) { /// A wait within `PUT_WAIT`, random. fn wait() -> Duration { + wait_within(PUT_WAIT) +} + +/// A wait from `least` to `most`, random. +fn wait_within((least, most): (Duration, Duration)) -> Duration { let mut bytes = [0u8; 8]; - // Without randomness, the longest: the others put first. + // Without randomness, the longest: the others go first. let random = getrandom::fill(&mut bytes).map_or(u64::MAX, |()| u64::from_le_bytes(bytes)); - let (least, most) = PUT_WAIT; least + (most - least).mul_f64(random as f64 / u64::MAX as f64) } @@ -1985,6 +2049,64 @@ mod tests { ); } + /// A node with a checkpoint due proposes it not as it acts, but when asked to + /// (`propose`), which its worker does a random wait later: nodes proposing at once, + /// each at the heads it holds then, make as many proposals, and each party's one `true` + /// is on its own. + #[test] + fn a_node_proposes_a_checkpoint_only_when_asked() { + let (tv, lass, makefu) = ( + Party::new("tv", 1), + Party::new("lass", 2), + Party::new("makefu", 3), + ); + let first = Spec::first(&[&tv, &lass, &makefu], &[]); + let root = first.root(); + let mut doc = events::started(Federation::NAME, &root, &[]).unwrap(); + let dir = crate::files::scratch_dir("held-proposes-when-asked"); + let record = dir.join("makefu.json"); + let version = Version::read(&first.json()).unwrap(); + let mut begun = Record::begin(Id::of(&root), "makefu", &version); + begun.began = Id::of(b"before the federation").to_string(); + begun.save(&record).unwrap(); + let holding = Holding::open( + None, + Arc::new(Files::default()), + None, + Some("makefu".into()), + ) + .unwrap() + .voting(Some(Voter { + key: makefu.key.clone(), + record, + rules: Rules { + propose_events: Some(1), + ..Rules::default() + }, + })); + read(&holding, &doc, 0); + assert!(!holding.proposes()); + put( + &mut doc, + &tv.write(&[Id::of(&root)], "home/tv/x", harness::str("1")), + ); + read(&holding, &doc, 0); + assert_eq!(holding.act(), Vec::<Vec<u8>>::new()); + assert!(holding.proposes()); + let proposed = holding.propose(); + assert_eq!(proposed.len(), 1); + assert!(matches!( + Event::read_taken(&proposed[0]), + Some(Event::Signed(Signed { + does: Does::Proposal { .. }, + .. + })) + )); + // Proposed: it backs its own, and none is due. + assert_eq!(holding.act().len(), 1); + assert!(!holding.proposes()); + } + /// A node voting by itself whose store stopped casts nothing, by itself or by hand: /// what it reads is behind what passed. #[test] |
