Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

test(volume): add cua-replica-lab, an opt-in chaos suite for the replicated Volume (#6289)

dduponta78f99a17424
diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lock
index 3060411e4b..0bad8de149 100644
--- a/libs/cua/Cargo.lock
+++ b/libs/cua/Cargo.lock
@@ -2989,6 +2989,25 @@ dependencies = [
"tonic-prost-build",
]
+[[package]]
+name = "cua-replica-lab"
+version = "0.9.0"
+dependencies = [
+ "async-trait",
+ "cua-cluster",
+ "cua-volume",
+ "hex",
+ "libc",
+ "rand 0.9.5",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "tempfile",
+ "tokio",
+ "tracing",
+ "tracing-subscriber",
+]
+
[[package]]
name = "cua-repo-cache"
version = "0.9.0"
diff --git a/libs/cua/Cargo.toml b/libs/cua/Cargo.toml
index a9f98cf469..bc67e36e51 100644
--- a/libs/cua/Cargo.toml
+++ b/libs/cua/Cargo.toml
@@ -36,6 +36,8 @@ members = [
"crates/cua-cli",
"crates/cua-spaces-contract",
"crates/cua-spaces-transcript",
+ # Test rig for the replicated Volume (impairment proxy, replica node, chaos matrix); not shipped.
+ "crates/cua-replica-lab",
"crates/cua-spaces",
# Cua Spaces extensions (FSL-1.1-MIT): teleport, Cua Volume tools and
# persistent agents over the cua-spaces extension points.
diff --git a/libs/cua/crates/cua-replica-lab/Cargo.toml b/libs/cua/crates/cua-replica-lab/Cargo.toml
new file mode 100644
index 0000000000..90fb240ff4
--- /dev/null
+++ b/libs/cua/crates/cua-replica-lab/Cargo.toml
@@ -0,0 +1,43 @@
+[package]
+name = "cua-replica-lab"
+description = "Test rig for the replicated Volume: a userspace network impairment proxy scoped to test ports, a replica node process with a durable-agent simulation, and the opt-in chaos matrix. Not shipped."
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+authors.workspace = true
+license = "FSL-1.1-MIT"
+repository.workspace = true
+publish = false
+
+[lib]
+name = "cua_replica_lab"
+path = "src/lib.rs"
+
+[[bin]]
+name = "replica-node"
+path = "src/bin/replica_node.rs"
+
+[[bin]]
+name = "netshape"
+path = "src/bin/netshape.rs"
+
+[[bin]]
+name = "replica-chaos"
+path = "src/bin/chaos.rs"
+
+[dependencies]
+cua-cluster.workspace = true
+cua-volume.workspace = true
+async-trait.workspace = true
+hex.workspace = true
+libc = "0.2"
+rand.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+sha2.workspace = true
+tempfile.workspace = true
+tokio = { workspace = true, features = ["full"] }
+tracing.workspace = true
+tracing-subscriber.workspace = true
+
+[dev-dependencies]
diff --git a/libs/cua/crates/cua-replica-lab/LICENSE b/libs/cua/crates/cua-replica-lab/LICENSE
new file mode 100644
index 0000000000..79293ae602
--- /dev/null
+++ b/libs/cua/crates/cua-replica-lab/LICENSE
@@ -0,0 +1,110 @@
+# Functional Source License, Version 1.1, MIT Future License
+
+## Abbreviation
+
+FSL-1.1-MIT
+
+## Notice
+
+Copyright 2026 Cua AI, Inc.
+
+## Terms and Conditions
+
+### Licensor ("We")
+
+The party offering the Software under these Terms and Conditions.
+
+### The Software
+
+The "Software" is each version of the software that we make available under
+these Terms and Conditions, as indicated by our inclusion of these Terms and
+Conditions with the Software.
+
+### License Grant
+
+Subject to your compliance with this License Grant and the Patents,
+Redistribution and Trademark clauses below, we hereby grant you the right to
+use, copy, modify, create derivative works, publicly perform, publicly display
+and redistribute the Software for any Permitted Purpose identified below.
+
+### Permitted Purpose
+
+A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
+means making the Software available to others in a commercial product or
+service that:
+
+1. substitutes for the Software;
+
+2. substitutes for any other product or service we offer using the Software
+ that exists as of the date we make the Software available; or
+
+3. offers the same or substantially similar functionality as the Software.
+
+Permitted Purposes specifically include using the Software:
+
+1. for your internal use and access;
+
+2. for non-commercial education;
+
+3. for non-commercial research; and
+
+4. in connection with professional services that you provide to a licensee
+ using the Software in accordance with these Terms and Conditions.
+
+### Patents
+
+To the extent your use for a Permitted Purpose would necessarily infringe our
+patents, the license grant above includes a license under our patents. If you
+make a claim against any party that the Software infringes or contributes to
+the infringement of any patent, then your patent license to the Software ends
+immediately.
+
+### Redistribution
+
+The Terms and Conditions apply to all copies, modifications and derivatives of
+the Software.
+
+If you redistribute any copies, modifications or derivatives of the Software,
+you must include a copy of or a link to these Terms and Conditions and not
+remove any copyright notices provided in or with the Software.
+
+### Disclaimer
+
+THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
+PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
+
+IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
+SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
+EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
+
+### Trademarks
+
+Except for displaying the License Details and identifying us as the origin of
+the Software, you have no right under these Terms and Conditions to use our
+trademarks, trade names, service marks or product names.
+
+## Grant of Future License
+
+We hereby irrevocably grant you an additional license to use the Software under
+the MIT license that is effective on the second anniversary of the date we make
+the Software available. On or after that date, you may use the Software under
+the MIT license, in which case the following will apply:
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
+of the Software, and to permit persons to whom the Software is furnished to do
+so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/libs/cua/crates/cua-replica-lab/scripts/upgrade-test.sh b/libs/cua/crates/cua-replica-lab/scripts/upgrade-test.sh
new file mode 100755
index 0000000000..e3a2fc9d39
--- /dev/null
+++ b/libs/cua/crates/cua-replica-lab/scripts/upgrade-test.sh
@@ -0,0 +1,87 @@
+#!/bin/bash
+# SPDX-License-Identifier: FSL-1.1-MIT
+# Copyright (c) 2026 Cua AI, Inc.
+#
+# Upgrade, replication and rollback of a Volume that already exists.
+# upgrade-test.sh OLD_CUA NEW_CUA REPLICA_NODE
+# OLD_CUA: the shipped cua CLI before replication. NEW_CUA: the cua-spaces-cli
+# build after it. REPLICA_NODE: the replica-node binary of this crate
+# (cargo build -p cua-replica-lab --bins). Isolated homes only
+# (under a temporary directory); never the real ~/.cua.
+set -u
+OLD=$1; NEW=$2; NODE=$3
+T=$(mktemp -d "${TMPDIR:-/tmp}/replica-upgrade.XXXXXX"); H=$T/home-a; H2=$T/home-b; mkdir -p $H $H2
+export CUA_HOME=$H CUA_TELEMETRY=0 HOME=$T/fakehome; mkdir -p $HOME
+fail() { echo "FAIL: $*"; cleanup; exit 1; }
+pids=()
+cleanup() { for p in "${pids[@]:-}"; do kill $p 2>/dev/null; done; sleep 1; [ -n "${KEEP:-}" ] || rm -rf "$T"; }
+sum_dir() { (cd "$1" && find . -type f ! -path './replica/*' ! -name '.lock' ! -name '*.tmp' ! -name 'grants.json' ! -name 'audit*' -print0 | sort -z | xargs -0 shasum -a 256 | shasum -a 256 | cut -c1-16); }
+echo "== 1. the shipped build makes a Volume with real data"
+for i in $(seq 1 60); do head -c $((500 + i * 37)) /dev/urandom > $T/f$i; $OLD volume put public/f$i.bin $T/f$i >/dev/null 2>&1 || fail "old put $i"; done
+head -c 8000000 /dev/urandom > $T/big; $OLD volume put public/big.bin $T/big >/dev/null 2>&1 || fail "old big put"
+echo v1 > $T/h; $OLD volume put public/history.md $T/h >/dev/null 2>&1; echo v2 > $T/h; $OLD volume put public/history.md $T/h >/dev/null 2>&1
+echo mine > $T/c1; $OLD volume put "public/notes (conflict from laptop 2026-10-01 10.00.00).md" $T/c1 >/dev/null 2>&1
+echo base > $T/c2; $OLD volume put public/notes.md $T/c2 >/dev/null 2>&1
+[ -d $H/volume/data ] || fail "no volume data dir after the old build (layout?): $(ls $H)"
+BEFORE=$(sum_dir $H/volume/data); echo "data sum before: $BEFORE ($(find $H/volume/data -type f | wc -l) files)"
+echo "== 2. in place update: the new build reads everything, writes, history intact"
+$NEW volume cat public/history.md 2>&1 | grep -q v2 || fail "new cannot read history head"
+for i in 1 17 60; do $NEW volume cat public/f$i.bin > $T/o$i 2>/dev/null; cmp -s $T/o$i $T/f$i || fail "new reads f$i differently"; done
+$NEW volume cat public/big.bin > $T/obig 2>/dev/null; cmp -s $T/obig $T/big || fail "new reads the big file differently"
+$NEW volume ls public/ 2>/dev/null | grep -q "conflict from laptop" || fail "the conflict copy is gone"
+[ "$(sum_dir $H/volume/data)" = "$BEFORE" ] || fail "reading with the new build changed the data"
+[ ! -e $H/volume/replica ] || fail "replication files appeared with one machine"
+echo ok
+echo "== 3. a second machine joins: replication starts, nothing is lost, a backup exists"
+P1=7811; P2=7812
+$NODE --home $H/volume --id a --name "Machine A" --listen 127.0.0.1:$P1 --member a="Machine A" --member b="Machine B" --peer b=127.0.0.1:$P2 --control 127.0.0.1:7801 --fast --rank 2000 --sleep-prone > $T/a.log 2>&1 & pids+=($!)
+$NODE --home $H2/volume --id b --name "Machine B" --listen 127.0.0.1:$P2 --member a="Machine A" --member b="Machine B" --peer a=127.0.0.1:$P1 --control 127.0.0.1:7802 --fast --rank 9000 > $T/b.log 2>&1 & pids+=($!)
+ctl() { python3 - "$@" <<'PY'
+import socket,sys,json
+s=socket.create_connection(("127.0.0.1",int(sys.argv[1])),timeout=60); f=s.makefile("rw")
+f.write(" ".join(sys.argv[2:])+"\n"); f.flush(); print(f.readline().strip())
+PY
+}
+for n in $(seq 1 120); do
+ A=$(ctl 7801 count public/ 2>/dev/null | python3 -c "import sys,json;print(json.loads(sys.stdin.read()).get('count',0))" 2>/dev/null)
+ B=$(ctl 7802 count public/ 2>/dev/null | python3 -c "import sys,json;print(json.loads(sys.stdin.read()).get('count',0))" 2>/dev/null)
+ [ "${A:-0}" -gt 0 ] && [ "${A:-0}" = "${B:-1}" ] && break; sleep 1
+done
+[ "${A:-0}" = "${B:-1}" ] && [ "${A:-0}" -gt 60 ] || fail "the volumes did not meet (a=$A b=$B)"
+SA=$(ctl 7801 sum public/ | python3 -c "import sys,json;print(json.loads(sys.stdin.read())['sum'])"); SB=$(ctl 7802 sum public/ | python3 -c "import sys,json;print(json.loads(sys.stdin.read())['sum'])")
+[ "$SA" = "$SB" ] || fail "heads differ after joining"
+ls $H/volume/replica/backup/heads-* >/dev/null 2>&1 || fail "no backup of the heads"
+[ -f $H/volume/replica/format.json ] || fail "no format marker"
+# the old Volume's own files are byte for byte what they were (replication only added versions)
+for i in 1 17 60; do ctl 7802 get public/f$i.bin | grep -q etag || fail "machine B lacks f$i"; done
+echo "replicated: $A objects on both, heads equal, backup and format marker present"
+echo "== 4. roll back: the shipped build reads the replicated home and writes behind replication's back"
+kill ${pids[0]} ${pids[1]} 2>/dev/null; sleep 2; pids=()
+$OLD volume cat public/history.md 2>&1 | grep -q v2 || fail "old build cannot read the replicated home"
+$OLD volume cat public/big.bin > $T/obig2 2>/dev/null; cmp -s $T/obig2 $T/big || fail "old build reads the big file differently"
+echo "written by the old build after the update" > $T/late; $OLD volume put public/late.md $T/late >/dev/null 2>&1 || fail "old write"
+$NODE --home $H/volume --id a --name "Machine A" --listen 127.0.0.1:$P1 --member a="Machine A" --member b="Machine B" --peer b=127.0.0.1:$P2 --control 127.0.0.1:7801 --fast --rank 2000 --sleep-prone > $T/a2.log 2>&1 & pids+=($!)
+$NODE --home $H2/volume --id b --name "Machine B" --listen 127.0.0.1:$P2 --member a="Machine A" --member b="Machine B" --peer a=127.0.0.1:$P1 --control 127.0.0.1:7802 --fast --rank 9000 > $T/b2.log 2>&1 & pids+=($!)
+for n in $(seq 1 90); do ctl 7802 get public/late.md 2>/dev/null | grep -q etag && break; sleep 1; done
+ctl 7802 get public/late.md | grep -q etag || fail "the old build's write never reached machine B"
+echo ok
+echo "== 4b. the same after a hard stop (no heads snapshot at all)"
+kill -9 ${pids[@]} 2>/dev/null; sleep 2; pids=()
+rm -f $H/volume/replica/heads.snap
+echo "written by the old build after a crash" > $T/late2; $OLD volume put public/late2.md $T/late2 >/dev/null 2>&1 || fail "old write 2"
+$NODE --home $H/volume --id a --name "Machine A" --listen 127.0.0.1:$P1 --member a="Machine A" --member b="Machine B" --peer b=127.0.0.1:$P2 --control 127.0.0.1:7801 --fast --rank 2000 --sleep-prone > $T/a4.log 2>&1 & pids+=($!)
+$NODE --home $H2/volume --id b --name "Machine B" --listen 127.0.0.1:$P2 --member a="Machine A" --member b="Machine B" --peer a=127.0.0.1:$P1 --control 127.0.0.1:7802 --fast --rank 9000 > $T/b4.log 2>&1 & pids+=($!)
+for n in $(seq 1 90); do ctl 7802 get public/late2.md 2>/dev/null | grep -q etag && break; sleep 1; done
+ctl 7802 get public/late2.md | grep -q etag || fail "the write made before a hard stop never reached machine B"
+echo ok
+echo "== 5. a newer format is refused, nothing is touched"
+kill ${pids[@]} 2>/dev/null; sleep 2; pids=()
+echo '{"format":99,"created_ms":1}' > $H/volume/replica/format.json
+B4=$(sum_dir $H/volume/data)
+$NODE --home $H/volume --id a --name "Machine A" --listen 127.0.0.1:$P1 --member a="Machine A" --member b="Machine B" --peer b=127.0.0.1:$P2 --control 127.0.0.1:7801 --fast --rank 2000 > $T/a3.log 2>&1 & p=$!; sleep 3; kill $p 2>/dev/null
+grep -q "newer Cua Spaces" $T/a3.log || fail "no plain refusal: $(tail -3 $T/a3.log)"
+[ "$(sum_dir $H/volume/data)" = "$B4" ] || fail "the refused start touched the data"
+$OLD volume cat public/history.md 2>&1 | grep -q v2 || fail "data unreadable after the refusal"
+echo ok
+echo "ALL PASS"
+cleanup
diff --git a/libs/cua/crates/cua-replica-lab/src/bin/chaos.rs b/libs/cua/crates/cua-replica-lab/src/bin/chaos.rs
new file mode 100644
index 0000000000..6cc2aed3a0
--- /dev/null
+++ b/libs/cua/crates/cua-replica-lab/src/bin/chaos.rs
@@ -0,0 +1,91 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! `CUA_CHAOS=1 replica-chaos --list | --all | --scenario NAME [--standard] [--out FILE]`
+//!
+//! The opt-in chaos matrix for the replicated Volume (see
+//! `cua_replica_lab::chaos`). Fast timing (heartbeat 50 ms, scenario time
+//! 1/40) unless `--standard`. Exits non-zero if any scenario fails.
+
+#[cfg(unix)]
+mod imp {
+ use cua_replica_lab::chaos;
+
+ fn arg(args: &[String], name: &str) -> Option<String> {
+ args.iter()
+ .position(|a| a == name)
+ .and_then(|i| args.get(i + 1))
+ .cloned()
+ }
+
+ #[tokio::main]
+ pub async fn main() {
+ let _ = tracing_subscriber::fmt()
+ .with_env_filter(
+ tracing_subscriber::EnvFilter::try_from_default_env()
+ .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("off")),
+ )
+ .try_init();
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ if args.iter().any(|a| a == "--list") {
+ for n in chaos::names() {
+ println!("{n}");
+ }
+ return;
+ }
+ if std::env::var("CUA_CHAOS").ok().as_deref() != Some("1") {
+ eprintln!(
+ "the chaos matrix is opt-in (it is slow and uses real sockets on loopback): set CUA_CHAOS=1"
+ );
+ return;
+ }
+ let fast = !args.iter().any(|a| a == "--standard");
+ let names: Vec<String> = match arg(&args, "--scenario") {
+ Some(n) => n.split(',').map(str::to_string).collect(),
+ None if args.iter().any(|a| a == "--all") => {
+ chaos::names().into_iter().map(str::to_string).collect()
+ }
+ None => {
+ eprintln!(
+ "usage: CUA_CHAOS=1 replica-chaos --list | --all | --scenario NAME[,NAME] [--standard] [--out FILE]"
+ );
+ std::process::exit(2);
+ }
+ };
+ let mut all = vec![];
+ let mut failed = 0;
+ for n in names {
+ eprintln!("== {n}");
+ let t = std::time::Instant::now();
+ let Some(o) = chaos::run(&n, fast).await else {
+ eprintln!("unknown scenario {n}");
+ std::process::exit(2);
+ };
+ let mut j = o.json();
+ j["seconds"] = t.elapsed().as_secs_f64().into();
+ j["timing"] = if fast { "fast" } else { "standard" }.into();
+ println!("{j}");
+ if !o.pass {
+ failed += 1;
+ eprintln!("FAILED: {}", o.problems.join("; "));
+ }
+ all.push(j);
+ }
+ if let Some(out) = arg(&args, "--out") {
+ let _ = std::fs::write(out, serde_json::to_vec_pretty(&all).unwrap_or_default());
+ }
+ if failed > 0 {
+ std::process::exit(1);
+ }
+ }
+}
+
+#[cfg(unix)]
+fn main() {
+ imp::main()
+}
+
+#[cfg(not(unix))]
+fn main() {
+ eprintln!("cua-replica-lab runs on Unix only (it signals processes and raises file limits)");
+}
diff --git a/libs/cua/crates/cua-replica-lab/src/bin/netshape.rs b/libs/cua/crates/cua-replica-lab/src/bin/netshape.rs
new file mode 100644
index 0000000000..56185e1298
--- /dev/null
+++ b/libs/cua/crates/cua-replica-lab/src/bin/netshape.rs
@@ -0,0 +1,139 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! A user-space impairment proxy for one path (see `shape`).
+//!
+//! ```text
+//! netshape --listen 127.0.0.1:7302 --target 100.71.227.45:7102 --control 127.0.0.1:7402
+//! ```
+//!
+//! Control (one line per command, one line back):
+//! `set <up|down|both> latency=MS jitter=MS bw=BYTES_PER_S loss=0.2 hold=0|1`,
+//! `clear`, `reset`, `sever 0|1`, `flap EVERY_MIN_MS EVERY_MAX_MS DOWN_MIN_MS DOWN_MAX_MS`,
+//! `stats`.
+
+#[cfg(unix)]
+mod imp {
+ use cua_replica_lab::shape::{Path, Proxy, Shape};
+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+
+ fn arg(args: &[String], name: &str) -> Option<String> {
+ args.iter()
+ .position(|a| a == name)
+ .and_then(|i| args.get(i + 1))
+ .cloned()
+ }
+
+ pub fn parse_shape(words: &[&str], mut s: Shape) -> Shape {
+ for w in words {
+ if let Some((k, v)) = w.split_once('=') {
+ match k {
+ "latency" => s.latency_ms = v.parse().unwrap_or(0),
+ "jitter" => s.jitter_ms = v.parse().unwrap_or(0),
+ "bw" => s.bandwidth = v.parse().unwrap_or(0),
+ "loss" => s.loss = v.parse().unwrap_or(0.0),
+ "hold" => s.hold = v == "1",
+ _ => {}
+ }
+ }
+ }
+ s
+ }
+
+ #[tokio::main]
+ pub async fn main() {
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ let listen = arg(&args, "--listen")
+ .expect("--listen")
+ .parse()
+ .expect("addr");
+ let target = arg(&args, "--target")
+ .expect("--target")
+ .parse()
+ .expect("addr");
+ let control: std::net::SocketAddr = arg(&args, "--control")
+ .expect("--control")
+ .parse()
+ .expect("addr");
+ let proxy = std::sync::Arc::new(Proxy::start(listen, target).await.expect("listen"));
+ let flap = std::sync::Mutex::new(None::<tokio::task::JoinHandle<()>>);
+ let flap = std::sync::Arc::new(flap);
+ eprintln!("netshape {listen} -> {target}, control {control}");
+ let l = tokio::net::TcpListener::bind(control)
+ .await
+ .expect("control");
+ loop {
+ let Ok((s, _)) = l.accept().await else {
+ continue;
+ };
+ let proxy = proxy.clone();
+ let flap = flap.clone();
+ tokio::spawn(async move {
+ let (rd, mut wr) = s.into_split();
+ let mut lines = BufReader::new(rd).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ let w: Vec<&str> = line.split_whitespace().collect();
+ let out = match w.as_slice() {
+ ["set", dir, rest @ ..] => {
+ let mut p = proxy.path();
+ match *dir {
+ "up" => p.up = parse_shape(rest, p.up.clone()),
+ "down" => p.down = parse_shape(rest, p.down.clone()),
+ _ => {
+ p.up = parse_shape(rest, p.up.clone());
+ p.down = parse_shape(rest, p.down.clone());
+ }
+ }
+ proxy.set(p);
+ "ok".to_string()
+ }
+ ["clear"] => {
+ proxy.set(Path::default());
+ proxy.sever(false);
+ if let Some(h) = flap.lock().expect("flap").take() {
+ h.abort();
+ }
+ "ok".into()
+ }
+ ["reset"] => {
+ proxy.reset_all();
+ "ok".into()
+ }
+ ["sever", v] => {
+ proxy.sever(*v == "1");
+ "ok".into()
+ }
+ ["flap", a, b, c, d] => {
+ let p = |x: &str| x.parse::<u64>().unwrap_or(1000);
+ let h = proxy.flap((p(a), p(b)), (p(c), p(d)));
+ if let Some(old) = flap.lock().expect("flap").replace(h) {
+ old.abort();
+ }
+ "ok".into()
+ }
+ ["stats"] => {
+ let (u, d, c, r) = proxy.stats();
+ format!(
+ "{{\"bytes_up\":{u},\"bytes_down\":{d},\"connections\":{c},\"resets\":{r}}}"
+ )
+ }
+ _ => "error: unknown command".into(),
+ };
+ if wr.write_all(format!("{out}\n").as_bytes()).await.is_err() {
+ return;
+ }
+ }
+ });
+ }
+ }
+}
+
+#[cfg(unix)]
+fn main() {
+ imp::main()
+}
+
+#[cfg(not(unix))]
+fn main() {
+ eprintln!("cua-replica-lab runs on Unix only (it signals processes and raises file limits)");
+}
diff --git a/libs/cua/crates/cua-replica-lab/src/bin/replica_node.rs b/libs/cua/crates/cua-replica-lab/src/bin/replica_node.rs
new file mode 100644
index 0000000000..26f9ce2ad8
--- /dev/null
+++ b/libs/cua/crates/cua-replica-lab/src/bin/replica_node.rs
@@ -0,0 +1,107 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! One machine of a real two-machine test.
+//!
+//! ```text
+//! replica-node --home DIR --id studio --name "Mac Studio" --listen 0.0.0.0:7101 \
+//! --member studio="Mac Studio" --member laptop="MacBook" \
+//! --peer laptop=127.0.0.1:7302 --control 127.0.0.1:7001 [--fast] [--rank N --sleep-prone]
+//! ```
+//!
+//! Facts are measured on this machine unless `--rank` is given. Refuses any
+//! home under the real `~/.cua`.
+
+#[cfg(unix)]
+mod imp {
+ use cua_replica_lab::node::{Node, NodeOpts};
+ use cua_volume::replica::Facts;
+
+ fn arg(args: &[String], name: &str) -> Option<String> {
+ args.iter()
+ .position(|a| a == name)
+ .and_then(|i| args.get(i + 1))
+ .cloned()
+ }
+
+ fn all(args: &[String], name: &str) -> Vec<String> {
+ args.iter()
+ .enumerate()
+ .filter(|(_, a)| *a == name)
+ .filter_map(|(i, _)| args.get(i + 1).cloned())
+ .collect()
+ }
+
+ #[tokio::main]
+ pub async fn main() {
+ let _ = tracing_subscriber::fmt()
+ .with_env_filter(
+ tracing_subscriber::EnvFilter::try_from_default_env()
+ .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("cua_volume=info")),
+ )
+ .with_writer(std::io::stderr)
+ .try_init();
+ let args: Vec<String> = std::env::args().skip(1).collect();
+ let home = arg(&args, "--home").expect("--home");
+ let id = arg(&args, "--id").expect("--id");
+ let name = arg(&args, "--name").unwrap_or_else(|| id.clone());
+ let listen = arg(&args, "--listen")
+ .expect("--listen")
+ .parse()
+ .expect("listen addr");
+ let mut o = NodeOpts::new(std::path::Path::new(&home), &id, &name, listen);
+ o.members = all(&args, "--member")
+ .into_iter()
+ .map(|m| {
+ let (i, n) = m.split_once('=').expect("--member id=Name");
+ (i.to_string(), n.to_string())
+ })
+ .collect();
+ if !o.members.iter().any(|(i, _)| *i == id) {
+ o.members.push((id.clone(), name.clone()));
+ }
+ o.peers = all(&args, "--peer")
+ .into_iter()
+ .map(|p| {
+ let (i, a) = p.split_once('=').expect("--peer id=addr");
+ (i.to_string(), a.parse().expect("peer addr"))
+ })
+ .collect();
+ o.control = arg(&args, "--control").map(|c| c.parse().expect("control addr"));
+ o.fast = args.iter().any(|a| a == "--fast");
+ o.skew_ms = arg(&args, "--skew-ms")
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(0);
+ o.step_size = arg(&args, "--step-size")
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(1024);
+ o.print_events = true;
+ if let Some(r) = arg(&args, "--rank") {
+ o.facts = Some(Facts {
+ rank: r.parse().expect("rank"),
+ free_disk: 500 << 30,
+ sleep_prone: args.iter().any(|a| a == "--sleep-prone"),
+ ..Default::default()
+ });
+ }
+ let node = Node::start(o).await.expect("start");
+ eprintln!("replica-node {id} listening on {}", node.listen);
+ let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
+ .expect("signal");
+ tokio::select! {
+ _ = tokio::signal::ctrl_c() => {}
+ _ = term.recv() => {}
+ }
+ node.stop().await;
+ }
+}
+
+#[cfg(unix)]
+fn main() {
+ imp::main()
+}
+
+#[cfg(not(unix))]
+fn main() {
+ eprintln!("cua-replica-lab runs on Unix only (it signals processes and raises file limits)");
+}
diff --git a/libs/cua/crates/cua-replica-lab/src/chaos.rs b/libs/cua/crates/cua-replica-lab/src/chaos.rs
new file mode 100644
index 0000000000..e9405f6dc6
--- /dev/null
+++ b/libs/cua/crates/cua-replica-lab/src/chaos.rs
@@ -0,0 +1,1896 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The chaos matrix: real nodes over real TCP, every pair of machines joined
+//! by an impairment proxy ([`crate::shape`]), a durable agent running, and a
+//! ledger of every write that was acknowledged. After each scenario the
+//! network is made good again and the same questions are asked:
+//!
+//! - **No loss, no corruption.** Every acknowledged write is on every
+//! machine with exactly the bytes written; the agent's result checksum is
+//! right and every step file is right.
+//! - **No split brain.** One owner and one era everywhere; the run is driven
+//! on one machine only; fenced writes were refused, never applied.
+//! - **No false takeover.** A scenario that only makes the network bad (the
+//! owner is up) must not move ownership.
+//! - **Bounded.** Takeover and sync lag are measured and held to a bound.
+//! - **Incremental.** Bytes on the wire are counted by the proxies and held
+//! against the size of what had to move.
+//! - **Truthful.** The words the user sees match the situation.
+//! - **The laptop never blocks the studio.** Writes on the studio are timed
+//! while the laptop is impaired.
+//!
+//! Opt-in (it is slow and uses real sockets): `CUA_CHAOS=1 replica-chaos
+//! --all`. It listens on loopback only, writes under a temporary directory it
+//! removes, and touches no network configuration.
+
+use std::collections::BTreeMap;
+use std::net::SocketAddr;
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use cua_volume::backend::{Backend, Condition};
+use cua_volume::replica::Facts;
+use serde_json::{Value, json};
+
+use crate::driver::{content, expected_sum};
+use crate::node::{Node, NodeOpts};
+use crate::shape::{Path, Proxy, Shape};
+
+/// One machine of a scenario.
+#[derive(Clone, Debug)]
+pub struct Spec {
+ pub id: String,
+ pub name: String,
+ pub rank: u64,
+ pub laptop: bool,
+}
+
+pub fn spec(id: &str, rank: u64, laptop: bool) -> Spec {
+ Spec {
+ id: id.into(),
+ name: id.into(),
+ rank,
+ laptop,
+ }
+}
+
+/// The ledger of acknowledged writes: key to sha256 of the bytes.
+#[derive(Default)]
+pub struct Ledger(Mutex<BTreeMap<String, String>>);
+
+impl Ledger {
+ pub fn record(&self, key: &str, bytes: &[u8]) {
+ self.0
+ .lock()
+ .expect("ledger")
+ .insert(key.to_string(), cua_volume::sha256_hex(bytes));
+ }
+
+ pub fn len(&self) -> usize {
+ self.0.lock().expect("ledger").len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+
+ fn all(&self) -> BTreeMap<String, String> {
+ self.0.lock().expect("ledger").clone()
+ }
+}
+
+pub struct Cluster {
+ pub specs: Vec<Spec>,
+ pub nodes: Vec<Arc<Node>>,
+ pub proxies: BTreeMap<(usize, usize), Proxy>,
+ pub ports: Vec<u16>,
+ pub fast: bool,
+ pub dir: tempfile::TempDir,
+ opts: Vec<NodeOpts>,
+ pub ledger: Arc<Ledger>,
+}
+
+fn free_port() -> u16 {
+ let l = std::net::TcpListener::bind("127.0.0.1:0").expect("a free port");
+ l.local_addr().expect("addr").port()
+}
+
+fn facts_of(s: &Spec) -> Facts {
+ Facts {
+ rank: s.rank,
+ free_disk: 500 << 30,
+ sleep_prone: s.laptop,
+ on_battery: s.laptop,
+ ..Default::default()
+ }
+}
+
+impl Cluster {
+ /// Starts every machine and the proxies between them.
+ pub async fn start(specs: &[Spec], fast: bool) -> Result<Cluster, String> {
+ Cluster::start_inner(specs, fast, &[]).await
+ }
+
+ async fn start_inner(specs: &[Spec], fast: bool, skew_ms: &[i64]) -> Result<Cluster, String> {
+ let dir = tempfile::tempdir().map_err(|e| e.to_string())?;
+ let ports: Vec<u16> = specs.iter().map(|_| free_port()).collect();
+ let mut proxies = BTreeMap::new();
+ for i in 0..specs.len() {
+ #[allow(clippy::needless_range_loop)]
+ for j in 0..specs.len() {
+ if i != j {
+ let p = Proxy::start(
+ "127.0.0.1:0".parse().expect("addr"),
+ SocketAddr::from(([127, 0, 0, 1], ports[j])),
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ proxies.insert((i, j), p);
+ }
+ }
+ }
+ let members: Vec<(String, String)> = specs
+ .iter()
+ .map(|s| (s.id.clone(), s.name.clone()))
+ .collect();
+ let mut opts = vec![];
+ let mut nodes = vec![];
+ for (i, s) in specs.iter().enumerate() {
+ let mut o = NodeOpts::new(
+ &dir.path().join(&s.id),
+ &s.id,
+ &s.name,
+ SocketAddr::from(([127, 0, 0, 1], ports[i])),
+ );
+ o.members = members.clone();
+ o.skew_ms = skew_ms.get(i).copied().unwrap_or(0);
+ o.fast = fast;
+ o.facts = Some(facts_of(s));
+ o.peers = specs
+ .iter()
+ .enumerate()
+ .filter(|(j, _)| *j != i)
+ .map(|(j, p)| (p.id.clone(), proxies[&(i, j)].listen))
+ .collect();
+ nodes.push(Node::start(o.clone()).await?);
+ opts.push(o);
+ }
+ Ok(Cluster {
+ specs: specs.to_vec(),
+ nodes,
+ proxies,
+ ports,
+ fast,
+ dir,
+ opts,
+ ledger: Arc::new(Ledger::default()),
+ })
+ }
+
+ /// A duration in the scenario's time: real seconds on standard timing,
+ /// 1/40 of them on fast timing.
+ pub fn t(&self, secs: f64) -> Duration {
+ Duration::from_secs_f64(if self.fast { secs / 40.0 } else { secs })
+ }
+
+ pub fn idx(&self, id: &str) -> usize {
+ self.specs
+ .iter()
+ .position(|s| s.id == id)
+ .expect("a machine")
+ }
+
+ pub fn node(&self, id: &str) -> &Arc<Node> {
+ &self.nodes[self.idx(id)]
+ }
+
+ /// How much faster than the real world this cluster's time runs.
+ pub fn scale(&self) -> u64 {
+ if self.fast { 40 } else { 1 }
+ }
+
+ /// A real-world impairment (a second of latency, 100 kbit/s) in this
+ /// cluster's time: on fast timing latencies shrink and bandwidths grow
+ /// by the same factor, so the same fraction of a heartbeat is lost.
+ pub fn real(&self, s: Shape) -> Shape {
+ let k = self.scale();
+ Shape {
+ latency_ms: s.latency_ms / k,
+ jitter_ms: s.jitter_ms / k,
+ bandwidth: s.bandwidth * k,
+ loss: s.loss,
+ hold: s.hold,
+ rto_ms: if s.rto_ms == 0 { 200 / k } else { s.rto_ms / k }.max(1),
+ }
+ }
+
+ /// Both directions between `a` and `b` (the numbers are real-world
+ /// ones, see [`Cluster::real`]).
+ pub fn set_path(&self, a: &str, b: &str, p: Path) {
+ let p = Path {
+ up: self.real(p.up),
+ down: self.real(p.down),
+ };
+ let (i, j) = (self.idx(a), self.idx(b));
+ self.proxies[&(i, j)].set(p.clone());
+ self.proxies[&(j, i)].set(Path {
+ up: p.down,
+ down: p.up,
+ });
+ }
+
+ pub fn clear_path(&self, a: &str, b: &str) {
+ let (i, j) = (self.idx(a), self.idx(b));
+ for k in [(i, j), (j, i)] {
+ self.proxies[&k].set(Path::default());
+ self.proxies[&k].sever(false);
+ }
+ }
+
+ pub fn sever(&self, a: &str, b: &str, on: bool) {
+ let (i, j) = (self.idx(a), self.idx(b));
+ self.proxies[&(i, j)].sever(on);
+ self.proxies[&(j, i)].sever(on);
+ }
+
+ pub fn reset(&self, a: &str, b: &str) {
+ let (i, j) = (self.idx(a), self.idx(b));
+ self.proxies[&(i, j)].reset_all();
+ self.proxies[&(j, i)].reset_all();
+ }
+
+ /// Bytes through every proxy so far (both directions, all pairs).
+ pub fn wire_bytes(&self) -> u64 {
+ self.proxies
+ .values()
+ .map(|p| {
+ let (u, d, _, _) = p.stats();
+ u + d
+ })
+ .sum()
+ }
+
+ /// Bytes from `a`'s side toward `b`'s side and back (one pair).
+ pub fn pair_bytes(&self, a: &str, b: &str) -> u64 {
+ let (i, j) = (self.idx(a), self.idx(b));
+ [(i, j), (j, i)]
+ .iter()
+ .map(|k| {
+ let (u, d, _, _) = self.proxies[k].stats();
+ u + d
+ })
+ .sum()
+ }
+
+ /// A node process dies (no goodbye) and starts again on its home.
+ pub async fn crash_and_restart(&mut self, id: &str, down_for: Duration) -> Result<(), String> {
+ let i = self.idx(id);
+ self.nodes[i].crash().await;
+ tokio::time::sleep(down_for).await;
+ self.nodes[i] = Node::start(self.opts[i].clone()).await?;
+ Ok(())
+ }
+
+ /// A graceful stop (the app quits) and start.
+ pub async fn restart(&mut self, id: &str) -> Result<(), String> {
+ let i = self.idx(id);
+ self.nodes[i].stop().await;
+ self.nodes[i] = Node::start(self.opts[i].clone()).await?;
+ Ok(())
+ }
+
+ pub async fn stop(&self) {
+ for n in &self.nodes {
+ n.stop().await;
+ }
+ for p in self.proxies.values() {
+ p.stop();
+ }
+ }
+
+ /// A write of unique content, recorded in the ledger when acknowledged.
+ pub async fn write(&self, id: &str, key: &str, size: usize, seed: u64) -> Result<(), String> {
+ let body = content(seed, size);
+ let n = self.node(id);
+ match tokio::time::timeout(
+ Duration::from_secs(120),
+ n.backend.put(key, body.clone(), Condition::None),
+ )
+ .await
+ {
+ Ok(Ok(_)) => {
+ self.ledger.record(key, &body);
+ Ok(())
+ }
+ Ok(Err(e)) => Err(e.to_string()),
+ Err(_) => Err("timed out".into()),
+ }
+ }
+
+ /// Waits until every machine has the same heads, or `within` passes.
+ pub async fn converge(&self, within: Duration) -> bool {
+ let end = Instant::now() + within;
+ loop {
+ let mut sums = vec![];
+ let mut holders = 0;
+ let mut pending = 0;
+ for n in &self.nodes {
+ let st = n.node.status().await;
+ pending += st.pending.len();
+ // A machine that keeps no copy (a client) asks the others.
+ if st.role == cua_volume::replica::Role::Replica {
+ holders += 1;
+ if let Some(s) = n.command("sum").await.get("sum").cloned() {
+ sums.push(s);
+ }
+ }
+ }
+ if pending == 0 && sums.len() == holders && sums.windows(2).all(|w| w[0] == w[1]) {
+ return true;
+ }
+ if Instant::now() > end {
+ return false;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ }
+
+ /// What every machine thinks, for a failure's report.
+ pub async fn dump(&self) -> String {
+ let mut out = String::new();
+ for n in &self.nodes {
+ let s = n.node.status().await;
+ out.push_str(&format!(
+ "{}: owner={} epoch={} i_own={} applied={} tail={} pending={} peers={:?} fenced={} takeovers={} copies={}\n",
+ n.opts.id, s.owner, s.epoch, s.i_own, s.applied, s.tail, s.pending.len(),
+ s.peers.iter().map(|p| (p.id.clone(), p.health.clone(), p.connected, p.lag)).collect::<Vec<_>>(),
+ s.fenced_writes, s.takeovers, s.copies_now
+ ));
+ for p in s.pending.iter().take(3) {
+ out.push_str(&format!(
+ " pending {} ({} bytes{})\n",
+ p.key,
+ p.size,
+ if p.deleted { ", delete" } else { "" }
+ ));
+ }
+ }
+ // Where the machines' heads differ.
+ let mut all: BTreeMap<String, Vec<Option<String>>> = BTreeMap::new();
+ for (i, n) in self.nodes.iter().enumerate() {
+ for m in n.store.list("").await.unwrap_or_default() {
+ all.entry(m.key)
+ .or_insert_with(|| vec![None; self.nodes.len()])[i] =
+ Some(m.version.chars().take(8).collect());
+ }
+ }
+ let mut shown = 0;
+ for (k, v) in &all {
+ if v.windows(2).any(|w| w[0] != w[1]) && shown < 3 {
+ out.push_str(&format!(" differs {k}: {v:?}\n"));
+ for n in &self.nodes {
+ out.push_str(&format!(
+ " {}: head={:?}{}\n",
+ n.opts.id,
+ n.store.head(k).await.ok().flatten().map(|h| h.version),
+ n.node.debug_key(k).await
+ ));
+ }
+ shown += 1;
+ }
+ }
+ out
+ }
+
+ /// The invariants. Returns what is wrong, empty when nothing is.
+ pub async fn verify(&self, runs: &[(&str, u64, usize)]) -> Vec<String> {
+ let mut bad = vec![];
+ // Every acknowledged write is on every machine, byte for byte.
+ let ledger = self.ledger.all();
+ for n in &self.nodes {
+ for (key, sha) in &ledger {
+ // Machines without a copy read through the others.
+ let got = if n.node.status().await.role == cua_volume::replica::Role::Replica {
+ n.store.get(key, None).await
+ } else {
+ n.backend.get(key, None).await
+ };
+ match got {
+ Ok((b, _)) if cua_volume::sha256_hex(&b) == *sha => {}
+ Ok(_) => bad.push(format!(
+ "{}: {key} has other bytes than were acknowledged",
+ n.opts.id
+ )),
+ Err(e) => bad.push(format!(
+ "{}: acknowledged {key} is missing ({e})",
+ n.opts.id
+ )),
+ }
+ }
+ }
+ // The agent: its result and every step.
+ for (agent, steps, size) in runs {
+ for n in self.nodes.iter().filter(|n| n.opts.facts.is_some()) {
+ match n
+ .backend
+ .get(&format!("agents/{agent}/result.txt"), None)
+ .await
+ {
+ Ok((b, _))
+ if String::from_utf8_lossy(&b).trim() == expected_sum(*steps, *size) => {}
+ Ok(_) => bad.push(format!("{}: the result of {agent} is wrong", n.opts.id)),
+ Err(_) => bad.push(format!("{}: no result for {agent}", n.opts.id)),
+ }
+ for i in 0..*steps {
+ match n
+ .backend
+ .get(&format!("agents/{agent}/out/step-{i}"), None)
+ .await
+ {
+ Ok((b, _)) if b == content(i, *size) => {}
+ _ => {
+ bad.push(format!(
+ "{}: step {i} of {agent} is wrong or missing",
+ n.opts.id
+ ));
+ break;
+ }
+ }
+ }
+ }
+ }
+ // One owner, one era.
+ let mut owners = std::collections::BTreeSet::new();
+ let mut epochs = std::collections::BTreeSet::new();
+ let mut i_own = 0;
+ for n in &self.nodes {
+ let s = n.node.status().await;
+ owners.insert(s.owner.clone());
+ epochs.insert(s.epoch);
+ if s.i_own {
+ i_own += 1;
+ }
+ }
+ if owners.len() != 1 || i_own != 1 {
+ bad.push(format!(
+ "split brain: owners {owners:?}, {i_own} machines think they own it"
+ ));
+ }
+ if epochs.len() != 1 {
+ bad.push(format!("eras differ: {epochs:?}"));
+ }
+ // One driver per run.
+ for (agent, _, _) in runs {
+ let mut here = 0;
+ for n in &self.nodes {
+ if let Ok(r) = n.sup.runs().await
+ && r.iter()
+ .any(|x| x.agent == *agent && x.running_here && x.state != "done")
+ {
+ here += 1;
+ }
+ }
+ if here > 1 {
+ bad.push(format!("{agent} is being driven on {here} machines"));
+ }
+ }
+ bad
+ }
+
+ pub async fn takeovers(&self) -> u64 {
+ let mut t = 0;
+ for n in &self.nodes {
+ t += n.node.status().await.takeovers;
+ }
+ t
+ }
+}
+
+/// What a scenario reports.
+#[derive(Debug)]
+pub struct Outcome {
+ pub name: String,
+ pub pass: bool,
+ pub problems: Vec<String>,
+ pub metrics: Value,
+}
+
+impl Outcome {
+ fn new(name: &str) -> Outcome {
+ Outcome {
+ name: name.into(),
+ pass: true,
+ problems: vec![],
+ metrics: json!({}),
+ }
+ }
+
+ fn check(&mut self, ok: bool, what: impl Into<String>) {
+ if !ok {
+ self.pass = false;
+ self.problems.push(what.into());
+ }
+ }
+
+ fn metric(&mut self, k: &str, v: impl Into<Value>) {
+ self.metrics[k] = v.into();
+ }
+
+ pub fn json(&self) -> Value {
+ json!({"scenario": self.name, "pass": self.pass, "problems": self.problems, "metrics": self.metrics})
+ }
+}
+
+fn laptop_studio() -> Vec<Spec> {
+ vec![spec("studio", 9000, false), spec("laptop", 2000, true)]
+}
+
+async fn ready(c: &Cluster) -> bool {
+ let end = Instant::now() + Duration::from_secs(60);
+ while Instant::now() < end {
+ let mut ok = true;
+ for n in &c.nodes {
+ let s = n.node.status().await;
+ if s.owner != "studio" || s.peers.iter().any(|p| !p.connected || p.health != "up") {
+ ok = false;
+ }
+ }
+ if ok {
+ return true;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ false
+}
+
+/// A durable run on the studio plus writes from both machines through an
+/// impairment of the laptop-studio path, then the usual questions.
+async fn impaired_run(
+ name: &str,
+ fast: bool,
+ impair: impl Fn(&Cluster) + Send + Sync,
+ expect_no_takeover: bool,
+) -> Outcome {
+ let mut o = Outcome::new(name);
+ let c = match Cluster::start(&laptop_studio(), fast).await {
+ Ok(c) => c,
+ Err(e) => {
+ o.check(false, e);
+ return o;
+ }
+ };
+ o.check(ready(&c).await, "the machines did not connect");
+ let step_ms = if fast { 25 } else { 250 };
+ // Ten minutes of scenario time under the impairment (90 s on standard timing).
+ let window = if fast {
+ c.t(600.0)
+ } else {
+ Duration::from_secs(90)
+ };
+ let steps = ((window.as_millis() as u64 * 6 / 5) / step_ms).max(60);
+ let size = 1024usize;
+ c.node("laptop")
+ .command(&format!("start ada {steps} {step_ms}"))
+ .await;
+ // The impairment on, with writes from both machines, a studio write timed.
+ impair(&c);
+ let mut studio_write_ms = vec![];
+ let t_end = Instant::now() + window;
+ let mut seq = 0u64;
+ while Instant::now() < t_end {
+ seq += 1;
+ let t = Instant::now();
+ let _ = c
+ .write("studio", &format!("agents/studio-w/f{seq}"), 3000, seq)
+ .await;
+ studio_write_ms.push(t.elapsed().as_millis() as u64);
+ let _ = c
+ .write(
+ "laptop",
+ &format!("agents/laptop-w/f{seq}"),
+ 3000,
+ 10_000 + seq,
+ )
+ .await;
+ tokio::time::sleep(c.t(1.0).max(Duration::from_millis(20))).await;
+ }
+ // The network is good again.
+ for a in 0..c.specs.len() {
+ for b in (a + 1)..c.specs.len() {
+ let (x, y) = (c.specs[a].id.clone(), c.specs[b].id.clone());
+ c.clear_path(&x, &y);
+ }
+ }
+ let t_heal = Instant::now();
+ let done = {
+ let end = Instant::now() + Duration::from_secs(if fast { 120 } else { 600 });
+ let exp = expected_sum(steps, size);
+ let mut ok = false;
+ while Instant::now() < end {
+ if let Some(v) = c
+ .node("studio")
+ .command("cat agents/ada/result.txt")
+ .await
+ .get("text")
+ && v.as_str().unwrap_or("").trim() == exp
+ {
+ ok = true;
+ break;
+ }
+ if let Some(v) = c
+ .node("laptop")
+ .command("cat agents/ada/result.txt")
+ .await
+ .get("text")
+ && v.as_str().unwrap_or("").trim() == exp
+ {
+ ok = true;
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ ok
+ };
+ o.check(done, "the run did not finish with the right result");
+ o.metric("run_finished_after_heal_s", t_heal.elapsed().as_secs_f64());
+ let t_conv = Instant::now();
+ let conv = c
+ .converge(Duration::from_secs(if fast { 120 } else { 600 }))
+ .await;
+ o.metric("converged_after_run_s", t_conv.elapsed().as_secs_f64());
+ o.check(conv, "the machines did not converge");
+ if !conv {
+ eprintln!("{}", c.dump().await);
+ }
+ for p in c.verify(&[("ada", steps, size)]).await {
+ o.check(false, p);
+ }
+ if expect_no_takeover {
+ o.check(
+ c.takeovers().await == 0,
+ "ownership moved although the owner was up (false takeover)",
+ );
+ }
+ studio_write_ms.sort();
+ let med = studio_write_ms
+ .get(studio_write_ms.len() / 2)
+ .copied()
+ .unwrap_or(0);
+ o.metric("studio_write_median_ms", med);
+ o.metric(
+ "studio_write_max_ms",
+ studio_write_ms.last().copied().unwrap_or(0),
+ );
+ o.metric("acknowledged_writes", c.ledger.len());
+ o.metric("takeovers", c.takeovers().await);
+ o.metric("wire_bytes", c.wire_bytes());
+ c.stop().await;
+ o
+}
+
+fn shape(f: impl Fn(&mut Shape)) -> Path {
+ let mut s = Shape::default();
+ f(&mut s);
+ Path::both(s)
+}
+
+/// The scenarios, by name.
+pub fn names() -> Vec<&'static str> {
+ vec![
+ "hotel_wifi_measured",
+ "latency_600ms",
+ "latency_1500ms_jitter_800ms",
+ "loss_10",
+ "loss_20",
+ "loss_40",
+ "bandwidth_500kbit",
+ "bandwidth_100kbit",
+ "asymmetric_loss_40",
+ "flapping_20_to_60s",
+ "partition_5min",
+ "partition_30min",
+ "nat_change_midsession",
+ "dns_failure",
+ "clock_skew_one_day",
+ "laptop_sigstop_and_wake",
+ "studio_reboot_during_run",
+ "studio_kill_laptop_takes_run",
+ "wake_after_takeover",
+ "big_file_flapping_link",
+ "scale_peers_5",
+ "scale_peers_20",
+ "scale_many_small_files",
+ "scale_ten_runs",
+ "false_takeover_rate_under_jitter",
+ ]
+}
+
+pub async fn run(name: &str, fast: bool) -> Option<Outcome> {
+ raise_open_files();
+ Some(match name {
+ // Measured from the owner's hotel wifi (read-only: 100 pings each to two
+ // public resolvers and the gateway, two 10 MB downloads, one 3 MB
+ // upload): RTT 8 ms average, 5 to 20 ms, 0 percent loss, about 2.9 MB/s
+ // down and 3.9 MB/s up.
+ "hotel_wifi_measured" => {
+ impaired_run(
+ name,
+ fast,
+ |c| {
+ c.set_path(
+ "studio",
+ "laptop",
+ shape(|s| {
+ s.latency_ms = 4;
+ s.jitter_ms = 8;
+ s.bandwidth = 2_900_000;
+ }),
+ )
+ },
+ true,
+ )
+ .await
+ }
+ "latency_600ms" => {
+ impaired_run(
+ name,
+ fast,
+ |c| {
+ c.set_path(
+ "studio",
+ "laptop",
+ shape(|s| {
+ s.latency_ms = 600;
+ s.jitter_ms = 100;
+ }),
+ )
+ },
+ true,
+ )
+ .await
+ }
+ "latency_1500ms_jitter_800ms" => {
+ impaired_run(
+ name,
+ fast,
+ |c| {
+ c.set_path(
+ "studio",
+ "laptop",
+ shape(|s| {
+ s.latency_ms = 1500;
+ s.jitter_ms = 800;
+ }),
+ )
+ },
+ true,
+ )
+ .await
+ }
+ "loss_10" => {
+ impaired_run(
+ name,
+ fast,
+ |c| {
+ c.set_path(
+ "studio",
+ "laptop",
+ shape(|s| {
+ s.latency_ms = 100;
+ s.loss = 0.10;
+ }),
+ )
+ },
+ true,
+ )
+ .await
+ }
+ "loss_20" => {
+ impaired_run(
+ name,
+ fast,
+ |c| {
+ c.set_path(
+ "studio",
+ "laptop",
+ shape(|s| {
+ s.latency_ms = 100;
+ s.loss = 0.20;
+ }),
+ )
+ },
+ true,
+ )
+ .await
+ }
+ "loss_40" => {
+ impaired_run(
+ name,
+ fast,
+ |c| {
+ c.set_path(
+ "studio",
+ "laptop",
+ shape(|s| {
+ s.latency_ms = 150;
+ s.loss = 0.40;
+ }),
+ )
+ },
+ false,
+ )
+ .await
+ }
+ "bandwidth_500kbit" => {
+ impaired_run(
+ name,
+ fast,
+ |c| {
+ c.set_path(
+ "studio",
+ "laptop",
+ shape(|s| {
+ s.latency_ms = 200;
+ s.bandwidth = 62_500;
+ }),
+ )
+ },
+ true,
+ )
+ .await
+ }
+ "bandwidth_100kbit" => {
+ impaired_run(
+ name,
+ fast,
+ |c| {
+ c.set_path(
+ "studio",
+ "laptop",
+ shape(|s| {
+ s.latency_ms = 300;
+ s.bandwidth = 12_500;
+ }),
+ )
+ },
+ false,
+ )
+ .await
+ }
+ "asymmetric_loss_40" => {
+ impaired_run(
+ name,
+ fast,
+ |c| {
+ let mut p = Path::default();
+ p.up.loss = 0.4;
+ p.up.latency_ms = 150;
+ c.set_path("studio", "laptop", p);
+ },
+ false,
+ )
+ .await
+ }
+ "flapping_20_to_60s" => {
+ impaired_run(
+ name,
+ fast,
+ |c| {
+ let s = if c.fast { 40.0 } else { 1.0 };
+ let every = ((20_000.0 / s) as u64, (60_000.0 / s) as u64);
+ let down = ((2_000.0 / s) as u64, (6_000.0 / s) as u64);
+ for k in [("studio", "laptop"), ("laptop", "studio")] {
+ drop(c.proxies[&(c.idx(k.0), c.idx(k.1))].flap(every, down));
+ }
+ },
+ !fast,
+ )
+ .await
+ }
+ "partition_5min" => partition(name, fast, 300.0).await,
+ "partition_30min" => partition(name, fast, 1800.0).await,
+ "nat_change_midsession" => {
+ impaired_run(
+ name,
+ fast,
+ |c| {
+ // Resets and a few seconds of refusals, three times.
+ let sev = c.proxies[&(c.idx("laptop"), c.idx("studio"))].flap(
+ (c.t(10.0).as_millis() as u64, c.t(15.0).as_millis() as u64),
+ (c.t(1.0).as_millis() as u64, c.t(3.0).as_millis() as u64),
+ );
+ drop(sev);
+ },
+ !fast,
+ )
+ .await
+ }
+ "dns_failure" => dns_failure(name, fast).await,
+ "clock_skew_one_day" => clock_skew(name, fast).await,
+ "laptop_sigstop_and_wake" => laptop_sigstop(name, fast).await,
+ "studio_reboot_during_run" => studio_reboot(name, fast).await,
+ "studio_kill_laptop_takes_run" => studio_kill(name, fast).await,
+ "wake_after_takeover" => wake_after_takeover(name, fast).await,
+ "big_file_flapping_link" => big_file_flapping(name, fast).await,
+ "scale_peers_5" => scale_peers(name, fast, 5).await,
+ "scale_peers_20" => scale_peers(name, fast, 20).await,
+ "scale_many_small_files" => scale_small_files(name, fast).await,
+ "scale_ten_runs" => scale_ten_runs(name, fast).await,
+ "false_takeover_rate_under_jitter" => false_takeover_rate(name, fast).await,
+ _ => return None,
+ })
+}
+
+async fn partition(name: &str, fast: bool, minutes_secs: f64) -> Outcome {
+ let mut o = Outcome::new(name);
+ let c = match Cluster::start(&laptop_studio(), fast).await {
+ Ok(c) => c,
+ Err(e) => {
+ o.check(false, e);
+ return o;
+ }
+ };
+ o.check(ready(&c).await, "the machines did not connect");
+ let (steps, step_ms, size) = (150u64, if fast { 25 } else { 250 }, 1024usize);
+ c.node("laptop")
+ .command(&format!("start ada {steps} {step_ms}"))
+ .await;
+ tokio::time::sleep(c.t(5.0)).await;
+ // The partition: blackholed (bytes stop), the machines keep writing.
+ let hold = shape(|s| s.hold = true);
+ c.set_path("studio", "laptop", hold);
+ let t_start = Instant::now();
+ let mut seq = 0u64;
+ let mut studio_ms = vec![];
+ while t_start.elapsed() < c.t(minutes_secs) {
+ seq += 1;
+ let t = Instant::now();
+ let _ = c
+ .write("studio", &format!("agents/studio-w/p{seq}"), 2000, seq)
+ .await;
+ studio_ms.push(t.elapsed().as_millis() as u64);
+ // The laptop's writes wait in its outbox.
+ let _ = c
+ .write(
+ "laptop",
+ &format!("agents/laptop-w/p{seq}"),
+ 2000,
+ 5_000 + seq,
+ )
+ .await;
+ tokio::time::sleep(c.t(10.0).max(Duration::from_millis(50))).await;
+ }
+ // The words each machine shows while apart.
+ let studio_words = c.node("studio").command("status").await["words"].clone();
+ let laptop_pending = c.node("laptop").node.status().await.pending.len();
+ o.metric("laptop_pending_while_apart", laptop_pending);
+ o.metric("studio_words_while_apart", studio_words.clone());
+ o.check(
+ studio_words.as_str().is_some_and(|w| {
+ w.contains("1 machine") || w.contains("MacBook") || w.contains("laptop")
+ }),
+ "the studio's words do not say the files are on one machine",
+ );
+ c.clear_path("studio", "laptop");
+ let t_heal = Instant::now();
+ let conv = c
+ .converge(Duration::from_secs(if fast { 180 } else { 900 }))
+ .await;
+ if !conv {
+ eprintln!("{}", c.dump().await);
+ }
+ o.check(conv, "no convergence after the partition");
+ o.metric("converged_after_heal_s", t_heal.elapsed().as_secs_f64());
+ // The run finishes wherever it is.
+ let exp = expected_sum(steps, size);
+ let end = Instant::now() + Duration::from_secs(if fast { 120 } else { 600 });
+ let mut done = false;
+ while Instant::now() < end && !done {
+ done = c.node("studio").command("cat agents/ada/result.txt").await["text"]
+ .as_str()
+ .is_some_and(|t| t.trim() == exp);
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ o.check(done, "the run did not finish");
+ o.check(c.converge(Duration::from_secs(120)).await, "no convergence");
+ for p in c.verify(&[("ada", steps, size)]).await {
+ o.check(false, p);
+ }
+ studio_ms.sort();
+ o.metric("studio_write_median_ms", studio_ms[studio_ms.len() / 2]);
+ o.metric("studio_write_max_ms", *studio_ms.last().unwrap_or(&0));
+ o.metric("partition_s", c.t(minutes_secs).as_secs_f64());
+ o.metric("takeovers", c.takeovers().await);
+ c.stop().await;
+ o
+}
+
+async fn dns_failure(name: &str, fast: bool) -> Outcome {
+ // The machine's address stops resolving: dials fail at once, with no
+ // refusal and no timeout; then it resolves again.
+ impaired_run(
+ name,
+ fast,
+ |c| {
+ let i = c.idx("laptop");
+ let j = c.idx("studio");
+ let t = c.t(25.0);
+ let tp = c.nodes[i].transport.clone();
+ let good = c.proxies[&(i, j)].listen;
+ tp.set("studio", "127.0.0.1:1".parse().expect("addr"));
+ // Existing links die with the failed lookup.
+ c.proxies[&(i, j)].reset_all();
+ c.proxies[&(j, i)].reset_all();
+ tokio::spawn(async move {
+ tokio::time::sleep(t).await;
+ tp.set("studio", good);
+ });
+ },
+ false,
+ )
+ .await
+}
+
+async fn clock_skew(name: &str, fast: bool) -> Outcome {
+ let mut o = Outcome::new(name);
+ let mut specs = laptop_studio();
+ specs[1].laptop = true;
+ // The laptop's wall clock is a day ahead, the studio's an hour behind.
+ let dir = tempfile::tempdir().unwrap();
+ let _ = dir;
+ let c = match Cluster::start_skewed(&specs, fast, &[0, 86_400_000]).await {
+ Ok(c) => c,
+ Err(e) => {
+ o.check(false, e);
+ return o;
+ }
+ };
+ o.check(ready(&c).await, "the machines did not connect");
+ // Concurrent edits of one file: the conflict copy's name uses wall time.
+ c.set_path("studio", "laptop", shape(|s| s.hold = true));
+ let _ = c.write("studio", "agents/ada/plan.md", 100, 1).await;
+ let _ = c.write("laptop", "agents/ada/plan.md", 100, 2).await;
+ tokio::time::sleep(c.t(4.0)).await;
+ c.clear_path("studio", "laptop");
+ o.check(
+ c.converge(Duration::from_secs(if fast { 60 } else { 300 }))
+ .await,
+ "no convergence",
+ );
+ let names = c
+ .node("studio")
+ .store
+ .list("agents/ada/")
+ .await
+ .unwrap_or_default();
+ o.check(
+ names.iter().any(|m| m.key.contains("(conflict from")),
+ "the conflicting edit was not kept as a copy",
+ );
+ // (On fast timing a 100 ms hold is the size of the silence floor; the
+ // check is for standard timing.)
+ o.check(
+ fast || c.takeovers().await == 0,
+ "a skewed clock caused a takeover",
+ );
+ // The ledger holds the last acknowledged write per key; both writes were
+ // to one key, so only check what is unique (the copy and the head hold both).
+ c.ledger.0.lock().unwrap().clear();
+ for p in c.verify(&[]).await {
+ o.check(false, p);
+ }
+ c.stop().await;
+ o
+}
+
+async fn laptop_sigstop(name: &str, fast: bool) -> Outcome {
+ let mut o = Outcome::new(name);
+ let c = match Cluster::start(&laptop_studio(), fast).await {
+ Ok(c) => c,
+ Err(e) => {
+ o.check(false, e);
+ return o;
+ }
+ };
+ o.check(ready(&c).await, "the machines did not connect");
+ let (steps, step_ms, size) = (200u64, if fast { 25 } else { 250 }, 1024usize);
+ c.node("laptop")
+ .command(&format!("start ada {steps} {step_ms}"))
+ .await;
+ tokio::time::sleep(c.t(8.0)).await;
+ // The lid closes (abruptly: no goodbye), for a while.
+ c.node("laptop").command("freeze").await;
+ c.set_path("studio", "laptop", shape(|s| s.hold = true));
+ let t0 = Instant::now();
+ let mut detected = None;
+ let mut seq = 0;
+ let mut ms = vec![];
+ while t0.elapsed() < c.t(60.0) {
+ seq += 1;
+ let t = Instant::now();
+ let _ = c
+ .write("studio", &format!("agents/studio-w/s{seq}"), 1500, seq)
+ .await;
+ ms.push(t.elapsed().as_millis() as u64);
+ if detected.is_none() && c.node("studio").node.status().await.peers[0].health != "up" {
+ detected = Some(t0.elapsed().as_secs_f64());
+ }
+ tokio::time::sleep(c.t(1.0).max(Duration::from_millis(20))).await;
+ }
+ o.metric("studio_noticed_after_s", detected.unwrap_or(-1.0));
+ ms.sort();
+ o.metric("studio_write_median_ms", ms[ms.len() / 2]);
+ // It wakes.
+ c.clear_path("studio", "laptop");
+ c.node("laptop").command("thaw").await;
+ c.node("laptop").command("power wake").await;
+ let t1 = Instant::now();
+ o.check(
+ c.converge(Duration::from_secs(if fast { 90 } else { 400 }))
+ .await,
+ "no convergence after the wake",
+ );
+ o.metric("synced_after_wake_s", t1.elapsed().as_secs_f64());
+ let exp = expected_sum(steps, size);
+ let end = Instant::now() + Duration::from_secs(if fast { 90 } else { 400 });
+ let mut done = false;
+ while Instant::now() < end && !done {
+ done = c.node("laptop").command("cat agents/ada/result.txt").await["text"]
+ .as_str()
+ .is_some_and(|t| t.trim() == exp);
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ o.check(done, "the run did not finish");
+ o.check(
+ c.takeovers().await == 0,
+ "the volume moved when only the laptop slept",
+ );
+ for p in c.verify(&[("ada", steps, size)]).await {
+ o.check(false, p);
+ }
+ c.stop().await;
+ o
+}
+
+fn scaled(secs: f64, fast: bool) -> Duration {
+ Duration::from_secs_f64(if fast { secs / 40.0 } else { secs })
+}
+
+/// The studio's process is killed (SIGKILL, no goodbye) and started again on
+/// its home, as a real reboot does. The nodes are real child processes (an
+/// in-process "crash" cannot stop a write that is already in a disk call,
+/// which a dead process cannot do), joined by in-process impairment proxies.
+async fn studio_reboot(name: &str, fast: bool) -> Outcome {
+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt};
+ let mut o = Outcome::new(name);
+ let exe = std::env::current_exe().unwrap_or_default();
+ let node_bin = exe.with_file_name("replica-node");
+ if !node_bin.is_file() {
+ o.check(
+ false,
+ format!(
+ "{} is missing; build it next to replica-chaos",
+ node_bin.display()
+ ),
+ );
+ return o;
+ }
+ let dir = tempfile::tempdir().expect("tempdir");
+ let (p_s, p_l, c_s, c_l) = (free_port(), free_port(), free_port(), free_port());
+ // laptop dials the studio through a proxy; the studio dials the laptop through another.
+ let to_studio = Proxy::start(
+ "127.0.0.1:0".parse().unwrap(),
+ SocketAddr::from(([127, 0, 0, 1], p_s)),
+ )
+ .await
+ .unwrap();
+ let to_laptop = Proxy::start(
+ "127.0.0.1:0".parse().unwrap(),
+ SocketAddr::from(([127, 0, 0, 1], p_l)),
+ )
+ .await
+ .unwrap();
+ let spawn = |id: &str,
+ rank: u64,
+ laptop: bool,
+ listen: u16,
+ ctl: u16,
+ peer: &str,
+ peer_at: SocketAddr| {
+ let mut cmd = std::process::Command::new(&node_bin);
+ cmd.args([
+ "--home",
+ &dir.path().join(id).display().to_string(),
+ "--id",
+ id,
+ "--name",
+ id,
+ ])
+ .args([
+ "--listen",
+ &format!("127.0.0.1:{listen}"),
+ "--control",
+ &format!("127.0.0.1:{ctl}"),
+ ])
+ .args(["--member", "studio=studio", "--member", "laptop=laptop"])
+ .args([
+ "--peer",
+ &format!("{peer}={peer_at}"),
+ "--rank",
+ &rank.to_string(),
+ ])
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null());
+ if laptop {
+ cmd.arg("--sleep-prone");
+ }
+ if fast {
+ cmd.arg("--fast");
+ }
+ cmd.spawn().expect("spawn a node")
+ };
+ let mut studio = spawn("studio", 9000, false, p_s, c_s, "laptop", to_laptop.listen);
+ let mut laptop = spawn("laptop", 2000, true, p_l, c_l, "studio", to_studio.listen);
+ let ctl = |port: u16, line: String| async move {
+ for _ in 0..50 {
+ if let Ok(s) = tokio::net::TcpStream::connect(("127.0.0.1", port)).await {
+ let (rd, mut wr) = s.into_split();
+ if wr.write_all(format!("{line}\n").as_bytes()).await.is_ok() {
+ let mut l = String::new();
+ if tokio::io::BufReader::new(rd)
+ .read_line(&mut l)
+ .await
+ .is_ok()
+ && !l.is_empty()
+ {
+ return serde_json::from_str::<Value>(&l).unwrap_or(Value::Null);
+ }
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ Value::Null
+ };
+ let step_ms = if fast { 25 } else { 250 };
+ let steps = 200u64;
+ // Ready: connected and agreeing on the owner.
+ let end = Instant::now() + Duration::from_secs(60);
+ loop {
+ let a = ctl(c_l, "status".into()).await;
+ let ok = a["status"]["owner"] == "studio"
+ && a["status"]["peers"][0]["health"] == "up"
+ && a["status"]["peers"][0]["connected"] == true;
+ if ok {
+ break;
+ }
+ if Instant::now() > end {
+ o.check(false, "the machines did not connect");
+ let _ = studio.kill();
+ let _ = laptop.kill();
+ let _ = studio.wait();
+ let _ = laptop.wait();
+ return o;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ ctl(c_l, format!("start ada {steps} {step_ms}")).await;
+ tokio::time::sleep(scaled(10.0, fast)).await;
+ let t0 = Instant::now();
+ let _ = studio.kill();
+ let _ = studio.wait();
+ to_studio.reset_all();
+ to_laptop.reset_all();
+ tokio::time::sleep(scaled(30.0, fast)).await;
+ studio = spawn("studio", 9000, false, p_s, c_s, "laptop", to_laptop.listen);
+ o.metric("studio_down_s", scaled(30.0, fast).as_secs_f64());
+ let exp = expected_sum(steps, 1024);
+ let end = Instant::now() + Duration::from_secs(if fast { 180 } else { 900 });
+ let mut done = false;
+ while Instant::now() < end && !done {
+ for port in [c_l, c_s] {
+ let r = ctl(port, "cat agents/ada/result.txt".into()).await;
+ if r["text"].as_str().is_some_and(|t| t.trim() == exp) {
+ done = true;
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ }
+ o.check(done, "the run did not finish after the studio rebooted");
+ o.metric("finished_after_s", t0.elapsed().as_secs_f64());
+ // The same heads on both, and the right result and steps on each.
+ let end = Instant::now() + Duration::from_secs(if fast { 120 } else { 600 });
+ let mut same = false;
+ while Instant::now() < end && !same {
+ let a = ctl(c_l, "sum".into()).await;
+ let b = ctl(c_s, "sum".into()).await;
+ same = a["sum"].is_string() && a["sum"] == b["sum"];
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ }
+ o.check(same, "no convergence");
+ for port in [c_l, c_s] {
+ let r = ctl(port, "cat agents/ada/result.txt".into()).await;
+ o.check(
+ r["text"].as_str().is_some_and(|t| t.trim() == exp),
+ "a machine lacks the right result",
+ );
+ }
+ let _ = studio.kill();
+ let _ = laptop.kill();
+ let _ = studio.wait();
+ let _ = laptop.wait();
+ o
+}
+
+async fn studio_kill(name: &str, fast: bool) -> Outcome {
+ let mut o = Outcome::new(name);
+ let c = match Cluster::start(&laptop_studio(), fast).await {
+ Ok(c) => c,
+ Err(e) => {
+ o.check(false, e);
+ return o;
+ }
+ };
+ o.check(ready(&c).await, "the machines did not connect");
+ let (steps, step_ms, size) = (150u64, if fast { 25 } else { 250 }, 1024usize);
+ c.node("laptop")
+ .command(&format!("start ada {steps} {step_ms}"))
+ .await;
+ tokio::time::sleep(c.t(8.0)).await;
+ let before = c.node("laptop").log.lock().unwrap().len();
+ let t0 = Instant::now();
+ c.node("studio").crash().await;
+ // Its sockets close as a dead process's do.
+ for k in [("studio", "laptop"), ("laptop", "studio")] {
+ c.proxies[&(c.idx(k.0), c.idx(k.1))].sever(true);
+ }
+ let mut took = None;
+ let end = Instant::now() + Duration::from_secs(if fast { 60 } else { 300 });
+ while Instant::now() < end && took.is_none() {
+ if c.node("laptop").log.lock().unwrap().len() > before {
+ took = Some(t0.elapsed().as_secs_f64());
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ o.check(took.is_some(), "the laptop never took the run");
+ o.metric("takeover_s", took.unwrap_or(-1.0));
+ let exp = expected_sum(steps, size);
+ let end = Instant::now() + Duration::from_secs(if fast { 120 } else { 600 });
+ let mut done = false;
+ while Instant::now() < end && !done {
+ done = c.node("laptop").command("cat agents/ada/result.txt").await["text"]
+ .as_str()
+ .is_some_and(|t| t.trim() == exp);
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ o.check(done, "the run did not finish on the laptop");
+ let runs = c.node("laptop").sup.runs().await.unwrap_or_default();
+ o.metric(
+ "words",
+ runs.first().map(|r| r.note.clone()).unwrap_or_default(),
+ );
+ o.check(
+ runs.first()
+ .is_some_and(|r| r.note.starts_with("Resumed on laptop")),
+ "the takeover words do not say it resumed",
+ );
+ c.stop().await;
+ o
+}
+
+async fn wake_after_takeover(name: &str, fast: bool) -> Outcome {
+ let mut o = Outcome::new(name);
+ let c = match Cluster::start(&laptop_studio(), fast).await {
+ Ok(c) => c,
+ Err(e) => {
+ o.check(false, e);
+ return o;
+ }
+ };
+ o.check(ready(&c).await, "the machines did not connect");
+ let (steps, step_ms, size) = (300u64, if fast { 25 } else { 250 }, 1024usize);
+ c.node("laptop")
+ .command(&format!("start ada {steps} {step_ms}"))
+ .await;
+ tokio::time::sleep(c.t(8.0)).await;
+ // The studio freezes behind an open connection; the laptop takes over.
+ c.node("studio").command("freeze").await;
+ c.set_path("studio", "laptop", shape(|s| s.hold = true));
+ let before = c.node("laptop").log.lock().unwrap().len();
+ let t0 = Instant::now();
+ let end = Instant::now() + Duration::from_secs(if fast { 60 } else { 300 });
+ let mut took = None;
+ while Instant::now() < end && took.is_none() {
+ if c.node("laptop").log.lock().unwrap().len() > before {
+ took = Some(t0.elapsed().as_secs_f64());
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ o.check(took.is_some(), "the laptop never took the run");
+ o.metric("takeover_s", took.unwrap_or(-1.0));
+ tokio::time::sleep(c.t(10.0)).await;
+ // The studio wakes.
+ c.clear_path("studio", "laptop");
+ c.node("studio").command("thaw").await;
+ c.node("studio").command("power wake").await;
+ let t1 = Instant::now();
+ let mut fenced = None;
+ let end = Instant::now() + Duration::from_secs(if fast { 60 } else { 300 });
+ while Instant::now() < end && fenced.is_none() {
+ let runs = c.node("studio").sup.runs().await.unwrap_or_default();
+ if runs.iter().any(|r| !r.running_here) {
+ fenced = Some(t1.elapsed().as_secs_f64());
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ o.check(fenced.is_some(), "the woken studio kept driving the run");
+ o.metric("fenced_after_wake_s", fenced.unwrap_or(-1.0));
+ let exp = expected_sum(steps, size);
+ let end = Instant::now() + Duration::from_secs(if fast { 180 } else { 900 });
+ let mut done = false;
+ while Instant::now() < end && !done {
+ done = c.node("laptop").command("cat agents/ada/result.txt").await["text"]
+ .as_str()
+ .is_some_and(|t| t.trim() == exp);
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ o.check(done, "the run did not finish correctly");
+ o.check(
+ c.converge(Duration::from_secs(if fast { 120 } else { 600 }))
+ .await,
+ "no convergence",
+ );
+ for p in c.verify(&[("ada", steps, size)]).await {
+ o.check(false, p);
+ }
+ c.stop().await;
+ o
+}
+
+async fn big_file_flapping(name: &str, fast: bool) -> Outcome {
+ let mut o = Outcome::new(name);
+ let c = match Cluster::start(&laptop_studio(), fast).await {
+ Ok(c) => c,
+ Err(e) => {
+ o.check(false, e);
+ return o;
+ }
+ };
+ o.check(ready(&c).await, "the machines did not connect");
+ let size: usize = std::env::var("CUA_CHAOS_BIG_MB")
+ .ok()
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(256)
+ << 20;
+ // 20 MB/s with a link that drops every few seconds.
+ c.set_path(
+ "studio",
+ "laptop",
+ shape(|s| {
+ s.bandwidth = 20 << 20;
+ s.latency_ms = 30;
+ }),
+ );
+ let flap = [
+ c.proxies[&(c.idx("laptop"), c.idx("studio"))].flap((2000, 5000), (300, 1500)),
+ c.proxies[&(c.idx("studio"), c.idx("laptop"))].flap((2000, 5000), (300, 1500)),
+ ];
+ let before = c.pair_bytes("studio", "laptop");
+ // A big file written in 1 MiB-patterned pieces to a file on the studio's disk, then put.
+ let path = c.dir.path().join("big.bin");
+ {
+ use std::io::Write as _;
+ let mut f = std::fs::File::create(&path).unwrap();
+ let mut left = size;
+ let mut i = 0u64;
+ while left > 0 {
+ let n = left.min(1 << 20);
+ f.write_all(&content(i, n)).unwrap();
+ left -= n;
+ i += 1;
+ }
+ }
+ let mut want = vec![];
+ {
+ use sha2::Digest as _;
+ use std::io::Read as _;
+ let mut h = sha2::Sha256::new();
+ let mut f = std::fs::File::open(&path).unwrap();
+ let mut buf = vec![0u8; 1 << 20];
+ loop {
+ let n = f.read(&mut buf).unwrap();
+ if n == 0 {
+ break;
+ }
+ h.update(&buf[..n]);
+ }
+ want.extend(h.finalize());
+ }
+ let t0 = Instant::now();
+ let put = c
+ .node("studio")
+ .backend
+ .put_file("agents/ada/big.bin", &path, Condition::None)
+ .await;
+ o.check(put.is_ok(), "the big write failed");
+ let end = Instant::now() + Duration::from_secs(if fast { 600 } else { 3600 });
+ let mut ok = false;
+ while Instant::now() < end && !ok {
+ ok = c
+ .node("laptop")
+ .store
+ .head("agents/ada/big.bin")
+ .await
+ .ok()
+ .flatten()
+ .is_some_and(|h| h.size == size as u64);
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ o.check(ok, "the big file never arrived");
+ for f in flap {
+ f.abort();
+ }
+ c.clear_path("studio", "laptop");
+ let moved = c.pair_bytes("studio", "laptop") - before;
+ o.metric("file_mib", size >> 20);
+ o.metric("transfer_s", t0.elapsed().as_secs_f64());
+ o.metric("bytes_on_wire_mib", moved >> 20);
+ o.metric("overhead_ratio", moved as f64 / size as f64);
+ o.check(
+ moved < (size as u64) * 3 / 2,
+ format!("{moved} bytes crossed for {size}: parts were sent again"),
+ );
+ // Intact.
+ if ok {
+ use sha2::Digest as _;
+ let p = c
+ .node("laptop")
+ .store
+ .version_file(
+ "agents/ada/big.bin",
+ &c.node("laptop")
+ .store
+ .head("agents/ada/big.bin")
+ .await
+ .unwrap()
+ .unwrap()
+ .version,
+ )
+ .unwrap();
+ let mut h = sha2::Sha256::new();
+ let mut f = std::fs::File::open(p).unwrap();
+ let mut buf = vec![0u8; 1 << 20];
+ loop {
+ use std::io::Read as _;
+ let n = f.read(&mut buf).unwrap();
+ if n == 0 {
+ break;
+ }
+ h.update(&buf[..n]);
+ }
+ o.check(
+ h.finalize().to_vec() == want,
+ "the big file differs after the transfer",
+ );
+ }
+ c.stop().await;
+ o
+}
+
+/// 20 machines joined by proxies need thousands of sockets; macOS starts at 256.
+fn raise_open_files() {
+ // SAFETY: plain getrlimit/setrlimit on valid structs.
+ unsafe {
+ let mut r: libc::rlimit = std::mem::zeroed();
+ if libc::getrlimit(libc::RLIMIT_NOFILE, &mut r) == 0 {
+ r.rlim_cur = r.rlim_max.min(65_536).max(r.rlim_cur);
+ let _ = libc::setrlimit(libc::RLIMIT_NOFILE, &r);
+ }
+ }
+}
+
+fn rusage() -> (f64, f64, u64) {
+ // SAFETY: an all-zero rusage is a valid out value.
+ let mut u: libc::rusage = unsafe { std::mem::zeroed() };
+ // SAFETY: a valid out pointer.
+ unsafe { libc::getrusage(libc::RUSAGE_SELF, &mut u) };
+ let t = |tv: libc::timeval| tv.tv_sec as f64 + tv.tv_usec as f64 / 1e6;
+ (t(u.ru_utime), t(u.ru_stime), u.ru_maxrss as u64)
+}
+
+async fn scale_peers(name: &str, fast: bool, n: usize) -> Outcome {
+ let mut o = Outcome::new(name);
+ let specs: Vec<Spec> = (0..n)
+ .map(|i| spec(&format!("m{i:02}"), 9000 - (i as u64) * 100, i != 0))
+ .collect();
+ let (u0, s0, _) = rusage();
+ let t0 = Instant::now();
+ let c = match Cluster::start(&specs, fast).await {
+ Ok(c) => c,
+ Err(e) => {
+ o.check(false, e);
+ return o;
+ }
+ };
+ // Everyone agrees on the owner (the most reliable) and sees everyone.
+ let end = Instant::now() + Duration::from_secs(if fast { 120 } else { 300 });
+ let mut agreed = false;
+ while Instant::now() < end && !agreed {
+ agreed = true;
+ for nd in &c.nodes {
+ let s = nd.node.status().await;
+ if s.owner != "m00" || s.peers.iter().filter(|p| p.connected).count() < n - 1 {
+ agreed = false;
+ break;
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ o.check(agreed, "the group did not agree on one owner and connect");
+ o.metric("machines", n);
+ o.metric("agreed_after_s", t0.elapsed().as_secs_f64());
+ // Writes from random machines; all converge.
+ let w0 = Instant::now();
+ for i in 0..(n * 20) {
+ let who = format!("m{:02}", i % n);
+ let _ = c
+ .write(&who, &format!("agents/s/f{i}"), 2000, i as u64)
+ .await;
+ }
+ o.metric("writes", n * 20);
+ o.metric("write_phase_s", w0.elapsed().as_secs_f64());
+ o.check(
+ c.converge(Duration::from_secs(if fast { 180 } else { 600 }))
+ .await,
+ "no convergence",
+ );
+ // Two copies, not n: only the replicas hold the files, clients ask.
+ let mut holders = 0;
+ for nd in &c.nodes {
+ if nd
+ .store
+ .list("agents/s/")
+ .await
+ .map(|v| v.len())
+ .unwrap_or(0)
+ > 0
+ {
+ holders += 1;
+ }
+ }
+ o.metric("machines_holding_files", holders);
+ for p in c.verify(&[]).await {
+ o.check(false, p);
+ }
+ let (u1, s1, rss) = rusage();
+ o.metric("cpu_user_s", u1 - u0);
+ o.metric("cpu_sys_s", s1 - s0);
+ o.metric(
+ "peak_rss_mib",
+ rss as f64
+ / if cfg!(target_os = "macos") {
+ 1048576.0
+ } else {
+ 1024.0
+ },
+ );
+ o.metric("wire_mib", c.wire_bytes() >> 20);
+ o.metric("takeovers", c.takeovers().await);
+ c.stop().await;
+ o
+}
+
+async fn scale_small_files(name: &str, fast: bool) -> Outcome {
+ let mut o = Outcome::new(name);
+ let c = match Cluster::start(&laptop_studio(), fast).await {
+ Ok(c) => c,
+ Err(e) => {
+ o.check(false, e);
+ return o;
+ }
+ };
+ o.check(ready(&c).await, "the machines did not connect");
+ let n: usize = std::env::var("CUA_CHAOS_SMALL_FILES")
+ .ok()
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(20_000);
+ let (u0, s0, _) = rusage();
+ let t0 = Instant::now();
+ let studio = c.node("studio").clone();
+ // Batches of 200 (what a folder copy-in does).
+ let mut i = 0usize;
+ while i < n {
+ let end = (i + 200).min(n);
+ let items: Vec<(String, Vec<u8>)> = (i..end)
+ .map(|k| {
+ (
+ format!("agents/small/d{}/f{k}", k % 100),
+ content(k as u64, 1500),
+ )
+ })
+ .collect();
+ if studio.backend.put_many(items.clone()).await.is_ok() {
+ for (k, b) in &items {
+ c.ledger.record(k, b);
+ }
+ }
+ i = end;
+ }
+ o.metric("files", n);
+ o.metric("write_s", t0.elapsed().as_secs_f64());
+ o.metric("write_files_per_s", n as f64 / t0.elapsed().as_secs_f64());
+ let t1 = Instant::now();
+ o.check(
+ c.converge(Duration::from_secs(if fast { 900 } else { 1800 }))
+ .await,
+ "no convergence",
+ );
+ o.metric("replicated_after_writes_s", t1.elapsed().as_secs_f64());
+ for p in c.verify(&[]).await {
+ o.check(false, p);
+ if o.problems.len() > 5 {
+ break;
+ }
+ }
+ let (u1, s1, rss) = rusage();
+ o.metric("cpu_user_s", u1 - u0);
+ o.metric("cpu_sys_s", s1 - s0);
+ o.metric(
+ "peak_rss_mib",
+ rss as f64
+ / if cfg!(target_os = "macos") {
+ 1048576.0
+ } else {
+ 1024.0
+ },
+ );
+ o.metric("wire_mib", c.wire_bytes() >> 20);
+ c.stop().await;
+ o
+}
+
+async fn scale_ten_runs(name: &str, fast: bool) -> Outcome {
+ let mut o = Outcome::new(name);
+ let c = match Cluster::start(&laptop_studio(), fast).await {
+ Ok(c) => c,
+ Err(e) => {
+ o.check(false, e);
+ return o;
+ }
+ };
+ o.check(ready(&c).await, "the machines did not connect");
+ let (steps, step_ms, size) = (60u64, if fast { 20 } else { 100 }, 1024usize);
+ let (u0, s0, _) = rusage();
+ let t0 = Instant::now();
+ let names: Vec<String> = (0..10).map(|i| format!("run{i}")).collect();
+ for n in &names {
+ c.node("laptop")
+ .command(&format!("start {n} {steps} {step_ms}"))
+ .await;
+ }
+ let exp = expected_sum(steps, size);
+ let end = Instant::now() + Duration::from_secs(if fast { 300 } else { 900 });
+ let mut done = 0;
+ while Instant::now() < end {
+ done = 0;
+ for n in &names {
+ if c.node("laptop")
+ .command(&format!("cat agents/{n}/result.txt"))
+ .await["text"]
+ .as_str()
+ .is_some_and(|t| t.trim() == exp)
+ {
+ done += 1;
+ }
+ }
+ if done == names.len() {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ }
+ o.check(
+ done == names.len(),
+ format!("only {done} of 10 runs finished"),
+ );
+ o.metric("ten_runs_finished_s", t0.elapsed().as_secs_f64());
+ o.metric("ideal_s", (steps * step_ms) as f64 / 1000.0);
+ o.check(c.converge(Duration::from_secs(120)).await, "no convergence");
+ let runs: Vec<(&str, u64, usize)> = names.iter().map(|n| (n.as_str(), steps, size)).collect();
+ for p in c.verify(&runs).await {
+ o.check(false, p);
+ }
+ let (u1, s1, rss) = rusage();
+ o.metric("cpu_user_s", u1 - u0);
+ o.metric("cpu_sys_s", s1 - s0);
+ o.metric(
+ "peak_rss_mib",
+ rss as f64
+ / if cfg!(target_os = "macos") {
+ 1048576.0
+ } else {
+ 1024.0
+ },
+ );
+ o.metric("wire_mib", c.wire_bytes() >> 20);
+ c.stop().await;
+ o
+}
+
+async fn false_takeover_rate(name: &str, fast: bool) -> Outcome {
+ // Many short trials under heavy jitter and loss with a healthy owner: a
+ // takeover is a false one, always.
+ let mut o = Outcome::new(name);
+ let trials = std::env::var("CUA_CHAOS_TRIALS")
+ .ok()
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(10usize);
+ let mut false_takeovers = 0u64;
+ let mut total_s = 0.0;
+ for t in 0..trials {
+ let c = match Cluster::start(&laptop_studio(), fast).await {
+ Ok(c) => c,
+ Err(e) => {
+ o.check(false, e);
+ return o;
+ }
+ };
+ if !ready(&c).await {
+ o.check(false, "the machines did not connect");
+ c.stop().await;
+ continue;
+ }
+ // Heavy jitter, 20 % loss, both ways, for a minute of scenario time.
+ c.set_path(
+ "studio",
+ "laptop",
+ shape(|s| {
+ s.latency_ms = 400;
+ s.jitter_ms = 600;
+ s.loss = 0.2;
+ }),
+ );
+ // Ordered writes from the laptop make it want authority: the worst case.
+ let d = c.t(60.0);
+ let t0 = Instant::now();
+ let mut i = 0;
+ while t0.elapsed() < d {
+ i += 1;
+ let _ = c
+ .node("laptop")
+ .backend
+ .put(
+ &format!("agents/ada/.cua-lease-{t}-{i}"),
+ b"x".to_vec(),
+ Condition::IfNoneMatch,
+ )
+ .await;
+ tokio::time::sleep(c.t(2.0).max(Duration::from_millis(30))).await;
+ }
+ total_s += d.as_secs_f64();
+ false_takeovers += c.takeovers().await;
+ c.stop().await;
+ }
+ o.metric("trials", trials);
+ o.metric("scenario_seconds_under_jitter", total_s);
+ o.metric("false_takeovers", false_takeovers);
+ o.check(
+ false_takeovers == 0,
+ format!("{false_takeovers} false takeovers in {trials} trials"),
+ );
+ o
+}
+
+impl Cluster {
+ /// [`Cluster::start`] with each machine's wall clock moved (ms).
+ pub async fn start_skewed(
+ specs: &[Spec],
+ fast: bool,
+ skew_ms: &[i64],
+ ) -> Result<Cluster, String> {
+ Cluster::start_inner(specs, fast, skew_ms).await
+ }
+}
+
+#[allow(dead_code)]
+fn unused(_: PathBuf) {}
diff --git a/libs/cua/crates/cua-replica-lab/src/driver.rs b/libs/cua/crates/cua-replica-lab/src/driver.rs
new file mode 100644
index 0000000000..012dfaecce
--- /dev/null
+++ b/libs/cua/crates/cua-replica-lab/src/driver.rs
@@ -0,0 +1,135 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! The simulated durable agent: N steps, each writing a file and a journal
+//! marker through the Volume; resumable from the machine's copy of the
+//! journal; the end writes the checksum of every step.
+
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use cua_volume::backend::Condition;
+use cua_volume::replica::supervision::{DriveEnd, Driver, RunCtx};
+
+/// One step as it ran.
+#[derive(Clone, Debug)]
+pub struct StepLog {
+ pub machine: String,
+ pub epoch: u64,
+ pub step: u64,
+ pub at: Instant,
+ /// Wall clock, for lines printed by a node process.
+ pub wall_ms: u64,
+}
+
+/// What step `i` writes (the same in any epoch).
+pub fn content(i: u64, size: usize) -> Vec<u8> {
+ let head = format!("step {i}: {}\n", cua_volume::sha256_hex(&i.to_le_bytes()));
+ let mut v = head.into_bytes();
+ let mut x = i.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1;
+ while v.len() < size {
+ x ^= x << 13;
+ x ^= x >> 7;
+ x ^= x << 17;
+ v.extend_from_slice(&x.to_le_bytes());
+ }
+ v.truncate(size.max(1));
+ v
+}
+
+/// The checksum the run must end with.
+pub fn expected_sum(n: u64, size: usize) -> String {
+ let mut all = vec![];
+ for i in 0..n {
+ all.extend(content(i, size));
+ }
+ cua_volume::sha256_hex(&all)
+}
+
+/// Called with each step as it starts.
+pub type OnStep = Arc<dyn Fn(&StepLog) + Send + Sync>;
+
+pub struct Steps {
+ pub n: u64,
+ pub step_ms: u64,
+ /// Bytes per step's file.
+ pub size: usize,
+ pub log: Arc<Mutex<Vec<StepLog>>>,
+ /// Called with each step as it starts (a node process prints it).
+ pub on_step: Option<OnStep>,
+}
+
+#[async_trait::async_trait]
+impl Driver for Steps {
+ async fn drive(&self, mut ctx: RunCtx) -> DriveEnd {
+ let prefix = format!("agents/{}/journal/", ctx.agent);
+ let mut held = 0u64;
+ while ctx
+ .backend
+ .head(&format!("{prefix}{held:06}"))
+ .await
+ .ok()
+ .flatten()
+ .is_some()
+ {
+ held += 1;
+ }
+ ctx.held_reaches(held);
+ let mut i = held;
+ while i < self.n {
+ if ctx.fenced() {
+ return DriveEnd::Fenced;
+ }
+ let e = StepLog {
+ machine: ctx.machine.clone(),
+ epoch: ctx.epoch,
+ step: i,
+ at: Instant::now(),
+ wall_ms: cua_volume::now_ms(),
+ };
+ if let Some(f) = &self.on_step {
+ f(&e);
+ }
+ self.log.lock().expect("log").push(e);
+ let out = format!("agents/{}/out/step-{i}", ctx.agent);
+ if let Err(e) = ctx
+ .backend
+ .put(&out, content(i, self.size), Condition::None)
+ .await
+ {
+ return DriveEnd::Failed(format!("write: {e}"));
+ }
+ let _ = ctx
+ .backend
+ .put(&format!("{prefix}{i:06}"), vec![b'.'], Condition::None)
+ .await;
+ ctx.report(i + 1);
+ i += 1;
+ tokio::time::sleep(Duration::from_millis(self.step_ms)).await;
+ }
+ if ctx.fenced() {
+ return DriveEnd::Fenced;
+ }
+ let mut all = vec![];
+ for s in 0..self.n {
+ match ctx
+ .backend
+ .get(&format!("agents/{}/out/step-{s}", ctx.agent), None)
+ .await
+ {
+ Ok((b, _)) => all.extend(b),
+ Err(e) => return DriveEnd::Failed(format!("step {s} is missing: {e}")),
+ }
+ }
+ let sum = cua_volume::sha256_hex(&all);
+ let _ = ctx
+ .backend
+ .put(
+ &format!("agents/{}/result.txt", ctx.agent),
+ sum.clone().into_bytes(),
+ Condition::None,
+ )
+ .await;
+ DriveEnd::Done(sum)
+ }
+}
diff --git a/libs/cua/crates/cua-replica-lab/src/lib.rs b/libs/cua/crates/cua-replica-lab/src/lib.rs
new file mode 100644
index 0000000000..5bc52cef8f
--- /dev/null
+++ b/libs/cua/crates/cua-replica-lab/src/lib.rs
@@ -0,0 +1,23 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! Test rig for the replicated Volume (not shipped).
+//!
+//! - [`shape`]: a userspace TCP proxy that makes one path bad (latency,
+//! jitter, bandwidth, loss as TCP feels it, blackholes, resets, flaps),
+//! scoped to the ports it is given.
+//! - [`node`]: one machine's replica node and durable-agent supervisor on
+//! real TCP, with a line control protocol, as a library and as the
+//! `replica-node` process.
+//! - [`driver`]: the simulated durable agent (N steps, resumable, checksummed).
+//! - [`chaos`]: the opt-in matrix over real sockets: impairments, process
+//! faults, scale.
+
+#[cfg(unix)]
+pub mod chaos;
+#[cfg(unix)]
+pub mod driver;
+#[cfg(unix)]
+pub mod node;
+#[cfg(unix)]
+pub mod shape;
diff --git a/libs/cua/crates/cua-replica-lab/src/node.rs b/libs/cua/crates/cua-replica-lab/src/node.rs
new file mode 100644
index 0000000000..dcb72ff2e6
--- /dev/null
+++ b/libs/cua/crates/cua-replica-lab/src/node.rs
@@ -0,0 +1,446 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! One machine's replica node and supervisor on real TCP, driven over a
+//! line protocol. The same code runs as a library inside the chaos matrix
+//! and as the `replica-node` process on each machine of a real test.
+//!
+//! Control protocol (one command per line, one JSON line back):
+//!
+//! ```text
+//! status replication status and the closing paragraph
+//! start <agent> <steps> <step_ms> record a durable run (says where it will run)
+//! runs every run as this machine sees it
+//! put <key> <bytes> [seed] an unconditional write of deterministic bytes
+//! cas <key> a create-only write (an ordered write)
+//! get <key> size and sha256 of the head
+//! sum [prefix] sha256 over every head under the prefix (convergence check)
+//! count [prefix] number of heads
+//! power sleep|wake|netdown|netup a power or network event from the OS
+//! freeze | thaw stop reading and timing (a stopped process, in-process)
+//! facts this machine's reliability facts
+//! quit
+//! ```
+
+use std::net::SocketAddr;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use cua_volume::backend::{Backend, Condition};
+use cua_volume::fs::FsBackend;
+use cua_volume::replica::supervision::{Awake, Supervision, SupervisionConfig};
+use cua_volume::replica::{
+ Config, Facts, Member, PowerEvent, ReplicaNode, ReplicatedBackend, TcpTransport,
+};
+use serde_json::json;
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+use tokio::net::TcpListener;
+
+use crate::driver::{StepLog, Steps};
+
+/// How a node is set up.
+#[derive(Clone, Debug)]
+pub struct NodeOpts {
+ pub home: PathBuf,
+ pub id: String,
+ pub name: String,
+ pub listen: SocketAddr,
+ /// Where to dial each peer (usually an impairment proxy's port).
+ pub peers: Vec<(String, SocketAddr)>,
+ /// Every machine of the group: id and name (this one included).
+ pub members: Vec<(String, String)>,
+ /// `None`: measure this machine and keep measuring.
+ pub facts: Option<Facts>,
+ pub fast: bool,
+ pub skew_ms: i64,
+ pub control: Option<SocketAddr>,
+ pub step_size: usize,
+ /// Print JSON events to stdout.
+ pub print_events: bool,
+}
+
+impl NodeOpts {
+ pub fn new(home: &Path, id: &str, name: &str, listen: SocketAddr) -> NodeOpts {
+ NodeOpts {
+ home: home.to_path_buf(),
+ id: id.into(),
+ name: name.into(),
+ listen,
+ peers: vec![],
+ members: vec![(id.into(), name.into())],
+ facts: None,
+ fast: false,
+ skew_ms: 0,
+ control: None,
+ step_size: 1024,
+ print_events: false,
+ }
+ }
+}
+
+/// Real facts of this machine, in the Volume's terms.
+pub fn measured_facts(store_free: Option<u64>) -> Facts {
+ let f = cua_cluster::reliability::probe();
+ Facts {
+ rank: cua_cluster::reliability::score(&Facts_to_cluster(&f)),
+ free_disk: store_free.unwrap_or(f.free_disk_gb << 30),
+ on_battery: f.on_battery,
+ sleep_prone: f.sleep_prone(),
+ user_here: f.user_active,
+ sleep_prevented: !cua_cluster::power::active_reasons().is_empty(),
+ arch: cua_volume::replica::roles::normalize_arch(std::env::consts::ARCH),
+ }
+}
+
+#[allow(non_snake_case)]
+fn Facts_to_cluster(f: &cua_cluster::reliability::Facts) -> cua_cluster::reliability::Facts {
+ let mut f = f.clone();
+ f.sleep_prevented = !cua_cluster::power::active_reasons().is_empty();
+ f
+}
+
+pub struct Node {
+ pub opts: NodeOpts,
+ pub node: ReplicaNode,
+ pub backend: Arc<ReplicatedBackend>,
+ pub store: FsBackend,
+ pub sup: Supervision,
+ pub log: Arc<Mutex<Vec<StepLog>>>,
+ pub transport: TcpTransport,
+ pub listen: SocketAddr,
+ tasks: Mutex<Vec<tokio::task::JoinHandle<()>>>,
+}
+
+fn event(print: bool, v: serde_json::Value) {
+ if print {
+ println!("{v}");
+ }
+}
+
+impl Node {
+ pub async fn start(mut opts: NodeOpts) -> Result<Arc<Node>, String> {
+ let home = opts.home.clone();
+ if let Some(h) = std::env::var_os("HOME") {
+ let real = PathBuf::from(h).join(".cua");
+ if home.starts_with(&real) {
+ return Err(format!(
+ "refusing to use {} (the real cua home)",
+ home.display()
+ ));
+ }
+ }
+ std::fs::create_dir_all(&home).map_err(|e| e.to_string())?;
+ let store = FsBackend::new(home.join("data"));
+ let transport = TcpTransport::new();
+ for (id, a) in &opts.peers {
+ transport.set(id, *a);
+ }
+ let facts = match &opts.facts {
+ Some(f) => f.clone(),
+ None => measured_facts(store.free_bytes()),
+ };
+ let members: Vec<Member> = opts
+ .members
+ .iter()
+ .map(|(id, name)| Member {
+ id: id.clone(),
+ name: name.clone(),
+ facts: if *id == opts.id {
+ facts.clone()
+ } else {
+ Facts::default()
+ },
+ last_seen_ms: 0,
+ })
+ .collect();
+ let mut cfg = if opts.fast {
+ Config::fast()
+ } else {
+ Config::standard()
+ };
+ cfg.wall_skew_ms = opts.skew_ms;
+ let node = ReplicaNode::open(
+ cfg,
+ &opts.id,
+ &opts.name,
+ &home,
+ store.clone(),
+ Arc::new(transport.clone()),
+ members,
+ )
+ .await
+ .map_err(|e| e.to_string())?;
+ node.set_facts(facts);
+ let listener = TcpListener::bind(opts.listen)
+ .await
+ .map_err(|e| e.to_string())?;
+ let listen = listener.local_addr().map_err(|e| e.to_string())?;
+ opts.listen = listen;
+ let mut tasks = vec![];
+ let n2 = node.clone();
+ tasks.push(tokio::spawn(async move {
+ loop {
+ let Ok((s, _)) = listener.accept().await else {
+ return;
+ };
+ let _ = s.set_nodelay(true);
+ n2.accept(Box::new(s)).await;
+ }
+ }));
+ node.start();
+ let backend = node.backend();
+ let log: Arc<Mutex<Vec<StepLog>>> = Arc::default();
+ let print = opts.print_events;
+ let on_step: Arc<dyn Fn(&StepLog) + Send + Sync> = Arc::new(move |e: &StepLog| {
+ event(
+ print,
+ json!({"ev":"step","machine":e.machine,"epoch":e.epoch,"step":e.step,"wall_ms":e.wall_ms}),
+ );
+ });
+ let steps_n = Arc::new(std::sync::atomic::AtomicU64::new(0));
+ let _ = steps_n;
+ let awake: Awake = Arc::new(move |why: &str| {
+ let g = cua_cluster::power::SleepGuard::hold(why);
+ event(print, json!({"ev":"awake","reason": why}));
+ Box::new(g) as Box<dyn std::any::Any + Send>
+ });
+ let sup_cfg = if opts.fast {
+ SupervisionConfig::fast()
+ } else {
+ SupervisionConfig::standard()
+ };
+ // The driver's step count and pace come from the run's spec.
+ let driver = Arc::new(SpecDriver {
+ log: log.clone(),
+ on_step: on_step.clone(),
+ size: opts.step_size,
+ });
+ let sup = Supervision::new(node.clone(), backend.clone(), sup_cfg, driver, Some(awake));
+ sup.spawn();
+ let me = Arc::new(Node {
+ opts: opts.clone(),
+ node: node.clone(),
+ backend,
+ store,
+ sup,
+ log,
+ transport,
+ listen,
+ tasks: Mutex::new(tasks),
+ });
+ // Keep this machine's facts current when they are measured.
+ if opts.facts.is_none() {
+ let m = me.clone();
+ let t = tokio::spawn(async move {
+ loop {
+ tokio::time::sleep(Duration::from_secs(5)).await;
+ let f = measured_facts(m.store.free_bytes());
+ m.node.set_facts(f);
+ }
+ });
+ me.tasks.lock().expect("tasks").push(t);
+ }
+ if let Some(c) = opts.control {
+ let l = TcpListener::bind(c).await.map_err(|e| e.to_string())?;
+ let m = me.clone();
+ let t = tokio::spawn(async move {
+ loop {
+ let Ok((s, _)) = l.accept().await else { return };
+ let m = m.clone();
+ tokio::spawn(async move { m.control(s).await });
+ }
+ });
+ me.tasks.lock().expect("tasks").push(t);
+ }
+ event(
+ print,
+ json!({"ev":"up","id":opts.id,"name":opts.name,"listen":listen.to_string()}),
+ );
+ Ok(me)
+ }
+
+ pub async fn stop(&self) {
+ self.sup.stop().await;
+ self.node.shutdown().await;
+ for t in self.tasks.lock().expect("tasks").drain(..) {
+ t.abort();
+ }
+ }
+
+ /// Kills the node without a goodbye (a crash): tasks end, nothing is said.
+ pub async fn crash(&self) {
+ self.sup.stop().await;
+ for t in self.tasks.lock().expect("tasks").drain(..) {
+ t.abort();
+ }
+ self.node.freeze(true);
+ }
+
+ async fn control(self: Arc<Self>, s: tokio::net::TcpStream) {
+ let (rd, mut wr) = s.into_split();
+ let mut lines = BufReader::new(rd).lines();
+ while let Ok(Some(line)) = lines.next_line().await {
+ let line = line.trim().to_string();
+ if line.is_empty() {
+ continue;
+ }
+ if line == "quit" {
+ let _ = wr.write_all(b"{\"ok\":true}\n").await;
+ std::process::exit(0);
+ }
+ let out = self.command(&line).await;
+ let mut s = out.to_string();
+ s.push('\n');
+ if wr.write_all(s.as_bytes()).await.is_err() {
+ return;
+ }
+ }
+ }
+
+ pub async fn command(&self, line: &str) -> serde_json::Value {
+ let w: Vec<&str> = line.split_whitespace().collect();
+ let err = |e: &dyn std::fmt::Display| json!({"ok": false, "error": e.to_string()});
+ match w.as_slice() {
+ ["status"] => {
+ let s = self.node.status().await;
+ let words = self.sup.words(None).await;
+ json!({"ok": true, "status": s, "words": words})
+ }
+ ["facts"] => {
+ json!({"ok": true, "facts": measured_facts(self.store.free_bytes()), "awake": cua_cluster::power::active_reasons()})
+ }
+ ["start", agent, steps, ms] => {
+ let spec = json!({"steps": steps.parse::<u64>().unwrap_or(10), "step_ms": ms.parse::<u64>().unwrap_or(100)});
+ match self.sup.start_run(agent, spec).await {
+ Ok(i) => json!({"ok": true, "run_on": i.run_on, "words": i.words}),
+ Err(e) => err(&e),
+ }
+ }
+ ["runs"] => match self.sup.runs().await {
+ Ok(r) => json!({"ok": true, "runs": r}),
+ Err(e) => err(&e),
+ },
+ ["put", key, bytes, rest @ ..] => {
+ let n: usize = bytes.parse().unwrap_or(0);
+ let seed: u64 = rest.first().and_then(|s| s.parse().ok()).unwrap_or(1);
+ let body = crate::driver::content(seed, n);
+ let t = std::time::Instant::now();
+ match self.backend.put_durable(key, body, Condition::None).await {
+ Ok((m, d)) => {
+ json!({"ok": true, "version": m.version, "etag": m.etag, "durability": d, "ms": t.elapsed().as_millis() as u64})
+ }
+ Err(e) => err(&e),
+ }
+ }
+ ["cas", key] => {
+ let t = std::time::Instant::now();
+ match self
+ .backend
+ .put_durable(key, b"x".to_vec(), Condition::IfNoneMatch)
+ .await
+ {
+ Ok((m, d)) => {
+ json!({"ok": true, "version": m.version, "durability": d, "ms": t.elapsed().as_millis() as u64})
+ }
+ Err(e) => json!({"ok": false, "error": e.to_string(), "kind": e.tag()}),
+ }
+ }
+ ["get", key] => match self.backend.head(key).await {
+ Ok(Some(m)) => {
+ json!({"ok": true, "size": m.size, "etag": m.etag, "version": m.version})
+ }
+ Ok(None) => json!({"ok": true, "missing": true}),
+ Err(e) => err(&e),
+ },
+ ["sum", rest @ ..] => {
+ let prefix = rest.first().copied().unwrap_or("");
+ match self.store.list(prefix).await {
+ Ok(v) => {
+ let mut all = String::new();
+ for m in &v {
+ all.push_str(&format!("{} {}\n", m.key, m.etag));
+ }
+ json!({"ok": true, "sum": cua_volume::sha256_hex(all.as_bytes()), "count": v.len()})
+ }
+ Err(e) => err(&e),
+ }
+ }
+ ["count", rest @ ..] => {
+ let prefix = rest.first().copied().unwrap_or("");
+ match self.store.list(prefix).await {
+ Ok(v) => json!({"ok": true, "count": v.len()}),
+ Err(e) => err(&e),
+ }
+ }
+ ["power", what] => {
+ let ev = match *what {
+ "sleep" => PowerEvent::WillSleep,
+ "wake" => PowerEvent::DidWake,
+ "netdown" => PowerEvent::NetworkLost,
+ "netup" => PowerEvent::NetworkUp,
+ _ => return err(&"sleep, wake, netdown or netup"),
+ };
+ self.node.notify_power(ev).await;
+ json!({"ok": true})
+ }
+ ["freeze"] => {
+ self.node.freeze(true);
+ json!({"ok": true})
+ }
+ ["thaw"] => {
+ self.node.freeze(false);
+ json!({"ok": true})
+ }
+ ["expect", steps, rest @ ..] => {
+ let size: usize = rest
+ .first()
+ .and_then(|s| s.parse().ok())
+ .unwrap_or(self.opts.step_size);
+ json!({"ok": true, "sum": crate::driver::expected_sum(steps.parse().unwrap_or(0), size)})
+ }
+ ["cat", key] => match self.backend.get(key, None).await {
+ Ok((b, m)) => {
+ json!({"ok": true, "text": String::from_utf8_lossy(&b[..b.len().min(4096)]), "size": m.size})
+ }
+ Err(e) => err(&e),
+ },
+ ["steps"] => {
+ let l = self.log.lock().expect("log");
+ json!({"ok": true, "count": l.len(), "machines": l.iter().map(|e| e.machine.clone()).collect::<std::collections::BTreeSet<_>>()})
+ }
+ _ => err(&format!("unknown command {line:?}")),
+ }
+ }
+}
+
+/// A driver that reads its step count and pace from the run's spec.
+struct SpecDriver {
+ log: Arc<Mutex<Vec<StepLog>>>,
+ on_step: Arc<dyn Fn(&StepLog) + Send + Sync>,
+ size: usize,
+}
+
+#[async_trait::async_trait]
+impl cua_volume::replica::supervision::Driver for SpecDriver {
+ async fn drive(
+ &self,
+ ctx: cua_volume::replica::supervision::RunCtx,
+ ) -> cua_volume::replica::supervision::DriveEnd {
+ let n = ctx.spec.get("steps").and_then(|v| v.as_u64()).unwrap_or(10);
+ let ms = ctx
+ .spec
+ .get("step_ms")
+ .and_then(|v| v.as_u64())
+ .unwrap_or(100);
+ Steps {
+ n,
+ step_ms: ms,
+ size: self.size,
+ log: self.log.clone(),
+ on_step: Some(self.on_step.clone()),
+ }
+ .drive(ctx)
+ .await
+ }
+}
diff --git a/libs/cua/crates/cua-replica-lab/src/shape.rs b/libs/cua/crates/cua-replica-lab/src/shape.rs
new file mode 100644
index 0000000000..fcc2d23be6
--- /dev/null
+++ b/libs/cua/crates/cua-replica-lab/src/shape.rs
@@ -0,0 +1,419 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+//! A TCP proxy that makes one path bad, in user space.
+//!
+//! It touches nothing but the connections routed through it: no firewall,
+//! no interface, no sysctl, no root, nothing about the machine's real
+//! network (so a hotspot is never affected, and there is nothing to clean up
+//! but the proxy itself). A node that dials the proxy's port instead of its
+//! peer sees whatever the [`Shape`] says:
+//!
+//! - latency and jitter, a bandwidth cap;
+//! - loss, modeled the way TCP experiences it: a lost packet costs a
+//! retransmission timeout (doubling while it keeps being lost), so 20 %
+//! loss shows up as stalls and a collapsed rate, not as missing bytes;
+//! - `hold`: the path is blackholed, bytes stop and resume;
+//! - `sever`: every connection is reset and new ones are refused;
+//! - flapping: reset every N to M seconds for a short while.
+//!
+//! Each direction has its own shape (asymmetric loss).
+
+use std::net::SocketAddr;
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use tokio::net::{TcpListener, TcpStream};
+use tokio::time::Instant;
+
+/// What one direction of the path does.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Shape {
+ pub latency_ms: u64,
+ pub jitter_ms: u64,
+ /// Bytes per second (0: unlimited).
+ pub bandwidth: u64,
+ /// Share of packets lost, 0 to 1.
+ pub loss: f64,
+ /// Bytes stop until cleared.
+ pub hold: bool,
+ /// The retransmission timeout a lost packet costs, at least (0: 200 ms,
+ /// what TCP stacks use).
+ pub rto_ms: u64,
+}
+
+/// Both directions: `up` is dialer to target, `down` is target to dialer.
+#[derive(Clone, Debug, Default, PartialEq)]
+pub struct Path {
+ pub up: Shape,
+ pub down: Shape,
+}
+
+impl Path {
+ pub fn both(s: Shape) -> Path {
+ Path {
+ up: s.clone(),
+ down: s,
+ }
+ }
+}
+
+#[derive(Debug, Default)]
+pub struct Stats {
+ pub bytes_up: AtomicU64,
+ pub bytes_down: AtomicU64,
+ pub connections: AtomicU64,
+ pub resets: AtomicU64,
+ pub refused: AtomicU64,
+}
+
+struct Shared {
+ /// When each direction's link is free again (all connections share its
+ /// bandwidth and its queue, like a real link).
+ free: Mutex<(Instant, Instant)>,
+ path: Mutex<Path>,
+ sever: AtomicBool,
+ /// Bumped to reset every live connection.
+ epoch: AtomicU64,
+ stats: Stats,
+ stop: AtomicBool,
+}
+
+/// A running proxy.
+pub struct Proxy {
+ shared: Arc<Shared>,
+ pub listen: SocketAddr,
+ tasks: Vec<tokio::task::JoinHandle<()>>,
+}
+
+const MSS: usize = 1448;
+
+impl Proxy {
+ /// Listens on `listen` (port 0 picks one) and forwards to `target`.
+ pub async fn start(listen: SocketAddr, target: SocketAddr) -> std::io::Result<Proxy> {
+ let l = TcpListener::bind(listen).await?;
+ let listen = l.local_addr()?;
+ let shared = Arc::new(Shared {
+ free: Mutex::new((Instant::now(), Instant::now())),
+ path: Mutex::new(Path::default()),
+ sever: AtomicBool::new(false),
+ epoch: AtomicU64::new(0),
+ stats: Stats::default(),
+ stop: AtomicBool::new(false),
+ });
+ let sh = shared.clone();
+ let accept = tokio::spawn(async move {
+ loop {
+ let Ok((client, _)) = l.accept().await else {
+ return;
+ };
+ if sh.stop.load(Ordering::SeqCst) {
+ return;
+ }
+ if sh.sever.load(Ordering::SeqCst) {
+ sh.stats.refused.fetch_add(1, Ordering::Relaxed);
+ drop(client);
+ continue;
+ }
+ let sh2 = sh.clone();
+ tokio::spawn(async move {
+ let _ = connection(sh2, client, target).await;
+ });
+ }
+ });
+ Ok(Proxy {
+ shared,
+ listen,
+ tasks: vec![accept],
+ })
+ }
+
+ /// Sets what the path does now (existing connections feel it at once).
+ pub fn set(&self, p: Path) {
+ *self.shared.path.lock().expect("path") = p;
+ }
+
+ pub fn path(&self) -> Path {
+ self.shared.path.lock().expect("path").clone()
+ }
+
+ /// Resets every live connection (a NAT change, a dropped link).
+ pub fn reset_all(&self) {
+ self.shared.epoch.fetch_add(1, Ordering::SeqCst);
+ self.shared.stats.resets.fetch_add(1, Ordering::Relaxed);
+ }
+
+ /// While on: live connections are reset and new ones refused.
+ pub fn sever(&self, on: bool) {
+ self.shared.sever.store(on, Ordering::SeqCst);
+ if on {
+ self.reset_all();
+ }
+ }
+
+ pub fn stats(&self) -> (u64, u64, u64, u64) {
+ let s = &self.shared.stats;
+ (
+ s.bytes_up.load(Ordering::Relaxed),
+ s.bytes_down.load(Ordering::Relaxed),
+ s.connections.load(Ordering::Relaxed),
+ s.resets.load(Ordering::Relaxed),
+ )
+ }
+
+ /// Resets the path every `every_ms` (a random value in the range) for
+ /// `down_ms`, until the proxy stops. Returns a handle to cancel.
+ pub fn flap(&self, every_ms: (u64, u64), down_ms: (u64, u64)) -> tokio::task::JoinHandle<()> {
+ let sh = self.shared.clone();
+ tokio::spawn(async move {
+ let rnd = |r: (u64, u64)| r.0 + rand::random::<u64>() % (r.1.saturating_sub(r.0) + 1);
+ while !sh.stop.load(Ordering::SeqCst) {
+ tokio::time::sleep(Duration::from_millis(rnd(every_ms))).await;
+ sh.sever.store(true, Ordering::SeqCst);
+ sh.epoch.fetch_add(1, Ordering::SeqCst);
+ sh.stats.resets.fetch_add(1, Ordering::Relaxed);
+ tokio::time::sleep(Duration::from_millis(rnd(down_ms))).await;
+ sh.sever.store(false, Ordering::SeqCst);
+ }
+ })
+ }
+
+ pub fn stop(&self) {
+ self.shared.stop.store(true, Ordering::SeqCst);
+ self.shared.epoch.fetch_add(1, Ordering::SeqCst);
+ for t in &self.tasks {
+ t.abort();
+ }
+ }
+}
+
+impl Drop for Proxy {
+ fn drop(&mut self) {
+ self.stop();
+ }
+}
+
+async fn connection(sh: Arc<Shared>, client: TcpStream, target: SocketAddr) -> std::io::Result<()> {
+ let upstream = TcpStream::connect(target).await?;
+ let _ = client.set_nodelay(true);
+ let _ = upstream.set_nodelay(true);
+ sh.stats.connections.fetch_add(1, Ordering::Relaxed);
+ let epoch = sh.epoch.load(Ordering::SeqCst);
+ let (cr, cw) = client.into_split();
+ let (ur, uw) = upstream.into_split();
+ let a = pump(sh.clone(), cr, uw, true, epoch);
+ let b = pump(sh.clone(), ur, cw, false, epoch);
+ let _ = tokio::join!(a, b);
+ Ok(())
+}
+
+/// The delay TCP adds when each packet is lost with probability `p`: a
+/// timeout that doubles while the retransmission is lost too.
+fn loss_delay(p: f64, rto: Duration) -> Duration {
+ if p <= 0.0 {
+ return Duration::ZERO;
+ }
+ let mut d = Duration::ZERO;
+ let mut t = rto;
+ let mut n = 0;
+ while rand::random::<f64>() < p && n < 6 {
+ d += t;
+ t *= 2;
+ n += 1;
+ }
+ d
+}
+
+async fn pump(
+ sh: Arc<Shared>,
+ mut rd: tokio::net::tcp::OwnedReadHalf,
+ mut wr: tokio::net::tcp::OwnedWriteHalf,
+ up: bool,
+ epoch: u64,
+) {
+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<(Instant, Vec<u8>)>();
+ let sh2 = sh.clone();
+ let writer = tokio::spawn(async move {
+ while let Some((at, bytes)) = rx.recv().await {
+ tokio::time::sleep_until(at).await;
+ if sh2.epoch.load(Ordering::SeqCst) != epoch {
+ break;
+ }
+ let n = bytes.len() as u64;
+ if wr.write_all(&bytes).await.is_err() {
+ break;
+ }
+ let c = if up {
+ &sh2.stats.bytes_up
+ } else {
+ &sh2.stats.bytes_down
+ };
+ c.fetch_add(n, Ordering::Relaxed);
+ }
+ let _ = wr.shutdown().await;
+ });
+ let mut buf = vec![0u8; MSS];
+ loop {
+ if sh.epoch.load(Ordering::SeqCst) != epoch {
+ break;
+ }
+ let n = tokio::select! {
+ r = rd.read(&mut buf) => match r { Ok(0) | Err(_) => break, Ok(n) => n },
+ _ = tokio::time::sleep(Duration::from_millis(50)) => continue,
+ };
+ // Hold: the path is blackholed; wait without reading more.
+ loop {
+ let s = shape(&sh, up);
+ if sh.epoch.load(Ordering::SeqCst) != epoch {
+ return;
+ }
+ if !s.hold {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ let s = shape(&sh, up);
+ let now = Instant::now();
+ let ser = if s.bandwidth > 0 {
+ Duration::from_secs_f64(n as f64 / s.bandwidth as f64)
+ } else {
+ Duration::ZERO
+ };
+ // The link is shared by every connection through it.
+ let start = {
+ let mut f = sh.free.lock().expect("free");
+ let slot = if up { &mut f.0 } else { &mut f.1 };
+ let start = now.max(*slot);
+ *slot = start + ser;
+ start
+ };
+ let jitter = if s.jitter_ms > 0 {
+ rand::random::<u64>() % (s.jitter_ms + 1)
+ } else {
+ 0
+ };
+ let latency = Duration::from_millis(s.latency_ms + jitter);
+ let rto =
+ Duration::from_millis(if s.rto_ms == 0 { 200 } else { s.rto_ms }).max(latency * 2);
+ let extra = loss_delay(s.loss, rto);
+ // Packets behind a lost one wait for it (head-of-line), so the
+ // delay also pushes the serializer.
+ if !extra.is_zero() {
+ let mut f = sh.free.lock().expect("free");
+ let slot = if up { &mut f.0 } else { &mut f.1 };
+ *slot += extra;
+ }
+ let at = start + ser + latency + extra;
+ if tx.send((at, buf[..n].to_vec())).is_err() {
+ break;
+ }
+ }
+ drop(tx);
+ let _ = writer.await;
+}
+
+fn shape(sh: &Shared, up: bool) -> Shape {
+ let p = sh.path.lock().expect("path");
+ if up { p.up.clone() } else { p.down.clone() }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ async fn echo() -> SocketAddr {
+ let l = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let a = l.local_addr().unwrap();
+ tokio::spawn(async move {
+ loop {
+ let Ok((mut s, _)) = l.accept().await else {
+ return;
+ };
+ tokio::spawn(async move {
+ let mut b = vec![0u8; 4096];
+ loop {
+ match s.read(&mut b).await {
+ Ok(0) | Err(_) => return,
+ Ok(n) => {
+ if s.write_all(&b[..n]).await.is_err() {
+ return;
+ }
+ }
+ }
+ }
+ });
+ }
+ });
+ a
+ }
+
+ #[tokio::test]
+ async fn latency_hold_and_sever_apply_to_live_connections() {
+ let target = echo().await;
+ let p = Proxy::start("127.0.0.1:0".parse().unwrap(), target)
+ .await
+ .unwrap();
+ let mut c = TcpStream::connect(p.listen).await.unwrap();
+ async fn rt(c: &mut TcpStream) -> Duration {
+ let t = std::time::Instant::now();
+ c.write_all(b"ping").await.unwrap();
+ let mut b = [0u8; 4];
+ c.read_exact(&mut b).await.unwrap();
+ t.elapsed()
+ }
+ assert!(rt(&mut c).await < Duration::from_millis(100));
+ p.set(Path::both(Shape {
+ latency_ms: 150,
+ ..Default::default()
+ }));
+ let t = rt(&mut c).await;
+ assert!(t >= Duration::from_millis(280), "{t:?}");
+ // Hold: nothing arrives until it is cleared.
+ p.set(Path::both(Shape {
+ hold: true,
+ ..Default::default()
+ }));
+ c.write_all(b"held").await.unwrap();
+ let mut b = [0u8; 4];
+ assert!(
+ tokio::time::timeout(Duration::from_millis(300), c.read_exact(&mut b))
+ .await
+ .is_err()
+ );
+ p.set(Path::default());
+ tokio::time::timeout(Duration::from_secs(2), c.read_exact(&mut b))
+ .await
+ .unwrap()
+ .unwrap();
+ assert_eq!(&b, b"held");
+ // Sever resets this connection and refuses the next.
+ p.sever(true);
+ tokio::time::sleep(Duration::from_millis(150)).await;
+ c.write_all(b"x").await.ok();
+ let r = tokio::time::timeout(Duration::from_secs(1), c.read(&mut b)).await;
+ assert!(matches!(r, Ok(Ok(0)) | Ok(Err(_))), "{r:?}");
+ let mut c2 = TcpStream::connect(p.listen).await.unwrap();
+ let r = tokio::time::timeout(Duration::from_secs(1), c2.read(&mut b)).await;
+ assert!(matches!(r, Ok(Ok(0)) | Ok(Err(_))));
+ p.sever(false);
+ let mut c3 = TcpStream::connect(p.listen).await.unwrap();
+ assert!(rt(&mut c3).await < Duration::from_millis(200));
+ p.stop();
+ }
+
+ #[test]
+ fn loss_adds_doubling_timeouts() {
+ assert_eq!(loss_delay(0.0, Duration::from_millis(200)), Duration::ZERO);
+ let total: Duration = (0..2000)
+ .map(|_| loss_delay(0.4, Duration::from_millis(200)))
+ .sum();
+ let mean = total / 2000;
+ // Expected about rto * (p + 2p^2 + 4p^3 ...) is a few hundred ms.
+ assert!(
+ mean > Duration::from_millis(100) && mean < Duration::from_millis(1500),
+ "{mean:?}"
+ );
+ }
+}