diff --git a/.github/workflows/nightly-dst.yml b/.github/workflows/nightly-dst.yml index 157271c..b39c881 100644 --- a/.github/workflows/nightly-dst.yml +++ b/.github/workflows/nightly-dst.yml @@ -9,6 +9,9 @@ on: description: "Seeds per scenario per topology" required: false default: "500" + start_seed: + description: "Starting seed (defaults to a new window for each run)" + required: false permissions: contents: read @@ -29,9 +32,23 @@ jobs: - uses: Swatinem/rust-cache@v2 - name: Run multi-seed DST campaign + env: + DST_SEEDS: ${{ inputs.seeds || '500' }} + DST_START_SEED: ${{ inputs.start_seed }} + DST_TOPOLOGY: ${{ matrix.topology }} run: | - SEEDS="${{ github.event.inputs.seeds || '500' }}" + mkdir -p dst-artifacts + start_seed="${DST_START_SEED:-$(((GITHUB_RUN_NUMBER - 1) * 500 + 1))}" cargo run --release -p rustfs-dst-cli -- run \ --scenario all \ - --topology "${{ matrix.topology }}" \ - --seeds "$SEEDS" + --topology "$DST_TOPOLOGY" \ + --start-seed "$start_seed" \ + --seeds "$DST_SEEDS" \ + --json > "dst-artifacts/$DST_TOPOLOGY.json" + + - name: Upload campaign report + if: always() + uses: actions/upload-artifact@v4 + with: + name: dst-campaign-${{ matrix.topology }} + path: dst-artifacts/*.json diff --git a/Cargo.toml b/Cargo.toml index 06f3e92..41cfd07 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -53,6 +53,7 @@ uuid = { version = "1", features = ["v4", "serde"] } [workspace.lints.rust] unsafe_code = "forbid" +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(madsim)"] } [workspace.lints.clippy] all = { level = "warn", priority = -1 } diff --git a/README.md b/README.md index 30a4061..29c135f 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ **RustFS DST** is the official Deterministic Simulation Testing (DST) framework, runtime trait abstraction layer, virtual fault simulator, and multi-seed correctness verifier for [RustFS](https://github.com/rustfs/rustfs). -Inspired by FoundationDB's Flow simulator, Tokio [`turmoil`](https://github.com/tokio-rs/turmoil), [`madsim`](https://github.com/madsim-rs/madsim), and [Antithesis](https://antithesis.com/), RustFS DST abstracts every source of non-determinism in a distributed storage engine behind clean Rust traits so complex multi-node failure modes execute deterministically inside a single process and reproduce bit-for-bit from a single `u64` seed. +Inspired by FoundationDB's Flow simulator, Tokio [`turmoil`](https://github.com/tokio-rs/turmoil), [`madsim`](https://github.com/madsim-rs/madsim), and [Antithesis](https://antithesis.com/), RustFS DST uses runtime traits to run a storage model against seeded faults. The scenarios execute `SimECStore` or the Turmoil quorum model. The [upstream adoption plan](docs/architecture.md) describes how to apply these runtime traits to RustFS itself. ## Core Architecture @@ -38,8 +38,8 @@ Inspired by FoundationDB's Flow simulator, Tokio [`turmoil`](https://github.com/ ## Verified Invariants -1. **Linearizability & Monotonic Read-After-Write**: Readers never observe a generation older than an acknowledged write or delete, even across degraded quorums (`W + R > N`). -2. **Bit-Exact Data Integrity**: Every readable object matches the exact SHA-256 of a submitted payload; silent bitrot up to the parity limit is detected and reconstructed transparently. +1. **Sequential S3 Read-After-Write Consistency**: GET responses must match a possible current version after acknowledged or indeterminate writes and deletes. LIST is checked against acknowledged live keys and their version metadata before repair. +2. **Bit-Exact Data Integrity**: Every readable object matches the exact SHA-256 of an acknowledged or indeterminate write for that version. Silent bitrot up to the parity limit is detected and reconstructed transparently. 3. **Crash Atomicity (Old-or-New-Never-Mixed)**: Abrupt power loss (`SimDiskIo::crash_and_reboot`) at any RustFS `xl.meta` commit window drops un-fsynced page-cache state without corrupting previously committed versions. 4. **Quorum Safety**: Writes fail closed on minority partitions and roll back partial drive writes cleanly; reply drops after remote apply are modeled as indeterminate outcomes. 5. **Distributed Lock Mutual Exclusion & Monotonic Fencing**: Monotonic-clock quorum leases remain immune to wall-clock skew jumps and issue strictly increasing fencing epochs. @@ -51,7 +51,7 @@ Inspired by FoundationDB's Flow simulator, Tokio [`turmoil`](https://github.com/ # Run the full unit and integration test suite cargo test --workspace -# Prove bit-for-bit determinism across every scenario +# Compare two passing reports for every scenario cargo run --release -p rustfs-dst-cli -- verify-determinism --topology 4x4 --seed 2026 # Run a 100-seed parallel DST campaign on 4x4 and 3x2 topologies diff --git a/crates/rustfs-dst-cli/src/main.rs b/crates/rustfs-dst-cli/src/main.rs index af7d878..8cb3c99 100644 --- a/crates/rustfs-dst-cli/src/main.rs +++ b/crates/rustfs-dst-cli/src/main.rs @@ -18,8 +18,11 @@ use clap::{Parser, Subcommand}; use rayon::prelude::*; use rustfs_dst_faults::probe::ProbeRegistry; +use rustfs_dst_sim::oracle::InvariantViolation; use rustfs_dst_sim::scenarios::{ScenarioKind, ScenarioReport, run_scenario}; use rustfs_dst_sim::topology::TopologyKind; +use std::ops::RangeInclusive; +use std::panic::{UnwindSafe, catch_unwind}; use std::process::ExitCode; #[derive(Parser, Debug)] @@ -62,7 +65,7 @@ enum Command { #[arg(long)] seed: u64, }, - /// Execute each scenario twice with the same seed and verify identical SHA-256 trace hashes. + /// Execute each scenario twice with the same seed and compare both passing reports. VerifyDeterminism { #[arg(long, default_value = "4x4")] topology: TopologyKind, @@ -82,6 +85,46 @@ fn parse_scenarios(raw: &str) -> Result, String> { .collect::, _>>() } +fn seed_range(start_seed: u64, count: u64) -> Result, &'static str> { + let last_offset = count.checked_sub(1).ok_or("--seeds must be at least 1")?; + let last_seed = start_seed + .checked_add(last_offset) + .ok_or("seed range exceeds u64::MAX")?; + Ok(start_seed..=last_seed) +} + +fn run_case( + scenario: ScenarioKind, + topology: TopologyKind, + seed: u64, + simulate: impl FnOnce(ScenarioKind, TopologyKind, u64) -> ScenarioReport + UnwindSafe, +) -> ScenarioReport { + match catch_unwind(|| simulate(scenario, topology, seed)) { + Ok(report) => report, + Err(panic) => { + let detail = panic + .downcast_ref::() + .map(String::as_str) + .or_else(|| panic.downcast_ref::<&str>().copied()) + .unwrap_or("simulation panicked"); + ScenarioReport { + scenario, + topology: topology.to_string(), + seed, + passed: false, + operations: 0, + trace_sha256: String::new(), + violations: vec![InvariantViolation { + invariant: "simulation_panic".to_string(), + key: "scenario".to_string(), + detail: detail.to_string(), + }], + probes: Default::default(), + } + } + } +} + fn main() -> ExitCode { let cli = Cli::parse(); match cli.command { @@ -97,7 +140,7 @@ fn main() -> ExitCode { topology, seed, } => { - let report = run_scenario(scenario, topology, seed); + let report = run_case(scenario, topology, seed, run_scenario); println!( "{}", serde_json::to_string_pretty(&report).expect("serialize ScenarioReport") @@ -111,13 +154,19 @@ fn main() -> ExitCode { Command::VerifyDeterminism { topology, seed } => { let mut ok = true; for scenario in ScenarioKind::ALL { - let r1 = run_scenario(scenario, topology, seed); - let r2 = run_scenario(scenario, topology, seed); - if !r1.passed || r1.trace_sha256 != r2.trace_sha256 { + let r1 = run_case(scenario, topology, seed, run_scenario); + let r2 = run_case(scenario, topology, seed, run_scenario); + if !r1.passed || r1 != r2 { eprintln!( - "FAIL determinism check: scenario={scenario} topo={topology} seed={seed} passed={} h1={} h2={}", - r1.passed, r1.trace_sha256, r2.trace_sha256 + "FAIL replay: scenario={scenario} topo={topology} seed={seed} passed_1={} passed_2={} trace_1={} trace_2={}", + r1.passed, r2.passed, r1.trace_sha256, r2.trace_sha256 ); + for (replay, report) in [(1, r1), (2, r2)] { + eprintln!( + " replay {replay} operations={} probes={:?} violations={:?}", + report.operations, report.probes, report.violations + ); + } ok = false; } else { println!( @@ -148,32 +197,53 @@ fn main() -> ExitCode { return ExitCode::FAILURE; } }; - let work: Vec<(ScenarioKind, u64)> = scenarios - .iter() - .flat_map(|&sc| (start_seed..start_seed + seeds).map(move |seed| (sc, seed))) - .collect(); + let range = match seed_range(start_seed, seeds) { + Ok(range) => range, + Err(err) => { + eprintln!("error: {err}"); + return ExitCode::FAILURE; + } + }; + let Some((seeds_per_scenario, total_runs)) = + usize::try_from(seeds).ok().and_then(|count| { + count + .checked_mul(scenarios.len()) + .map(|total| (count, total)) + }) + else { + eprintln!("error: campaign run count exceeds platform capacity"); + return ExitCode::FAILURE; + }; - let reports: Vec = work - .par_iter() - .map(|&(sc, seed)| run_scenario(sc, topology, seed)) + let reports: Vec<_> = (0..total_runs) + .into_par_iter() + .map(|index| { + let scenario = scenarios[index / seeds_per_scenario]; + let seed = range.start() + (index % seeds_per_scenario) as u64; + run_case(scenario, topology, seed, run_scenario) + }) .collect(); let aggregate_probes = ProbeRegistry::new(); let mut failures = Vec::new(); let mut total_ops = 0u64; - for rep in &reports { - total_ops += rep.operations; - aggregate_probes.merge_from(&rep.probes); - if !rep.passed { - failures.push(rep); + for report in reports { + total_ops += report.operations; + aggregate_probes.merge_from(&report.probes); + if !report.passed { + failures.push(report); } } if json { let summary = serde_json::json!({ "topology": topology.to_string(), - "total_runs": reports.len(), - "passed_runs": reports.len() - failures.len(), + "scenarios": scenarios.iter().map(|scenario| scenario.slug()).collect::>(), + "start_seed": range.start(), + "end_seed": range.end(), + "seeds_per_scenario": seeds, + "total_runs": total_runs, + "passed_runs": total_runs - failures.len(), "failed_runs": failures.len(), "total_operations": total_ops, "probes": aggregate_probes.snapshot(), @@ -185,9 +255,9 @@ fn main() -> ExitCode { ); } else { println!( - "RustFS DST Summary: topology={topology} runs={} passed={} failed={} ops={total_ops}", - reports.len(), - reports.len() - failures.len(), + "RustFS DST Summary: topology={topology} seeds={range:?} runs={} passed={} failed={} ops={total_ops}", + total_runs, + total_runs - failures.len(), failures.len(), ); let probes = aggregate_probes.snapshot(); @@ -227,3 +297,33 @@ fn main() -> ExitCode { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_empty_or_overflowing_campaigns_and_accepts_the_final_seed() { + assert!(seed_range(1, 0).is_err()); + assert!(seed_range(u64::MAX, 2).is_err()); + assert_eq!( + seed_range(u64::MAX, 1).unwrap().collect::>(), + vec![u64::MAX] + ); + } + + #[test] + fn turns_a_scenario_panic_into_a_reproducible_failure_report() { + let scenario = ScenarioKind::ErasureQuorum; + let topology = TopologyKind::FourByFour; + let report = run_case(scenario, topology, 55, |_, _, _| { + panic!("initial write failed"); + }); + assert!(!report.passed); + assert_eq!(report.scenario, scenario); + assert_eq!(report.topology, topology.to_string()); + assert_eq!(report.seed, 55); + assert_eq!(report.violations[0].invariant, "simulation_panic"); + assert_eq!(report.violations[0].detail, "initial write failed"); + } +} diff --git a/crates/rustfs-dst-faults/src/buggify.rs b/crates/rustfs-dst-faults/src/buggify.rs index 5880967..29a9772 100644 --- a/crates/rustfs-dst-faults/src/buggify.rs +++ b/crates/rustfs-dst-faults/src/buggify.rs @@ -28,13 +28,18 @@ use std::collections::BTreeMap; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Mutex}; +#[derive(Debug)] +struct SiteState { + active: bool, + rng: SimRng, + fired: u64, +} + #[derive(Debug)] struct BuggifyInner { seed: u64, activation_prob: f64, - rng: SimRng, - activated: BTreeMap, - fired_counts: BTreeMap, + sites: BTreeMap, } /// Deterministic two-stage fault injector modeled on FoundationDB's `BUGGIFY`. @@ -52,9 +57,7 @@ impl Buggify { inner: Arc::new(Mutex::new(BuggifyInner { seed: 0, activation_prob: 0.0, - rng: SimRng::from_seed(0), - activated: BTreeMap::new(), - fired_counts: BTreeMap::new(), + sites: BTreeMap::new(), })), } } @@ -66,9 +69,7 @@ impl Buggify { inner: Arc::new(Mutex::new(BuggifyInner { seed, activation_prob: activation_prob.clamp(0.0, 1.0), - rng: SimRng::from_seed(seed).fork("buggify"), - activated: BTreeMap::new(), - fired_counts: BTreeMap::new(), + sites: BTreeMap::new(), })), } } @@ -89,19 +90,27 @@ impl Buggify { return false; } let mut inner = self.inner.lock().expect("Buggify lock poisoned"); - let is_active = if let Some(&cached) = inner.activated.get(site) { - cached - } else { + if !inner.sites.contains_key(site) { let active = deterministic_activation(inner.seed, site, inner.activation_prob); - inner.activated.insert(site.to_string(), active); - active - }; - if !is_active { + // Per-site sub-stream: firing one site must not shift another site's + // sequence when a new buggify point is added. + let rng = SimRng::from_seed(inner.seed).fork(&format!("buggify:{site}")); + inner.sites.insert( + site.to_string(), + SiteState { + active, + rng, + fired: 0, + }, + ); + } + let state = inner.sites.get_mut(site).expect("buggify site"); + if !state.active { return false; } - let fired = inner.rng.gen_bool(fire_prob); + let fired = state.rng.gen_bool(fire_prob); if fired { - *inner.fired_counts.entry(site.to_string()).or_insert(0) += 1; + state.fired += 1; } fired } @@ -111,8 +120,11 @@ impl Buggify { self.inner .lock() .expect("Buggify lock poisoned") - .fired_counts - .clone() + .sites + .iter() + .filter(|(_, state)| state.fired > 0) + .map(|(site, state)| (site.clone(), state.fired)) + .collect() } } @@ -151,6 +163,22 @@ mod tests { assert_eq!(seq1, seq2); } + #[test] + fn buggify_sites_do_not_perturb_each_other() { + let exercised = Buggify::seeded(99, 1.0); + let control = Buggify::seeded(99, 1.0); + for _ in 0..20 { + let _ = exercised.should_fire_with_prob("ecstore.skip_tmp_cleanup", 0.5); + } + let from_exercised: Vec = (0..30) + .map(|_| exercised.should_fire_with_prob("ecstore.other_site", 0.4)) + .collect(); + let from_control: Vec = (0..30) + .map(|_| control.should_fire_with_prob("ecstore.other_site", 0.4)) + .collect(); + assert_eq!(from_exercised, from_control); + } + #[test] fn disabled_buggify_never_fires() { let b = Buggify::disabled(); diff --git a/crates/rustfs-dst-faults/src/probe.rs b/crates/rustfs-dst-faults/src/probe.rs index 12f7b05..97dfad0 100644 --- a/crates/rustfs-dst-faults/src/probe.rs +++ b/crates/rustfs-dst-faults/src/probe.rs @@ -176,6 +176,10 @@ impl ProbeRegistry { } fn append_jsonl(&self, path: &PathBuf, payload: &T) { + // Campaigns run seeds on a rayon pool. Each seed has its own registry, + // so the file append itself has to be process-wide or JSONL lines tear. + static APPEND_LOCK: Mutex<()> = Mutex::new(()); + let _guard = APPEND_LOCK.lock().expect("antithesis append lock poisoned"); if let Some(parent) = path.parent() { let _ = std::fs::create_dir_all(parent); } diff --git a/crates/rustfs-dst-runtime/src/clock.rs b/crates/rustfs-dst-runtime/src/clock.rs index 789d38a..b8a5134 100644 --- a/crates/rustfs-dst-runtime/src/clock.rs +++ b/crates/rustfs-dst-runtime/src/clock.rs @@ -298,19 +298,30 @@ impl Clock for SimClock { self.advance(duration); return; } - let notify = { + let delta_ns = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX); + let deadline = { + let inner = self.inner.lock().expect("SimClock lock poisoned"); + inner.now_ns.saturating_add(delta_ns) + }; + // Register interest before checking the deadline. `Notify::notified` + // drops a `notify_waiters` that arrives before the future is polled, + // which previously hung the sleeper if `advance` won that race. + let notify = Arc::new(Notify::new()); + let notified = notify.notified(); + tokio::pin!(notified); + notified.as_mut().enable(); + { let mut inner = self.inner.lock().expect("SimClock lock poisoned"); - let delta_ns = u64::try_from(duration.as_nanos()).unwrap_or(u64::MAX); - let deadline = inner.now_ns.saturating_add(delta_ns); - let notify = Arc::new(Notify::new()); + if inner.now_ns >= deadline { + return; + } inner .waiters .entry(deadline) .or_default() .push(Arc::clone(¬ify)); - notify - }; - notify.notified().await; + } + notified.await; } } diff --git a/crates/rustfs-dst-runtime/src/disk.rs b/crates/rustfs-dst-runtime/src/disk.rs index d09efb7..b73ce9f 100644 --- a/crates/rustfs-dst-runtime/src/disk.rs +++ b/crates/rustfs-dst-runtime/src/disk.rs @@ -26,7 +26,7 @@ use bytes::Bytes; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::{BTreeMap, BTreeSet}; -use std::path::{Path, PathBuf}; +use std::path::PathBuf; use std::sync::{Arc, Mutex}; use thiserror::Error; @@ -219,38 +219,41 @@ pub struct DiskFaultConfig { pub torn_write_prob: f64, } -#[derive(Clone, Debug, Default)] -struct FsImage { - dirs: BTreeSet, - files: BTreeMap, +/// Inode tracked separately from directory entries so file bytes and names +/// become durable at different barriers. +/// +/// - [`DiskIo::fsync_file`] copies `volatile_data` into `durable_data` and does +/// not publish the directory entry. +/// - [`DiskIo::fsync_dir`] publishes this directory's child names and makes the +/// directory reachable from the filesystem root. It does **not** flush dirty +/// file bytes. +#[derive(Clone, Debug)] +struct Inode { + is_dir: bool, + volatile_data: Bytes, + durable_data: Option, + volatile_children: BTreeMap, + durable_children: BTreeMap, } -impl FsImage { - fn new() -> Self { - let mut dirs = BTreeSet::new(); - dirs.insert(String::new()); +impl Inode { + fn file() -> Self { Self { - dirs, - files: BTreeMap::new(), + is_dir: false, + volatile_data: Bytes::new(), + durable_data: None, + volatile_children: BTreeMap::new(), + durable_children: BTreeMap::new(), } } - fn total_bytes(&self) -> u64 { - self.files.values().map(|b| b.len() as u64).sum() - } - - fn ensure_parents(&mut self, path: &str) { - let mut current = String::new(); - let parts: Vec<&str> = path.split('/').filter(|p| !p.is_empty()).collect(); - if parts.len() <= 1 { - return; - } - for part in &parts[..parts.len() - 1] { - if !current.is_empty() { - current.push('/'); - } - current.push_str(part); - self.dirs.insert(current.clone()); + fn dir() -> Self { + Self { + is_dir: true, + volatile_data: Bytes::new(), + durable_data: None, + volatile_children: BTreeMap::new(), + durable_children: BTreeMap::new(), } } } @@ -258,24 +261,205 @@ impl FsImage { #[derive(Debug)] struct SimDiskInner { id: String, - /// Volatile OS page cache visible to live reads/writes. - volatile: FsImage, - /// Durable platter/NVMe image populated only via `fsync_file` / `fsync_dir`. - durable: FsImage, + inodes: BTreeMap, + next_inode: u64, + root: u64, faults: DiskFaultConfig, /// Total power-loss crashes simulated on this drive. crash_count: u64, } +impl SimDiskInner { + fn empty(id: String) -> Self { + let root = 1; + let mut inodes = BTreeMap::new(); + inodes.insert(root, Inode::dir()); + Self { + id, + inodes, + next_inode: 2, + root, + faults: DiskFaultConfig::default(), + crash_count: 0, + } + } + + fn alloc(&mut self, is_dir: bool) -> u64 { + let id = self.next_inode; + self.next_inode += 1; + self.inodes + .insert(id, if is_dir { Inode::dir() } else { Inode::file() }); + id + } + + fn children(&self, id: u64, durable: bool) -> Option<&BTreeMap> { + let inode = self.inodes.get(&id)?; + Some(if durable { + &inode.durable_children + } else { + &inode.volatile_children + }) + } + + fn lookup(&self, path: &str, durable: bool) -> Option { + let mut id = self.root; + if path.is_empty() { + return Some(id); + } + for part in path.split('/') { + id = *self.children(id, durable)?.get(part)?; + } + Some(id) + } + + fn ensure_online(&self) -> Result<(), DiskError> { + if self.faults.offline { + Err(DiskError::Offline) + } else { + Ok(()) + } + } + + /// Create missing volatile directories along `path` and return the directory inode. + fn ensure_volatile_dir(&mut self, path: &str) -> Result { + let mut id = self.root; + if path.is_empty() { + return Ok(id); + } + for part in path.split('/') { + if let Some(child) = self + .inodes + .get(&id) + .and_then(|inode| inode.volatile_children.get(part)) + .copied() + { + if !self.inodes.get(&child).is_some_and(|inode| inode.is_dir) { + return Err(DiskError::AlreadyExists(path.to_string())); + } + id = child; + } else { + let child = self.alloc(true); + self.inodes + .get_mut(&id) + .expect("parent inode") + .volatile_children + .insert(part.to_string(), child); + id = child; + } + } + Ok(id) + } + + /// Link each path component into its parent's durable directory so a nested + /// `fsync_dir` stays reachable after power loss. Sibling entries of those + /// parents are left untouched — only this chain is published. + fn publish_volatile_path(&mut self, path: &str) { + let mut parent = self.root; + for part in path.split('/').filter(|part| !part.is_empty()) { + let Some(child) = self + .inodes + .get(&parent) + .and_then(|inode| inode.volatile_children.get(part)) + .copied() + else { + return; + }; + self.inodes + .get_mut(&parent) + .expect("parent inode") + .durable_children + .insert(part.to_string(), child); + parent = child; + } + } + + fn total_volatile_bytes(&self) -> u64 { + self.inodes + .values() + .filter(|inode| !inode.is_dir) + .map(|inode| inode.volatile_data.len() as u64) + .sum() + } + + fn crash_and_reboot(&mut self) { + for inode in self.inodes.values_mut() { + inode.volatile_children = inode.durable_children.clone(); + if !inode.is_dir { + inode.volatile_data = inode.durable_data.clone().unwrap_or_else(Bytes::new); + } + } + self.gc_unreachable(); + self.crash_count += 1; + } + + fn gc_unreachable(&mut self) { + let mut reachable = BTreeSet::new(); + let mut stack = vec![self.root]; + while let Some(id) = stack.pop() { + if !reachable.insert(id) { + continue; + } + if let Some(inode) = self.inodes.get(&id) { + stack.extend(inode.volatile_children.values().copied()); + } + } + self.inodes.retain(|id, _| reachable.contains(id)); + } + + fn walk( + &self, + id: u64, + prefix: &str, + durable: bool, + files: &mut Vec<(String, Bytes)>, + dirs: &mut Vec, + ) { + if let Some(inode) = self.inodes.get(&id) + && inode.is_dir + { + dirs.push(prefix.to_string()); + } + let Some(children) = self.children(id, durable) else { + return; + }; + for (name, child) in children { + let path = if prefix.is_empty() { + name.clone() + } else { + format!("{prefix}/{name}") + }; + let Some(inode) = self.inodes.get(child) else { + continue; + }; + if inode.is_dir { + self.walk(*child, &path, durable, files, dirs); + } else { + let data = if durable { + inode.durable_data.clone().unwrap_or_else(Bytes::new) + } else { + inode.volatile_data.clone() + }; + files.push((path, data)); + } + } + } +} + +fn split_parent(path: &str) -> (&str, &str) { + match path.rfind('/') { + Some(idx) => (&path[..idx], &path[idx + 1..]), + None => ("", path), + } +} + /// Deterministic crash-consistent virtual disk simulator. /// /// Models: -/// - **Volatile vs durable split**: writes land in `volatile` and only reach -/// `durable` when `fsync_file` is called; directory entries (renames, -/// unlinks, mkdirs) only reach `durable` when `fsync_dir` is called on the -/// parent directory. -/// - **Power loss ([`SimDiskIo::crash_and_reboot`])**: discards all un-fsynced -/// volatile buffers and restores `volatile = durable`. +/// - **Inode bytes vs directory entries**: `fsync_file` persists file bytes +/// only. `fsync_dir` persists that directory's names and makes the directory +/// reachable from the root. It does not flush dirty file data. +/// - **Power loss ([`SimDiskIo::crash_and_reboot`])**: restores every inode +/// from its durable bytes and durable directory links. /// - **Bitrot ([`SimDiskIo::inject_bitrot`])**: flips a deterministic byte in a /// persisted file on both layers to test checksum detection & erasure healing. /// - **Capacity, EIO, torn writes, and offline drives**. @@ -288,13 +472,7 @@ pub struct SimDiskIo { impl SimDiskIo { pub fn new(id: impl Into, rng: SimRng) -> Self { Self { - inner: Arc::new(Mutex::new(SimDiskInner { - id: id.into(), - volatile: FsImage::new(), - durable: FsImage::new(), - faults: DiskFaultConfig::default(), - crash_count: 0, - })), + inner: Arc::new(Mutex::new(SimDiskInner::empty(id.into()))), rng, } } @@ -329,61 +507,84 @@ impl SimDiskIo { /// directory mutation is lost, and the OS boots from the durable image. pub fn crash_and_reboot(&self) { let mut inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - inner.volatile = inner.durable.clone(); - inner.crash_count += 1; + inner.crash_and_reboot(); } /// Deterministically corrupt one byte of `path` on both volatile and durable - /// layers (silent bitrot). Returns `true` if the file existed and was flipped. + /// layers when they still have the same length (silent bitrot). Returns + /// `true` if the file existed and was flipped. pub fn inject_bitrot(&self, path: &str) -> bool { let Ok(norm) = normalize_path(path) else { return false; }; let mut inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - let Some(existing) = inner.volatile.files.get(&norm).cloned() else { + let Some(id) = inner.lookup(&norm, false) else { return false; }; - if existing.is_empty() { + let Some(existing) = inner.inodes.get(&id).and_then(|inode| { + if inode.is_dir || inode.volatile_data.is_empty() { + None + } else { + Some(inode.volatile_data.clone()) + } + }) else { return false; - } + }; let idx = self.rng.gen_range_usize(existing.len()); let mut corrupted = existing.to_vec(); corrupted[idx] ^= 0xFF; let bytes = Bytes::from(corrupted); - inner.volatile.files.insert(norm.clone(), bytes.clone()); - if inner.durable.files.contains_key(&norm) { - inner.durable.files.insert(norm, bytes); + let inode = inner.inodes.get_mut(&id).expect("inode"); + if inode + .durable_data + .as_ref() + .is_some_and(|durable| durable.len() == existing.len()) + { + let mut durable = inode.durable_data.as_ref().expect("durable bytes").to_vec(); + durable[idx] ^= 0xFF; + inode.durable_data = Some(Bytes::from(durable)); } + inode.volatile_data = bytes; true } /// Wipe the entire drive (simulating drive replacement with a fresh empty disk). pub fn wipe_drive(&self) { let mut inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - inner.volatile = FsImage::new(); - inner.durable = FsImage::new(); + let id = inner.id.clone(); + let faults = inner.faults.clone(); + let crash_count = inner.crash_count; + *inner = SimDiskInner::empty(id); + inner.faults = faults; + inner.crash_count = crash_count; } /// Return all file paths currently present in the volatile image. pub fn all_files(&self) -> Vec { let inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - inner.volatile.files.keys().cloned().collect() + let mut files = Vec::new(); + let mut dirs = Vec::new(); + inner.walk(inner.root, "", false, &mut files, &mut dirs); + files.into_iter().map(|(path, _)| path).collect() } - /// Compute a deterministic SHA-256 digest of the entire durable image. + /// Compute a deterministic SHA-256 digest of the durable namespace. pub fn durable_state_hash(&self) -> [u8; 32] { let inner = self.inner.lock().expect("SimDiskIo lock poisoned"); + let mut files = Vec::new(); + let mut dirs = Vec::new(); + inner.walk(inner.root, "", true, &mut files, &mut dirs); let mut hasher = Sha256::new(); - for dir in &inner.durable.dirs { + for dir in dirs { hasher.update(b"D:"); hasher.update(dir.as_bytes()); hasher.update(b"\n"); } - for (path, data) in &inner.durable.files { + for (path, data) in files { hasher.update(b"F:"); hasher.update(path.as_bytes()); hasher.update(b"="); - hasher.update(data); + hasher.update(&data); hasher.update(b"\n"); } hasher.finalize().into() @@ -409,32 +610,13 @@ fn normalize_path(raw: &str) -> Result { Ok(parts.join("/")) } -fn parent_dir(norm: &str) -> String { - match norm.rsplit_once('/') { - Some((parent, _)) => parent.to_string(), - None => String::new(), - } -} - #[async_trait] impl DiskIo for SimDiskIo { async fn create_dir_all(&self, path: &str) -> Result<(), DiskError> { let norm = normalize_path(path)?; let mut inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - if inner.faults.offline { - return Err(DiskError::Offline); - } - if norm.is_empty() { - return Ok(()); - } - let mut acc = String::new(); - for part in norm.split('/') { - if !acc.is_empty() { - acc.push('/'); - } - acc.push_str(part); - inner.volatile.dirs.insert(acc.clone()); - } + inner.ensure_online()?; + inner.ensure_volatile_dir(&norm)?; Ok(()) } @@ -444,253 +626,233 @@ impl DiskIo for SimDiskIo { return Err(DiskError::InvalidPath(path.to_string())); } let mut inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - if inner.faults.offline { - return Err(DiskError::Offline); - } + inner.ensure_online()?; if self.rng.gen_bool(inner.faults.write_error_prob) { return Err(DiskError::Io("injected write failure".to_string())); } + let (parent_path, name) = split_parent(&norm); + let parent_id = inner.ensure_volatile_dir(parent_path)?; + let existing = inner + .inodes + .get(&parent_id) + .and_then(|inode| inode.volatile_children.get(name)) + .copied(); + if let Some(id) = existing + && inner.inodes.get(&id).is_some_and(|inode| inode.is_dir) + { + return Err(DiskError::AlreadyExists(path.to_string())); + } if let Some(cap) = inner.faults.capacity_bytes { - let old_len = inner - .volatile - .files - .get(&norm) - .map(|b| b.len() as u64) + let old_len = existing + .and_then(|id| inner.inodes.get(&id)) + .map(|inode| inode.volatile_data.len() as u64) .unwrap_or(0); - let projected = inner.volatile.total_bytes() - old_len + data.len() as u64; + let projected = inner.total_volatile_bytes() - old_len + data.len() as u64; if projected > cap { return Err(DiskError::NoSpace); } } - inner.volatile.ensure_parents(&norm); - if self.rng.gen_bool(inner.faults.torn_write_prob) && data.len() > 1 { + let torn = self.rng.gen_bool(inner.faults.torn_write_prob) && data.len() > 1; + let stored = if torn { let cut = 1 + self.rng.gen_range_usize(data.len() - 1); - inner.volatile.files.insert(norm, data.slice(..cut)); + data.slice(..cut) + } else { + data + }; + if let Some(id) = existing { + inner.inodes.get_mut(&id).expect("file inode").volatile_data = stored; + } else { + let id = inner.alloc(false); + inner.inodes.get_mut(&id).expect("new file").volatile_data = stored; + inner + .inodes + .get_mut(&parent_id) + .expect("parent dir") + .volatile_children + .insert(name.to_string(), id); + } + if torn { return Err(DiskError::Io("injected torn write".to_string())); } - inner.volatile.files.insert(norm, data); Ok(()) } async fn read_file(&self, path: &str) -> Result { let norm = normalize_path(path)?; let inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - if inner.faults.offline { - return Err(DiskError::Offline); - } + inner.ensure_online()?; if self.rng.gen_bool(inner.faults.read_error_prob) { return Err(DiskError::Io("injected read failure".to_string())); } - inner - .volatile - .files - .get(&norm) - .cloned() - .ok_or_else(|| DiskError::NotFound(path.to_string())) + let id = inner + .lookup(&norm, false) + .ok_or_else(|| DiskError::NotFound(path.to_string()))?; + let inode = inner.inodes.get(&id).expect("inode"); + if inode.is_dir { + return Err(DiskError::InvalidPath(path.to_string())); + } + Ok(inode.volatile_data.clone()) } async fn rename(&self, from: &str, to: &str) -> Result<(), DiskError> { let src = normalize_path(from)?; let dst = normalize_path(to)?; - let mut inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - if inner.faults.offline { - return Err(DiskError::Offline); + if src.is_empty() || dst.is_empty() { + return Err(DiskError::InvalidPath(from.to_string())); } + let mut inner = self.inner.lock().expect("SimDiskIo lock poisoned"); + inner.ensure_online()?; if self.rng.gen_bool(inner.faults.write_error_prob) { return Err(DiskError::Io("injected rename failure".to_string())); } - if let Some(bytes) = inner.volatile.files.remove(&src) { - inner.volatile.ensure_parents(&dst); - inner.volatile.files.insert(dst, bytes); - return Ok(()); - } - if inner.volatile.dirs.contains(&src) { - let prefix = format!("{src}/"); - let moving_dirs: Vec = inner - .volatile - .dirs - .iter() - .filter(|d| *d == &src || d.starts_with(&prefix)) - .cloned() - .collect(); - let moving_files: Vec<(String, Bytes)> = inner - .volatile - .files - .iter() - .filter(|(k, _)| k.starts_with(&prefix)) - .map(|(k, v)| (k.clone(), v.clone())) - .collect(); - - for d in &moving_dirs { - inner.volatile.dirs.remove(d); - } - for (k, _) in &moving_files { - inner.volatile.files.remove(k); - } - - inner.volatile.ensure_parents(&dst); - for d in moving_dirs { - let suffix = d.strip_prefix(&src).unwrap_or(""); - inner.volatile.dirs.insert(format!("{dst}{suffix}")); - } - for (k, v) in moving_files { - let suffix = k.strip_prefix(&src).unwrap_or(""); - inner.volatile.files.insert(format!("{dst}{suffix}"), v); - } - return Ok(()); - } - Err(DiskError::NotFound(from.to_string())) + let (src_parent, src_name) = split_parent(&src); + let src_parent_id = inner + .lookup(src_parent, false) + .ok_or_else(|| DiskError::NotFound(from.to_string()))?; + let src_id = inner + .inodes + .get(&src_parent_id) + .and_then(|inode| inode.volatile_children.get(src_name)) + .copied() + .ok_or_else(|| DiskError::NotFound(from.to_string()))?; + let (dst_parent, dst_name) = split_parent(&dst); + let dst_parent_id = inner.ensure_volatile_dir(dst_parent)?; + inner + .inodes + .get_mut(&src_parent_id) + .expect("src parent") + .volatile_children + .remove(src_name); + inner + .inodes + .get_mut(&dst_parent_id) + .expect("dst parent") + .volatile_children + .insert(dst_name.to_string(), src_id); + Ok(()) } async fn remove_file(&self, path: &str) -> Result<(), DiskError> { let norm = normalize_path(path)?; let mut inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - if inner.faults.offline { - return Err(DiskError::Offline); + inner.ensure_online()?; + let (parent, name) = split_parent(&norm); + let parent_id = inner + .lookup(parent, false) + .ok_or_else(|| DiskError::NotFound(path.to_string()))?; + let child = inner + .inodes + .get(&parent_id) + .and_then(|inode| inode.volatile_children.get(name)) + .copied() + .ok_or_else(|| DiskError::NotFound(path.to_string()))?; + if inner.inodes.get(&child).is_some_and(|inode| inode.is_dir) { + return Err(DiskError::InvalidPath(path.to_string())); } inner - .volatile - .files - .remove(&norm) - .map(|_| ()) - .ok_or_else(|| DiskError::NotFound(path.to_string())) + .inodes + .get_mut(&parent_id) + .expect("parent") + .volatile_children + .remove(name); + Ok(()) } async fn remove_dir_all(&self, path: &str) -> Result<(), DiskError> { let norm = normalize_path(path)?; let mut inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - if inner.faults.offline { - return Err(DiskError::Offline); - } + inner.ensure_online()?; if norm.is_empty() { - inner.volatile = FsImage::new(); + let root = inner.root; + if let Some(inode) = inner.inodes.get_mut(&root) { + inode.volatile_children.clear(); + } return Ok(()); } - let prefix = format!("{norm}/"); + let (parent, name) = split_parent(&norm); + let Some(parent_id) = inner.lookup(parent, false) else { + return Ok(()); + }; inner - .volatile - .dirs - .retain(|d| d != &norm && !d.starts_with(&prefix)); - inner.volatile.files.retain(|k, _| !k.starts_with(&prefix)); + .inodes + .get_mut(&parent_id) + .expect("parent") + .volatile_children + .remove(name); Ok(()) } async fn fsync_file(&self, path: &str) -> Result<(), DiskError> { let norm = normalize_path(path)?; let mut inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - if inner.faults.offline { - return Err(DiskError::Offline); - } - let data = inner - .volatile - .files - .get(&norm) - .cloned() + inner.ensure_online()?; + let id = inner + .lookup(&norm, false) .ok_or_else(|| DiskError::NotFound(path.to_string()))?; - inner.durable.ensure_parents(&norm); - inner.durable.files.insert(norm, data); + let inode = inner.inodes.get_mut(&id).expect("inode"); + if inode.is_dir { + return Err(DiskError::InvalidPath(path.to_string())); + } + inode.durable_data = Some(inode.volatile_data.clone()); Ok(()) } async fn fsync_dir(&self, path: &str) -> Result<(), DiskError> { let norm = normalize_path(path)?; let mut inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - if inner.faults.offline { - return Err(DiskError::Offline); - } - if !inner.volatile.dirs.contains(&norm) { - return Err(DiskError::NotFound(path.to_string())); - } - // Persist the directory and synchronize direct children (entries created, - // renamed, or unlinked inside `norm`). - let mut acc = String::new(); - for part in norm.split('/').filter(|p| !p.is_empty()) { - if !acc.is_empty() { - acc.push('/'); - } - acc.push_str(part); - inner.durable.dirs.insert(acc.clone()); - } - - let direct_volatile_files: BTreeMap = inner - .volatile - .files - .iter() - .filter(|(k, _)| parent_dir(k) == norm) - .map(|(k, v)| (k.clone(), v.clone())) - .collect(); - inner.durable.files.retain(|k, _| parent_dir(k) != norm); - for (k, v) in direct_volatile_files { - inner.durable.files.insert(k, v); - } - - let direct_volatile_dirs: BTreeSet = inner - .volatile - .dirs - .iter() - .filter(|d| !d.is_empty() && parent_dir(d) == norm) - .cloned() - .collect(); - inner - .durable - .dirs - .retain(|d| d.is_empty() || parent_dir(d) != norm || direct_volatile_dirs.contains(d)); - for d in direct_volatile_dirs { - inner.durable.dirs.insert(d); + inner.ensure_online()?; + let id = inner + .lookup(&norm, false) + .ok_or_else(|| DiskError::NotFound(path.to_string()))?; + if !inner.inodes.get(&id).is_some_and(|inode| inode.is_dir) { + return Err(DiskError::InvalidPath(path.to_string())); } + if !norm.is_empty() { + inner.publish_volatile_path(&norm); + } + let children = inner + .inodes + .get(&id) + .expect("dir") + .volatile_children + .clone(); + inner.inodes.get_mut(&id).expect("dir").durable_children = children; Ok(()) } async fn list_dir(&self, path: &str) -> Result, DiskError> { let norm = normalize_path(path)?; let inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - if inner.faults.offline { - return Err(DiskError::Offline); - } - if !inner.volatile.dirs.contains(&norm) { - return Err(DiskError::NotFound(path.to_string())); - } - let mut entries = BTreeSet::new(); - for f in inner.volatile.files.keys() { - if parent_dir(f) == norm { - let name = Path::new(f) - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or(f); - entries.insert(name.to_string()); - } - } - for d in &inner.volatile.dirs { - if !d.is_empty() && parent_dir(d) == norm { - let name = Path::new(d) - .file_name() - .and_then(|s| s.to_str()) - .unwrap_or(d); - entries.insert(name.to_string()); - } + inner.ensure_online()?; + let id = inner + .lookup(&norm, false) + .ok_or_else(|| DiskError::NotFound(path.to_string()))?; + let inode = inner.inodes.get(&id).expect("inode"); + if !inode.is_dir { + return Err(DiskError::InvalidPath(path.to_string())); } - Ok(entries.into_iter().collect()) + Ok(inode.volatile_children.keys().cloned().collect()) } async fn stat(&self, path: &str) -> Result { let norm = normalize_path(path)?; let inner = self.inner.lock().expect("SimDiskIo lock poisoned"); - if inner.faults.offline { - return Err(DiskError::Offline); - } - if let Some(bytes) = inner.volatile.files.get(&norm) { - return Ok(FileStat { - size: bytes.len() as u64, - is_dir: false, - }); - } - if inner.volatile.dirs.contains(&norm) { - return Ok(FileStat { + inner.ensure_online()?; + let id = inner + .lookup(&norm, false) + .ok_or_else(|| DiskError::NotFound(path.to_string()))?; + let inode = inner.inodes.get(&id).expect("inode"); + if inode.is_dir { + Ok(FileStat { size: 0, is_dir: true, - }); + }) + } else { + Ok(FileStat { + size: inode.volatile_data.len() as u64, + is_dir: false, + }) } - Err(DiskError::NotFound(path.to_string())) } } @@ -738,4 +900,65 @@ mod tests { assert_ne!(b1, payload); assert_eq!(b1, b2); } + + #[tokio::test] + async fn fsync_file_without_directory_sync_does_not_survive_crash() { + let disk = SimDiskIo::new("d1", SimRng::from_seed(3)); + disk.create_dir_all("bucket/obj").await.unwrap(); + disk.write_file("bucket/obj/xl.meta", Bytes::from_static(b"v1")) + .await + .unwrap(); + disk.fsync_file("bucket/obj/xl.meta").await.unwrap(); + disk.crash_and_reboot(); + assert!(matches!( + disk.read_file("bucket/obj/xl.meta").await, + Err(DiskError::NotFound(_)) + )); + } + + #[tokio::test] + async fn fsync_dir_does_not_persist_dirty_file_bytes() { + let disk = SimDiskIo::new("d1", SimRng::from_seed(4)); + disk.create_dir_all("bucket/obj").await.unwrap(); + disk.write_file("bucket/obj/xl.meta", Bytes::from_static(b"v1")) + .await + .unwrap(); + disk.fsync_file("bucket/obj/xl.meta").await.unwrap(); + disk.fsync_dir("bucket/obj").await.unwrap(); + + disk.write_file("bucket/obj/xl.meta", Bytes::from_static(b"v2-dirty")) + .await + .unwrap(); + disk.fsync_dir("bucket/obj").await.unwrap(); + disk.crash_and_reboot(); + + let after = disk.read_file("bucket/obj/xl.meta").await.unwrap(); + assert_eq!(after, Bytes::from_static(b"v1")); + } + + #[tokio::test] + async fn rename_without_dir_fsync_keeps_the_old_directory_entry() { + let disk = SimDiskIo::new("d1", SimRng::from_seed(5)); + disk.create_dir_all("bucket/obj").await.unwrap(); + disk.write_file("bucket/obj/xl.meta", Bytes::from_static(b"v1")) + .await + .unwrap(); + disk.fsync_file("bucket/obj/xl.meta").await.unwrap(); + disk.fsync_dir("bucket/obj").await.unwrap(); + + disk.rename("bucket/obj/xl.meta", "bucket/obj/xl.meta.next") + .await + .unwrap(); + disk.fsync_file("bucket/obj/xl.meta.next").await.unwrap(); + disk.crash_and_reboot(); + + assert_eq!( + disk.read_file("bucket/obj/xl.meta").await.unwrap(), + Bytes::from_static(b"v1") + ); + assert!(matches!( + disk.read_file("bucket/obj/xl.meta.next").await, + Err(DiskError::NotFound(_)) + )); + } } diff --git a/crates/rustfs-dst-runtime/src/madsim_compat.rs b/crates/rustfs-dst-runtime/src/madsim_compat.rs index 949e49a..484a487 100644 --- a/crates/rustfs-dst-runtime/src/madsim_compat.rs +++ b/crates/rustfs-dst-runtime/src/madsim_compat.rs @@ -27,12 +27,25 @@ //! replacement for `tokio`, `tonic`, and `rand` when testing unmodified //! gRPC/Tonic servers in `rustfs/rustfs`. -/// Returns `true` when compiled under `madsim` (`RUSTFLAGS="--cfg madsim"`). +/// Returns `true` when this crate is compiled with `RUSTFLAGS="--cfg madsim"`. +/// +/// The `madsim-compat` feature only marks the hook. It does not activate +/// madsim; Cargo patches and `--cfg madsim` do. pub const fn is_madsim_active() -> bool { - cfg!(feature = "madsim-compat") + cfg!(madsim) } /// Yield execution cleanly across standard Tokio, Turmoil, and Madsim runtimes. pub async fn yield_now() { tokio::task::yield_now().await; } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn default_build_does_not_report_madsim_active() { + assert!(!is_madsim_active()); + } +} diff --git a/crates/rustfs-dst-sim/src/ecstore.rs b/crates/rustfs-dst-sim/src/ecstore.rs index fb4eb9c..d90174b 100644 --- a/crates/rustfs-dst-sim/src/ecstore.rs +++ b/crates/rustfs-dst-sim/src/ecstore.rs @@ -51,6 +51,7 @@ const METHOD_DISK_HEAL_WRITE: &str = "rustfs.disk.HealWrite"; const METHOD_DISK_STAGE_PART: &str = "rustfs.disk.StagePart"; const METHOD_DISK_READ_PART: &str = "rustfs.disk.ReadPart"; const METHOD_DISK_CLEANUP_MP: &str = "rustfs.disk.CleanupMultipart"; +const METHOD_DISK_CLEANUP_PART: &str = "rustfs.disk.CleanupPart"; const METHOD_DISK_SWEEP_TMP: &str = "rustfs.disk.SweepTmp"; type ShardReadEntry = (usize, XlMeta, Option>); @@ -178,6 +179,22 @@ struct StagePartReq { drive_idx: usize, upload_id: String, part_number: u32, + attempt_id: String, + part_etag: String, + shard_sha256: String, + shard_bytes: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct PartOnDiskMeta { + part_etag: String, + shard_sha256: String, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct ReadPartResp { + part_etag: String, + shard_sha256: String, shard_bytes: Vec, } @@ -186,6 +203,7 @@ struct ReadPartReq { drive_idx: usize, upload_id: String, part_number: u32, + attempt_id: String, } #[derive(Clone, Debug, Serialize, Deserialize)] @@ -194,6 +212,18 @@ struct CleanupMultipartReq { upload_id: String, } +#[derive(Clone, Debug, Serialize, Deserialize)] +struct CleanupPartReq { + drive_idx: usize, + upload_id: String, + part_number: u32, + attempt_id: String, +} + +fn multipart_part_path(upload_id: &str, part_number: u32, attempt_id: &str) -> String { + format!(".rustfs.sys/multipart/{upload_id}/part.{part_number}.{attempt_id}") +} + #[derive(Clone, Debug, Serialize, Deserialize)] struct SweepTmpReq { drive_idx: usize, @@ -500,7 +530,14 @@ impl NodeRpcServer { async fn handle_stage_part(&self, req: StagePartReq) -> Result { let disk = self.disk(req.drive_idx)?; let dir = format!(".rustfs.sys/multipart/{}", req.upload_id); - let path = format!("{dir}/part.{}", req.part_number); + let path = multipart_part_path(&req.upload_id, req.part_number, &req.attempt_id); + let meta_path = format!("{path}.meta"); + let meta = PartOnDiskMeta { + part_etag: req.part_etag, + shard_sha256: req.shard_sha256, + }; + let meta_bytes = + Bytes::from(serde_json::to_vec(&meta).map_err(|e| NetError::Io(e.to_string()))?); disk.create_dir_all(&dir) .await .map_err(|e| NetError::Io(e.to_string()))?; @@ -510,6 +547,12 @@ impl NodeRpcServer { disk.fsync_file(&path) .await .map_err(|e| NetError::Io(e.to_string()))?; + disk.write_file(&meta_path, meta_bytes) + .await + .map_err(|e| NetError::Io(e.to_string()))?; + disk.fsync_file(&meta_path) + .await + .map_err(|e| NetError::Io(e.to_string()))?; disk.fsync_dir(&dir) .await .map_err(|e| NetError::Io(e.to_string()))?; @@ -518,15 +561,39 @@ impl NodeRpcServer { async fn handle_read_part(&self, req: ReadPartReq) -> Result { let disk = self.disk(req.drive_idx)?; - let path = format!( - ".rustfs.sys/multipart/{}/part.{}", - req.upload_id, req.part_number - ); + let path = multipart_part_path(&req.upload_id, req.part_number, &req.attempt_id); + let meta_path = format!("{path}.meta"); + let meta_bytes = disk + .read_file(&meta_path) + .await + .map_err(|e| NetError::Io(e.to_string()))?; + let meta: PartOnDiskMeta = serde_json::from_slice(&meta_bytes) + .map_err(|e| NetError::Io(format!("corrupt part meta: {e}")))?; let data = disk .read_file(&path) .await .map_err(|e| NetError::Io(e.to_string()))?; - Ok(RpcFrame::new(METHOD_DISK_READ_PART, data)) + if sha256_hex(&data) != meta.shard_sha256 { + return Err(NetError::Io("staged part checksum mismatch".to_string())); + } + let resp = ReadPartResp { + part_etag: meta.part_etag, + shard_sha256: meta.shard_sha256, + shard_bytes: data.to_vec(), + }; + let payload = serde_json::to_vec(&resp).map_err(|e| NetError::Io(e.to_string()))?; + Ok(RpcFrame::new(METHOD_DISK_READ_PART, payload)) + } + + async fn handle_cleanup_part(&self, req: CleanupPartReq) -> Result { + let disk = self.disk(req.drive_idx)?; + let dir = format!(".rustfs.sys/multipart/{}", req.upload_id); + let path = multipart_part_path(&req.upload_id, req.part_number, &req.attempt_id); + let meta_path = format!("{path}.meta"); + let _ = disk.remove_file(&path).await; + let _ = disk.remove_file(&meta_path).await; + let _ = disk.fsync_dir(&dir).await; + Ok(RpcFrame::new(METHOD_DISK_CLEANUP_PART, Vec::new())) } async fn handle_cleanup_mp(&self, req: CleanupMultipartReq) -> Result { @@ -596,6 +663,11 @@ impl RpcHandler for NodeRpcServer { .map_err(|e| NetError::Io(e.to_string()))?; self.handle_cleanup_mp(req).await } + METHOD_DISK_CLEANUP_PART => { + let req: CleanupPartReq = serde_json::from_slice(&request.payload) + .map_err(|e| NetError::Io(e.to_string()))?; + self.handle_cleanup_part(req).await + } METHOD_DISK_SWEEP_TMP => { let req: SweepTmpReq = serde_json::from_slice(&request.payload) .map_err(|e| NetError::Io(e.to_string()))?; @@ -611,7 +683,14 @@ impl RpcHandler for NodeRpcServer { struct MultipartSession { bucket: String, key: String, - parts: BTreeMap, // part_number -> orig_len + parts: BTreeMap, +} + +#[derive(Clone, Debug)] +struct MultipartPart { + attempt_id: String, + etag: String, + original_len: usize, } /// A simulated multi-node RustFS cluster wired over deterministic runtime traits. @@ -836,9 +915,9 @@ impl SimCluster { let (responded, found) = self.read_all_metas(via_node, bucket, key, false).await; if responded < self.topology.read_quorum { lock_client.release(&lease).await; - return Err(StoreError::WriteQuorumNotMet { - acked: responded, - required: self.topology.write_quorum, + return Err(StoreError::ReadQuorumNotMet { + healthy: responded, + required: self.topology.read_quorum, }); } @@ -1019,50 +1098,61 @@ impl SimCluster { by_gen.entry(entry.1.generation).or_default().push(entry); } - // Inspect generations from highest to lowest. - // If `entries.len() + unreachable < data_shards`, that generation could - // NEVER have achieved write quorum (W >= data_shards) and is mathematically - // guaranteed to be an uncommitted orphan; otherwise it may be committed and - // we MUST either serve it or fail closed with ReadQuorumNotMet (never stale!). + // Newest generation first. RustFS accepts a delete marker only at write + // quorum (`default_write_quorum` / early-stop), which is data+1 when + // data == parity. An object version is readable from any `data_shards` + // healthy shards, including a write that reached exactly that many and + // then failed the higher write quorum. A newer version that cannot have + // been committed and cannot be reconstructed must not hide the older one. for (_gen, top_entries) in by_gen.into_iter().rev() { let canonical = &top_entries[0].1; - let max_possible = top_entries.len() + unreachable; - if max_possible < self.topology.data_shards { - self.probes.reachable( - "ecstore.skipped_provably_uncommitted_orphan", - json!({"bucket": bucket, "key": key, "orphan_gen": canonical.generation}), - ); - continue; - } + let votes = top_entries.len(); + let max_possible = votes + unreachable; if canonical.is_delete_marker { - if top_entries.len() >= self.topology.read_quorum { + if votes >= self.topology.write_quorum { return Err(StoreError::NotFound(format!("{bucket}/{key}"))); } + if max_possible < self.topology.write_quorum { + self.probes.reachable( + "ecstore.skipped_provably_uncommitted_orphan", + json!({"bucket": bucket, "key": key, "orphan_gen": canonical.generation}), + ); + continue; + } return Err(StoreError::ReadQuorumNotMet { - healthy: top_entries.len(), - required: self.topology.read_quorum, + healthy: votes, + required: self.topology.write_quorum, }); } // Verify per-shard SHA-256 checksums to filter out silent bitrot! let mut healthy_shards = Vec::new(); let mut bitrot_detected = false; - for (global_idx, meta, maybe_bytes) in &top_entries { + for (_global_idx, meta, maybe_bytes) in &top_entries { if let Some(bytes) = maybe_bytes { if sha256_hex(bytes) == meta.shard_sha256 { - healthy_shards.push((*global_idx, bytes.clone())); + healthy_shards.push((meta.shard_index, bytes.clone())); } else { bitrot_detected = true; self.probes.reachable( "ecstore.bitrot_detected_on_read", - json!({"bucket": bucket, "key": key, "shard": global_idx}), + json!({"bucket": bucket, "key": key, "shard": meta.shard_index}), ); } } } + healthy_shards.sort_by_key(|(idx, _)| *idx); + healthy_shards.dedup_by_key(|(idx, _)| *idx); if healthy_shards.len() < self.topology.data_shards { + if max_possible < self.topology.write_quorum { + self.probes.reachable( + "ecstore.skipped_provably_uncommitted_orphan", + json!({"bucket": bucket, "key": key, "orphan_gen": canonical.generation}), + ); + continue; + } return Err(StoreError::ReadQuorumNotMet { healthy: healthy_shards.len(), required: self.topology.data_shards, @@ -1145,16 +1235,54 @@ impl SimCluster { }); } + let unreachable = self.topology.total_drives.saturating_sub(responded); let mut out = Vec::new(); for (key, metas) in by_key { - let max_gen = metas.iter().map(|m| m.generation).max().unwrap_or(0); - let top: Vec<&XlMeta> = metas.iter().filter(|m| m.generation == max_gen).collect(); - if top.len() >= self.topology.read_quorum && !top[0].is_delete_marker { + let mut gens: Vec = metas.iter().map(|meta| meta.generation).collect(); + gens.sort_unstable(); + gens.dedup(); + let mut choice: Option<&XlMeta> = None; + let mut ambiguous = false; + for generation in gens.into_iter().rev() { + let top: Vec<&XlMeta> = metas + .iter() + .filter(|meta| meta.generation == generation) + .collect(); + let votes = top.len(); + let max_possible = votes + unreachable; + if top[0].is_delete_marker { + if votes >= self.topology.write_quorum { + choice = None; + break; + } + if max_possible < self.topology.write_quorum { + continue; + } + ambiguous = true; + break; + } + if votes >= self.topology.read_quorum { + choice = Some(top[0]); + break; + } + if max_possible < self.topology.read_quorum { + continue; + } + ambiguous = true; + break; + } + if ambiguous { + return Err(StoreError::ReadQuorumNotMet { + healthy: responded, + required: self.topology.read_quorum, + }); + } + if let Some(meta) = choice { out.push(ListedObject { key, - generation: top[0].generation, - version_id: top[0].version_id.clone(), - payload_sha256: top[0].payload_sha256.clone(), + generation: meta.generation, + version_id: meta.version_id.clone(), + payload_sha256: meta.payload_sha256.clone(), }); } } @@ -1188,14 +1316,23 @@ impl SimCluster { } let shards = encode(data, self.topology.data_shards, self.topology.parity_shards) .map_err(|e| StoreError::Internal(e.to_string()))?; + let part = MultipartPart { + attempt_id: self.rng.gen_uuid_v4().to_string(), + etag: sha256_hex(data), + original_len: data.len(), + }; let mut acked = 0usize; for (node_id, drive_idx, global_idx) in self.drive_slots() { + let shard = &shards[global_idx]; let req = StagePartReq { drive_idx, upload_id: upload_id.to_string(), part_number, - shard_bytes: shards[global_idx].bytes.clone(), + attempt_id: part.attempt_id.clone(), + part_etag: part.etag.clone(), + shard_sha256: shard.sha256_hex.clone(), + shard_bytes: shard.bytes.clone(), }; let payload = serde_json::to_vec(&req).expect("serialize StagePartReq"); if self @@ -1213,17 +1350,53 @@ impl SimCluster { } if acked < self.topology.write_quorum { + self.cleanup_multipart_part(via_node, upload_id, part_number, &part.attempt_id) + .await; return Err(StoreError::WriteQuorumNotMet { acked, required: self.topology.write_quorum, }); } - if let Some(sess) = self.multipart_sessions.get_mut(upload_id) { - sess.parts.insert(part_number, data.len()); + + let previous = self + .multipart_sessions + .get_mut(upload_id) + .expect("upload session cannot change during staging") + .parts + .insert(part_number, part); + if let Some(previous) = previous { + self.cleanup_multipart_part(via_node, upload_id, part_number, &previous.attempt_id) + .await; } Ok(()) } + async fn cleanup_multipart_part( + &self, + via_node: &str, + upload_id: &str, + part_number: u32, + attempt_id: &str, + ) { + for (node_id, drive_idx, _) in self.drive_slots() { + let req = CleanupPartReq { + drive_idx, + upload_id: upload_id.to_string(), + part_number, + attempt_id: attempt_id.to_string(), + }; + let payload = serde_json::to_vec(&req).expect("serialize CleanupPartReq"); + let _ = self + .network + .call( + via_node, + &node_id, + RpcFrame::new(METHOD_DISK_CLEANUP_PART, payload), + ) + .await; + } + } + /// Atomically assemble staged multipart parts and commit the final object. pub async fn complete_multipart( &mut self, @@ -1237,16 +1410,17 @@ impl SimCluster { .ok_or_else(|| StoreError::UploadNotFound(upload_id.to_string()))?; let mut assembled = Vec::new(); - for (&part_number, &orig_len) in &sess.parts { + for (&part_number, part) in &sess.parts { let mut shards = Vec::new(); for (node_id, drive_idx, global_idx) in self.drive_slots() { let req = ReadPartReq { drive_idx, upload_id: upload_id.to_string(), part_number, + attempt_id: part.attempt_id.clone(), }; let payload = serde_json::to_vec(&req).expect("serialize ReadPartReq"); - if let Ok(frame) = self + let Ok(frame) = self .network .call( via_node, @@ -1254,8 +1428,15 @@ impl SimCluster { RpcFrame::new(METHOD_DISK_READ_PART, payload), ) .await + else { + continue; + }; + let Ok(resp) = serde_json::from_slice::(&frame.payload) else { + continue; + }; + if resp.part_etag == part.etag && sha256_hex(&resp.shard_bytes) == resp.shard_sha256 { - shards.push((global_idx, frame.payload.to_vec())); + shards.push((global_idx, resp.shard_bytes)); } } if shards.len() < self.topology.data_shards { @@ -1268,9 +1449,14 @@ impl SimCluster { &shards, self.topology.data_shards, self.topology.parity_shards, - orig_len, + part.original_len, ) .map_err(|e| StoreError::Internal(e.to_string()))?; + if sha256_hex(&part_bytes) != part.etag { + return Err(StoreError::Internal(format!( + "reconstructed payload digest mismatch for part {part_number}" + ))); + } assembled.extend_from_slice(&part_bytes); } @@ -1354,7 +1540,9 @@ impl SimCluster { } } let min_needed = if canonical.is_delete_marker { - self.topology.read_quorum + // Same threshold as GET early-stop: a sub-write-quorum delete + // marker must not be healed into a durable deletion. + self.topology.write_quorum } else { self.topology.data_shards }; @@ -1524,3 +1712,196 @@ impl SimCluster { errors } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::topology::TopologyKind; + use rustfs_dst_runtime::disk::DiskIo; + + async fn plant_meta(cluster: &SimCluster, drives: usize, meta: &XlMeta) { + let bytes = Bytes::from(serde_json::to_vec(meta).expect("meta")); + let path = format!("{}/{}/xl.meta", meta.bucket, meta.key); + for (node_id, drive_idx, _) in cluster.drive_slots().into_iter().take(drives) { + cluster.nodes[&node_id].disks[drive_idx] + .write_file(&path, bytes.clone()) + .await + .expect("plant xl.meta"); + } + } + + fn delete_meta(generation: u64) -> XlMeta { + XlMeta { + bucket: "bkt".to_string(), + key: "obj".to_string(), + version_id: format!("del-{generation}"), + generation, + is_delete_marker: true, + orig_len: 0, + payload_sha256: String::new(), + shard_index: 0, + shard_sha256: String::new(), + } + } + + #[tokio::test] + async fn sub_write_quorum_delete_marker_does_not_hide_the_object() { + let cluster = SimCluster::new(TopologyKind::ThreeByTwo.spec(), 11); + let payload = b"ledger-v1-visible"; + let put = cluster + .put_object("n1", "bkt", "obj", payload, PutConditions::default()) + .await + .expect("put"); + // 3x2 write quorum is 4. Three delete markers used to satisfy read + // quorum (3) and were reported as NotFound. + plant_meta(&cluster, 3, &delete_meta(put.generation + 1)).await; + + let got = cluster + .get_object("n2", "bkt", "obj") + .await + .expect("older object remains readable"); + assert_eq!(got.payload, payload); + assert_eq!(got.generation, put.generation); + + let listed = cluster.list_objects("n1", "bkt").await.expect("list"); + assert_eq!(listed.len(), 1); + assert_eq!(listed[0].key, "obj"); + + plant_meta( + &cluster, + cluster.topology.total_drives, + &delete_meta(put.generation + 2), + ) + .await; + assert!(matches!( + cluster.get_object("n1", "bkt", "obj").await, + Err(StoreError::NotFound(_)) + )); + let listed = cluster + .list_objects("n1", "bkt") + .await + .expect("list after quorum delete"); + assert!(listed.is_empty()); + } + + #[tokio::test] + async fn unreadable_uncommitted_version_falls_back_to_older_object() { + let cluster = SimCluster::new(TopologyKind::ThreeByTwo.spec(), 12); + let payload = b"committed-v1"; + let put = cluster + .put_object("n1", "bkt", "obj", payload, PutConditions::default()) + .await + .expect("put"); + let mut bogus = delete_meta(put.generation + 1); + bogus.is_delete_marker = false; + bogus.orig_len = 4; + bogus.payload_sha256 = "not-a-real-payload".to_string(); + bogus.shard_sha256 = "00".to_string(); + // Metadata without a matching shard cannot be reconstructed, and three + // copies are below write quorum, so GET must return v1 instead of failing closed. + plant_meta(&cluster, 3, &bogus).await; + let got = cluster + .get_object("n3", "bkt", "obj") + .await + .expect("fallback"); + assert_eq!(got.payload, payload); + assert_eq!(got.generation, put.generation); + } + + #[tokio::test] + async fn heal_does_not_promote_a_sub_write_quorum_delete() { + let cluster = SimCluster::new(TopologyKind::ThreeByTwo.spec(), 13); + let payload = b"keep-me"; + let put = cluster + .put_object("n1", "bkt", "obj", payload, PutConditions::default()) + .await + .expect("put"); + plant_meta(&cluster, 3, &delete_meta(put.generation + 1)).await; + cluster.heal_object("n1", "bkt", "obj").await.expect("heal"); + let got = cluster + .get_object("n2", "bkt", "obj") + .await + .expect("still live"); + assert_eq!(got.payload, payload); + let errors = cluster + .verify_cluster_convergence("bkt", &["obj".to_string()]) + .await; + assert!(errors.is_empty(), "{errors:?}"); + } + + #[tokio::test] + async fn failed_upload_part_removes_only_that_attempt() { + let mut cluster = SimCluster::new(TopologyKind::ThreeByTwo.spec(), 14); + for (node_id, drive_idx, _) in cluster.drive_slots().into_iter().skip(3) { + cluster.set_drive_offline(&node_id, drive_idx, true); + } + let upload_id = cluster.create_multipart("bkt", "obj"); + let err = cluster + .upload_part("n1", &upload_id, 1, b"partial-part-bytes") + .await; + assert!(matches!(err, Err(StoreError::WriteQuorumNotMet { .. }))); + for env in cluster.nodes.values() { + for disk in &env.disks { + let leaked: Vec = disk + .all_files() + .into_iter() + .filter(|path| path.contains("multipart")) + .collect(); + assert!(leaked.is_empty(), "{leaked:?}"); + } + } + } + #[tokio::test] + async fn failed_replacement_preserves_the_acknowledged_part() { + let original = b"acknowledged-part"; + for replacement in [original.as_slice(), b"different-payload"] { + let mut cluster = SimCluster::new(TopologyKind::ThreeByTwo.spec(), 15); + let upload_id = cluster.create_multipart("bkt", "obj"); + // The acknowledged part initially exists on exactly the write quorum. + for (node, drive, _) in cluster.drive_slots().into_iter().skip(4) { + cluster.set_drive_offline(&node, drive, true); + } + cluster + .upload_part("n1", &upload_id, 1, original) + .await + .expect("initial part"); + + for (node, drive, _) in cluster.drive_slots().into_iter().skip(3) { + cluster.set_drive_offline(&node, drive, true); + } + assert!(matches!( + cluster.upload_part("n1", &upload_id, 1, replacement).await, + Err(StoreError::WriteQuorumNotMet { .. }) + )); + cluster.heal_infrastructure(); + + cluster + .complete_multipart("n1", &upload_id) + .await + .expect("previously acknowledged part must still complete"); + let got = cluster.get_object("n2", "bkt", "obj").await.expect("get"); + assert_eq!(got.payload, original); + } + } + + #[tokio::test] + async fn successful_replacement_is_selected_by_completion() { + let mut cluster = SimCluster::new(TopologyKind::ThreeByTwo.spec(), 16); + let upload_id = cluster.create_multipart("bkt", "obj"); + cluster + .upload_part("n1", &upload_id, 1, b"old-part") + .await + .expect("initial part"); + cluster + .upload_part("n1", &upload_id, 1, b"new-part-with-different-length") + .await + .expect("replace part"); + + cluster + .complete_multipart("n1", &upload_id) + .await + .expect("complete replacement"); + let got = cluster.get_object("n2", "bkt", "obj").await.expect("get"); + assert_eq!(got.payload, b"new-part-with-different-length"); + } +} diff --git a/crates/rustfs-dst-sim/src/oracle.rs b/crates/rustfs-dst-sim/src/oracle.rs index 370194c..4d3b87a 100644 --- a/crates/rustfs-dst-sim/src/oracle.rs +++ b/crates/rustfs-dst-sim/src/oracle.rs @@ -16,8 +16,8 @@ //! //! Tracks every committed, indeterminate (reply-dropped), and deleted object //! state across the simulation and asserts: -//! 1. **Linearizability / Monotonicity**: Reads never return a generation older -//! than the latest acknowledged write/delete. +//! 1. **Sequential read-after-write consistency**: A GET or LIST observes a +//! valid current state after acknowledged or indeterminate mutations. //! 2. **Bit-Exact Integrity**: Every returned payload matches the exact SHA-256 //! of a committed or indeterminate write (no torn mixes, no silent bitrot). //! 3. **Crash Atomicity (Old-or-New-Never-Mixed)**: After hard power loss, @@ -29,6 +29,7 @@ //! 6. **Heal Convergence**: Post-heal, every drive in the erasure set agrees on //! the identical generation and zero temporary staging artifacts leak. +use crate::ecstore::{GetResult, ListedObject}; use crate::erasure::sha256_hex; use rustfs_dst_faults::probe::ProbeRegistry; use serde::{Deserialize, Serialize}; @@ -62,8 +63,8 @@ pub struct ConsistencyOracle { indeterminate: BTreeMap>, /// Set of all payload hashes ever submitted for a key (for bit-exactness check). ever_written_hashes: BTreeMap>, - /// Highest generation ever observed by any successful read per key. - max_observed_gen: BTreeMap, + /// Most recent accepted state, or the earliest possible observed delete. + observed: BTreeMap, /// Active lock holder tracking for mutual exclusion verification. active_locks: BTreeMap, /// Accumulated violations. @@ -78,7 +79,7 @@ impl ConsistencyOracle { acked: BTreeMap::new(), indeterminate: BTreeMap::new(), ever_written_hashes: BTreeMap::new(), - max_observed_gen: BTreeMap::new(), + observed: BTreeMap::new(), active_locks: BTreeMap::new(), violations: Vec::new(), probes, @@ -126,6 +127,23 @@ impl ConsistencyOracle { self.indeterminate.remove(full_key); } + pub fn record_indeterminate_delete( + &mut self, + full_key: &str, + generation: u64, + version_id: String, + ) { + self.indeterminate + .entry(full_key.to_string()) + .or_default() + .push(CommittedState { + generation, + version_id, + is_deleted: true, + payload_sha256: None, + }); + } + pub fn record_indeterminate_put( &mut self, full_key: &str, @@ -148,103 +166,161 @@ impl ConsistencyOracle { }); } - /// Verify a successful `GetObject` response against invariants 1 & 2. + /// Verify a successful `GetObject` response including its version and checksum. + pub fn check_get_result(&mut self, full_key: &str, result: &GetResult) { + let actual_hash = sha256_hex(&result.payload); + if result.payload_sha256 != actual_hash { + self.record_violation( + "bit_exact_integrity", + full_key, + format!( + "response checksum {} does not match payload digest {actual_hash}", + result.payload_sha256 + ), + ); + } + self.check_present( + full_key, + result.generation, + Some(&result.version_id), + &actual_hash, + ); + } + + /// Verify an observation without a version ID, for callers that only have bytes. pub fn check_read_present(&mut self, full_key: &str, generation: u64, payload: &[u8]) { - let got_hash = sha256_hex(payload); + self.check_present(full_key, generation, None, &sha256_hex(payload)); + } - // Invariant 2: Bit-exact integrity (never corrupted or torn). + fn check_present( + &mut self, + full_key: &str, + generation: u64, + version_id: Option<&str>, + actual_hash: &str, + ) { let hash_valid = self .ever_written_hashes .get(full_key) - .is_some_and(|set| set.contains(&got_hash)); + .is_some_and(|set| set.contains(actual_hash)); self.probes.always( "invariant.bit_exact_integrity", hash_valid, - json!({"key": full_key, "generation": generation, "sha256": got_hash}), + json!({"key": full_key, "generation": generation, "sha256": actual_hash}), ); if !hash_valid { self.violations.push(InvariantViolation { invariant: "bit_exact_integrity".to_string(), key: full_key.to_string(), detail: format!( - "read returned unknown/corrupted payload digest {got_hash} at gen {generation}" + "read returned unknown/corrupted payload digest {actual_hash} at gen {generation}" ), }); } - // Invariant 1a: Read-after-write monotonicity against acknowledged writes. - if let Some(acked) = self.acked.get(full_key) { - let linearizable = if generation < acked.generation { - false - } else if generation == acked.generation { - !acked.is_deleted && acked.payload_sha256.as_deref() == Some(got_hash.as_str()) - } else { - // Generation > acked is only legal if an indeterminate write landed. - self.indeterminate - .get(full_key) - .is_some_and(|cands| cands.iter().any(|c| c.generation == generation)) - }; - self.probes.always( - "invariant.linearizable_read", - linearizable, - json!({ - "key": full_key, - "read_gen": generation, - "acked_gen": acked.generation, - "acked_deleted": acked.is_deleted, - }), - ); - if !linearizable { - self.violations.push(InvariantViolation { - invariant: "linearizable_read".to_string(), - key: full_key.to_string(), - detail: format!( - "stale or inconsistent read: got gen={generation}, acked gen={} deleted={}", - acked.generation, acked.is_deleted - ), - }); - } + let read_state = self + .possible_states(full_key) + .find(|state| { + !state.is_deleted + && state.generation == generation + && version_id.is_none_or(|id| state.version_id == id) + && state.payload_sha256.as_deref() == Some(actual_hash) + }) + .cloned(); + self.probes.always( + "invariant.linearizable_read", + read_state.is_some(), + json!({ + "key": full_key, + "read_gen": generation, + "version_id": version_id, + "sha256": actual_hash, + }), + ); + if let Some(state) = read_state { + self.observed.insert(full_key.to_string(), state); + } else { + self.violations.push(InvariantViolation { + invariant: "linearizable_read".to_string(), + key: full_key.to_string(), + detail: format!( + "read gen={generation}, version={version_id:?}, sha256={actual_hash} matches no possible current state" + ), + }); } + } - // Invariant 1b: Monotonic reads across sequential reads. - let prev_max = self.max_observed_gen.get(full_key).copied().unwrap_or(0); - let monotonic = generation >= prev_max; + /// Verify a `NotFound` read and remember the earliest deletion that could explain it. + pub fn check_read_not_found(&mut self, full_key: &str) { + let possibly_unwritten = + !self.acked.contains_key(full_key) && !self.observed.contains_key(full_key); + let deletion = if possibly_unwritten { + None + } else { + self.possible_states(full_key) + .filter(|state| state.is_deleted) + .min_by_key(|state| state.generation) + .cloned() + }; + let valid = possibly_unwritten || deletion.is_some(); self.probes.always( - "invariant.monotonic_read_generation", - monotonic, - json!({"key": full_key, "read_gen": generation, "prev_max": prev_max}), + "invariant.no_lost_acknowledged_write", + valid, + json!({"key": full_key, "possible_delete": deletion}), ); - if !monotonic { + if let Some(state) = deletion { + self.observed.insert(full_key.to_string(), state); + } else if !valid { self.violations.push(InvariantViolation { - invariant: "monotonic_read_generation".to_string(), + invariant: "no_lost_acknowledged_write".to_string(), key: full_key.to_string(), - detail: format!("generation regressed from {prev_max} to {generation}"), + detail: "read returned NotFound with no possible current deletion".to_string(), }); - } else { - self.max_observed_gen - .insert(full_key.to_string(), generation); } } - /// Verify a `NotFound` / deleted read response against acknowledged state. - pub fn check_read_not_found(&mut self, full_key: &str) { - if let Some(acked) = self.acked.get(full_key) { - let valid = acked.is_deleted; - self.probes.always( - "invariant.no_lost_acknowledged_write", - valid, - json!({"key": full_key, "acked_gen": acked.generation, "acked_deleted": acked.is_deleted}), - ); - if !valid { - self.violations.push(InvariantViolation { - invariant: "no_lost_acknowledged_write".to_string(), - key: full_key.to_string(), - detail: format!( - "read returned NotFound for acknowledged live object gen={}", - acked.generation - ), - }); - } + fn possible_states<'a>(&'a self, full_key: &str) -> impl Iterator { + let acked = self.acked.get(full_key); + let observed = self.observed.get(full_key); + acked + .into_iter() + .chain(self.indeterminate.get(full_key).into_iter().flatten()) + .filter(move |state| { + acked.is_none_or(|ack| state.generation > ack.generation || *state == ack) + && observed.is_none_or(|previous| { + state.generation > previous.generation || *state == previous + }) + }) + } + + /// Verify a complete listing after a sequence of acknowledged mutations. + pub fn check_acked_listing(&mut self, bucket: &str, listed: &[ListedObject]) { + let prefix = format!("{bucket}/"); + let expected: Vec<_> = self + .acked + .iter() + .filter_map(|(full_key, state)| { + let key = full_key.strip_prefix(&prefix)?; + let payload_sha256 = state.payload_sha256.clone()?; + Some(ListedObject { + key: key.to_string(), + generation: state.generation, + version_id: state.version_id.clone(), + payload_sha256, + }) + }) + .collect(); + self.probes.always( + "invariant.list_objects_exact_match", + listed == expected, + json!({"bucket": bucket, "listed": format!("{listed:?}"), "expected": format!("{expected:?}")}), + ); + if listed != expected { + self.violations.push(InvariantViolation { + invariant: "list_consistency".to_string(), + key: bucket.to_string(), + detail: format!("expected {expected:?}, got {listed:?}"), + }); } } @@ -325,3 +401,97 @@ impl ConsistencyOracle { self.violations.is_empty() && self.probes.violations().is_empty() } } + +#[cfg(test)] +mod tests { + use super::*; + + const KEY: &str = "bucket/key"; + + fn get_result(generation: u64, version_id: &str, payload: &[u8]) -> GetResult { + GetResult { + generation, + version_id: version_id.to_string(), + payload: payload.to_vec(), + payload_sha256: sha256_hex(payload), + } + } + + #[test] + fn rejects_a_definitely_failed_write_even_if_its_payload_was_submitted() { + let mut oracle = ConsistencyOracle::new(ProbeRegistry::new()); + oracle.record_submitted_payload(KEY, b"uncommitted"); + oracle.check_get_result(KEY, &get_result(1, "failed", b"uncommitted")); + assert_eq!(oracle.violations()[0].invariant, "linearizable_read"); + } + + #[test] + fn a_get_must_match_the_same_mutation_for_generation_version_and_payload() { + for unexpected in [ + get_result(2, "wrong-version", b"new"), + get_result(2, "new-version", b"old"), + get_result(3, "delete-marker", b"new"), + ] { + let mut oracle = ConsistencyOracle::new(ProbeRegistry::new()); + oracle.record_acked_put(KEY, 1, "old-version".into(), sha256_hex(b"old")); + oracle.record_indeterminate_put(KEY, 2, "new-version".into(), sha256_hex(b"new")); + oracle.record_indeterminate_delete(KEY, 3, "delete-marker".into()); + oracle.check_get_result(KEY, &get_result(2, "new-version", b"new")); + assert!(oracle.is_valid()); + oracle.check_get_result(KEY, &unexpected); + assert_eq!(oracle.violations()[0].invariant, "linearizable_read"); + } + } + + #[test] + fn sequential_reads_cannot_regress_after_an_indeterminate_mutation_is_observed() { + let mut oracle = ConsistencyOracle::new(ProbeRegistry::new()); + oracle.record_acked_put(KEY, 1, "old-version".into(), sha256_hex(b"old")); + oracle.record_indeterminate_delete(KEY, 2, "delete-marker".into()); + oracle.check_read_not_found(KEY); + assert!(oracle.is_valid()); + oracle.check_get_result(KEY, &get_result(1, "old-version", b"old")); + assert_eq!(oracle.violations()[0].invariant, "linearizable_read"); + + let mut oracle = ConsistencyOracle::new(ProbeRegistry::new()); + oracle.record_indeterminate_put(KEY, 1, "first-version".into(), sha256_hex(b"first")); + oracle.check_read_not_found(KEY); + oracle.check_get_result(KEY, &get_result(1, "first-version", b"first")); + assert!(oracle.is_valid()); + oracle.check_read_not_found(KEY); + assert_eq!( + oracle.violations()[0].invariant, + "no_lost_acknowledged_write" + ); + } + + #[test] + fn list_checks_versions_checksums_and_delete_markers_in_addition_to_keys() { + let mut oracle = ConsistencyOracle::new(ProbeRegistry::new()); + let expected = ListedObject { + key: "key".to_string(), + generation: 2, + version_id: "current".to_string(), + payload_sha256: sha256_hex(b"current"), + }; + oracle.record_acked_delete("bucket/another-key", 1, "delete-marker".into()); + oracle.record_acked_put( + KEY, + 2, + expected.version_id.clone(), + expected.payload_sha256.clone(), + ); + oracle.check_acked_listing("bucket", std::slice::from_ref(&expected)); + assert!(oracle.is_valid()); + oracle.check_acked_listing( + "bucket", + &[ListedObject { + generation: 1, + version_id: "stale".to_string(), + payload_sha256: sha256_hex(b"stale"), + ..expected + }], + ); + assert_eq!(oracle.violations()[0].invariant, "list_consistency"); + } +} diff --git a/crates/rustfs-dst-sim/src/scenarios.rs b/crates/rustfs-dst-sim/src/scenarios.rs index 516dcdb..101a713 100644 --- a/crates/rustfs-dst-sim/src/scenarios.rs +++ b/crates/rustfs-dst-sim/src/scenarios.rs @@ -131,7 +131,7 @@ impl FromStr for ScenarioKind { } /// Complete report produced by one deterministic `(scenario, topology, seed)` run. -#[derive(Clone, Debug, Serialize, Deserialize)] +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct ScenarioReport { pub scenario: ScenarioKind, pub topology: String, @@ -157,7 +157,7 @@ pub fn run_scenario(scenario: ScenarioKind, topology: TopologyKind, seed: u64) - } fn run_turmoil_scenario(topology: TopologySpec, seed: u64) -> ScenarioReport { - match run_turmoil_tcp_quorum_sim(seed) { + match run_turmoil_tcp_quorum_sim(topology.nodes, seed) { Ok(rep) => ScenarioReport { scenario: ScenarioKind::TurmoilTcpCluster, topology: topology.name.to_string(), @@ -195,6 +195,7 @@ fn hash_trace(cluster: &SimCluster, extra_events: &[String]) -> String { for net_ev in cluster.network.trace_snapshot() { hasher.update(b"N:"); hasher.update(net_ev.seq.to_le_bytes()); + hasher.update(net_ev.at_ms.to_le_bytes()); hasher.update(net_ev.from.as_bytes()); hasher.update(b"->"); hasher.update(net_ev.to.as_bytes()); @@ -269,16 +270,30 @@ async fn run_scenario_async( } let trace_sha256 = hash_trace(&cluster, &trace); - let passed = oracle.is_valid(); + let probes = cluster.probes.snapshot(); + let mut violations = oracle.violations().to_vec(); + for probe in probes.values().filter(|probe| probe.is_violated()) { + let invariant = probe.id.strip_prefix("invariant.").unwrap_or(&probe.id); + if !violations + .iter() + .any(|violation| violation.invariant == invariant) + { + violations.push(InvariantViolation { + invariant: invariant.to_string(), + key: "scenario".to_string(), + detail: format!("assertion failed {} times", probe.fail_count), + }); + } + } ScenarioReport { scenario, topology: topology.name.to_string(), seed, - passed, + passed: violations.is_empty(), operations: ops, trace_sha256, - violations: oracle.violations().to_vec(), - probes: cluster.probes.snapshot(), + violations, + probes, } } @@ -369,7 +384,7 @@ async fn scenario_erasure_quorum( // Read from another surviving node must return exact new payload. let reader = &live_nodes[rng.gen_range_usize(live_nodes.len())]; match cluster.get_object(reader, bucket, key).await { - Ok(got) => oracle.check_read_present(&full, got.generation, &got.payload), + Ok(got) => oracle.check_get_result(&full, &got), Err(e) => oracle.record_violation( "degraded_read_availability", &full, @@ -432,34 +447,70 @@ async fn scenario_erasure_quorum( } ops += 1; - for key in &keys { - let _ = cluster.heal_object(&nodes[0], bucket, key).await; + // S3 If-None-Match: * treats a delete marker as "object does not exist". + let replacement = b"recreated-after-delete"; + let recreated = cluster + .put_object( + &nodes[0], + bucket, + del_key, + replacement, + PutConditions { + if_none_match_any: true, + if_match_sha256: None, + }, + ) + .await; + cluster.probes.always( + "invariant.if_none_match_allows_delete_marker", + recreated.is_ok(), + json!({"key": del_full, "outcome": format!("{recreated:?}")}), + ); + match recreated { + Ok(put) => { + let digest = oracle.record_submitted_payload(&del_full, replacement); + oracle.record_acked_put(&del_full, put.generation, put.version_id, digest); + match cluster.get_object(&nodes[1], bucket, del_key).await { + Ok(got) => oracle.check_get_result(&del_full, &got), + Err(err) => { + oracle.record_violation("recreate_visibility", &del_full, err.to_string()) + } + } + ops += 1; + } + Err(err) => oracle.record_violation( + "if_none_match_after_delete", + &del_full, + format!("If-None-Match rejected a delete marker: {err}"), + ), } - cluster.sweep_tmp_orphans(&nodes[0]).await; - - let listed = cluster - .list_objects(&nodes[0], bucket) + let deleted_again = cluster + .delete_object(&nodes[0], bucket, del_key) .await - .expect("list_objects"); - let listed_keys: Vec = listed.iter().map(|o| o.key.clone()).collect(); - let expected_live: Vec = keys[..keys.len() - 1].to_vec(); - cluster.probes.always( - "invariant.list_objects_exact_match", - listed_keys == expected_live, - json!({"listed": listed_keys, "expected": expected_live}), + .expect("delete restored key"); + oracle.record_acked_delete( + &del_full, + deleted_again.generation, + deleted_again.version_id, ); - if listed_keys != expected_live { - oracle.record_violation( - "list_consistency", - bucket, - format!("expected {expected_live:?}, got {listed_keys:?}"), - ); + ops += 2; + + // LIST must reflect the acknowledged overwrite and delete before repair runs. + match cluster.list_objects(&nodes[0], bucket).await { + Ok(listed) => oracle.check_acked_listing(bucket, &listed), + Err(err) => oracle.record_violation("list_availability", bucket, err.to_string()), + } + ops += 1; + + for key in &keys { + let _ = cluster.heal_object(&nodes[0], bucket, key).await; } + cluster.sweep_tmp_orphans(&nodes[0]).await; for err in cluster.verify_cluster_convergence(bucket, &keys).await { oracle.record_violation("heal_convergence", bucket, err); } - ops + 1 + ops } async fn scenario_crash_consistency( @@ -526,7 +577,7 @@ async fn scenario_crash_consistency( .get_object(&nodes[1 % nodes.len()], bucket, &key) .await .expect("object must remain readable as intact old or intact new after crash"); - oracle.check_read_present(&full, got.generation, &got.payload); + oracle.check_get_result(&full, &got); cluster.probes.reachable( "ecstore.crash_window_survived_cleanly", json!({"crash_point": format!("{cp:?}"), "key": full, "read_gen": got.generation}), @@ -580,7 +631,7 @@ async fn scenario_bitrot_heal( .get_object(&nodes[nodes.len() - 1], bucket, key) .await .expect("RS must transparently recover from parity_shards bitrotted drives"); - oracle.check_read_present(&full, got.generation, &got.payload); + oracle.check_get_result(&full, &got); // Run online heal and confirm every bitrotted drive is repaired cleanly. let healed = cluster @@ -656,7 +707,7 @@ async fn scenario_multipart_commit( .get_object(&nodes[0], bucket, key) .await .expect("pre-complete read"); - oracle.check_read_present(&full, pre.generation, &pre.payload); + oracle.check_get_result(&full, &pre); // Arm crash window during multipart commit, then complete! cluster @@ -676,7 +727,7 @@ async fn scenario_multipart_commit( .get_object(&nodes[1 % nodes.len()], bucket, key) .await .expect("post-complete read"); - oracle.check_read_present(&full, post.generation, &post.payload); + oracle.check_get_result(&full, &post); // Also test AbortMultipartUpload leaves live object untouched. let aborted_id = cluster.create_multipart(bucket, key); @@ -690,7 +741,7 @@ async fn scenario_multipart_commit( .get_object(&nodes[0], bucket, key) .await .expect("read after abort"); - oracle.check_read_present(&full, after_abort.generation, &after_abort.payload); + oracle.check_get_result(&full, &after_abort); let _ = cluster.heal_object(&nodes[0], bucket, key).await; cluster.sweep_tmp_orphans(&nodes[0]).await; @@ -774,7 +825,33 @@ async fn scenario_distributed_lock_skew( } c2.release(&lease2).await; oracle.record_lock_released(resource, "owner-2"); - ops + 2 + ops += 2; + + // Negative control: a wall-clock lease MUST expire when skew jumps past + // its TTL. Monotonic leases above must keep failing that test. + cluster.clock.clear_faults(); + let wall = "dst-locks/wall-clock-lease"; + let wall_lease = c1 + .acquire(wall, "owner-wall", 5_000, true) + .await + .expect("wall-clock lease"); + for node in &nodes { + cluster.clock.set_node_skew_ms(node, 60_000); + } + let stolen = c2.acquire(wall, "owner-wall-2", 5_000, true).await; + cluster.probes.always( + "invariant.wall_clock_lease_expires_under_skew", + stolen.is_ok(), + json!({"stolen": format!("{stolen:?}"), "fence": wall_lease.fence_token}), + ); + if stolen.is_err() { + oracle.record_violation( + "wall_clock_lease_skew", + wall, + "wall-clock lease survived a 60s skew jump", + ); + } + ops + 1 } async fn scenario_swizzle_clog_chaos( @@ -816,7 +893,8 @@ async fn scenario_swizzle_clog_chaos( let key = &keys[rng.gen_range_usize(keys.len())]; let full = format!("{bucket}/{key}"); let via = &nodes[rng.gen_range_usize(nodes.len())]; - if rng.gen_bool(0.55) { + let roll = rng.next_u64() % 100; + if roll < 45 { let payload = deterministic_payload(rng, 128, 1024); let hash = oracle.record_submitted_payload(&full, &payload); match cluster @@ -834,9 +912,22 @@ async fn scenario_swizzle_clog_chaos( } Err(_) => {} } + } else if roll < 65 { + match cluster.delete_object(via, bucket, key).await { + Ok(res) => { + oracle.record_acked_delete(&full, res.generation, res.version_id); + } + Err(StoreError::Indeterminate { + generation, + version_id, + }) => { + oracle.record_indeterminate_delete(&full, generation, version_id); + } + Err(_) => {} + } } else { match cluster.get_object(via, bucket, key).await { - Ok(got) => oracle.check_read_present(&full, got.generation, &got.payload), + Ok(got) => oracle.check_get_result(&full, &got), Err(StoreError::NotFound(_)) => oracle.check_read_not_found(&full), Err(_) => {} } @@ -856,7 +947,7 @@ async fn scenario_swizzle_clog_chaos( for key in &keys { let full = format!("{bucket}/{key}"); match cluster.get_object(&nodes[0], bucket, key).await { - Ok(got) => oracle.check_read_present(&full, got.generation, &got.payload), + Ok(got) => oracle.check_get_result(&full, &got), Err(StoreError::NotFound(_)) => oracle.check_read_not_found(&full), Err(e) => oracle.record_violation( "post_chaos_availability", diff --git a/crates/rustfs-dst-sim/src/turmoil_cluster.rs b/crates/rustfs-dst-sim/src/turmoil_cluster.rs index 0b69849..95c79c8 100644 --- a/crates/rustfs-dst-sim/src/turmoil_cluster.rs +++ b/crates/rustfs-dst-sim/src/turmoil_cluster.rs @@ -12,13 +12,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -//! Real Tokio [`turmoil`] virtual-TCP multi-node RustFS quorum simulation. +//! Real Tokio [`turmoil`] virtual-TCP multi-node quorum simulation. //! -//! Spawns 4 virtual RustFS storage nodes (`n1`..`n4`) inside `turmoil::Sim` -//! communicating over real virtual TCP sockets (`turmoil::net::{TcpListener, -//! TcpStream}`) and drives quorum writes/reads through deterministic -//! `turmoil::partition`, `turmoil::hold`, `turmoil::repair`, and -//! `turmoil::bounce` fault sequences. +//! This tier checks the virtual TCP transport (framing, `partition`, `hold`, +//! `repair`, `bounce`) with a node-majority quorum. It is not the erasure-set +//! `SimECStore`: drive-level Reed-Solomon quorum stays in the in-process +//! simulator. Node count follows the topology (`3` for `3x2`, `4` for `4x4` +//! and `4x2`) and the write quorum is `nodes / 2 + 1`. use rustfs_dst_runtime::network::RpcFrame; use rustfs_dst_runtime::turmoil_net::{ @@ -27,11 +27,20 @@ use rustfs_dst_runtime::turmoil_net::{ use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::collections::BTreeMap; +use std::sync::atomic::{AtomicU8, Ordering}; use std::sync::{Arc, Mutex}; use std::time::Duration; const RPC_PORT: u16 = 9000; -type DurableKvDisk = Arc>>; + +#[derive(Clone, Debug)] +struct Record { + generation: u64, + value: String, + prev: Option<(u64, String)>, +} + +type DurableKvDisk = Arc>>; #[derive(Clone, Debug, Serialize, Deserialize)] struct ShardPutReq { @@ -40,6 +49,12 @@ struct ShardPutReq { value: String, } +#[derive(Clone, Debug, Serialize, Deserialize)] +struct ShardRollbackReq { + key: String, + generation: u64, +} + #[derive(Clone, Debug, Serialize, Deserialize)] struct ShardGetReq { key: String, @@ -60,18 +75,14 @@ pub struct TurmoilClusterReport { pub trace_sha256: String, } -/// Run a deterministic 4-node virtual-TCP quorum cluster inside Tokio `turmoil`. +/// Run a deterministic virtual-TCP quorum cluster inside Tokio `turmoil`. /// -/// Exercises: -/// 1. Healthy quorum PUT/GET across all 4 TCP nodes (W=3, R=3 of 4 nodes). -/// 2. Minority isolation (`turmoil::partition("client", "n4")` + `turmoil::partition("n1", "n4")`): -/// writes still succeed on 3 healthy nodes (`n1..n3`). -/// 3. Majority split (2 nodes partitioned from client): writes MUST fail closed -/// below quorum (W=3) and MUST NOT lose prior acknowledged writes. -/// 4. Host bounce (`turmoil::bounce("n3")`) and link hold/repair (`turmoil::hold` / -/// `turmoil::repair`): surviving durable state converges and reads remain -/// strictly linearizable with deterministic trace digest. -pub fn run_turmoil_tcp_quorum_sim(seed: u64) -> Result { +/// `nodes` is the storage-node count (not the drive count). Quorum is a strict +/// majority of those nodes. +pub fn run_turmoil_tcp_quorum_sim(nodes: usize, seed: u64) -> Result { + if !(2..=8).contains(&nodes) { + return Err(format!("turmoil node count {nodes} is outside 2..=8")); + } let cfg = TurmoilConfig { seed, simulation_duration: Duration::from_secs(30), @@ -82,15 +93,16 @@ pub fn run_turmoil_tcp_quorum_sim(seed: u64) -> Result = (1..=nodes).map(|idx| format!("n{idx}")).collect(); // Durable per-node storage surviving `turmoil::bounce` restarts. let durable_disks: Vec = (0..node_names.len()) .map(|_| Arc::new(Mutex::new(BTreeMap::new()))) .collect(); - for (idx, &name) in node_names.iter().enumerate() { + for (idx, name) in node_names.iter().enumerate() { let disk = Arc::clone(&durable_disks[idx]); - sim.host(name, move || { + let host_name = name.clone(); + sim.host(host_name, move || { let disk = Arc::clone(&disk); async move { let listener = turmoil::net::TcpListener::bind(("0.0.0.0", RPC_PORT)).await?; @@ -105,9 +117,47 @@ pub fn run_turmoil_tcp_quorum_sim(seed: u64) -> Result existing_gen { - guard.insert(p.key, (p.generation, p.value)); + let prev = guard + .get(&p.key) + .map(|rec| (rec.generation, rec.value.clone())); + guard.insert( + p.key, + Record { + generation: p.generation, + value: p.value, + prev, + }, + ); + } + RpcFrame::new("ok", b"ok".as_slice()) + } + "rollback" => { + let p: ShardRollbackReq = + serde_json::from_slice(&req.payload).unwrap(); + let mut guard = disk.lock().unwrap(); + if guard + .get(&p.key) + .is_some_and(|rec| rec.generation == p.generation) + { + let prev = + guard.get(&p.key).and_then(|rec| rec.prev.clone()); + match prev { + Some((generation, value)) => { + guard.insert( + p.key, + Record { + generation, + value, + prev: None, + }, + ); + } + None => { + guard.remove(&p.key); + } + } } RpcFrame::new("ok", b"ok".as_slice()) } @@ -115,10 +165,10 @@ pub fn run_turmoil_tcp_quorum_sim(seed: u64) -> Result Result)); let report_out = Arc::clone(&report_slot); + let names_for_client = node_names.clone(); + let bounce_phase = Arc::new(AtomicU8::new(0)); + let bounce_phase_client = Arc::clone(&bounce_phase); + let bounce_name = node_names[0].clone(); sim.client("client", async move { - let peers = ["n1:9000", "n2:9000", "n3:9000", "n4:9000"]; - let quorum = 3usize; + let peers: Vec = names_for_client + .iter() + .map(|name| format!("{name}:{RPC_PORT}")) + .collect(); + let peer_refs: Vec<&str> = peers.iter().map(String::as_str).collect(); + let quorum = names_for_client.len() / 2 + 1; let timeout = Duration::from_millis(250); let mut trace = Vec::::new(); + trace.push(format!("nodes:{}:quorum:{quorum}", names_for_client.len())); let mut committed = 0u64; let mut rejected = 0u64; let mut reads = 0u64; @@ -162,16 +221,28 @@ pub fn run_turmoil_tcp_quorum_sim(seed: u64) -> Result= quorum + if applied.len() >= quorum { + return true; + } + for addr in applied { + let frame = RpcFrame::new("rollback", rollback_body.clone()); + let _ = turmoil_rpc_call(addr, frame, timeout).await; + } + false } async fn quorum_get( @@ -202,47 +273,98 @@ pub fn run_turmoil_tcp_quorum_sim(seed: u64) -> Result 3 healthy nodes still form quorum. - turmoil::partition("client", "n4"); - assert!(quorum_put(&peers, quorum, timeout, "obj-a", 2, "val-v2").await); + // Phase 2: Isolate the last node. The remainder is still a majority. + let isolated = names_for_client.last().expect("node").clone(); + turmoil::partition("client", isolated.clone()); + assert!( + quorum_put(&peer_refs, quorum, timeout, "obj-a", 2, "val-v2").await, + "majority remains after isolating one node" + ); committed += 1; - trace.push("put:obj-a:2:degraded_ok".to_string()); - let r2 = quorum_get(&peers, quorum, timeout, "obj-a") + trace.push(format!("put:obj-a:2:degraded_ok:isolated:{isolated}")); + let r2 = quorum_get(&peer_refs, quorum, timeout, "obj-a") .await .expect("degraded quorum read v2"); assert_eq!(r2, (2, "val-v2".to_string())); reads += 1; trace.push("get:obj-a:2".to_string()); - // Phase 3: Partition a second node (`n3`) -> only 2 reachable (< quorum 3), must reject write! - turmoil::partition("client", "n3"); - let w3 = quorum_put(&peers, quorum, timeout, "obj-a", 3, "val-v3-split").await; - assert!(!w3, "write must fail closed when only 2/4 nodes reachable"); + // Phase 3: Isolate one more node so the client is below majority. + // The partial put must roll back; a later read must still observe v2. + let second = names_for_client[names_for_client.len() - 2].clone(); + turmoil::partition("client", second.clone()); + let w3 = quorum_put(&peer_refs, quorum, timeout, "obj-a", 3, "val-v3-split").await; + assert!( + !w3, + "write must fail closed when fewer than {quorum} nodes are reachable" + ); rejected += 1; - trace.push("put:obj-a:3:rejected_no_quorum".to_string()); + trace.push(format!("put:obj-a:3:rejected_no_quorum:isolated:{second}")); + turmoil::repair("client", isolated); + turmoil::repair("client", second); + let after_reject = quorum_get(&peer_refs, quorum, timeout, "obj-a") + .await + .expect("read after rejected write"); + assert_eq!( + after_reject, + (2, "val-v2".to_string()), + "rejected write became visible" + ); + reads += 1; + trace.push("get:obj-a:2:after_rejected_put".to_string()); - // Phase 4: Repair partitions, bounce `n3`, verify linearizable read still sees >= v2 (or v3 if applied on 2 nodes — wait, v3 never reached quorum!). - turmoil::repair("client", "n3"); - turmoil::repair("client", "n4"); - turmoil::hold("client", "n2"); - turmoil::release("client", "n2"); + // Phase 4: Hold every link across an RPC so the timeout is real, then release. + for name in &names_for_client { + turmoil::hold("client", name.clone()); + } + let held = quorum_get(&peer_refs, quorum, timeout, "obj-a").await; + assert!( + held.is_none(), + "quorum read succeeded while every client link was held" + ); + trace.push("get:obj-a:held_timeout".to_string()); + for name in &names_for_client { + turmoil::release("client", name.clone()); + } + let after_release = quorum_get(&peer_refs, quorum, timeout, "obj-a") + .await + .expect("read after releasing holds"); + assert_eq!(after_release, (2, "val-v2".to_string())); + reads += 1; + trace.push("get:obj-a:2:after_hold".to_string()); + + // Phase 5: Ask the driver to bounce a node, then wait for that restart. + // `Sim::bounce` is not callable from inside a host. Durable state lives + // outside the restarted task. + bounce_phase_client.store(1, Ordering::SeqCst); + tokio::time::sleep(Duration::from_millis(200)).await; + let after_bounce = quorum_get(&peer_refs, quorum, timeout, "obj-a") + .await + .expect("read after host bounce"); + assert_eq!(after_bounce, (2, "val-v2".to_string())); + reads += 1; + trace.push(format!("get:obj-a:2:after_bounce:{}", names_for_client[0])); - // Write v4 on healed cluster -> supersedes any partial v3 shards deterministically. - assert!(quorum_put(&peers, quorum, timeout, "obj-a", 4, "val-v4").await); + assert!( + quorum_put(&peer_refs, quorum, timeout, "obj-a", 4, "val-v4").await, + "healed quorum put" + ); committed += 1; trace.push("put:obj-a:4:healed_ok".to_string()); - - let r4 = quorum_get(&peers, quorum, timeout, "obj-a") + let r4 = quorum_get(&peer_refs, quorum, timeout, "obj-a") .await .expect("post-heal read v4"); assert_eq!(r4, (4, "val-v4".to_string())); @@ -256,9 +378,9 @@ pub fn run_turmoil_tcp_quorum_sim(seed: u64) -> Result Result