From b6743899468db6304173aca4c7b32d05ea8d92c9 Mon Sep 17 00:00:00 2001 From: tv Date: Tue, 1 Dec 2026 03:23:21 +0000 Subject: remake: the switch worker looks when something changed, not every second It read the remake records and its peers' epochs once a second, whatever happened. It now looks when the records change, within a second of a peer saying another epoch than this node's, and when a vote is due; and by itself, once a second, only while something waits on time: a remake of this epoch open or committed, a rejoin, a catch-up, a member on another epoch. What it keeps for a time, an archived document or a remake's content, it wakes for when that is due. --- src/node.rs | 1 + src/remake/local.rs | 22 +++++++++++++++ src/remake/mod.rs | 4 +++ src/remake/records.rs | 7 +++++ src/remake/switch.rs | 72 +++++++++++++++++++++++++++++++++++++++++++++---- src/state/host.rs | 5 ++++ src/state/mod.rs | 3 +++ src/swarm/peer/epoch.rs | 5 ++++ 8 files changed, 114 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/node.rs b/src/node.rs index a4a5c85..792d62b 100644 --- a/src/node.rs +++ b/src/node.rs @@ -235,6 +235,7 @@ impl Node { neighbours: Default::default(), topology_changed: Default::default(), join_progress: Default::default(), + remake_wake: Default::default(), forget_records_changed: Default::default(), peers_due: Default::default(), pulling: Default::default(), diff --git a/src/remake/local.rs b/src/remake/local.rs index cf6f566..cdea68a 100644 --- a/src/remake/local.rs +++ b/src/remake/local.rs @@ -275,6 +275,28 @@ impl RemakeState { prune(&mut self.lock().archive, current_generation, now); } + /// How long until something kept for a time goes (`prune_archive`, + /// `prune_contents`), at `now`: an archived + /// document whose age limit is ahead, a remake's content within its grace. None + /// where nothing waits on time: what is kept by a count of epochs, or by a remake + /// that refers to it, goes when those change. + pub(crate) fn next_expiry(&self, now: UnixMillis) -> Option { + let inner = self.lock(); + let archives = inner.archive.iter().filter_map(|archived| { + archived + .retention + .age_left(now.ms_since(archived.archived_at)) + }); + let contents = inner + .contents + .values() + .filter_map(|(_, stored)| CONTENT_GRACE.checked_sub(stored.elapsed())); + archives + .chain(contents) + .min() + .map(|left| left + Duration::from_millis(1)) + } + pub(crate) fn catch_up(&self) -> Option { self.lock().catch_up.clone() } diff --git a/src/remake/mod.rs b/src/remake/mod.rs index 90ae436..4847d5c 100644 --- a/src/remake/mod.rs +++ b/src/remake/mod.rs @@ -311,6 +311,10 @@ pub(crate) trait Host: Clone + Send + Sync + 'static { /// Makes the next sync count as initial again. fn reset_initial_sync(&self); + /// Resolves when the remake worker has something to look at that no change of the + /// document tells: a peer said another epoch than this node's. + fn remake_woken(&self) -> impl Future + Send; + /// Store paths touched by each published document change. fn subscribe_changes(&self) -> broadcast::Receiver>; diff --git a/src/remake/records.rs b/src/remake/records.rs index 22aaee3..9b0c8f1 100644 --- a/src/remake/records.rs +++ b/src/remake/records.rs @@ -75,6 +75,13 @@ impl Retention { self.epochs.is_some_and(|limit| epochs <= limit) || self.age_ms.is_some_and(|limit| age_ms <= limit) } + + /// How long until its age limit passes, `age_ms` after the fact, where that is + /// ahead: none where it has none, or it passed, and the count of epochs decides. + pub(crate) fn age_left(&self, age_ms: u64) -> Option { + let left = self.age_ms?.checked_sub(age_ms)?; + Some(std::time::Duration::from_millis(left)) + } } #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] diff --git a/src/remake/switch.rs b/src/remake/switch.rs index 3baa164..91591c2 100644 --- a/src/remake/switch.rs +++ b/src/remake/switch.rs @@ -41,6 +41,9 @@ use crate::document::store::paths_related; use crate::document::{ActorId, ChangeHash, Document}; use crate::locks::MutexExt; +/// How often the worker looks while something waits on time: a remake of this epoch +/// open or committed, a rejoin, a catch-up, a member on another epoch. Otherwise it +/// waits for what wakes it (`look_again`). const TICK: Duration = Duration::from_secs(1); pub(crate) async fn run_worker(host: H) { @@ -49,16 +52,24 @@ pub(crate) async fn run_worker(host: H) { let records_dir = meta::path(&[REMAKES]); let mut changes = host.subscribe_changes(); let mut changes_closed = false; - let mut tick = tokio::time::interval(TICK); - tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + // What it finds at its start: a remake committed while the node was down. + let mut again = Some(tokio::time::Instant::now()); loop { - // React promptly to changes of the records; the timer covers the switch delay. + // React promptly to changes of the records, and to a peer saying another + // epoch; a timer only while something waits on time (`look_again`). // A vote waiting for its random delay (`vote`) is cast when due, not at the next // tick: with a short voting period, a second can make it too late. let vote_wait = host.remake().vote_wait(host.now_millis()); let should_check = tokio::select! { - _ = tick.tick() => true, + () = tokio::time::sleep_until(again.unwrap_or_else(tokio::time::Instant::now)), if again.is_some() => true, + // A peer said another epoch: looked at within `TICK`, not at once, as its + // message is still being taken, and others saying the same are on their way. + () = host.remake_woken() => { + let soon = tokio::time::Instant::now() + TICK; + again = Some(again.map_or(soon, |at| at.min(soon))); + false + } _ = tokio::time::sleep(vote_wait.unwrap_or_default()), if vote_wait.is_some() => true, received = changes.recv(), if !changes_closed => match received { Ok(set) => set.paths.iter().any(|path| paths_related(path, &records_dir)), @@ -66,17 +77,68 @@ pub(crate) async fn run_worker(host: H) { Err(broadcast::error::RecvError::Closed) => { warn!("Change events closed; remake worker continues on its timer only"); changes_closed = true; - false + again.is_none() } } }; if should_check { check(&host).await; + let wait = look_again(&host).await; + let wait = if changes_closed { + wait.or(Some(TICK)) + } else { + wait + }; + again = wait.map(|wait| tokio::time::Instant::now() + wait); } } } +/// How long until the worker looks again by itself (`check`); none while nothing it +/// does waits on time, and what changes that wakes it: a change of the remake +/// records, a peer saying another epoch than this node's (`Host::remake_woken`), a +/// vote due. +async fn look_again(host: &H) -> Option { + #[cfg(feature = "federation")] + if host.holding().of_a_set() { + return None; + } + let remake = host.remake(); + // A rejoin runs against its timeout, a catch-up against its retries. + if remake.is_rejoining() || remake.fetching_snapshot() || remake.catch_up().is_some() { + return Some(TICK); + } + let local = host.current_epoch(); + let (now, grace) = (host.now_millis(), host.dormant_after().as_millis() as u64); + // A remake of this epoch still voted on, to expire, or committed and to switch to. + let local_record = EpochRecord::from(local); + let open = host + .read_doc(move |doc| { + records::load_all(doc).iter().any(|(_, record)| { + record.proposal.from_epoch == local_record && record.phase(now, grace).is_open() + }) + }) + .await; + if open { + return Some(TICK); + } + // A member on another epoch than ours, not an earlier one: to be followed once + // enough say so, or once it is ready (`catchup::check`). + let elsewhere = host.peer_summaries().await.into_iter().any(|peer| { + peer.active + && peer.member + && peer + .epoch + .is_some_and(|epoch| epoch != local && epoch.generation >= local.generation) + }); + if elsewhere { + return Some(TICK); + } + // What it keeps for a time: archived documents, a remake's content. + remake.next_expiry(now) +} + async fn check(host: &H) { // A set of events has no epochs: the document a node holds beside one stays as // it is, whatever epoch its peers of both kinds say. diff --git a/src/state/host.rs b/src/state/host.rs index 66bb71c..9f6ff2b 100644 --- a/src/state/host.rs +++ b/src/state/host.rs @@ -371,6 +371,11 @@ impl Host for AppState { crate::swarm::source::reset(self); } + fn remake_woken(&self) -> impl Future + Send { + let wake = Arc::clone(&self.remake_wake); + async move { wake.notified().await } + } + fn subscribe_changes(&self) -> broadcast::Receiver> { self.change_events.subscribe() } diff --git a/src/state/mod.rs b/src/state/mod.rs index c3bb4e8..fe71b7b 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -244,6 +244,9 @@ pub(crate) struct AppState { /// Something a joining node waits for may have happened: the swarm ID learned, the /// initial sync done, a rejoin ended, a seed found (`swarm::bootstrap`). pub(crate) join_progress: Arc, + /// A peer said another epoch than this node's (`swarm::peer::epoch`): the remake + /// worker looks whether to follow it (`remake::switch`). + pub(crate) remake_wake: Arc, /// The forget records may have changed (`swarm::changes`): the peer worker acts on /// them at once instead of at its next periodic check. pub(crate) forget_records_changed: Arc, diff --git a/src/swarm/peer/epoch.rs b/src/swarm/peer/epoch.rs index d00a903..f276727 100644 --- a/src/swarm/peer/epoch.rs +++ b/src/swarm/peer/epoch.rs @@ -60,6 +60,11 @@ pub(super) async fn observe_peer_epoch( previous }; + // The remake worker looks whether to follow it, each time it says so. + if relation != EpochRelation::Same { + state.remake_wake.notify_one(); + } + // Log transitions only, not every keepalive. if previous != Some(remote) { match relation { -- cgit v1.3.1