aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CHANGELOG.md8
-rw-r--r--docs/example.toml16
-rw-r--r--docs/lifecycle.md30
-rw-r--r--docs/measurements.md2
-rw-r--r--src/config/mod.rs7
-rw-r--r--src/lib.rs12
-rw-r--r--src/node.rs1
-rw-r--r--src/simtest/signatures.rs35
-rw-r--r--src/state/mod.rs45
-rw-r--r--src/swarm/sync.rs19
10 files changed, 137 insertions, 38 deletions
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f495fb7..b70d7bd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,14 @@ it from the release before ([`docs/operations.md`](docs/operations.md),
## Unreleased
+* A node that stopped cleanly writes on as the writer of before (`--keep-actor`, on by
+ default; `keep-actor = false` in a configuration file turns it off), holding its
+ writes until it synced once with a ready neighbour, or 10 seconds passed, so that a
+ neighbour holding a copy's later changes of that writer hands them over first; a node
+ without a document file has nothing to keep, and no longer an error for it
+ ([`docs/lifecycle.md`](docs/lifecycle.md); [`src/state/mod.rs`](src/state/mod.rs),
+ [`src/lib.rs`](src/lib.rs)).
+
* Over Mycelium, a node waits in its daemon for what comes in only while it asks nothing
else of it, as the daemon holds back every other request while one waits: an idle node
sends at once, and two idle nodes reach each other. The daemon's API errors name their
diff --git a/docs/example.toml b/docs/example.toml
index 6a6f7b3..cdf942a 100644
--- a/docs/example.toml
+++ b/docs/example.toml
@@ -284,13 +284,15 @@ htpasswd = "/etc/continuum/htpasswd"
# document-rewrite = "1h"
# 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,
-# and every transfer of its history carries a signature per writer. Never start two
-# nodes from copies of one document file, nor a node from an older copy of its own (a
-# restored backup, a rolled-back disk): both would write as the same actor. Needs
-# document-file.
-# keep-actor = false
+# 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, and
+# every transfer of its history carries a signature per writer. A copy of the data
+# directory (two nodes from copies of one document file, a restored backup, a
+# rolled-back disk) writes as the same actor: a neighbour holding the other copy's later
+# changes hands them over within the wait, and the node takes a fresh actor. Without
+# document-file, nothing is kept.
+# keep-actor = true
# --- Timings and sizes -------------------------------------------------------------------
# Durations: seconds (30, 0.5) or with units (500ms, 30s, 1m, 1h30m, 7d).
diff --git a/docs/lifecycle.md b/docs/lifecycle.md
index a221063..41a4ddc 100644
--- a/docs/lifecycle.md
+++ b/docs/lifecycle.md
@@ -95,20 +95,22 @@ document file holding a document is an error with no override.
by a crash is dropped when reading. A file is read only by a version that knows
every kind of record in it: one a later version wrote is unusable to an earlier one,
which doesn't start on it unless told to move it aside (`--force badDocumentFile`). A node starting from it is ready at once; sync
- merges what it missed, or it rejoins a newer epoch. A node writes as a fresh actor
- each start, unless `--keep-actor` and it stopped cleanly (the file marks a clean
- stop, and the mark is undone as the node starts on it, before it decides its actor):
- then it writes on as the actor of before, as nothing it wrote is missing. Where the
- mark can't be undone (the disk full, say), it writes as a fresh one. Two nodes
- started on copies of one file would both write on as that actor, and each one's
- changes would be refused as forged by peers holding the other's: don't start a copy
- of a node's data directory while the node runs, or after it, with `--keep-actor`. A
- node receiving a change of its own actor that it didn't make, signed with its own
- key, writes on as a fresh actor at once, and logs a warning (unsigned, it is
- anyone's forgery: refused, and nothing switches); what both wrote before stays refused where the
- other's came first. Fewer actors mean fewer signatures in every
- transfer of the epoch's history (a writer each); a crash, a drop, or a switch or a
- rejoin still starts a fresh one.
+ merges what it missed, or it rejoins a newer epoch. A node that stopped cleanly writes
+ on as the actor of before (`--keep-actor`, on by default), as nothing it wrote is
+ missing: the file marks a clean stop, and the mark is undone as the node starts on it,
+ before it decides its actor. Where the mark can't be undone (the disk full, say), or
+ the node didn't stop cleanly, it writes as a fresh one. Writing on as the actor of
+ before, it holds its writes (the API's among them) until it synced once with a ready
+ neighbour, or 10 seconds passed. Two nodes started on copies of one file, or a node on
+ an older copy of its own (a restored backup, a rolled-back disk), write as the same
+ actor: a neighbour holding the other copy's later changes hands them over within that
+ wait, and a node receiving a change of its own actor that it didn't make, signed with
+ its own key, writes on as a fresh actor at once, and logs a warning (unsigned, it is
+ anyone's forgery: refused, and nothing switches). What both wrote before stays refused
+ where the other's came first, so don't start a copy of a node's data directory while
+ the node runs; `keep-actor = false` has a node write as a fresh actor each start.
+ Fewer actors mean fewer signatures in every transfer of the epoch's history (a writer
+ each); a crash, a drop, or a switch or a rejoin still starts a fresh one.
* **A backup** (`GET /admin/document`) is the whole document with its history, naming
its swarm and epoch. `--recover-from` starts a node on it; `--genesis --remake
import:FILE` starts a *new* swarm with its content; an `import` remake brings its
diff --git a/docs/measurements.md b/docs/measurements.md
index 2adc9ed..60eac40 100644
--- a/docs/measurements.md
+++ b/docs/measurements.md
@@ -39,7 +39,7 @@ whole seconds in JSON unless named `…Ms`; Prometheus has seconds throughout.
| JSON | Prometheus | Meaning |
|---|---|---|
| `document.heads` | `document_heads` | Heads of the local document now. 1 means every change has been merged into one line of history; more means concurrent writes not yet followed by a merging write. |
-| `document.writers` | `document_writers` | Writers (Automerge actors) with changes in the document, counted with the saved size. Each start, rejoin or drop of a node makes one (a start keeps the one of before with `--keep-actor` after a clean stop), and every transfer of the whole history carries a signature for each; a remake starts again from the writers that write in the new epoch. |
+| `document.writers` | `document_writers` | Writers (Automerge actors) with changes in the document, counted with the saved size. Each rejoin or drop of a node makes one, and each start but after a clean stop (`--keep-actor`), and every transfer of the whole history carries a signature for each; a remake starts again from the writers that write in the new epoch. |
| `document.maxHeads` | `document_max_heads` | The most heads seen right after applying a sync message. A high value shows how concurrent the swarm's writing gets; it also bounds keepalive size (above 32 heads, keepalives carry a digest and 32 of them). |
| `document.savedBytes` | `document_saved_bytes` | The document as Automerge saves it (compressed): roughly what a joining node downloads and what a document file rewrite writes. Measured in the background, only after a change, at least a minute apart and at most 1% of the time (a document that takes 2 s to save is measured every 200 s at most); an export (`GET /admin/document`) counts as a measurement. `savedBytesSecsAgo` and `savedBytesTookMs` say how fresh and how costly. |
| `document.lockWait.read`, `.write`: `count`, `sumUs`, `maxUs`, `buckets[]` (`leUs`) | `document_lock_wait_seconds{mode}` (histogram), `document_lock_wait_max_seconds{mode}` | How long takers of the document's lock waited for it, since start, by mode. Readers (the API's reads, topology, stats, generating sync messages, serving changes and deltas, saves) wait only for a writer; writers (applying sync messages and fetched changes, writes, epoch switches) wait for everyone. Buckets from 10 µs to 10 s, the last unbounded; not cumulative in JSON. |
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<u64>,
pub(crate) initial_sync_done: Arc<AtomicBool>,
+ /// 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<watch::Sender<bool>>,
/// 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<T, E>(
&self,
user: Option<String>,
@@ -595,6 +635,7 @@ impl AppState {
T: Send + 'static,
E: From<StoreError> + 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");