From 7926a9764626878f5cc244286cce9eb502358929 Mon Sep 17 00:00:00 2001 From: tv Date: Fri, 20 Nov 2026 04:16:12 +0000 Subject: keep-actor by default: the writer kept across a clean stop, writes held till a sync A node that stopped cleanly writes on as the writer of before, as `--keep-actor` had it, now by default: an epoch gathers a writer per node and per crash, drop or rejoin, not per start. `keep-actor = false`, in a configuration file, has a node write as a fresh writer each start; a node without a document file has nothing to keep, which is no longer an error. Writing on as the writer of before, a node holds its writes (`mutate_doc` and the API's through it) until it synced once with a ready neighbour, level with it, or 10 seconds passed (`AppState::hold_writes`, `KEPT_WRITER_WAIT`): a neighbour holding later changes of that writer, which a copy of the node's files made (a backup restored, a disk rolled back), hands them over first, and the node takes a fresh writer then, as it did. A node that reaches no neighbour within the wait writes on. --- src/config/mod.rs | 7 ++----- src/lib.rs | 12 +++++++++--- src/node.rs | 1 + src/simtest/signatures.rs | 35 +++++++++++++++++++++++++++++++++++ src/state/mod.rs | 45 +++++++++++++++++++++++++++++++++++++++++++-- src/swarm/sync.rs | 19 +++++++++++++------ 6 files changed, 103 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/config/mod.rs b/src/config/mod.rs index 1f6ad60..672b8f8 100644 --- a/src/config/mod.rs +++ b/src/config/mod.rs @@ -410,8 +410,8 @@ pub(crate) const OPTIONS: &[OptionSpec] = &[ "keep-actor", Kind::Flag, "BOOL", - Some("false"), - "Resume writing as the actor this node wrote with before it stopped, if it stopped cleanly (its document file holds everything it wrote then), instead of a fresh one: an epoch then gathers a writer per node and per crash or drop rather than per start, which every transfer of its history carries a signature for. Needs document-file.", + Some("true"), + "Resume writing as the actor this node wrote with before it stopped, if it stopped cleanly (its document file holds everything it wrote then), instead of a fresh one, holding its writes until it synced once with a ready neighbour, or 10s passed: an epoch then gathers a writer per node and per crash or drop rather than per start, which every transfer of its history carries a signature for. Without document-file, nothing is kept. Off (false, in a configuration file) a node writes as a fresh actor each start.", ), option( "document-append", @@ -1273,9 +1273,6 @@ impl Settings { if self.document_append.is_zero() || self.document_rewrite.is_zero() { bail!("document-append and document-rewrite must be longer than 0"); } - if self.keep_actor && self.document_file.is_none() { - bail!("keep-actor needs document-file: it tells whether this node stopped cleanly"); - } if self.keepalive < Duration::from_millis(100) { bail!("keepalive must be at least 100ms"); } diff --git a/src/lib.rs b/src/lib.rs index a2e24ba..f88ad30 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -262,21 +262,24 @@ pub async fn run() -> Result<()> { let opened = document_file.as_ref().is_none_or(|file| file.open()); // Writing on as the actor of before, where this node stopped cleanly: everything it // wrote as that one is in the document, so no change of it comes twice. - match resumable.filter(|_| args.keep_actor && opened) { + let kept = match resumable.filter(|_| args.keep_actor && opened) { Some(actor) => { info!(actor = %actor, "Writing on as the actor of before (--keep-actor)"); initial_doc.set_actor(actor); + true } None if args.keep_actor && !opened => { warn!( "Writing as a fresh actor: the document file couldn't be marked as opened (--keep-actor)" ); + false } None if args.keep_actor && starting_epoch.is_some() => { info!("Writing as a fresh actor: this node didn't stop cleanly (--keep-actor)"); + false } - None => {} - } + None => false, + }; if let Some(spec) = &args.remake { remake::remake_genesis(spec, &files, &mut initial_doc) .with_context(|| format!("Making the genesis document (--remake {spec})"))?; @@ -386,6 +389,9 @@ pub async fn run() -> Result<()> { clock: Default::default(), }); let state = node.state.clone(); + if kept { + state.hold_writes(); + } // Join the remembered swarm and no other; HELLOs claim it. A document to start on // names its swarm itself (checked against the remembered one above). diff --git a/src/node.rs b/src/node.rs index 6fc8c66..3d1c882 100644 --- a/src/node.rs +++ b/src/node.rs @@ -176,6 +176,7 @@ impl Node { sync_events: sync_tx, change_tx, initial_sync_done: Arc::new(AtomicBool::new(false)), + writes_held: Arc::new(watch::channel(false).0), closing: Arc::new(watch::channel(false).0), change_events, timing: config.timing, diff --git a/src/simtest/signatures.rs b/src/simtest/signatures.rs index b65b3a7..cc087a9 100644 --- a/src/simtest/signatures.rs +++ b/src/simtest/signatures.rs @@ -110,3 +110,38 @@ async fn a_signed_write_vouches_for_the_writes_before() { .await; } } + +/// A node writing on as its writer of before holds its writes until it synced once with a +/// ready neighbour (`AppState::hold_writes`): a write waits while the node is alone, and +/// goes once a neighbour came and the node is level with it, before the wait ran out. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_kept_writer_writes_once_it_synced_with_a_neighbour() { + let sim = Sim::new(62); + let a = sim.start("a", &[], Start::Genesis); + sim.wait_ready(&[&a], SOON).await; + a.hold_writes(); + let writing = tokio::spawn({ + let a = a.clone(); + async move { super::write(&a, "users/alice", json!(1)).await } + }); + tokio::time::sleep(Duration::from_secs(1)).await; + assert!(*a.writes_held.borrow(), "writes go while alone"); + assert!( + !writing.is_finished(), + "a write went while writes were held" + ); + + let b = sim.start("b", &["a"], Start::Join); + sim.wait_until( + "a synced with b", + crate::state::KEPT_WRITER_WAIT - Duration::from_secs(2), + || async { !*a.writes_held.borrow() }, + ) + .await; + tokio::time::timeout(SOON, writing) + .await + .expect("the write went") + .expect("the write task"); + sim.wait_converged(&[&a, &b], SOON).await; + assert_eq!(super::read(&b, "users/alice").await, Some(json!(1))); +} diff --git a/src/state/mod.rs b/src/state/mod.rs index 68eafec..a812b91 100644 --- a/src/state/mod.rs +++ b/src/state/mod.rs @@ -35,7 +35,7 @@ use std::time::Duration; use anyhow::{Result, bail}; use tokio::sync::{Mutex, RwLock, broadcast, mpsc, watch}; use tokio::time::Instant; -use tracing::{debug, error, warn}; +use tracing::{debug, error, info, warn}; use crate::document::lock::DocumentLock; use crate::document::replica::{Epoch, Stamp}; @@ -94,6 +94,11 @@ pub(crate) struct AppState { pub(crate) change_tx: watch::Sender, pub(crate) initial_sync_done: Arc, + /// True while this node, writing on as its writer of before (`--keep-actor`), has + /// neither synced once with a ready neighbour nor waited `KEPT_WRITER_WAIT`: its + /// writes wait (`mutate_doc_as`), so that peers holding later changes of that writer, + /// made by another copy of its files, hand them over first (`hold_writes`). + pub(crate) writes_held: Arc>, /// True once the node shuts down (a signal, a failed join, a transport gone): the /// HTTP API drains and its long-lived responses end, and keepalives say the node /// isn't ready and is leaving (`peer::farewell`). @@ -310,7 +315,41 @@ fn roll_back( Ok(()) } +/// How long a node writing on as its writer of before waits for a ready neighbour to sync +/// with before it writes anyway (`AppState::hold_writes`). +pub(crate) const KEPT_WRITER_WAIT: Duration = Duration::from_secs(10); + impl AppState { + /// Holds this node's writes, as it writes on as its writer of before (`--keep-actor`), + /// until it synced once with a ready neighbour (`release_writes`, `swarm::sync`), or + /// `KEPT_WRITER_WAIT` passed: so that a neighbour holding later changes of that writer, + /// which another copy of its files made (a backup restored, a disk rolled back), hands + /// them over first, and the node takes a fresh writer then (`access::screen`). + pub(crate) fn hold_writes(&self) { + self.writes_held.send_replace(true); + let held = Arc::clone(&self.writes_held); + tokio::spawn(async move { + tokio::time::sleep(KEPT_WRITER_WAIT).await; + if held.send_replace(false) { + info!( + wait = ?KEPT_WRITER_WAIT, + "Writing on as the actor of before: no neighbour synced with within the wait" + ); + } + }); + } + + /// Lets this node's writes go, held while it writes on as its writer of before: it + /// synced once with `peer`, a ready neighbour. + pub(crate) fn release_writes(&self, peer: &str) { + if self.writes_held.send_replace(false) { + info!( + peer, + "Synced with a neighbour: writing on as the actor of before" + ); + } + } + /// Asks the sync worker to look at `peer` (`SyncEvent::PeerNeedsSync`): whether to /// send it a sync message now. Nothing if the worker is gone (the node stops). pub(crate) fn request_sync(&self, peer: &str) { @@ -583,7 +622,8 @@ impl AppState { } /// [`mutate_doc_for`](Self::mutate_doc_for); with `registering_first`, after this - /// node's registration if the policy needs it first. + /// node's registration if the policy needs it first. While writes are held + /// (`writes_held`), after they no longer are. async fn mutate_doc_as( &self, user: Option, @@ -595,6 +635,7 @@ impl AppState { T: Send + 'static, E: From + Send + 'static, { + let _ = self.writes_held.subscribe().wait_for(|held| !held).await; let state = self.clone(); tokio::task::spawn_blocking(move || { diff --git a/src/swarm/sync.rs b/src/swarm/sync.rs index 5f30440..ad8c0a0 100644 --- a/src/swarm/sync.rs +++ b/src/swarm/sync.rs @@ -602,6 +602,10 @@ pub(crate) async fn handle_sync( return Ok(()); } + let check_caught_up = !state.initial_sync_done.load(Ordering::Acquire); + // Writes held until a ready neighbour is synced with once (`AppState::hold_writes`). + let writes_held = *state.writes_held.borrow(); + let check_level = check_caught_up || writes_held; let applied = { let doc = Arc::clone(&state.doc); let peer_state_mutex = Arc::clone(&peer_state_mutex); @@ -611,7 +615,6 @@ pub(crate) async fn handle_sync( let rtt = state .lock_rtt() .effective(peer, Instant::now(), state.timing.rtt_fresh_for()); - let check_caught_up = !state.initial_sync_done.load(Ordering::Acquire); // While catching up, everything arrives late; that says nothing about propagation. let measure_propagation = !check_caught_up; let message = payload; @@ -620,9 +623,9 @@ pub(crate) async fn handle_sync( let ahead_ms = state.clock_ahead_ms.load(Ordering::Relaxed); let remake = Arc::clone(&state.remake); - // Some((caught_up, heads changed, carried changes, the new changes' authors with - // theirs, and whether any has none, how long to wait before answering if it - // brought only changes refused before)) when applied, None when the message + // Some((level with a ready peer, heads changed, carried changes, the new changes' + // authors with theirs, and whether any has none, how long to wait before answering + // if it brought only changes refused before)) when applied, None when the message // belongs to another epoch. type Applied = ( bool, @@ -810,7 +813,7 @@ pub(crate) async fn handle_sync( // catching up has them, and so does a ready peer whose document is empty // (a misconfigured second swarm, or a genesis node in its first seconds, // before it registered itself). - check_caught_up && from_ready && peer_state.sync.have_all_theirs(&replica.doc), + check_level && from_ready && peer_state.sync.have_all_theirs(&replica.doc), changed, carried, authors, @@ -822,7 +825,7 @@ pub(crate) async fn handle_sync( .context("Sync task panicked")?? }; - let Some((caught_up, changed, carried, (authors, unauthored), back_off, tell)) = applied else { + let Some((level, changed, carried, (authors, unauthored), back_off, tell)) = applied else { debug!(peer = %peer, epoch = %epoch_label, "Dropped sync message from another epoch"); return Ok(()); }; @@ -840,6 +843,10 @@ pub(crate) async fn handle_sync( source::reported(state, peer, from_ready, None); + if level && writes_held { + state.release_writes(peer); + } + let caught_up = level && check_caught_up; let just_caught_up = caught_up && !state.initial_sync_done.swap(true, Ordering::AcqRel); if just_caught_up { info!(peer = %peer, "Initial sync complete"); -- cgit v1.3.1