diff --git a/.github/workflows/dependency-audit.yml b/.github/workflows/dependency-audit.yml new file mode 100644 index 0000000..fdcc8b4 --- /dev/null +++ b/.github/workflows/dependency-audit.yml @@ -0,0 +1,45 @@ +name: Dependency audit + +on: + pull_request: + push: + +# Cancel a superseded run on the same ref. This does not change branch protection. +concurrency: + group: dependency-audit-${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + cargo-audit-and-deny: + name: cargo-audit and cargo-deny + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + + - name: Setup Rust 1.100.0 + uses: dtolnay/rust-toolchain@1.100.0 + + - name: Install cargo-audit 0.23.0 and cargo-deny 0.21.0 + id: install + run: | + cargo install cargo-audit --locked --version 0.23.0 + cargo install cargo-deny --locked --version 0.21.0 + + - name: cargo audit + id: cargo_audit + run: cargo audit -D unmaintained -D unsound -D yanked + + # Audit failures must not skip deny. A failed audit step still fails the job. + - name: cargo deny + id: cargo_deny + if: ${{ !cancelled() && steps.install.outcome == 'success' }} + run: cargo deny --locked check diff --git a/Cargo.lock b/Cargo.lock index a9c1739..c87cddc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -932,6 +932,7 @@ dependencies = [ "tonic", "tracing", "tracing-subscriber", + "wincode", ] [[package]] diff --git a/crates/metadb-cluster/tests/id_namespace_join_tests.rs b/crates/metadb-cluster/tests/id_namespace_join_tests.rs new file mode 100644 index 0000000..8b9ef25 --- /dev/null +++ b/crates/metadb-cluster/tests/id_namespace_join_tests.rs @@ -0,0 +1,276 @@ +//! Namespace isolation for [`DurableIdAllocator::open_for_node`](metadb_cluster::DurableIdAllocator::open_for_node). +//! +//! A fresh directory for `node_id > 1` starts in that node's inode, file-id, and shard-id +//! window. An allocator that has already granted ids is reopened from the stored counters. +//! Reopening it under a different node id must not silently relocate those counters. + +use metadb_cluster::{AllocIdKind, DurableIdAllocator}; +use metadb_core::{ + is_dir_inode_id, is_file_inode_id, make_file_inode_id, MetaDbError, FILE_INODE_TAG_BIT, +}; + +const MAX_NODE_ID: u64 = 32767; + +fn file_seq_window(node_id: u64) -> (u64, u64) { + let start = if node_id == 1 { 1 } else { (node_id << 48) + 1 }; + let end = if node_id == MAX_NODE_ID { + FILE_INODE_TAG_BIT + } else { + ((node_id + 1) << 48) + 1 + }; + (start, end) +} + +fn dir_inode_window(node_id: u64) -> (u64, u64) { + let start = if node_id == 1 { 2 } else { (node_id << 48) + 2 }; + let end = if node_id == MAX_NODE_ID { + FILE_INODE_TAG_BIT + } else { + ((node_id + 1) << 48) + 2 + }; + (start, end) +} + +fn file_id_window(node_id: u64) -> (u64, u64) { + file_seq_window(node_id) +} + +fn shard_id_window(node_id: u64) -> (u64, u64) { + let start = if node_id == 1 { 4 } else { (node_id << 32) + 4 }; + let end = if node_id == MAX_NODE_ID { + u64::MAX + } else { + ((node_id + 1) << 32) + 4 + }; + (start, end) +} + +fn assert_inside(kind: &str, node_id: u64, start: u64, count: u64, window: (u64, u64)) { + let end = start.checked_add(count).expect("grant end"); + assert!( + start >= window.0 && end <= window.1, + "{kind} grant [{start}, {end}) from node {node_id} escaped {window:?}" + ); +} + +fn grant(alloc: &DurableIdAllocator, uuid: u128, kind: AllocIdKind, count: u64) -> (u64, u64) { + alloc + .allocate_block(uuid, kind, count) + .unwrap_or_else(|err| panic!("allocate {kind:?} on uuid {uuid:#x}: {err}")) +} + +#[test] +fn fresh_node_above_one_starts_in_its_namespace() { + let dir = tempfile::tempdir().unwrap(); + let node_id = 6u64; + let alloc = DurableIdAllocator::open_for_node(dir.path(), node_id).unwrap(); + let (file_seq_start, _) = file_seq_window(node_id); + let (dir_start, _) = dir_inode_window(node_id); + let (file_id_start, _) = file_id_window(node_id); + let (shard_start, _) = shard_id_window(node_id); + + let (file_inode, file_count) = grant(&alloc, 0x11, AllocIdKind::FileInode, 4); + let (dir_inode, dir_count) = grant(&alloc, 0x12, AllocIdKind::DirInode, 4); + let (file_id, file_id_count) = grant(&alloc, 0x13, AllocIdKind::FileId, 4); + let (shard_id, shard_count) = grant(&alloc, 0x14, AllocIdKind::ShardId, 4); + + assert_eq!(file_inode, make_file_inode_id(file_seq_start)); + assert!(is_file_inode_id(file_inode)); + assert_eq!(dir_inode, dir_start); + assert!(is_dir_inode_id(dir_inode)); + assert_eq!(file_id, file_id_start); + assert_eq!(shard_id, shard_start); + assert_inside( + "file inode seq", + node_id, + file_seq_start, + file_count, + file_seq_window(node_id), + ); + assert_inside( + "dir inode", + node_id, + dir_inode, + dir_count, + dir_inode_window(node_id), + ); + assert_inside( + "file id", + node_id, + file_id, + file_id_count, + file_id_window(node_id), + ); + assert_inside( + "shard id", + node_id, + shard_id, + shard_count, + shard_id_window(node_id), + ); +} + +#[test] +fn dirty_allocator_reopens_as_stored_and_is_not_relocated() { + let dir = tempfile::tempdir().unwrap(); + let stored = { + let alloc = DurableIdAllocator::open_for_node(dir.path(), 4).unwrap(); + let (file_inode, _) = grant(&alloc, 0x21, AllocIdKind::FileInode, 3); + let (dir_inode, _) = grant(&alloc, 0x22, AllocIdKind::DirInode, 5); + let (file_id, _) = grant(&alloc, 0x23, AllocIdKind::FileId, 7); + let (shard_id, _) = grant(&alloc, 0x24, AllocIdKind::ShardId, 9); + (file_inode, dir_inode, file_id, shard_id) + }; + + // The directory already granted ids. Opening it as node 32767 must continue the + // stored watermarks from node 4, not jump to node 32767's fresh namespace. + let alloc = DurableIdAllocator::open_for_node(dir.path(), MAX_NODE_ID).unwrap(); + let (file_inode, _) = grant(&alloc, 0x31, AllocIdKind::FileInode, 1); + let (dir_inode, _) = grant(&alloc, 0x32, AllocIdKind::DirInode, 1); + let (file_id, _) = grant(&alloc, 0x33, AllocIdKind::FileId, 1); + let (shard_id, _) = grant(&alloc, 0x34, AllocIdKind::ShardId, 1); + + let (stored_file, stored_dir, stored_file_id, stored_shard) = stored; + assert_eq!(file_inode, stored_file + 3); + assert_eq!(dir_inode, stored_dir + 5); + assert_eq!(file_id, stored_file_id + 7); + assert_eq!(shard_id, stored_shard + 9); + + let (relocated_file_seq, _) = file_seq_window(MAX_NODE_ID); + let (relocated_dir, _) = dir_inode_window(MAX_NODE_ID); + let (relocated_file_id, _) = file_id_window(MAX_NODE_ID); + let (relocated_shard, _) = shard_id_window(MAX_NODE_ID); + assert_ne!(file_inode, make_file_inode_id(relocated_file_seq)); + assert_ne!(dir_inode, relocated_dir); + assert_ne!(file_id, relocated_file_id); + assert_ne!(shard_id, relocated_shard); +} + +#[test] +fn reopened_same_node_continues_the_stored_watermark() { + let dir = tempfile::tempdir().unwrap(); + let first_file_id = { + let alloc = DurableIdAllocator::open_for_node(dir.path(), 2).unwrap(); + let (file_id, count) = grant(&alloc, 0x41, AllocIdKind::FileId, 8); + assert_eq!(file_id, (2u64 << 48) + 1); + assert_eq!(count, 8); + file_id + }; + let alloc = DurableIdAllocator::open_for_node(dir.path(), 2).unwrap(); + let (next_file_id, _) = grant(&alloc, 0x42, AllocIdKind::FileId, 1); + assert_eq!(next_file_id, first_file_id + 8); + assert_inside("file id", 2, next_file_id, 1, file_id_window(2)); +} + +#[test] +fn independent_allocators_for_node_ids_1_through_32767_do_not_overlap() { + // Fresh `open_for_node` counters, confirmed against real allocators below: + // node 1 starts at the historical defaults, and every later node owns a + // disjoint `[node_id << 48, next)` inode/file window and `[node_id << 32, next)` shard window. + let sample = [1u64, 2, 3, 17, 255, 1024, 4096, 16384, 32766, MAX_NODE_ID]; + let mut issued_file_seqs = Vec::new(); + let mut issued_dir_inodes = Vec::new(); + let mut issued_file_ids = Vec::new(); + let mut issued_shard_ids = Vec::new(); + + for node_id in sample { + let dir = tempfile::tempdir().unwrap(); + let alloc = DurableIdAllocator::open_for_node(dir.path(), node_id).unwrap(); + let (file_inode, file_count) = grant(&alloc, 0x51, AllocIdKind::FileInode, 2); + let (dir_inode, dir_count) = grant(&alloc, 0x52, AllocIdKind::DirInode, 2); + let (file_id, file_id_count) = grant(&alloc, 0x53, AllocIdKind::FileId, 2); + let (shard_id, shard_count) = grant(&alloc, 0x54, AllocIdKind::ShardId, 2); + + let (file_seq_start, _) = file_seq_window(node_id); + assert_eq!( + file_inode, + make_file_inode_id(file_seq_start), + "node {node_id}" + ); + assert_eq!(dir_inode, dir_inode_window(node_id).0, "node {node_id}"); + assert_eq!(file_id, file_id_window(node_id).0, "node {node_id}"); + assert_eq!(shard_id, shard_id_window(node_id).0, "node {node_id}"); + assert!(is_file_inode_id(file_inode), "node {node_id}"); + assert!(is_dir_inode_id(dir_inode), "node {node_id}"); + + issued_file_seqs.push((file_seq_start, file_seq_start + file_count)); + issued_dir_inodes.push((dir_inode, dir_inode + dir_count)); + issued_file_ids.push((file_id, file_id + file_id_count)); + issued_shard_ids.push((shard_id, shard_id + shard_count)); + } + assert_ranges_disjoint("file inode seq", &issued_file_seqs); + assert_ranges_disjoint("dir inode", &issued_dir_inodes); + assert_ranges_disjoint("file id", &issued_file_ids); + assert_ranges_disjoint("shard id", &issued_shard_ids); + + // The same windows cover every legal node id. Adjacent windows meet and do not overlap, + // so two fresh allocators in `1..=32767` cannot hand out the same inode, file id, or shard id. + let mut previous_file = None; + let mut previous_dir = None; + let mut previous_file_id = None; + let mut previous_shard = None; + for node_id in 1..=MAX_NODE_ID { + previous_file = Some(assert_window_follows( + "file inode seq", + node_id, + file_seq_window(node_id), + previous_file, + )); + previous_dir = Some(assert_window_follows( + "dir inode", + node_id, + dir_inode_window(node_id), + previous_dir, + )); + previous_file_id = Some(assert_window_follows( + "file id", + node_id, + file_id_window(node_id), + previous_file_id, + )); + previous_shard = Some(assert_window_follows( + "shard id", + node_id, + shard_id_window(node_id), + previous_shard, + )); + } + + let rejected = DurableIdAllocator::open_for_node(tempfile::tempdir().unwrap().path(), 0); + assert!(matches!(rejected, Err(MetaDbError::IdentityRejected(_)))); + let above = + DurableIdAllocator::open_for_node(tempfile::tempdir().unwrap().path(), MAX_NODE_ID + 1); + assert!(matches!(above, Err(MetaDbError::IdentityRejected(_)))); +} + +fn assert_window_follows( + kind: &str, + node_id: u64, + window: (u64, u64), + previous_end: Option, +) -> u64 { + assert!( + window.0 < window.1, + "{kind} window for node {node_id} is empty: {window:?}" + ); + if let Some(previous_end) = previous_end { + assert!( + window.0 >= previous_end, + "{kind} window for node {node_id} overlaps the previous node at {window:?}, previous end {previous_end}" + ); + } + window.1 +} + +fn assert_ranges_disjoint(kind: &str, ranges: &[(u64, u64)]) { + let mut ordered = ranges.to_vec(); + ordered.sort_unstable(); + for pair in ordered.windows(2) { + assert!( + pair[0].1 <= pair[1].0, + "{kind} ranges overlap: {:?} and {:?}", + pair[0], + pair[1] + ); + } +} diff --git a/crates/metadb-cluster/tests/membership_retarget_tests.rs b/crates/metadb-cluster/tests/membership_retarget_tests.rs new file mode 100644 index 0000000..886ec8d --- /dev/null +++ b/crates/metadb-cluster/tests/membership_retarget_tests.rs @@ -0,0 +1,131 @@ +//! White-box checks for [`plan_membership_voters`](metadb_cluster::plan_membership_voters). +//! +//! Growth takes the lowest registered ids. Shrink drops the highest ids. `ensure_node` +//! is inserted even when `target_voters` is already satisfied. These cases exercise the +//! planner directly and do not start Raft. + +use std::collections::BTreeSet; + +use metadb_cluster::plan_membership_voters; +use metadb_core::MetaDbError; + +fn set_of(ids: &[u64]) -> BTreeSet { + ids.iter().copied().collect() +} + +fn plan( + current: &[u64], + registered: &[u64], + target_voters: usize, + ensure_node: Option, +) -> Result, MetaDbError> { + plan_membership_voters( + &set_of(current), + &set_of(registered), + target_voters, + ensure_node, + ) +} + +#[test] +fn grow_fills_the_lowest_registered_ids() { + let grown = plan(&[1], &[1, 4, 2, 3], 3, None).unwrap(); + assert_eq!(grown, set_of(&[1, 2, 3])); + + // 2 and 4 are already voters. The next id is the lowest registered id that is absent. + let skipped = plan(&[2, 4], &[1, 2, 3, 4, 5], 3, None).unwrap(); + assert_eq!(skipped, set_of(&[1, 2, 4])); + + let unchanged = plan(&[1, 2, 3], &[1, 2, 3, 9], 3, None).unwrap(); + assert_eq!(unchanged, set_of(&[1, 2, 3])); + + let from_empty = plan(&[], &[5, 1, 4], 2, None).unwrap(); + assert_eq!(from_empty, set_of(&[1, 4])); +} + +#[test] +fn shrink_drops_the_highest_ids() { + let to_two = plan(&[1, 2, 3], &[1, 2, 3], 2, None).unwrap(); + assert_eq!(to_two, set_of(&[1, 2])); + + let to_one = plan(&[1, 2, 3], &[1, 2, 3], 1, None).unwrap(); + assert_eq!(to_one, set_of(&[1])); + + // Registered ids do not choose who is removed. The highest current ids go first. + let unordered = plan(&[9, 2, 5, 7], &[1], 2, None).unwrap(); + assert_eq!(unordered, set_of(&[2, 5])); + + let already = plan(&[1, 2], &[9, 8, 7], 2, None).unwrap(); + assert_eq!(already, set_of(&[1, 2])); +} + +#[test] +fn ensure_node_is_kept_even_when_the_target_is_already_met() { + let kept = plan(&[1, 2], &[1, 2, 3], 2, Some(3)).unwrap(); + assert_eq!(kept, set_of(&[1, 2, 3])); + + let filled = plan(&[1], &[1, 2, 3], 3, Some(3)).unwrap(); + assert_eq!(filled, set_of(&[1, 2, 3])); + + let already_present = plan(&[1, 2, 3], &[1, 2, 3], 2, Some(2)).unwrap(); + assert_eq!(already_present, set_of(&[1, 2, 3])); + + // `ensure_node` does not shrink. A target below the ensured set stays at that set. + let no_shrink = plan(&[1, 2, 3], &[1, 2, 3], 1, Some(3)).unwrap(); + assert_eq!(no_shrink, set_of(&[1, 2, 3])); + + // A node that is already a voter is valid even when the registry omits it. + let current_only = plan(&[1, 7], &[1], 1, Some(7)).unwrap(); + assert_eq!(current_only, set_of(&[1, 7])); +} + +#[test] +fn target_zero_without_ensure_node_is_refused() { + let refused = plan(&[1, 2, 3], &[1, 2, 3], 0, None).unwrap_err(); + assert!( + matches!(refused, MetaDbError::ConsensusError(ref message) if message.contains("at least 1")), + "{refused}" + ); + + let empty = plan(&[], &[], 0, None).unwrap_err(); + assert!( + matches!(empty, MetaDbError::ConsensusError(ref message) if message.contains("at least 1")), + "{empty}" + ); +} + +#[test] +fn ensure_node_zero_is_refused() { + let refused = plan(&[1], &[1, 2], 2, Some(0)).unwrap_err(); + assert!( + matches!(refused, MetaDbError::IdentityRejected(ref message) if message.contains("node id 0")), + "{refused}" + ); +} + +#[test] +fn not_enough_registered_nodes_is_an_error() { + let short = plan(&[1], &[1, 2], 4, None).unwrap_err(); + assert!( + matches!(short, MetaDbError::ConsensusError(ref message) if message.contains("need 4") && message.contains("can form 2")), + "{short}" + ); + + let none_registered = plan(&[], &[], 1, None).unwrap_err(); + assert!( + matches!(none_registered, MetaDbError::ConsensusError(ref message) if message.contains("need 1") && message.contains("can form 0")), + "{none_registered}" + ); + + let unknown = plan(&[1], &[1, 2], 2, Some(9)).unwrap_err(); + assert!( + matches!(unknown, MetaDbError::ConsensusError(ref message) if message.contains("not registered")), + "{unknown}" + ); + + let ensure_still_short = plan(&[1], &[1, 2], 5, Some(2)).unwrap_err(); + assert!( + matches!(ensure_still_short, MetaDbError::ConsensusError(ref message) if message.contains("need 5") && message.contains("can form 2")), + "{ensure_still_short}" + ); +} diff --git a/crates/metadb-server/Cargo.toml b/crates/metadb-server/Cargo.toml index 3939546..b497c31 100644 --- a/crates/metadb-server/Cargo.toml +++ b/crates/metadb-server/Cargo.toml @@ -39,6 +39,7 @@ tracing-subscriber = { workspace = true } [dev-dependencies] tempfile = { workspace = true } +wincode = { workspace = true } openraft = { workspace = true } metadb-core = { workspace = true } metadb-cluster = { workspace = true } diff --git a/crates/metadb-server/tests/ci_bounded_prefix_load.rs b/crates/metadb-server/tests/ci_bounded_prefix_load.rs new file mode 100644 index 0000000..1d64bc2 --- /dev/null +++ b/crates/metadb-server/tests/ci_bounded_prefix_load.rs @@ -0,0 +1,267 @@ +//! Reduced CI prefix-load fixture. +//! +//! Shape: 4 prefixes × 25 creates, then 50 overwrite/delete operations, concurrency 4. +//! `errors` and `correctness_errors` must both be 0. +//! +//! This is a reduced CI fixture only. The official 100 prefixes × 10,000 creates + +//! 100,000 overwrite/delete at concurrency 64 belongs on three VMs, not in CI. A green +//! run of this file is not that load and is not a production benchmark. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use metadb_core::ROOT_INODE_ID; +use metadb_server::stress::persistent_config; +use metadb_server::PersistentMetaDbCluster; +use metadb_tx::SetAttrPatch; +use tempfile::tempdir; + +const PREFIXES: usize = 4; +const CREATES_PER_PREFIX: usize = 25; +const MUTATIONS: usize = 50; +const CONCURRENCY: usize = 4; +const CREATE_BYTES: i64 = 64; +const OVERWRITE_BYTES: i64 = 256; +const OPEN_TIMEOUT: Duration = Duration::from_secs(60); + +#[derive(Clone, Copy)] +enum Mutation { + Overwrite, + Delete, +} + +struct ExpectedFile { + size_bytes: i64, + mode: u32, +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn ci_bounded_prefix_load_has_no_errors() { + assert_eq!(CONCURRENCY, PREFIXES); + let dir = tempdir().unwrap(); + // Large split threshold: this fixture must not depend on a surprise shard split. + let cfg = persistent_config(dir.path(), 4 * 1024 * 1024 * 1024); + let (cluster, _) = + tokio::time::timeout(OPEN_TIMEOUT, PersistentMetaDbCluster::open_and_serve(cfg)) + .await + .expect("open_and_serve timed out") + .expect("open_and_serve failed"); + let cluster = Arc::new(cluster); + + let mut prefixes = Vec::with_capacity(PREFIXES); + for index in 0..PREFIXES { + let entry = cluster + .mkdir_auto_id(ROOT_INODE_ID, &format!("prefix_{index}"), 7, 0o755) + .await + .unwrap_or_else(|err| panic!("mkdir prefix_{index}: {err}")); + prefixes.push(entry.attr.inode_id); + } + + let errors = Arc::new(AtomicU64::new(0)); + let error_log = Arc::new(std::sync::Mutex::new(Vec::::new())); + let mut create_workers = Vec::with_capacity(CONCURRENCY); + for pid in prefixes.iter().copied() { + let cluster = Arc::clone(&cluster); + let errors = Arc::clone(&errors); + let error_log = Arc::clone(&error_log); + create_workers.push(tokio::spawn(async move { + for seq in 0..CREATES_PER_PREFIX { + let name = file_name(seq); + if let Err(err) = cluster + .create_file_auto_id(pid, &name, 7, 0o644, CREATE_BYTES) + .await + { + note_error( + &errors, + &error_log, + format!("create {name} in {pid}: {err}"), + ); + } + } + })); + } + for worker in create_workers { + worker.await.expect("create worker panicked"); + } + + // 50 mutations spread across the four prefixes. Each file is owned by one worker. + let plan = mutation_plan(); + assert_eq!(plan.len(), MUTATIONS); + let mut mutation_workers = Vec::with_capacity(CONCURRENCY); + for (worker, pid) in prefixes.iter().copied().enumerate() { + let cluster = Arc::clone(&cluster); + let errors = Arc::clone(&errors); + let error_log = Arc::clone(&error_log); + let owned: Vec<(usize, Mutation)> = plan + .iter() + .copied() + .filter(|(prefix, _, _)| *prefix == worker) + .map(|(_, seq, kind)| (seq, kind)) + .collect(); + mutation_workers.push(tokio::spawn(async move { + for (seq, kind) in owned { + let name = file_name(seq); + let result = match kind { + Mutation::Overwrite => cluster + .tx_router() + .setattr( + pid, + &name, + SetAttrPatch { + mode: Some(0o640), + uid: None, + size_bytes: Some(OVERWRITE_BYTES), + fid: None, + modify_time: None, + }, + ) + .await + .map(|_| ()), + Mutation::Delete => cluster.tx_router().unlink(pid, &name).await.map(|_| ()), + }; + if let Err(err) = result { + note_error( + &errors, + &error_log, + format!("{:?} {name} in {pid}: {err}", kind_name(kind)), + ); + } + } + })); + } + for worker in mutation_workers { + worker.await.expect("mutation worker panicked"); + } + + let mut expected: HashMap<(usize, usize), Option> = HashMap::new(); + for prefix in 0..PREFIXES { + for seq in 0..CREATES_PER_PREFIX { + expected.insert( + (prefix, seq), + Some(ExpectedFile { + size_bytes: CREATE_BYTES, + mode: 0o644, + }), + ); + } + } + for (prefix, seq, kind) in plan { + match kind { + Mutation::Overwrite => { + expected.insert( + (prefix, seq), + Some(ExpectedFile { + size_bytes: OVERWRITE_BYTES, + mode: 0o640, + }), + ); + } + Mutation::Delete => { + expected.insert((prefix, seq), None); + } + } + } + + let mut correctness_errors = 0u64; + let mut details = Vec::new(); + for (prefix, pid) in prefixes.iter().copied().enumerate() { + let mut children = 0i64; + let mut bytes = 0i64; + for seq in 0..CREATES_PER_PREFIX { + let name = file_name(seq); + let want = expected.get(&(prefix, seq)).and_then(|file| file.as_ref()); + match cluster.tx_router().lookup(pid, &name).await { + Ok(Some(entry)) => match want { + Some(file) => { + children += 1; + bytes += file.size_bytes; + if entry.attr.size_bytes != file.size_bytes || entry.attr.mode != file.mode + { + correctness_errors += 1; + details.push(format!( + "prefix {prefix} {name} size {} mode {:o}, want size {} mode {:o}", + entry.attr.size_bytes, entry.attr.mode, file.size_bytes, file.mode + )); + } + } + None => { + correctness_errors += 1; + details.push(format!("prefix {prefix} {name} still exists after delete")); + } + }, + Ok(None) => { + if want.is_some() { + correctness_errors += 1; + details.push(format!("prefix {prefix} {name} missing")); + } + } + Err(err) => { + correctness_errors += 1; + details.push(format!("lookup prefix {prefix} {name}: {err}")); + } + } + } + match cluster.tx_router().dirstat(pid).await { + Ok(stat) => { + if stat.num_children != children || stat.size_bytes != bytes { + correctness_errors += 1; + details.push(format!( + "prefix {prefix} dirstat children {} bytes {}, want children {children} bytes {bytes}", + stat.num_children, stat.size_bytes + )); + } + } + Err(err) => { + correctness_errors += 1; + details.push(format!("dirstat prefix {prefix}: {err}")); + } + } + } + + let error_count = errors.load(Ordering::Relaxed); + let logged = error_log.lock().unwrap().clone(); + cluster.shutdown().await.expect("shutdown"); + assert_eq!( + error_count, 0, + "errors={error_count} correctness_errors={correctness_errors} log={logged:?} details={details:?}" + ); + assert_eq!( + correctness_errors, 0, + "errors={error_count} correctness_errors={correctness_errors} details={details:?}" + ); +} + +fn file_name(seq: usize) -> String { + format!("f{seq:02}.dat") +} + +fn kind_name(kind: Mutation) -> &'static str { + match kind { + Mutation::Overwrite => "overwrite", + Mutation::Delete => "delete", + } +} + +fn note_error(errors: &AtomicU64, log: &std::sync::Mutex>, message: String) { + errors.fetch_add(1, Ordering::Relaxed); + log.lock().unwrap().push(message); +} + +/// 13 + 13 + 12 + 12 = 50 overwrite/delete operations, one file each. +fn mutation_plan() -> Vec<(usize, usize, Mutation)> { + let mut plan = Vec::with_capacity(MUTATIONS); + for prefix in 0..PREFIXES { + let overwrite = if prefix < 2 { 7 } else { 6 }; + let delete = 6; + for seq in 0..overwrite { + plan.push((prefix, seq, Mutation::Overwrite)); + } + for seq in overwrite..(overwrite + delete) { + plan.push((prefix, seq, Mutation::Delete)); + } + } + assert_eq!(plan.len(), MUTATIONS); + plan +} diff --git a/crates/metadb-server/tests/scale_in_restart_tests.rs b/crates/metadb-server/tests/scale_in_restart_tests.rs new file mode 100644 index 0000000..dd91ab2 --- /dev/null +++ b/crates/metadb-server/tests/scale_in_restart_tests.rs @@ -0,0 +1,427 @@ +//! Same-machine, in-process scale-in of three localhost voters. +//! +//! Three `PersistentMetaDbCluster` servers run inside this test process and talk over +//! localhost gRPC. `DurableCellManager::scale_out_replicas` shrinks the voter set from +//! the highest ids (3→2 drops node 3, 3→1 drops nodes 3 and 2). The test then shuts the +//! servers down and reopens the same data directories. +//! +//! This is a single-process test. It does not replace three-VM scale-in evidence. + +use std::collections::{BTreeMap, BTreeSet}; +use std::fs::File; +use std::io::Read; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::Duration; + +use metadb_cluster::{CompositeShardRoute, SplitPlanRecord}; +use metadb_core::codec; +use metadb_core::{ + make_file_inode_id, verify_crc32c_le, MetaDbError, NodeId, ShardId, ROOT_INODE_ID, +}; +use metadb_server::{PersistentMetaDbCluster, ServerTomlConfig}; +use tempfile::tempdir; + +const BUCKET_ID: u64 = 10; +const FILE_BYTES: i64 = 64; + +fn fast_config(dir: &Path, node_id: u64, join: &str) -> ServerTomlConfig { + let toml_text = format!( + r#" +[node] +node_id = {node_id} +cell_id = 1 +role = "all-in-one" +data_dir = "{}" +grpc_listen_addr = "127.0.0.1:0" + +[sharding] +bootstrap_table_shards = false +shard_split_threshold_bytes = 4294967296 + +[cluster] +join = "{join}" +"#, + dir.display() + ); + let mut cfg = ServerTomlConfig::from_toml_str(&toml_text).unwrap(); + cfg.raft_options.heartbeat_interval_ms = 80; + cfg.raft_options.election_timeout_min_ms = 200; + cfg.raft_options.election_timeout_max_ms = 400; + cfg +} + +fn raft_voters(cluster: &PersistentMetaDbCluster) -> BTreeSet { + let routes = cluster.cell_manager().list_routes(); + assert!(!routes.is_empty(), "cell has no shard routes"); + let mut found: Option> = None; + for route in routes { + let voters = cluster + .cell_manager() + .raft_voter_ids(route.shard_id) + .unwrap_or_else(|err| panic!("raft voters for shard {}: {err}", route.shard_id)); + match &found { + None => found = Some(voters), + Some(previous) => assert_eq!(previous, &voters, "shard voter sets diverged"), + } + } + found.unwrap() +} + +/// On-disk `CELL_MANAGER_STATE` body. Field order matches `DurableCellManager`'s +/// writer. `list_routes` overlays this cache with live Raft membership, so the +/// shrink check decodes the file instead. +#[derive(Debug, serde::Deserialize, wincode::SchemaRead)] +struct OnDiskCellState { + _nodes: BTreeMap, + routes: BTreeMap, + _split_plans: BTreeMap, + _joined_existing: bool, + _join_pending: bool, + _node_instances: BTreeMap, +} + +fn cell_dir(cluster: &PersistentMetaDbCluster) -> PathBuf { + cluster + .config() + .node + .data_dir + .join(format!("cell_{}", cluster.config().node.cell_id)) +} + +/// Voter ids stored in `CELL_MANAGER_STATE`, not the live Raft overlay. +fn voters_in_cell_state_file(cell_dir: &Path) -> BTreeSet { + let path = cell_dir.join("CELL_MANAGER_STATE"); + let mut raw = Vec::new(); + File::open(&path) + .unwrap_or_else(|err| panic!("open {}: {err}", path.display())) + .read_to_end(&mut raw) + .unwrap_or_else(|err| panic!("read {}: {err}", path.display())); + let body = verify_crc32c_le(&raw, "CELL_MANAGER_STATE") + .unwrap_or_else(|err| panic!("checksum {}: {err}", path.display())); + let state: OnDiskCellState = + codec::deserialize(body).unwrap_or_else(|err| panic!("decode {}: {err}", path.display())); + assert!( + !state.routes.is_empty(), + "CELL_MANAGER_STATE at {} has no routes", + path.display() + ); + let mut found: Option> = None; + for (shard_id, route) in &state.routes { + let voters = route + .peers + .iter() + .filter(|(_, (_, is_voter))| *is_voter) + .map(|(node_id, _)| *node_id) + .collect::>(); + match &found { + None => found = Some(voters), + Some(previous) => assert_eq!( + previous, &voters, + "on-disk voter sets diverged at shard {shard_id}" + ), + } + } + found.unwrap() +} + +async fn open_node(cfg: ServerTomlConfig) -> (Arc, String) { + tokio::time::timeout( + Duration::from_secs(90), + PersistentMetaDbCluster::open_and_serve(cfg), + ) + .await + .expect("open_and_serve timed out") + .expect("open_and_serve failed") +} + +async fn current_leader(nodes: &[Arc]) -> Arc { + for _ in 0..160 { + for node in nodes { + let Some(route) = node.cell_manager().list_routes().into_iter().next() else { + continue; + }; + let Ok((_, group, _)) = node.cell_manager().lookup_local_handle(route.shard_id) else { + continue; + }; + if group.linearizable_read(group.current_epoch()).await.is_ok() { + return Arc::clone(node); + } + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + panic!("timed out waiting for a Raft leader"); +} + +fn is_transient(err: &MetaDbError) -> bool { + matches!( + err, + MetaDbError::NotLeader { .. } | MetaDbError::EpochMismatch { .. } + ) +} + +async fn create_on_leader( + nodes: &[Arc], + name: &str, + inode_seq: u64, + fid: u64, + errors: &mut Vec, +) { + let mut last_transient = None; + for _ in 0..160 { + for node in nodes { + match node + .tx_router() + .create_file( + BUCKET_ID, + name, + make_file_inode_id(inode_seq), + fid, + 7, + 0o644, + FILE_BYTES, + ) + .await + { + Ok(_) => return, + Err(err) if is_transient(&err) => last_transient = Some(err.to_string()), + Err(err) => { + errors.push(format!( + "create {name} on node {}: {err}", + node.config().node.node_id + )); + return; + } + } + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + errors.push(format!( + "create {name} was not acknowledged ({})", + last_transient.unwrap_or_else(|| "no response".to_string()) + )); +} + +async fn expect_dirstat( + nodes: &[Arc], + label: &str, + errors: &mut Vec, +) { + let mut last_transient = None; + for _ in 0..160 { + for node in nodes { + match node.tx_router().dirstat(BUCKET_ID).await { + Ok(stat) => { + if stat.num_children != 2 || stat.size_bytes != FILE_BYTES * 2 { + errors.push(format!( + "dirstat {label} on node {} children={} bytes={}", + node.config().node.node_id, + stat.num_children, + stat.size_bytes + )); + } + return; + } + Err(err) if is_transient(&err) => last_transient = Some(err.to_string()), + Err(err) => { + errors.push(format!( + "dirstat {label} on node {}: {err}", + node.config().node.node_id + )); + return; + } + } + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + errors.push(format!( + "dirstat {label} was not acknowledged ({})", + last_transient.unwrap_or_else(|| "no response".to_string()) + )); +} + +async fn expect_readable( + nodes: &[Arc], + name: &str, + errors: &mut Vec, +) { + let mut last_transient = None; + for _ in 0..160 { + for node in nodes { + match node.tx_router().lookup(BUCKET_ID, name).await { + Ok(Some(entry)) => { + if entry.attr.size_bytes != FILE_BYTES { + errors.push(format!( + "lookup {name} size {} on node {}", + entry.attr.size_bytes, + node.config().node.node_id + )); + } + return; + } + Ok(None) => { + last_transient = + Some(format!("missing on node {}", node.config().node.node_id)); + } + Err(err) if is_transient(&err) => last_transient = Some(err.to_string()), + Err(err) => { + errors.push(format!( + "lookup {name} on node {}: {err}", + node.config().node.node_id + )); + return; + } + } + } + tokio::time::sleep(Duration::from_millis(50)).await; + } + errors.push(format!( + "lookup {name} was not readable ({})", + last_transient.unwrap_or_else(|| "no response".to_string()) + )); +} + +async fn shutdown_all(nodes: Vec>) { + for node in &nodes { + node.shutdown() + .await + .unwrap_or_else(|err| panic!("shutdown node {}: {err}", node.config().node.node_id)); + } + drop(nodes); +} + +async fn scale_in_and_reopen(target_voters: usize) { + assert!( + (1..=2).contains(&target_voters), + "this fixture only shrinks three voters to 2 or 1" + ); + let expected: BTreeSet = (1..=target_voters as u64).collect(); + let dir = tempdir().unwrap(); + let dir1 = dir.path().join("node1"); + let dir2 = dir.path().join("node2"); + let dir3 = dir.path().join("node3"); + let cfg1 = fast_config(&dir1, 1, ""); + + let (node1, addr1) = open_node(cfg1.clone()).await; + let mut errors = Vec::new(); + match node1 + .tx_router() + .mkdir(ROOT_INODE_ID, "bucket", BUCKET_ID, 7, 0o755) + .await + { + Ok(_) => {} + Err(err) => errors.push(format!("mkdir bucket: {err}")), + } + create_on_leader( + &[Arc::clone(&node1)], + "before_scale_in.dat", + 100, + 500, + &mut errors, + ) + .await; + + let cfg2 = fast_config(&dir2, 2, &addr1); + let cfg3 = fast_config(&dir3, 3, &addr1); + let (node2, _) = open_node(cfg2.clone()).await; + let (node3, _) = open_node(cfg3.clone()).await; + let initial = [Arc::clone(&node1), Arc::clone(&node2), Arc::clone(&node3)]; + assert_eq!( + raft_voters(&node1), + BTreeSet::from([1, 2, 3]), + "three localhost voters before scale-in" + ); + + let leader = current_leader(&initial).await; + let leader_cell = cell_dir(&leader); + match leader + .cell_manager() + .scale_out_replicas(target_voters) + .await + { + Ok(shards) => { + if shards == 0 { + errors.push("scale_out_replicas updated no shards".to_string()); + } + } + Err(err) => errors.push(format!( + "scale_out_replicas({target_voters}) on node {}: {err}", + leader.config().node.node_id + )), + } + if errors.is_empty() { + assert_eq!( + raft_voters(&leader), + expected, + "leader voter set after shrink to {target_voters}" + ); + assert_eq!( + voters_in_cell_state_file(&leader_cell), + expected, + "CELL_MANAGER_STATE on disk after shrink to {target_voters}" + ); + } + + let survivors: Vec<_> = initial + .iter() + .filter(|node| expected.contains(&node.config().node.node_id)) + .cloned() + .collect(); + create_on_leader(&survivors, "after_scale_in.dat", 101, 501, &mut errors).await; + expect_readable(&survivors, "before_scale_in.dat", &mut errors).await; + expect_readable(&survivors, "after_scale_in.dat", &mut errors).await; + expect_dirstat(&survivors, "before restart", &mut errors).await; + + // Shutdown, then drop every handle. The allocator lock lives until the last + // `PersistentMetaDbCluster` is dropped, and reopen needs that lock and the ports. + drop(survivors); + drop(leader); + drop(node1); + drop(node2); + drop(node3); + shutdown_all(Vec::from(initial)).await; + + let (re1, re2, re3) = tokio::join!(open_node(cfg1), open_node(cfg2), open_node(cfg3)); + let reopened = [re1.0, re2.0, re3.0]; + let reopened_survivors: Vec<_> = reopened + .iter() + .filter(|node| expected.contains(&node.config().node.node_id)) + .cloned() + .collect(); + for node in &reopened_survivors { + let voters = raft_voters(node); + if voters != expected { + errors.push(format!( + "reopened node {} voter set {voters:?}, want {expected:?}", + node.config().node.node_id + )); + } + } + expect_readable(&reopened_survivors, "before_scale_in.dat", &mut errors).await; + expect_readable(&reopened_survivors, "after_scale_in.dat", &mut errors).await; + expect_dirstat(&reopened_survivors, "after restart", &mut errors).await; + let on_disk = voters_in_cell_state_file(&leader_cell); + if on_disk != expected { + errors.push(format!( + "CELL_MANAGER_STATE after restart is {on_disk:?}, want {expected:?}" + )); + } + + shutdown_all(reopened.to_vec()).await; + assert!( + errors.is_empty(), + "application errors on the checked scale-in path (target {target_voters}): {errors:?}" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn in_process_scale_in_three_to_two_survives_restart() { + // One OS process, three localhost voters. Not a three-VM scale-in. + scale_in_and_reopen(2).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn in_process_scale_in_three_to_one_survives_restart() { + // One OS process, three localhost voters. Not a three-VM scale-in. + scale_in_and_reopen(1).await; +} diff --git a/deny.toml b/deny.toml new file mode 100644 index 0000000..23bc906 --- /dev/null +++ b/deny.toml @@ -0,0 +1,39 @@ +# Initial reporting config for `.github/workflows/dependency-audit.yml`. +# This is not a production-grade supply-chain policy. +# +# `unmaintained = "all"` and `unsound = "workspace"` make those advisory classes +# errors. Vulnerability advisories are always errors. Yanked crates warn. +# Duplicate versions warn via `[bans]`. + +[graph] +targets = [ + "x86_64-unknown-linux-gnu", + "aarch64-unknown-linux-gnu", +] + +[advisories] +unmaintained = "all" +unsound = "workspace" +yanked = "warn" +ignore = [] + +[licenses] +confidence-threshold = 0.8 +allow = [ + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "Unicode-3.0", + "Zlib", +] +exceptions = [] + +[bans] +multiple-versions = "warn" +wildcards = "allow" +highlight = "all" + +[sources] +unknown-registry = "deny" +unknown-git = "deny" +allow-registry = ["https://github.com/rust-lang/crates.io-index"] diff --git a/docs/en/ci-and-release-gates.md b/docs/en/ci-and-release-gates.md new file mode 100644 index 0000000..daeaff8 --- /dev/null +++ b/docs/en/ci-and-release-gates.md @@ -0,0 +1,66 @@ +# CI and release gates + +[Overview](./README.md) + +This page describes the gates that exist in this tree today. A green GitHub Actions run is not production readiness, and it is not evidence that the official million-operation load passed. + +## Current CI + +[`.github/workflows/ci.yml`](../../.github/workflows/ci.yml) is the test and package workflow. It runs on pull requests to `main`, on pushes to every branch, and on tags that start with `v`. + +### Format, Clippy, and tests + +Job `rust-check-lint-test` runs on `ubuntu-24.04` with a **45-minute** timeout. In order, it: + +1. Rejects `#[ignore]` tests that have an empty reason (`python3 .github/scripts/reject-bare-ignore.py --self-test crates`). +2. Installs `protobuf-compiler`. +3. Installs Rust **1.100.0** with rustfmt and clippy (`dtolnay/rust-toolchain@1.100.0`). +4. Checks formatting: `cargo fmt --all -- --check`. +5. Runs Clippy with warnings denied: `cargo clippy --workspace --all-targets --locked -- -D warnings`. +6. Runs the workspace tests: `cargo test --workspace --locked --no-fail-fast`. + +That test command builds every integration test under `crates/*/tests/`, including the fixtures added with this document: + +- `cargo test -p metadb-cluster --test membership_retarget_tests` +- `cargo test -p metadb-cluster --test id_namespace_join_tests` +- `cargo test -p metadb-server --test scale_in_restart_tests` +- `cargo test -p metadb-server --test ci_bounded_prefix_load` + +No separate CI job was added for those tests. They run because the existing locked workspace test step picks them up. + +### Packaging + +Job `package` also has a **45-minute** timeout. It runs on pull requests, on pushes to `main`, and on `v*` tags. The matrix builds release binaries with `cargo build --release --locked -p metadb-server --bins` for: + +- `x86_64-unknown-linux-gnu` on `ubuntu-24.04` +- `aarch64-unknown-linux-gnu` on `ubuntu-24.04-arm` + +The job then runs `.github/scripts/package-binaries.sh` and uploads the archive. Job `release` publishes a GitHub Release only for a push of a `v*` tag, and only after the test job and the package job succeed. This document does not change branch protection. + +## Bounded prefix load is not the official load + +`ci_bounded_prefix_load` is a reduced CI fixture: **4 prefixes × 25 creates, then 50 overwrite/delete operations, at concurrency 4**. It asserts that application `errors` and `correctness_errors` are both zero on that fixture. + +CI runs that fixture as part of `cargo test --workspace --locked`. It must not be reported as: + +- the official load +- a 1,000,000-operation load +- a paper-scale or production benchmark + +The official load stays on **three VMs**: **100 prefixes × 10,000 creates + 100,000 overwrite/delete operations at concurrency 64**. Passing the CI fixture does not mean that run passed. + +## In-process scale-in is not three-VM evidence + +`scale_in_restart_tests` starts three localhost voters inside **one OS process**, shrinks them to 2 and to 1 with `DurableCellManager::scale_out_replicas`, shuts them down, and reopens the same data directories. It checks that acknowledged writes are still readable, that the Raft voter set matches the shrink target, and that the checked path reports no application errors. + +That restart is same-machine and in-process. It does **not** replace three-VM scale-out or scale-in evidence. A green CI run of this test is not a three-machine membership result. + +## Dependency audit workflow + +[`.github/workflows/dependency-audit.yml`](../../.github/workflows/dependency-audit.yml) is a separate workflow. It runs on `pull_request` and `push`. It installs `cargo-audit` 0.23.0 and `cargo-deny` 0.21.0, then runs both against this workspace. `cargo audit -D unmaintained -D unsound -D yanked` fails the job on a vulnerability or on an unmaintained, unsound, or yanked advisory. `cargo deny --locked check` still runs when that audit step has already failed, so a license, ban, or source finding is not hidden. The job stays failed if either command fails. `cargo deny` fails on a vulnerability advisory, on an unmaintained advisory anywhere in the graph, on an unsound advisory in a workspace crate, on a license outside the allow list, or on an unknown registry or git source. Yanked crates and duplicate crate versions are warnings in `cargo deny` and do not by themselves fail that command. + +This is an **initial reporting job**. It is not a production-grade supply-chain program. It does not review transitive maintainers, pin a private advisory mirror, attest build provenance, or change who can merge. A green audit job is not proof that the tree is production ready, and a green `ci.yml` run is not that proof either. A red audit job means the tools reported a finding; it does not by itself say the workspace tests failed. + +`cargo-deny` reads [`deny.toml`](../../deny.toml) at the repository root. The license allow list is Apache-2.0, MIT, BSD-3-Clause, Unicode-3.0, and Zlib, which is the set `cargo deny check licenses` matched in this workspace when the file was added. Duplicate crate versions are warnings and did not fail the bans check. Unknown registries and unknown git sources are denied. + +When this file was added, `cargo audit` reported three unmaintained advisories and no vulnerability advisories: `chrono` 0.4.45 (`RUSTSEC-2026-0543`), `chrono-tz` 0.8.6 (`RUSTSEC-2026-0555`), and `chrono-tz-build` 0.2.1 (`RUSTSEC-2026-0559`). No fixed upgrade was listed. They come in through `openraft`. The dependency-audit job is expected to fail on those unmaintained findings until the lockfile no longer pulls them in. That failure is a report, not a production-readiness verdict.