From 7dfef4c81a80c4c7f9d5010fd4c193e50be9a823 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 19:37:28 +0000 Subject: [PATCH 1/3] Persist control-plane heartbeats and record safe jumbo placement Store node liveness in CELL_CONTROL_PLANE with a monotonic sequence, and send that record from the maintenance loop without installing shard descriptors as routes. Jumbo isolation still sets a route flag. A placement record now says whether a leadership transfer or a same-size voter replacement was actually committed. Transfers use a new Raft TransferLeader RPC. A change that would drop fault tolerance or add a node that has not joined is refused. This does not add a second cell, split server roles, or move shard files. Co-authored-by: RustFS --- crates/metadb-cluster/src/cell_manager.rs | 763 +++++++++++++++++- .../metadb-cluster/src/control_plane_state.rs | 245 ++++++ crates/metadb-cluster/src/jumbo_placement.rs | 445 ++++++++++ crates/metadb-cluster/src/lib.rs | 8 + .../tests/scale_control_plane_tests.rs | 179 ++++ .../proto/metadb/v1/control_plane.proto | 6 + .../metadb-proto/proto/metadb/v1/raft.proto | 4 + crates/metadb-raft/src/network.rs | 64 +- crates/metadb-server/src/grpc_services.rs | 39 +- crates/metadb-server/src/lib.rs | 74 +- .../tests/control_plane_claim_tests.rs | 107 ++- docs/en/README.md | 3 +- docs/en/architecture.md | 4 +- docs/en/operations.md | 12 +- docs/en/scale-control-plane-status.md | 69 ++ 15 files changed, 1975 insertions(+), 47 deletions(-) create mode 100644 crates/metadb-cluster/src/control_plane_state.rs create mode 100644 crates/metadb-cluster/src/jumbo_placement.rs create mode 100644 crates/metadb-cluster/tests/scale_control_plane_tests.rs create mode 100644 docs/en/scale-control-plane-status.md diff --git a/crates/metadb-cluster/src/cell_manager.rs b/crates/metadb-cluster/src/cell_manager.rs index 37d623c..26195b9 100644 --- a/crates/metadb-cluster/src/cell_manager.rs +++ b/crates/metadb-cluster/src/cell_manager.rs @@ -26,9 +26,18 @@ use metadb_storage::sstable::sync_dir; use metadb_storage::LsmEngineConfig; use metadb_tx::{RoutedShardHandle, TxStateMachineHandler}; +use crate::control_plane_state::{ + decide_heartbeat, normalize_ids, unix_ms, HeartbeatDecision, HeartbeatWrite, + PersistedControlPlane, StoredHeartbeat, StoredPlacement, CONTROL_PLANE_FILE, + CONTROL_PLANE_VERSION, PLACEMENT_RETRY_MS, +}; use crate::id_allocator::{AllocIdKind, DurableIdAllocator}; use crate::identity::{node_id_in_ha_range, ClusterIdentity}; use crate::jumbo::JumboIsolationPlanner; +use crate::jumbo_placement::{ + jumbo_membership_change_allowed, plan_jumbo_placement, CommittedMove, PlacementAction, + PlacementObservation, PlacementPhase, ShardVoters, +}; use crate::meta_cache::{CompositeMetaCache, CompositeShardRoute}; use crate::shard::{ShardHealthState, ShardSplitMode}; use crate::split_worker::{RaftShardSplitWorker, SplitCandidate, SplitCrashPoint}; @@ -136,6 +145,10 @@ pub struct DurableCellManager { membership_lock: tokio::sync::Mutex<()>, /// Raft-applied node instance bindings. Shared with every shard handler. instance_bindings: Arc>>, + /// Heartbeats and jumbo placement records. Not a route table. + control: Mutex, + /// Test hook: the next `n` `CELL_CONTROL_PLANE` persists fail before touching disk. + fail_control_persists: AtomicU32, } impl DurableCellManager { @@ -258,6 +271,7 @@ impl DurableCellManager { &persisted, is_existing, )?; + let control_plane = Self::load_control_plane(&state_dir)?; let mgr = Arc::new(Self { cell_id, @@ -276,6 +290,8 @@ impl DurableCellManager { identity: Mutex::new(preexisting_identity), membership_lock: tokio::sync::Mutex::new(()), instance_bindings: Arc::new(Mutex::new(BTreeMap::new())), + control: Mutex::new(control_plane), + fail_control_persists: AtomicU32::new(0), }); if let Err(error) = mgr.boot_local_shards().await { @@ -366,6 +382,7 @@ impl DurableCellManager { state_existed, )?; let identity = ClusterIdentity::load(&state_dir)?; + let control_plane = Self::load_control_plane(&state_dir)?; Ok(Arc::new(Self { cell_id, state_dir, @@ -383,6 +400,8 @@ impl DurableCellManager { identity: Mutex::new(identity), membership_lock: tokio::sync::Mutex::new(()), instance_bindings: Arc::new(Mutex::new(BTreeMap::new())), + control: Mutex::new(control_plane), + fail_control_persists: AtomicU32::new(0), })) } @@ -1192,28 +1211,45 @@ impl DurableCellManager { match candidate { SplitCandidate::Jumbo { dominant_pid } => { - let mut st = self.state.lock().unwrap(); - let nodes: Vec = st.nodes.keys().copied().collect(); - let all_routes: Vec = st.routes.values().cloned().collect(); - let new_health = JumboIsolationPlanner::select_dedicated_node( - shard_id, - dominant_pid, - live_route.leader_node, - &nodes, - &all_routes, - ); - if st.routes.contains_key(&shard_id) { - let mut next = st.clone(); - if let Some(r) = next.routes.get_mut(&shard_id) { - r.health_state = new_health; - } - let updated = next.routes.get(&shard_id).cloned(); - self.persist_sync(&next)?; - *st = next; - if let Some(updated) = updated { - self.meta_cache.upsert_route(updated); + let dedicated_node = { + let mut st = self.state.lock().unwrap(); + let nodes: Vec = st.nodes.keys().copied().collect(); + let all_routes: Vec = + st.routes.values().cloned().collect(); + let new_health = JumboIsolationPlanner::select_dedicated_node( + shard_id, + dominant_pid, + live_route.leader_node, + &nodes, + &all_routes, + ); + let ShardHealthState::JumboIsolated { dedicated_node, .. } = new_health else { + return Err(MetaDbError::ShardRoutingError( + "jumbo planner did not select a dedicated node".to_string(), + )); + }; + let already = st + .routes + .get(&shard_id) + .is_some_and(|route| route.health_state == new_health); + if !already && st.routes.contains_key(&shard_id) { + let mut next = st.clone(); + if let Some(route) = next.routes.get_mut(&shard_id) { + route.health_state = new_health; + } + let updated = next.routes.get(&shard_id).cloned(); + self.persist_sync(&next)?; + *st = next; + if let Some(updated) = updated { + self.meta_cache.upsert_route(updated); + } } - } + dedicated_node + }; + // The route flag is detection only. Placement below either performs a + // membership-safe move or records why it did not. + self.reconcile_jumbo_placement(shard_id, dominant_pid, dedicated_node) + .await?; Ok(None) } SplitCandidate::SplitAt { @@ -1880,6 +1916,638 @@ impl DurableCellManager { Ok(()) } + /// The next `n` `CELL_CONTROL_PLANE` persists fail before the file is replaced. + pub fn testing_fail_next_control_persists(&self, n: u32) { + self.fail_control_persists.store(n, Ordering::Relaxed); + } + + pub fn stored_heartbeat(&self, node_id: NodeId) -> Option { + self.control + .lock() + .unwrap() + .heartbeats + .get(&node_id) + .cloned() + } + + pub fn stored_placement(&self, shard_id: ShardId) -> Option { + self.control + .lock() + .unwrap() + .placements + .get(&shard_id) + .cloned() + } + + pub fn local_heartbeat_is_fresh(&self, now_ms: u64, interval_ms: u64) -> bool { + self.control + .lock() + .unwrap() + .heartbeats + .get(&self.host.node_id()) + .is_some_and(|heartbeat| { + now_ms.saturating_sub(heartbeat.observed_unix_ms) < interval_ms + }) + } + + /// gRPC addresses of Raft leaders of local shards when this process is not that leader. + pub fn remote_leader_addrs(&self) -> Vec { + let me = self.host.node_id(); + let shard_ids: Vec = self.state.lock().unwrap().routes.keys().copied().collect(); + let mut addrs = BTreeSet::new(); + for shard_id in shard_ids { + let Some(group) = self.host.get_group(shard_id) else { + continue; + }; + let Some(leader) = group.current_leader() else { + continue; + }; + if leader == me { + continue; + } + if let Some(addr) = group.peer_addr(leader) { + if !addr.is_empty() { + addrs.insert(addr); + } + } + } + addrs.into_iter().collect() + } + + /// Records this process's own heartbeat. Shard descriptors from clients are not an input. + /// Disk free space is left unknown; a zero is not stored as a measurement. + pub fn publish_local_heartbeat(&self) -> Result { + let me = self.host.node_id(); + node_id_in_ha_range(me)?; + let hosted = { + let state = self.state.lock().unwrap(); + let mut ids: Vec = state + .routes + .iter() + .filter(|(_, route)| route.peers.contains_key(&me)) + .map(|(id, _)| *id) + .collect(); + ids.sort_unstable(); + ids + }; + let hosted = normalize_ids(hosted).map_err(MetaDbError::ShardRoutingError)?; + let mut guard = self.control.lock().unwrap(); + let seq = guard.next_local_seq.max(1); + let write = HeartbeatWrite { + node_id: me, + seq, + observed_unix_ms: unix_ms(), + disk_free_bytes: None, + reported_shard_ids: Vec::new(), + local_hosted_shard_ids: hosted, + }; + let decision = decide_heartbeat(guard.heartbeats.get(&me), &write) + .map_err(MetaDbError::ShardRoutingError)?; + match decision { + HeartbeatDecision::Replay(existing) => Ok(existing), + HeartbeatDecision::Store(heartbeat) => { + let mut next = guard.clone(); + next.heartbeats.insert(me, heartbeat.clone()); + next.next_local_seq = seq.saturating_add(1); + self.persist_control(&next)?; + *guard = next; + Ok(heartbeat) + } + } + } + + /// Persists a registered peer's liveness. `reported_shard_ids` are stored as an annotation + /// and are not installed into `CELL_MANAGER_STATE` or `CompositeMetaCache`. + pub fn accept_remote_heartbeat( + &self, + node_id: NodeId, + seq: u64, + disk_free_bytes: Option, + reported_shard_ids: Vec, + ) -> Result<()> { + node_id_in_ha_range(node_id)?; + if node_id == self.host.node_id() { + return Err(MetaDbError::ShardRoutingError( + "refusing a remote heartbeat for the local node; this process writes its own heartbeat. Client shard descriptors are not applied to routes" + .to_string(), + )); + } + { + let state = self.state.lock().unwrap(); + if !state.nodes.contains_key(&node_id) { + return Err(MetaDbError::ShardRoutingError(format!( + "node {node_id} is not registered; client shard descriptors are not applied to routes" + ))); + } + } + let reported = normalize_ids(reported_shard_ids).map_err(MetaDbError::ShardRoutingError)?; + let write = HeartbeatWrite { + node_id, + seq, + observed_unix_ms: unix_ms(), + disk_free_bytes, + reported_shard_ids: reported, + local_hosted_shard_ids: Vec::new(), + }; + let mut guard = self.control.lock().unwrap(); + let decision = decide_heartbeat(guard.heartbeats.get(&node_id), &write) + .map_err(MetaDbError::ShardRoutingError)?; + match decision { + HeartbeatDecision::Replay(_) => Ok(()), + HeartbeatDecision::Store(heartbeat) => { + let mut next = guard.clone(); + next.heartbeats.insert(node_id, heartbeat); + self.persist_control(&next)?; + *guard = next; + Ok(()) + } + } + } + + /// Plans jumbo placement from live Raft voters and attempts only a safe move. + /// + /// A blocked plan is `Ok` with `PlacementPhase::Blocked` or `LeaderOnDedicated`. + /// That is not eviction. `Err` is a failed fsync of this record or a voter-set + /// persist after a committed membership change. + pub async fn reconcile_jumbo_placement( + &self, + shard_id: ShardId, + dominant_pid: InodeId, + dedicated_node: NodeId, + ) -> Result { + let _membership = self.membership_lock.lock().await; + let previous = self.stored_placement(shard_id); + let mut committed_moves = previous + .as_ref() + .map(|record| record.committed_moves.clone()) + .unwrap_or_default(); + let mut transfer_attempt = previous + .as_ref() + .map(|record| record.last_transfer_attempt_unix_ms) + .unwrap_or(0); + let mut replace_attempt = previous + .as_ref() + .map(|record| record.last_replace_attempt_unix_ms) + .unwrap_or(0); + + for _ in 0..8 { + let observation = + match self.placement_observation(shard_id, dominant_pid, dedicated_node) { + Ok(observation) => observation, + Err(error) => { + return self.finish_placement(placement_record( + shard_id, + dominant_pid, + dedicated_node, + PlacementPhase::Blocked, + format!("{error}; no membership change was proposed"), + committed_moves, + transfer_attempt, + replace_attempt, + )); + } + }; + for shard in &observation.shards { + self.sync_route_voters_from_raft(shard.shard_id)?; + } + let decision = plan_jumbo_placement(&observation); + let Some(action) = decision.actions.first().cloned() else { + return self.finish_placement(placement_record( + shard_id, + dominant_pid, + dedicated_node, + decision.phase, + decision.blocked_reason, + committed_moves, + transfer_attempt, + replace_attempt, + )); + }; + if !action_runs_on(self.host.node_id(), &observation, &action) { + return self.finish_placement(placement_record( + shard_id, + dominant_pid, + dedicated_node, + decision.phase, + decision.blocked_reason, + committed_moves, + transfer_attempt, + replace_attempt, + )); + } + match action { + PlacementAction::TransferLeadership { + shard_id: target, + to, + } => { + let now = unix_ms(); + if transfer_attempt != 0 + && now.saturating_sub(transfer_attempt) < PLACEMENT_RETRY_MS + { + let reason = append_reason( + &decision.blocked_reason, + "leadership transfer is in cooldown and was not submitted again", + ); + return self.finish_placement(placement_record( + shard_id, + dominant_pid, + dedicated_node, + PlacementPhase::Recorded, + reason, + committed_moves, + transfer_attempt, + replace_attempt, + )); + } + transfer_attempt = now; + self.save_placement(&placement_record( + shard_id, + dominant_pid, + dedicated_node, + decision.phase, + decision.blocked_reason.clone(), + committed_moves.clone(), + transfer_attempt, + replace_attempt, + ))?; + let moved = self.transfer_leadership(target, to).await?; + if moved { + push_move( + &mut committed_moves, + CommittedMove::LeadershipTransferred { + shard_id: target, + to, + }, + ); + continue; + } + let reason = append_reason( + &decision.blocked_reason, + &format!( + "transfer_leader to {to} did not make that node the leader within 3s; the move is not recorded as committed" + ), + ); + return self.finish_placement(placement_record( + shard_id, + dominant_pid, + dedicated_node, + PlacementPhase::Recorded, + reason, + committed_moves, + transfer_attempt, + replace_attempt, + )); + } + PlacementAction::ReplaceDedicatedOnPeer { + shard_id: target, + remove, + add, + } => { + let now = unix_ms(); + if replace_attempt != 0 + && now.saturating_sub(replace_attempt) < PLACEMENT_RETRY_MS + { + let reason = append_reason( + &decision.blocked_reason, + "peer voter replacement is in cooldown and was not submitted again", + ); + return self.finish_placement(placement_record( + shard_id, + dominant_pid, + dedicated_node, + decision.phase, + reason, + committed_moves, + transfer_attempt, + replace_attempt, + )); + } + replace_attempt = now; + self.save_placement(&placement_record( + shard_id, + dominant_pid, + dedicated_node, + decision.phase, + decision.blocked_reason.clone(), + committed_moves.clone(), + transfer_attempt, + replace_attempt, + ))?; + match self.replace_dedicated_voter(target, remove, add).await { + Ok(true) => { + push_move( + &mut committed_moves, + CommittedMove::VoterReplaced { + shard_id: target, + removed: remove, + added: add, + }, + ); + } + Ok(false) => {} + Err(error) => { + let reason = append_reason( + &decision.blocked_reason, + &format!( + "peer voter replacement failed: {error}; voters were not reported as drained" + ), + ); + return self.finish_placement(placement_record( + shard_id, + dominant_pid, + dedicated_node, + PlacementPhase::Blocked, + reason, + committed_moves, + transfer_attempt, + replace_attempt, + )); + } + } + } + } + } + Err(MetaDbError::ConsensusError( + "jumbo placement did not converge before the attempt limit".to_string(), + )) + } + + fn placement_observation( + &self, + shard_id: ShardId, + dominant_pid: InodeId, + dedicated_node: NodeId, + ) -> Result { + let routes: Vec = self + .state + .lock() + .unwrap() + .routes + .values() + .cloned() + .collect(); + let mut shards = Vec::new(); + let mut proven = BTreeSet::new(); + let mut reserved = BTreeSet::new(); + for route in routes { + if route.shard_id != shard_id { + if let ShardHealthState::JumboIsolated { + dedicated_node: other, + .. + } = route.health_state + { + reserved.insert(other); + } + } + let Some(group) = self.host.get_group(route.shard_id) else { + continue; + }; + let voters_map = group.uniform_voter_addrs()?; + let voters = voters_map.keys().copied().collect(); + proven.extend(voters_map.keys().copied()); + shards.push(ShardVoters { + shard_id: route.shard_id, + voters, + leader: group.current_leader(), + }); + } + Ok(PlacementObservation { + jumbo_shard_id: shard_id, + dominant_pid, + dedicated_node, + local_node: self.host.node_id(), + shards, + proven_voters: proven, + reserved_dedicated_nodes: reserved, + }) + } + + fn sync_route_voters_from_raft(&self, shard_id: ShardId) -> Result<()> { + let (_, group, _) = self.lookup_local_handle(shard_id)?; + let live = group.uniform_voter_addrs()?; + let stored = { + let state = self.state.lock().unwrap(); + state.routes.get(&shard_id).map(|route| { + route + .peers + .iter() + .filter(|(_, (_, voter))| *voter) + .map(|(id, (addr, _))| (*id, addr.clone())) + .collect::>() + }) + }; + if stored.as_ref() == Some(&live) { + return Ok(()); + } + self.persist_voter_set(shard_id, &live, group.current_epoch()) + } + + async fn transfer_leadership(&self, shard_id: ShardId, to: NodeId) -> Result { + let (_, group, _) = self.lookup_local_handle(shard_id)?; + if group.current_leader() == Some(to) { + return Ok(true); + } + if group.current_leader() != Some(self.host.node_id()) { + return Ok(false); + } + let voters = group.uniform_voter_addrs()?; + if !voters.contains_key(&to) { + return Err(MetaDbError::ConsensusError(format!( + "refusing to transfer leadership of shard {shard_id} to node {to}; that node is not a voter" + ))); + } + group + .raft() + .trigger() + .transfer_leader(to) + .await + .map_err(|error| { + MetaDbError::ConsensusError(format!("transfer_leader({to}) failed: {error}")) + })?; + let deadline = tokio::time::Instant::now() + Duration::from_secs(3); + loop { + if group.current_leader() == Some(to) { + return Ok(true); + } + if tokio::time::Instant::now() >= deadline { + return Ok(false); + } + tokio::time::sleep(Duration::from_millis(20)).await; + } + } + + /// `Ok(true)` only after the committed voter set is the planned set. + /// `Ok(false)` means this process did not propose a change. + async fn replace_dedicated_voter( + &self, + shard_id: ShardId, + remove: NodeId, + add: NodeId, + ) -> Result { + let (_, group, _) = self.lookup_local_handle(shard_id)?; + if group.current_leader() != Some(self.host.node_id()) { + return Ok(false); + } + let current = group.uniform_voter_addrs()?; + let old: BTreeSet = current.keys().copied().collect(); + if !old.contains(&remove) { + return Ok(false); + } + let mut proposed = old.clone(); + proposed.remove(&remove); + proposed.insert(add); + jumbo_membership_change_allowed(&old, &proposed).map_err(|refusal| { + MetaDbError::ConsensusError(format!( + "refusing jumbo voter change on shard {shard_id}: {refusal:?}" + )) + })?; + if !self.node_is_proven_voter(add)? { + return Err(MetaDbError::ConsensusError(format!( + "refusing to add node {add} on shard {shard_id}; it is not already a voter of a local shard" + ))); + } + if current.contains_key(&add) { + ConfChangeOrchestrator::change_voters(group.raft(), proposed.clone()).await?; + } else { + let addr = self.proven_voter_addr(add)?; + let min_matched = group.prepare_learner_snapshot().await?; + ConfChangeOrchestrator::add_learners_and_promote_voters( + group.raft(), + &[(add, addr)], + proposed.clone(), + 64, + Duration::from_secs(20), + min_matched, + ) + .await?; + } + let committed = group.wait_uniform_voter_addrs().await?; + let committed_ids: BTreeSet = committed.keys().copied().collect(); + if committed_ids != proposed { + return Err(MetaDbError::ConsensusError(format!( + "shard {shard_id} committed voters {committed_ids:?} but the plan required {proposed:?}; the placement is not marked drained" + ))); + } + self.persist_voter_set(shard_id, &committed, group.current_epoch())?; + Ok(true) + } + + fn node_is_proven_voter(&self, node_id: NodeId) -> Result { + let shard_ids: Vec = self.state.lock().unwrap().routes.keys().copied().collect(); + for shard_id in shard_ids { + let Some(group) = self.host.get_group(shard_id) else { + continue; + }; + if group.uniform_voter_addrs()?.contains_key(&node_id) { + return Ok(true); + } + } + Ok(false) + } + + fn proven_voter_addr(&self, node_id: NodeId) -> Result { + let shard_ids: Vec = self.state.lock().unwrap().routes.keys().copied().collect(); + for shard_id in shard_ids { + let Some(group) = self.host.get_group(shard_id) else { + continue; + }; + if let Some(addr) = group.uniform_voter_addrs()?.get(&node_id) { + if !addr.is_empty() { + return Ok(addr.clone()); + } + } + } + Err(MetaDbError::ConsensusError(format!( + "node {node_id} has no raft address on a local shard" + ))) + } + + fn finish_placement(&self, record: StoredPlacement) -> Result { + self.save_placement(&record)?; + Ok(self.stored_placement(record.shard_id).unwrap_or(record)) + } + + fn save_placement(&self, record: &StoredPlacement) -> Result<()> { + let mut guard = self.control.lock().unwrap(); + if guard + .placements + .get(&record.shard_id) + .is_some_and(|current| current.same_outcome(record)) + { + return Ok(()); + } + let mut next = guard.clone(); + next.placements.insert(record.shard_id, record.clone()); + self.persist_control(&next)?; + *guard = next; + Ok(()) + } + + fn persist_control(&self, state: &PersistedControlPlane) -> Result<()> { + if state.version != CONTROL_PLANE_VERSION { + return Err(MetaDbError::CodecError(format!( + "{CONTROL_PLANE_FILE} version {} is not supported", + state.version + ))); + } + if self.fail_control_persists.load(Ordering::Relaxed) > 0 { + self.fail_control_persists.fetch_sub(1, Ordering::Relaxed); + return Err(MetaDbError::StorageIoError( + "injected CELL_CONTROL_PLANE persist failure".to_string(), + )); + } + Self::write_control_file(&self.state_dir, state) + } + + fn load_control_plane(dir: &Path) -> Result { + let path = dir.join(CONTROL_PLANE_FILE); + if !path.exists() { + return Ok(PersistedControlPlane::default()); + } + let mut raw = Vec::new(); + File::open(&path)?.read_to_end(&mut raw)?; + let body = verify_crc32c_le(&raw, CONTROL_PLANE_FILE)?; + let state: PersistedControlPlane = codec::deserialize(body) + .map_err(|error| MetaDbError::CodecError(format!("{CONTROL_PLANE_FILE}: {error}")))?; + if state.version != CONTROL_PLANE_VERSION { + return Err(MetaDbError::CodecError(format!( + "{CONTROL_PLANE_FILE} version {} is not supported", + state.version + ))); + } + Ok(state) + } + + fn write_control_file(dir: &Path, state: &PersistedControlPlane) -> Result<()> { + let _shard_set = if dir + .file_name() + .and_then(|name| name.to_str()) + .is_some_and(|name| name.starts_with("cell_")) + { + let root = dir.parent().unwrap_or_else(|| Path::new(".")); + Some(metadb_raft::backup::lock_be_shard_set(&root.join("be"))?) + } else { + None + }; + let mut raw = + codec::serialize(state).map_err(|error| MetaDbError::CodecError(error.to_string()))?; + append_crc32c_le(&mut raw); + let tmp = dir.join(format!("{CONTROL_PLANE_FILE}.tmp")); + let dst = dir.join(CONTROL_PLANE_FILE); + { + let mut file = OpenOptions::new() + .create(true) + .write(true) + .truncate(true) + .open(&tmp)?; + file.write_all(&raw)?; + file.sync_data()?; + } + fs::rename(&tmp, &dst)?; + sync_dir(dir)?; + Ok(()) + } + fn verify_or_initialize_owner( dir: &Path, node_id: NodeId, @@ -1932,6 +2600,59 @@ impl DurableCellManager { } } +#[allow(clippy::too_many_arguments)] +fn placement_record( + shard_id: ShardId, + dominant_pid: InodeId, + dedicated_node: NodeId, + phase: PlacementPhase, + blocked_reason: String, + committed_moves: Vec, + last_transfer_attempt_unix_ms: u64, + last_replace_attempt_unix_ms: u64, +) -> StoredPlacement { + StoredPlacement { + shard_id, + dominant_pid, + dedicated_node, + phase, + blocked_reason, + committed_moves, + last_transfer_attempt_unix_ms, + last_replace_attempt_unix_ms, + updated_unix_ms: unix_ms(), + } +} + +fn append_reason(existing: &str, extra: &str) -> String { + if existing.is_empty() { + extra.to_string() + } else { + format!("{existing}; {extra}") + } +} + +fn action_runs_on( + local: NodeId, + observation: &PlacementObservation, + action: &PlacementAction, +) -> bool { + let shard_id = match action { + PlacementAction::TransferLeadership { shard_id, .. } + | PlacementAction::ReplaceDedicatedOnPeer { shard_id, .. } => *shard_id, + }; + observation + .shards + .iter() + .any(|shard| shard.shard_id == shard_id && shard.leader == Some(local)) +} + +fn push_move(moves: &mut Vec, movement: CommittedMove) { + if !moves.contains(&movement) { + moves.push(movement); + } +} + /// `SplitPlanRecord` gained `dual_mode_pid` after the first on-disk layout. /// Old `CELL_MANAGER_STATE` files still decode; missing mode is `None`. #[derive(Debug, Deserialize, wincode::SchemaRead)] diff --git a/crates/metadb-cluster/src/control_plane_state.rs b/crates/metadb-cluster/src/control_plane_state.rs new file mode 100644 index 0000000..f40bc99 --- /dev/null +++ b/crates/metadb-cluster/src/control_plane_state.rs @@ -0,0 +1,245 @@ +//! Durable cell heartbeats and Jumbo placement records (`CELL_CONTROL_PLANE`). +//! +//! This file is separate from `CELL_MANAGER_STATE`. A heartbeat must not rewrite +//! shard routes, and a placement record must not be confused with a route epoch. +//! The codec is the same CRC32C frame used by the cell state file. Version 1 is +//! the only layout this process reads; a different version fails the open. + +use std::collections::BTreeMap; +use std::time::{SystemTime, UNIX_EPOCH}; + +use serde::{Deserialize, Serialize}; + +use metadb_core::{InodeId, NodeId, ShardId}; + +use crate::jumbo_placement::{CommittedMove, PlacementPhase}; + +/// How often a process records and, when it is not the leader, sends its own heartbeat. +pub const HEARTBEAT_INTERVAL_MS: u64 = 3_000; + +/// Minimum gap between two leadership-transfer or peer-replacement attempts for one shard. +pub const PLACEMENT_RETRY_MS: u64 = 30_000; + +pub const CONTROL_PLANE_VERSION: u32 = 1; +pub const CONTROL_PLANE_FILE: &str = "CELL_CONTROL_PLANE"; + +/// Upper bound on shard ids stored from one heartbeat. The ids are annotations. +pub const MAX_REPORTED_SHARD_IDS: usize = 1_024; + +#[derive( + Debug, Clone, PartialEq, Eq, Serialize, Deserialize, wincode::SchemaWrite, wincode::SchemaRead, +)] +pub struct PersistedControlPlane { + pub version: u32, + pub heartbeats: BTreeMap, + /// Next sequence this process will assign to its own heartbeat. Remote sequences + /// do not consume it. Zero is never assigned. + pub next_local_seq: u64, + pub placements: BTreeMap, +} + +impl Default for PersistedControlPlane { + fn default() -> Self { + Self { + version: CONTROL_PLANE_VERSION, + heartbeats: BTreeMap::new(), + next_local_seq: 1, + placements: BTreeMap::new(), + } + } +} + +/// One accepted heartbeat. `reported_shard_ids` came from a client RPC and are not routes. +/// `local_hosted_shard_ids` is filled only when this process built the record from its own route table. +#[derive( + Debug, Clone, PartialEq, Eq, Serialize, Deserialize, wincode::SchemaWrite, wincode::SchemaRead, +)] +pub struct StoredHeartbeat { + pub node_id: NodeId, + pub seq: u64, + pub observed_unix_ms: u64, + pub disk_free_bytes: Option, + pub reported_shard_ids: Vec, + pub local_hosted_shard_ids: Vec, +} + +#[derive( + Debug, Clone, PartialEq, Eq, Serialize, Deserialize, wincode::SchemaWrite, wincode::SchemaRead, +)] +pub struct StoredPlacement { + pub shard_id: ShardId, + pub dominant_pid: InodeId, + pub dedicated_node: NodeId, + pub phase: PlacementPhase, + pub blocked_reason: String, + /// Moves this process observed after its own Raft call returned. A restart does not + /// invent entries for a move it cannot prove it committed. + pub committed_moves: Vec, + pub last_transfer_attempt_unix_ms: u64, + pub last_replace_attempt_unix_ms: u64, + pub updated_unix_ms: u64, +} + +impl StoredPlacement { + pub fn same_outcome(&self, other: &Self) -> bool { + self.shard_id == other.shard_id + && self.dominant_pid == other.dominant_pid + && self.dedicated_node == other.dedicated_node + && self.phase == other.phase + && self.blocked_reason == other.blocked_reason + && self.committed_moves == other.committed_moves + && self.last_transfer_attempt_unix_ms == other.last_transfer_attempt_unix_ms + && self.last_replace_attempt_unix_ms == other.last_replace_attempt_unix_ms + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HeartbeatWrite { + pub node_id: NodeId, + pub seq: u64, + pub observed_unix_ms: u64, + pub disk_free_bytes: Option, + pub reported_shard_ids: Vec, + pub local_hosted_shard_ids: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum HeartbeatDecision { + /// Persist `write` in place of any older record for this node. + Store(StoredHeartbeat), + /// The same sequence and body are already durable. Do not rewrite the timestamp. + Replay(StoredHeartbeat), +} + +pub fn unix_ms() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)) + .unwrap_or(0) +} + +pub fn normalize_ids(ids: impl IntoIterator) -> Result, String> { + let mut out: Vec = ids.into_iter().filter(|id| *id != 0).collect(); + out.sort_unstable(); + out.dedup(); + if out.len() > MAX_REPORTED_SHARD_IDS { + return Err(format!( + "heartbeat lists {} shard ids; the stored annotation limit is {MAX_REPORTED_SHARD_IDS}. Client shard descriptors are not applied to routes", + out.len() + )); + } + Ok(out) +} + +/// Decide whether `write` may update `existing`. +/// +/// A lower sequence is rejected and the stored record stays. An equal sequence with the +/// same body is a replay. An equal sequence with a different body is a conflict and must +/// not overwrite. A higher sequence replaces the record. +pub fn decide_heartbeat( + existing: Option<&StoredHeartbeat>, + write: &HeartbeatWrite, +) -> Result { + if write.seq == 0 { + return Err( + "monotonic_seq must be non-zero; client shard descriptors are not applied to routes" + .to_string(), + ); + } + let stored = StoredHeartbeat { + node_id: write.node_id, + seq: write.seq, + observed_unix_ms: write.observed_unix_ms, + disk_free_bytes: write.disk_free_bytes, + reported_shard_ids: write.reported_shard_ids.clone(), + local_hosted_shard_ids: write.local_hosted_shard_ids.clone(), + }; + let Some(previous) = existing else { + return Ok(HeartbeatDecision::Store(stored)); + }; + if previous.node_id != write.node_id { + return Err(format!( + "heartbeat map key {} does not match body node {}", + previous.node_id, write.node_id + )); + } + if write.seq < previous.seq { + return Err(format!( + "stale heartbeat seq {} is older than {}; the stored record was kept. Client shard descriptors are not applied to routes", + write.seq, previous.seq + )); + } + if write.seq == previous.seq { + if same_body(previous, write) { + return Ok(HeartbeatDecision::Replay(previous.clone())); + } + return Err(format!( + "heartbeat seq {} conflicts with the stored body; the stored record was kept. Client shard descriptors are not applied to routes", + write.seq + )); + } + Ok(HeartbeatDecision::Store(stored)) +} + +fn same_body(stored: &StoredHeartbeat, write: &HeartbeatWrite) -> bool { + stored.disk_free_bytes == write.disk_free_bytes + && stored.reported_shard_ids == write.reported_shard_ids + && stored.local_hosted_shard_ids == write.local_hosted_shard_ids +} + +#[cfg(test)] +mod tests { + use super::*; + + fn write(seq: u64, disk: Option, reported: &[u64]) -> HeartbeatWrite { + HeartbeatWrite { + node_id: 7, + seq, + observed_unix_ms: 10, + disk_free_bytes: disk, + reported_shard_ids: reported.to_vec(), + local_hosted_shard_ids: Vec::new(), + } + } + + #[test] + fn sequence_rules_keep_the_stored_body() { + assert!(decide_heartbeat(None, &write(0, None, &[])).is_err()); + let stored = match decide_heartbeat(None, &write(1, Some(5), &[9])).unwrap() { + HeartbeatDecision::Store(heartbeat) => heartbeat, + HeartbeatDecision::Replay(_) => panic!("first write stores"), + }; + assert!(matches!( + decide_heartbeat(Some(&stored), &write(1, Some(5), &[9])).unwrap(), + HeartbeatDecision::Replay(_) + )); + assert!(decide_heartbeat(Some(&stored), &write(1, Some(6), &[9])).is_err()); + assert!(decide_heartbeat(Some(&stored), &write(1, Some(5), &[8])).is_err()); + let zero_seq = decide_heartbeat(Some(&stored), &write(0, Some(5), &[9])).unwrap_err(); + assert!(zero_seq.contains("non-zero"), "{zero_seq}"); + let conflict = decide_heartbeat( + Some(&stored), + &HeartbeatWrite { + disk_free_bytes: Some(9), + ..write(1, Some(5), &[9]) + }, + ) + .unwrap_err(); + assert!(conflict.contains("conflicts"), "{conflict}"); + let next = match decide_heartbeat(Some(&stored), &write(2, None, &[4])).unwrap() { + HeartbeatDecision::Store(heartbeat) => heartbeat, + HeartbeatDecision::Replay(_) => panic!("higher seq stores"), + }; + assert_eq!(next.seq, 2); + assert!(decide_heartbeat(Some(&next), &write(1, None, &[4])) + .unwrap_err() + .contains("stale")); + } + + #[test] + fn too_many_shard_annotations_are_rejected() { + let ids = 0..(MAX_REPORTED_SHARD_IDS as u64 + 2); + let err = normalize_ids(ids).unwrap_err(); + assert!(err.contains("not applied")); + } +} diff --git a/crates/metadb-cluster/src/jumbo_placement.rs b/crates/metadb-cluster/src/jumbo_placement.rs new file mode 100644 index 0000000..2773ac3 --- /dev/null +++ b/crates/metadb-cluster/src/jumbo_placement.rs @@ -0,0 +1,445 @@ +//! Membership-safe Jumbo placement decisions. +//! +//! `JumboIsolated` on a route is a detection flag. It does not by itself move a replica. +//! This module plans the only moves this increment will attempt: +//! leadership transfer onto a node that is already a voter, and a same-size voter +//! replacement that keeps Raft fault tolerance and an old-majority overlap. +//! +//! A plan that cannot do either is `Blocked` or `LeaderOnDedicated` with a reason. +//! Neither of those is a completed eviction. + +use std::collections::BTreeSet; + +use serde::{Deserialize, Serialize}; + +use metadb_core::{InodeId, NodeId, ShardId}; + +/// Current Raft view of one shard. Built from live metrics, not from a client heartbeat. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ShardVoters { + pub shard_id: ShardId, + pub voters: BTreeSet, + pub leader: Option, +} + +/// Inputs to [`plan_jumbo_placement`]. Pure data; no I/O. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlacementObservation { + pub jumbo_shard_id: ShardId, + pub dominant_pid: InodeId, + pub dedicated_node: NodeId, + pub local_node: NodeId, + pub shards: Vec, + /// Nodes that are already voters of at least one shard observed here. + pub proven_voters: BTreeSet, + /// Dedicated nodes of other jumbo shards. They are not used as drain spares. + pub reserved_dedicated_nodes: BTreeSet, +} + +/// One Raft action the executor may attempt. The planner never emits an action that +/// drops fault tolerance or addresses a node that has not already joined a shard. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PlacementAction { + TransferLeadership { + shard_id: ShardId, + to: NodeId, + }, + ReplaceDedicatedOnPeer { + shard_id: ShardId, + remove: NodeId, + add: NodeId, + }, +} + +/// A move this process recorded only after its own Raft call reached the postcondition. +/// Variant order is part of the `CELL_CONTROL_PLANE` layout. +#[derive( + Debug, Clone, PartialEq, Eq, Serialize, Deserialize, wincode::SchemaWrite, wincode::SchemaRead, +)] +pub enum CommittedMove { + LeadershipTransferred { + shard_id: ShardId, + to: NodeId, + }, + VoterReplaced { + shard_id: ShardId, + removed: NodeId, + added: NodeId, + }, +} + +/// Durable phase. This describes the live membership condition, not a claim that +/// this process moved bytes. Variant order is part of the `CELL_CONTROL_PLANE` layout. +#[derive( + Debug, + Clone, + Copy, + PartialEq, + Eq, + Serialize, + Deserialize, + wincode::SchemaWrite, + wincode::SchemaRead, +)] +pub enum PlacementPhase { + /// The dedicated node is a voter, and leadership or a peer replacement is still outstanding. + Recorded, + /// The jumbo shard's current leader is the dedicated node. Peer shards may still list it. + LeaderOnDedicated, + /// At least one other local shard exists, and none of them currently has the dedicated node as a voter. + DedicatedNodeNotShared, + /// A required move was refused. No success is implied. + Blocked, +} + +/// What the executor should attempt, and the phase to publish if it attempts nothing. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PlacementDecision { + pub phase: PlacementPhase, + pub blocked_reason: String, + pub actions: Vec, +} + +/// Why a jumbo-driven voter-set change is refused. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum MembershipRefusal { + EmptyTarget, + /// The overlap is not a majority of the old voter set, so joint consensus can stall + /// even when the old majority is up. + LostOldMajorityOverlap { + overlap: usize, + old_majority: usize, + }, + FaultToleranceDropped { + previous: usize, + next: usize, + }, +} + +/// Voters that can fail and still leave a strict majority. `0` for one or two voters. +pub fn fault_tolerance(voter_count: usize) -> usize { + if voter_count == 0 { + 0 + } else { + voter_count - (voter_count / 2 + 1) + } +} + +/// Jumbo placement may change a voter set only when the new set is non-empty, fault +/// tolerance does not fall, and the overlap contains a majority of the old set. +pub fn jumbo_membership_change_allowed( + old: &BTreeSet, + new: &BTreeSet, +) -> Result<(), MembershipRefusal> { + if new.is_empty() { + return Err(MembershipRefusal::EmptyTarget); + } + let previous = fault_tolerance(old.len()); + let next = fault_tolerance(new.len()); + if next < previous { + return Err(MembershipRefusal::FaultToleranceDropped { previous, next }); + } + let old_majority = if old.is_empty() { 1 } else { old.len() / 2 + 1 }; + let overlap = old.intersection(new).count(); + if overlap < old_majority { + return Err(MembershipRefusal::LostOldMajorityOverlap { + overlap, + old_majority, + }); + } + Ok(()) +} + +pub fn plan_jumbo_placement(obs: &PlacementObservation) -> PlacementDecision { + let Some(jumbo) = obs + .shards + .iter() + .find(|shard| shard.shard_id == obs.jumbo_shard_id) + else { + return blocked( + "jumbo shard is not hosted on this process; no membership change was proposed", + ); + }; + if !jumbo.voters.contains(&obs.dedicated_node) { + return blocked(format!( + "dedicated node {} is not a current voter of shard {}; this increment does not add a voter that has not already joined a shard", + obs.dedicated_node, obs.jumbo_shard_id + )); + } + + let mut actions = Vec::new(); + let leader_here = jumbo.leader == Some(obs.dedicated_node); + if !leader_here { + if jumbo.leader.is_none() { + return blocked("jumbo shard has no current leader; leadership was not transferred"); + } + actions.push(PlacementAction::TransferLeadership { + shard_id: jumbo.shard_id, + to: obs.dedicated_node, + }); + } + + let mut reasons = Vec::new(); + let mut other_shards = 0usize; + for shard in &obs.shards { + if shard.shard_id == obs.jumbo_shard_id { + continue; + } + other_shards += 1; + if !shard.voters.contains(&obs.dedicated_node) { + continue; + } + match replacement_spare(shard, obs) { + Ok(add) => actions.push(PlacementAction::ReplaceDedicatedOnPeer { + shard_id: shard.shard_id, + remove: obs.dedicated_node, + add, + }), + Err(reason) => reasons.push(reason), + } + } + + if other_shards == 0 { + reasons.push( + "no other local shard exists; this record is not evidence that a co-located shard was moved" + .to_string(), + ); + } + + let phase = if !leader_here && jumbo.leader.is_some() { + PlacementPhase::Recorded + } else if reasons.is_empty() && other_shards > 0 && leader_here { + PlacementPhase::DedicatedNodeNotShared + } else if leader_here { + PlacementPhase::LeaderOnDedicated + } else { + PlacementPhase::Blocked + }; + + // A replacement that has not been applied yet is not the unshared condition. + let phase = if actions + .iter() + .any(|action| matches!(action, PlacementAction::ReplaceDedicatedOnPeer { .. })) + && phase == PlacementPhase::DedicatedNodeNotShared + { + PlacementPhase::LeaderOnDedicated + } else { + phase + }; + + PlacementDecision { + phase, + blocked_reason: reasons.join("; "), + actions, + } +} + +fn replacement_spare(shard: &ShardVoters, obs: &PlacementObservation) -> Result { + let mut candidates: Vec = obs + .proven_voters + .iter() + .copied() + .filter(|node| { + *node != obs.dedicated_node + && !shard.voters.contains(node) + && !obs.reserved_dedicated_nodes.contains(node) + }) + .collect(); + candidates.sort_unstable(); + let mut last_refusal = None; + for add in candidates { + let mut proposed = shard.voters.clone(); + proposed.remove(&obs.dedicated_node); + proposed.insert(add); + match jumbo_membership_change_allowed(&shard.voters, &proposed) { + Ok(()) => return Ok(add), + Err(refusal) => last_refusal = Some(refusal), + } + } + let detail = match last_refusal { + Some(MembershipRefusal::FaultToleranceDropped { previous, next }) => { + format!("last candidate would drop fault tolerance from {previous} to {next}") + } + Some(MembershipRefusal::LostOldMajorityOverlap { + overlap, + old_majority, + }) => format!("last candidate overlap {overlap} is below the old majority {old_majority}"), + Some(MembershipRefusal::EmptyTarget) => "candidate produced an empty voter set".to_string(), + None => "no proven voter is outside this shard's voter set".to_string(), + }; + Err(format!( + "shard {} cannot move dedicated node {} off its voter set without dropping Raft fault tolerance or losing an old majority ({detail})", + shard.shard_id, obs.dedicated_node + )) +} + +fn blocked(reason: impl Into) -> PlacementDecision { + PlacementDecision { + phase: PlacementPhase::Blocked, + blocked_reason: reason.into(), + actions: Vec::new(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn voters(ids: &[u64]) -> BTreeSet { + ids.iter().copied().collect() + } + + fn shard(id: u64, ids: &[u64], leader: Option) -> ShardVoters { + ShardVoters { + shard_id: id, + voters: voters(ids), + leader, + } + } + + fn obs(dedicated: u64, shards: Vec, proven: &[u64]) -> PlacementObservation { + PlacementObservation { + jumbo_shard_id: 1, + dominant_pid: 800, + dedicated_node: dedicated, + local_node: 1, + shards, + proven_voters: voters(proven), + reserved_dedicated_nodes: BTreeSet::new(), + } + } + + #[test] + fn single_voter_cell_does_not_plan_a_membership_change() { + let decision = plan_jumbo_placement(&obs( + 1, + vec![ + shard(1, &[1], Some(1)), + shard(2, &[1], Some(1)), + shard(3, &[1], Some(1)), + ], + &[1], + )); + assert_eq!(decision.phase, PlacementPhase::LeaderOnDedicated); + assert!(decision.actions.is_empty(), "{decision:?}"); + assert!( + decision.blocked_reason.contains("fault tolerance") + || decision.blocked_reason.contains("proven voter"), + "{}", + decision.blocked_reason + ); + } + + #[test] + fn a_registered_non_voter_is_not_added() { + let decision = plan_jumbo_placement(&obs( + 3, + vec![shard(1, &[1], Some(1)), shard(2, &[1], Some(1))], + &[1], + )); + assert_eq!(decision.phase, PlacementPhase::Blocked); + assert!(decision.actions.is_empty(), "{decision:?}"); + assert!( + decision.blocked_reason.contains("not a current voter"), + "{}", + decision.blocked_reason + ); + } + + #[test] + fn uniform_three_voters_transfer_leadership_and_refuse_to_shrink() { + let decision = plan_jumbo_placement(&obs( + 2, + vec![shard(1, &[1, 2, 3], Some(1)), shard(2, &[1, 2, 3], Some(1))], + &[1, 2, 3], + )); + assert_eq!(decision.phase, PlacementPhase::Recorded); + assert_eq!( + decision.actions, + vec![PlacementAction::TransferLeadership { shard_id: 1, to: 2 }] + ); + assert!( + decision.blocked_reason.contains("fault tolerance") + || decision.blocked_reason.contains("proven voter"), + "{}", + decision.blocked_reason + ); + } + + #[test] + fn a_proven_spare_keeps_the_same_fault_tolerance() { + let decision = plan_jumbo_placement(&obs( + 2, + vec![shard(1, &[1, 2, 3], Some(2)), shard(2, &[1, 2, 3], Some(1))], + &[1, 2, 3, 4], + )); + assert_eq!(decision.phase, PlacementPhase::LeaderOnDedicated); + assert_eq!( + decision.actions, + vec![PlacementAction::ReplaceDedicatedOnPeer { + shard_id: 2, + remove: 2, + add: 4 + }] + ); + let mut proposed = voters(&[1, 2, 3]); + proposed.remove(&2); + proposed.insert(4); + assert!(jumbo_membership_change_allowed(&voters(&[1, 2, 3]), &proposed).is_ok()); + } + + #[test] + fn shrinking_and_disjoint_replacement_are_refused() { + let shrink = jumbo_membership_change_allowed(&voters(&[1, 2, 3]), &voters(&[1, 2])); + assert!(matches!( + shrink, + Err(MembershipRefusal::FaultToleranceDropped { + previous: 1, + next: 0 + }) + )); + let disjoint = jumbo_membership_change_allowed(&voters(&[1]), &voters(&[2])); + assert!(matches!( + disjoint, + Err(MembershipRefusal::LostOldMajorityOverlap { .. }) + )); + assert!(jumbo_membership_change_allowed(&voters(&[]), &BTreeSet::new()).is_err()); + } + + #[test] + fn one_shard_is_not_reported_as_unshared() { + let decision = plan_jumbo_placement(&obs(1, vec![shard(1, &[1], Some(1))], &[1])); + assert_eq!(decision.phase, PlacementPhase::LeaderOnDedicated); + assert_ne!(decision.phase, PlacementPhase::DedicatedNodeNotShared); + assert!(decision.blocked_reason.contains("no other local shard")); + } + + #[test] + fn already_unshared_membership_has_no_actions() { + let decision = plan_jumbo_placement(&obs( + 2, + vec![shard(1, &[2, 3, 4], Some(2)), shard(2, &[1, 3, 4], Some(1))], + &[1, 2, 3, 4], + )); + assert_eq!(decision.phase, PlacementPhase::DedicatedNodeNotShared); + assert!(decision.actions.is_empty(), "{decision:?}"); + assert!( + decision.blocked_reason.is_empty(), + "{}", + decision.blocked_reason + ); + } + + #[test] + fn another_jumbo_node_is_not_used_as_the_spare() { + let mut observation = obs( + 2, + vec![shard(1, &[1, 2, 3], Some(2)), shard(2, &[1, 2, 3], Some(1))], + &[1, 2, 3, 4], + ); + observation.reserved_dedicated_nodes.insert(4); + let decision = plan_jumbo_placement(&observation); + assert!(decision.actions.is_empty(), "{decision:?}"); + assert_eq!(decision.phase, PlacementPhase::LeaderOnDedicated); + } +} diff --git a/crates/metadb-cluster/src/lib.rs b/crates/metadb-cluster/src/lib.rs index d9a3101..7eb0cb1 100644 --- a/crates/metadb-cluster/src/lib.rs +++ b/crates/metadb-cluster/src/lib.rs @@ -8,10 +8,12 @@ pub mod cell_manager; pub mod control_plane; +pub mod control_plane_state; pub mod global_manager; pub mod id_allocator; pub mod identity; pub mod jumbo; +pub mod jumbo_placement; pub mod meta_cache; pub mod shard; pub mod split_worker; @@ -21,6 +23,7 @@ pub use cell_manager::{ SplitPlanRecord, SplitPlanState, }; pub use control_plane::{CellId, CellLocalManager, GlobalManager, MetaCache, ShardRoute}; +pub use control_plane_state::{StoredHeartbeat, StoredPlacement, HEARTBEAT_INTERVAL_MS}; pub use global_manager::DurableGlobalManager; pub use id_allocator::{ AllocIdKind, DurableIdAllocator, LocalIdBuffer, CELL_DIR_AFFINITY_BLOCK_SIZE, @@ -28,6 +31,11 @@ pub use id_allocator::{ }; pub use identity::{node_id_in_ha_range, ClusterIdentity, CLUSTER_IDENTITY_FILE}; pub use jumbo::JumboIsolationPlanner; +pub use jumbo_placement::{ + fault_tolerance, jumbo_membership_change_allowed, plan_jumbo_placement, CommittedMove, + MembershipRefusal, PlacementAction, PlacementDecision, PlacementObservation, PlacementPhase, + ShardVoters, +}; pub use meta_cache::{CompositeMetaCache, CompositeShardRoute}; pub use shard::{ PolicyShardSplitter, RaftMemberRole, RaftMembership, ShardDescriptor, ShardHealthState, diff --git a/crates/metadb-cluster/tests/scale_control_plane_tests.rs b/crates/metadb-cluster/tests/scale_control_plane_tests.rs new file mode 100644 index 0000000..5de18b2 --- /dev/null +++ b/crates/metadb-cluster/tests/scale_control_plane_tests.rs @@ -0,0 +1,179 @@ +//! Durable control-plane heartbeat and the single-voter jumbo placement refusal. +//! +//! These tests use one `DurableCellManager` and its Raft groups. They do not start +//! three voters, and they do not claim a leadership transfer or a peer drain ran. + +use std::sync::Arc; + +use metadb_cluster::{CompositeMetaCache, DurableCellManager, DurableIdAllocator, PlacementPhase}; +use metadb_core::HybridLogicalClock; +use metadb_raft::{RaftNodeOptions, ShardGroupHost}; +use metadb_storage::{LsmEngineConfig, ShardedBlockCache}; +use tempfile::tempdir; + +async fn open_cell(dir: &std::path::Path) -> (Arc, Arc) { + let cache = Arc::new(ShardedBlockCache::new(8 * 1024 * 1024)); + let clock = Arc::new(HybridLogicalClock::new()); + let host = Arc::new(ShardGroupHost::open(1, dir.join("be"), cache, clock).unwrap()); + let alloc = Arc::new(DurableIdAllocator::open(dir.join("alloc")).unwrap()); + let cell = DurableCellManager::open_or_bootstrap( + 1, + dir.join("cell_1"), + host.clone(), + "127.0.0.1:1".to_string(), + true, + 4 * 1024 * 1024 * 1024, + LsmEngineConfig::default(), + RaftNodeOptions::default(), + alloc, + Arc::new(CompositeMetaCache::new()), + ) + .await + .unwrap(); + (host, cell) +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn heartbeat_survives_reopen_and_a_lower_sequence_does_not_replace_it() { + let dir = tempdir().unwrap(); + let (host, cell) = open_cell(dir.path()).await; + let first = cell.publish_local_heartbeat().unwrap(); + assert_eq!(first.seq, 1); + assert!(first.disk_free_bytes.is_none()); + assert!(first.local_hosted_shard_ids.contains(&1)); + assert!(first.reported_shard_ids.is_empty()); + host.shutdown_all().await.unwrap(); + drop(cell); + drop(host); + + let (host, cell) = open_cell(dir.path()).await; + let reloaded = cell + .stored_heartbeat(1) + .expect("heartbeat reloads from disk"); + assert_eq!(reloaded.seq, 1); + assert_eq!( + reloaded.local_hosted_shard_ids, + first.local_hosted_shard_ids + ); + let second = cell.publish_local_heartbeat().unwrap(); + assert_eq!(second.seq, 2); + let stale = cell.accept_remote_heartbeat(1, 1, None, vec![999]); + assert!( + stale.is_err(), + "the local node does not accept its own remote heartbeat" + ); + cell.register_node(4, "127.0.0.1:4".to_string()).unwrap(); + cell.accept_remote_heartbeat(4, 3, Some(8), vec![999, 999]) + .unwrap(); + let peer = cell.stored_heartbeat(4).unwrap(); + assert_eq!(peer.reported_shard_ids, vec![999]); + assert!(cell.list_routes().iter().all(|route| route.shard_id != 999)); + let conflict = cell.accept_remote_heartbeat(4, 3, Some(9), vec![999]); + assert!(conflict.unwrap_err().to_string().contains("conflicts")); + assert_eq!(cell.stored_heartbeat(4).unwrap().disk_free_bytes, Some(8)); + let older = cell.accept_remote_heartbeat(4, 2, Some(8), vec![999]); + assert!(older.unwrap_err().to_string().contains("stale")); + cell.testing_fail_next_control_persists(1); + let failed = cell.accept_remote_heartbeat(4, 4, Some(8), vec![999]); + assert!(failed.is_err()); + assert_eq!(cell.stored_heartbeat(4).unwrap().seq, 3); + + host.shutdown_all().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn single_voter_jumbo_placement_does_not_change_membership() { + let dir = tempdir().unwrap(); + let (host, cell) = open_cell(dir.path()).await; + let before: Vec<_> = cell.raft_voter_ids(1).unwrap().into_iter().collect(); + assert_eq!(before, vec![1]); + + let blocked = cell.reconcile_jumbo_placement(1, 800, 3).await.unwrap(); + assert_eq!(blocked.phase, PlacementPhase::Blocked); + assert!(blocked.committed_moves.is_empty(), "{blocked:?}"); + assert!(blocked.blocked_reason.contains("not a current voter")); + assert_eq!( + cell.raft_voter_ids(1).unwrap(), + cell.raft_voter_ids(2).unwrap() + ); + assert_eq!( + cell.raft_voter_ids(1) + .unwrap() + .into_iter() + .collect::>(), + vec![1] + ); + + let local = cell.reconcile_jumbo_placement(1, 800, 1).await.unwrap(); + assert_eq!(local.phase, PlacementPhase::LeaderOnDedicated); + assert_ne!(local.phase, PlacementPhase::DedicatedNodeNotShared); + assert!(local.committed_moves.is_empty(), "{local:?}"); + assert!( + local.blocked_reason.contains("proven voter") + || local.blocked_reason.contains("fault tolerance"), + "{}", + local.blocked_reason + ); + for shard_id in [1, 2, 3] { + assert_eq!( + cell.raft_voter_ids(shard_id) + .unwrap() + .into_iter() + .collect::>(), + vec![1], + "shard {shard_id}" + ); + } + + host.shutdown_all().await.unwrap(); + drop(cell); + drop(host); + + let (host, cell) = open_cell(dir.path()).await; + let reloaded = cell.stored_placement(1).expect("placement reloads"); + assert_eq!(reloaded.phase, PlacementPhase::LeaderOnDedicated); + assert!(reloaded.committed_moves.is_empty()); + host.shutdown_all().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_corrupt_control_plane_file_refuses_to_open() { + let dir = tempdir().unwrap(); + let (host, cell) = open_cell(dir.path()).await; + cell.publish_local_heartbeat().unwrap(); + host.shutdown_all().await.unwrap(); + drop(cell); + drop(host); + + let path = dir.path().join("cell_1").join("CELL_CONTROL_PLANE"); + let mut raw = std::fs::read(&path).unwrap(); + raw.extend_from_slice(&[1, 2, 3, 4]); + std::fs::write(&path, raw).unwrap(); + + let cache = Arc::new(ShardedBlockCache::new(1024 * 1024)); + let clock = Arc::new(HybridLogicalClock::new()); + let host = ShardGroupHost::open(1, dir.path().join("be"), cache, clock).unwrap(); + let alloc = Arc::new(DurableIdAllocator::open(dir.path().join("alloc")).unwrap()); + let opened = DurableCellManager::open_or_bootstrap( + 1, + dir.path().join("cell_1"), + Arc::new(host), + "127.0.0.1:1".to_string(), + true, + 4 * 1024 * 1024 * 1024, + LsmEngineConfig::default(), + RaftNodeOptions::default(), + alloc, + Arc::new(CompositeMetaCache::new()), + ) + .await; + let error = match opened { + Ok(_) => panic!("a torn control-plane file must not open"), + Err(error) => error, + }; + let text = error.to_string(); + assert!( + text.contains("CELL_CONTROL_PLANE") || text.contains("checksum"), + "{text}" + ); +} diff --git a/crates/metadb-proto/proto/metadb/v1/control_plane.proto b/crates/metadb-proto/proto/metadb/v1/control_plane.proto index 5ff67b3..bacb208 100644 --- a/crates/metadb-proto/proto/metadb/v1/control_plane.proto +++ b/crates/metadb-proto/proto/metadb/v1/control_plane.proto @@ -29,7 +29,13 @@ message StoreHeartbeatRequest { uint64 cell_id = 1; uint64 node_id = 2; uint64 disk_free_bytes = 3; + // Annotations only. The server does not install these descriptors as routes. repeated ShardHeartbeatStatsProto shards = 4; + // Required. Zero is rejected. A lower sequence than the stored one is rejected. + // The same sequence and the same disk/shard annotation is an idempotent replay. + uint64 monotonic_seq = 5; + // When false, disk_free_bytes is not a measurement and is stored as unknown. + bool disk_free_known = 6; } message StoreHeartbeatResponse { diff --git a/crates/metadb-proto/proto/metadb/v1/raft.proto b/crates/metadb-proto/proto/metadb/v1/raft.proto index a5ca9f7..9ea6196 100644 --- a/crates/metadb-proto/proto/metadb/v1/raft.proto +++ b/crates/metadb-proto/proto/metadb/v1/raft.proto @@ -33,6 +33,10 @@ message SnapshotChunkResponse { service RaftTransportService { rpc AppendEntries(RaftRpcEnvelope) returns (RaftRpcReply); rpc Vote(RaftRpcEnvelope) returns (RaftRpcReply); + // OpenRaft leadership transfer. The payload is `TransferLeaderRequest`. + // A node that does not implement this RPC must not be asked to take leadership: + // the sender disables its leader lease before the broadcast. + rpc TransferLeader(RaftRpcEnvelope) returns (RaftRpcReply); rpc InstallSnapshot(stream SnapshotChunkRequest) returns (SnapshotChunkResponse); // Follower client proposals. The handler calls `client_write` on the local // group and does not forward again. diff --git a/crates/metadb-raft/src/network.rs b/crates/metadb-raft/src/network.rs index af6a1a3..eda26d5 100644 --- a/crates/metadb-raft/src/network.rs +++ b/crates/metadb-raft/src/network.rs @@ -10,8 +10,8 @@ use openraft::entry::RaftEntry; use openraft::errors::{RPCError, ReplicationClosed, StreamingError, Unreachable}; use openraft::network::{RPCOption, RaftNetworkFactory, RaftNetworkV2}; use openraft::raft::{ - AppendEntriesRequest, AppendEntriesResponse, AppendResult, SnapshotResponse, VoteRequest, - VoteResponse, + AppendEntriesRequest, AppendEntriesResponse, AppendResult, SnapshotResponse, + TransferLeaderRequest, TransferLeaderResponse, VoteRequest, VoteResponse, }; use openraft::type_config::alias::{SnapshotMetaOf, SnapshotOf, VoteOf}; use openraft::{BasicNode, OptionalSend, Raft, Snapshot}; @@ -290,6 +290,36 @@ impl RaftNetworkV2 for TonicRaftNetworkClient { codec::deserialize_serde(&reply.bincode_payload).map_err(Self::unreachable) } + async fn transfer_leader( + &mut self, + rpc: TransferLeaderRequest, + _option: RPCOption, + ) -> Result, RPCError> { + let channel = self + .pool + .connect(&self.target_addr) + .await + .map_err(Self::unreachable)?; + let mut client = RaftTransportServiceClient::new(channel); + let bincode_payload = codec::serialize_serde(&rpc).map_err(Self::unreachable)?; + let reply = client + .transfer_leader( + self.pool + .authenticate(Request::new(RaftRpcEnvelope { + shard_id: self.shard_id, + bincode_payload, + })) + .map_err(Self::unreachable)?, + ) + .await + .map_err(Self::unreachable)? + .into_inner(); + if !reply.error_message.is_empty() { + return Err(Self::unreachable(reply.error_message)); + } + codec::deserialize_serde(&reply.bincode_payload).map_err(Self::unreachable) + } + async fn full_snapshot( &mut self, vote: VoteOf, @@ -429,6 +459,36 @@ impl RaftTransportService for MultiRaftTransportServer { } } + async fn transfer_leader( + &self, + request: Request, + ) -> Result, Status> { + let env = request.into_inner(); + let Some(raft) = self.router.get_group(env.shard_id) else { + return Ok(Response::new(RaftRpcReply { + bincode_payload: Vec::new(), + error_message: format!("unknown shard {}", env.shard_id), + })); + }; + let req: TransferLeaderRequest = + codec::deserialize_serde(&env.bincode_payload) + .map_err(|error| Status::invalid_argument(error.to_string()))?; + match raft.handle_transfer_leader(req).await { + Ok(response) => { + let bincode_payload = codec::serialize_serde(&response) + .map_err(|error| Status::internal(error.to_string()))?; + Ok(Response::new(RaftRpcReply { + bincode_payload, + error_message: String::new(), + })) + } + Err(error) => Ok(Response::new(RaftRpcReply { + bincode_payload: Vec::new(), + error_message: error.to_string(), + })), + } + } + async fn install_snapshot( &self, request: Request>, diff --git a/crates/metadb-server/src/grpc_services.rs b/crates/metadb-server/src/grpc_services.rs index c972db5..1b552d5 100644 --- a/crates/metadb-server/src/grpc_services.rs +++ b/crates/metadb-server/src/grpc_services.rs @@ -983,18 +983,33 @@ impl ControlPlaneService for MetaDbGrpcService { &self, request: Request, ) -> Result, Status> { - // Client heartbeat descriptors are not a routing source. Installing them - // replaced `CompositeMetaCache` entries and could wedge `route_user_key` - // onto a shard id this process does not host. Split scheduling still runs - // from the local maintenance tick, not from this RPC. - let _req = request.into_inner(); - let e = MetaDbError::ShardRoutingError( - "StoreHeartbeat does not update routes or schedule splits; client shard descriptors are not applied" - .to_string(), - ); - Ok(Response::new(StoreHeartbeatResponse { - error: Some(ErrorDetailProto::from(&e)), - })) + // Shard descriptors in this RPC are annotations. They are not installed + // into `CompositeMetaCache` and they do not schedule splits. + let req = request.into_inner(); + let Some(cell) = self.global_manager.get_cell(req.cell_id) else { + let error = MetaDbError::ShardRoutingError(format!( + "unknown cell {}; client shard descriptors are not applied to routes", + req.cell_id + )); + return Ok(Response::new(StoreHeartbeatResponse { + error: Some(ErrorDetailProto::from(&error)), + })); + }; + let mut reported = Vec::new(); + for shard in &req.shards { + if let Some(descriptor) = &shard.descriptor { + if descriptor.shard_id != 0 { + reported.push(descriptor.shard_id); + } + } + } + let disk_free = req.disk_free_known.then_some(req.disk_free_bytes); + match cell.accept_remote_heartbeat(req.node_id, req.monotonic_seq, disk_free, reported) { + Ok(()) => Ok(Response::new(StoreHeartbeatResponse { error: None })), + Err(error) => Ok(Response::new(StoreHeartbeatResponse { + error: Some(ErrorDetailProto::from(&error)), + })), + } } async fn get_routes( diff --git a/crates/metadb-server/src/lib.rs b/crates/metadb-server/src/lib.rs index 34530cf..f67f4bb 100644 --- a/crates/metadb-server/src/lib.rs +++ b/crates/metadb-server/src/lib.rs @@ -109,6 +109,7 @@ impl Interceptor for BearerAuthClient { } } +use metadb_cluster::HEARTBEAT_INTERVAL_MS; use metadb_cluster::{ CellDirectoryRole, CellId, CellLocalManager, CompositeMetaCache, DurableCellManager, DurableGlobalManager, DurableIdAllocator, GlobalManager, LocalIdBuffer, MetaCache, @@ -124,7 +125,9 @@ use metadb_proto::control_plane_service_server::ControlPlaneServiceServer; use metadb_proto::metadata_service_server::MetadataServiceServer; use metadb_proto::raft_transport_service_server::RaftTransportServiceServer; use metadb_proto::transaction_service_server::TransactionServiceServer; -use metadb_proto::{GetRoutesRequest, RegisterNodeRequest, ScaleShardReplicasRequest}; +use metadb_proto::{ + GetRoutesRequest, RegisterNodeRequest, ScaleShardReplicasRequest, StoreHeartbeatRequest, +}; use metadb_proxy::{MetadataSqlCommand, SqlTemplateParser, StatelessProxyRouter}; use metadb_raft::backup::{self, OnlineShard}; use metadb_raft::{ @@ -878,6 +881,75 @@ impl PersistentMetaDbCluster { grp.flush_snapshot_and_purge().await?; } } + if let Err(error) = self.publish_control_heartbeat_if_due().await { + tracing::warn!(%error, "control heartbeat was not published"); + } + Ok(()) + } + + async fn publish_control_heartbeat_if_due(&self) -> Result<()> { + let now = metadb_cluster::control_plane_state::unix_ms(); + if self + .cell_manager + .local_heartbeat_is_fresh(now, HEARTBEAT_INTERVAL_MS) + { + return Ok(()); + } + self.publish_control_heartbeat().await + } + + /// Persists this process's heartbeat, then sends that same sequence to the current + /// Raft leader when this process is not the leader. The sender does not include + /// shard descriptors. A failed send does not roll the local sequence back: the + /// next interval uses a new sequence, and a replay of this sequence is idempotent. + pub async fn publish_control_heartbeat(&self) -> Result<()> { + let heartbeat = self.cell_manager.publish_local_heartbeat()?; + let leaders = self.cell_manager.remote_leader_addrs(); + for addr in leaders { + if let Err(error) = self.send_heartbeat_with_retry(&addr, &heartbeat).await { + tracing::warn!(%error, %addr, "leader did not accept the control heartbeat"); + } + } + Ok(()) + } + + async fn send_heartbeat_with_retry( + &self, + addr: &str, + heartbeat: &metadb_cluster::StoredHeartbeat, + ) -> Result<()> { + let first = self.send_heartbeat_once(addr, heartbeat).await; + if first.is_ok() { + return Ok(()); + } + self.send_heartbeat_once(addr, heartbeat).await + } + + async fn send_heartbeat_once( + &self, + addr: &str, + heartbeat: &metadb_cluster::StoredHeartbeat, + ) -> Result<()> { + let endpoint = normalize_rpc_addr(addr); + let mut client = + control_plane_client(&endpoint, &self.config.security.shared_secret).await?; + let response = client + .store_heartbeat(StoreHeartbeatRequest { + cell_id: self.cell_manager.cell_id(), + node_id: heartbeat.node_id, + disk_free_bytes: heartbeat.disk_free_bytes.unwrap_or(0), + disk_free_known: heartbeat.disk_free_bytes.is_some(), + monotonic_seq: heartbeat.seq, + shards: Vec::new(), + }) + .await + .map_err(|error| { + MetaDbError::ConsensusError(format!("store_heartbeat at {endpoint}: {error}")) + })? + .into_inner(); + if let Some(error) = rpc_app_error(response.error) { + return Err(error); + } Ok(()) } diff --git a/crates/metadb-server/tests/control_plane_claim_tests.rs b/crates/metadb-server/tests/control_plane_claim_tests.rs index 5d107bf..9637a33 100644 --- a/crates/metadb-server/tests/control_plane_claim_tests.rs +++ b/crates/metadb-server/tests/control_plane_claim_tests.rs @@ -12,6 +12,35 @@ use metadb_server::{MetaDbGrpcService, PersistentMetaDbCluster, ServerRole, Serv use tempfile::tempdir; use tonic::Request; +fn heartbeat_request(seq: u64, node_id: u64, disk_free_bytes: u64) -> StoreHeartbeatRequest { + StoreHeartbeatRequest { + cell_id: 1, + node_id, + disk_free_bytes, + monotonic_seq: seq, + disk_free_known: true, + shards: vec![ShardHeartbeatStatsProto { + descriptor: Some(ShardDescriptorProto { + cell_id: 1, + shard_id: 999, + start_key: vec![0x01], + end_key: vec![0x02], + epoch: None, + leader_node_id: node_id, + peers: vec![], + dual_mode_fine_grained: false, + jumbo_isolated: true, + dominant_pid: 1, + }), + approximate_bytes: 1, + qps: 1, + unsplittable_jumbo: true, + dominant_pid: 1, + safe_purge_index: 0, + }], + } +} + #[tokio::test] async fn disaggregated_roles_are_rejected_before_listen() { for role in [ @@ -61,6 +90,8 @@ async fn control_plane_does_not_pretend_missing_topology_ops_succeeded() { cell_id: 1, node_id: 99, disk_free_bytes: 1, + monotonic_seq: 1, + disk_free_known: true, shards: vec![ShardHeartbeatStatsProto { descriptor: Some(ShardDescriptorProto { cell_id: 1, @@ -84,14 +115,86 @@ async fn control_plane_does_not_pretend_missing_topology_ops_succeeded() { .await .unwrap() .into_inner(); - let heartbeat_err = heartbeat.error.expect("heartbeat must not succeed"); + let heartbeat_err = heartbeat + .error + .expect("unregistered heartbeat must not succeed"); assert!( - heartbeat_err.message.contains("does not update routes"), + heartbeat_err.message.contains("not registered"), "{}", heartbeat_err.message ); + assert!( + heartbeat_err.message.contains("not applied"), + "{}", + heartbeat_err.message + ); + cluster + .cell_manager() + .register_node(7, "127.0.0.1:9".to_string()) + .unwrap(); + let forged = heartbeat_request(1, 7, 4); + let accepted = svc + .store_heartbeat(Request::new(forged)) + .await + .unwrap() + .into_inner(); + assert!(accepted.error.is_none(), "{:?}", accepted.error); + let stored = cluster + .cell_manager() + .stored_heartbeat(7) + .expect("registered heartbeat is durable"); + assert_eq!(stored.seq, 1); + assert_eq!(stored.reported_shard_ids, vec![999]); + assert!(stored.local_hosted_shard_ids.is_empty()); + let replay = svc + .store_heartbeat(Request::new(heartbeat_request(1, 7, 4))) + .await + .unwrap() + .into_inner(); + assert!(replay.error.is_none(), "{:?}", replay.error); + assert_eq!( + cluster.cell_manager().stored_heartbeat(7).unwrap().seq, + 1, + "an identical sequence must not allocate a new record" + ); + let conflict = svc + .store_heartbeat(Request::new(heartbeat_request(1, 7, 9))) + .await + .unwrap() + .into_inner(); + let conflict_err = conflict + .error + .expect("a conflicting sequence must not overwrite"); + assert!( + conflict_err.message.contains("conflicts"), + "{}", + conflict_err.message + ); + assert_eq!( + cluster + .cell_manager() + .stored_heartbeat(7) + .unwrap() + .disk_free_bytes, + Some(4) + ); + cluster.cell_manager().testing_fail_next_control_persists(1); + let failed = svc + .store_heartbeat(Request::new(heartbeat_request(2, 7, 4))) + .await + .unwrap() + .into_inner(); + assert!( + failed.error.is_some(), + "a failed heartbeat fsync must not be reported as stored" + ); + assert_eq!(cluster.cell_manager().stored_heartbeat(7).unwrap().seq, 1); let after = cluster.global_manager().meta_cache().all_routes(); assert_eq!(after.len(), before.len()); + assert!( + after.iter().all(|route| route.shard_id != 999), + "a heartbeat annotation must not become a route" + ); assert_eq!( after .iter() diff --git a/docs/en/README.md b/docs/en/README.md index 1cd8459..438c446 100644 --- a/docs/en/README.md +++ b/docs/en/README.md @@ -18,7 +18,7 @@ The workspace version is `0.1.0` (Apache-2.0). The Rust toolchain is pinned to * - one cell (`node.cell_id`, default `1`) - one OpenRaft voter per shard (this process) - one gRPC listener that serves `MetadataService`, `TransactionService`, `ControlPlaneService`, and `RaftTransportService` -- a background loop every 250 ms that drains auxiliary outboxes, runs 2PC recovery, checks split policy, and snapshots Raft logs +- a background loop every 250 ms that drains auxiliary outboxes, runs 2PC recovery, checks split policy, and snapshots Raft logs. About every 3 seconds that loop also persists a control-plane heartbeat and, when this process is not the Raft leader, sends that liveness record to the leader. The heartbeat does not install routes. `ServerRole` also parses `be`, `proxy`, `cell-manager`, and `global-manager`. `open_and_serve` rejects every role except `all-in-one`. A second `metadbd` with an empty data directory and `[cluster] join` (or `--join` / `--cell-manager`) set to the current leader joins that cell's Raft groups: the leader adds it as a learner and then promotes it to a voter. A directory that already has cell state reopens local Raft and does not join again. `RegisterCell` returns an application error and does not add a cell; `metadb-ctl cell register` exits non-zero. `GetRoutes` for an unknown non-zero `cell_id` returns an error. `cell_id = 0` still lists every cached route. @@ -32,6 +32,7 @@ Shard splits, dual-mode `(PID, name)` splits, and jumbo route flags do run insid | [Build and run](./build-and-run.md) | Toolchain, binaries, embedded library, shutdown | | [Configuration](./configuration.md) | TOML fields, defaults, and fields the process does not apply | | [Operations](./operations.md) | `metadb-ctl`, metrics, scale-out, splits, limitations, documentation gaps | +| [Scale control plane](./scale-control-plane-status.md) | What multi-cell routing, roles, jumbo placement, heartbeats, and membership safety do in this tree, and what is still missing | | [Tests and benches](./testing.md) | `cargo test`, what each suite actually exercises, `metadb-ctl bench` | | [Simulation testing](./simulation-testing.md) | Seeded workload catalog, and how it relates to FoundationDB's testing design | diff --git a/docs/en/architecture.md b/docs/en/architecture.md index 06d8495..5d4ff6e 100644 --- a/docs/en/architecture.md +++ b/docs/en/architecture.md @@ -125,7 +125,7 @@ A directory rename also holds one `DirRenameLease` in the ID allocator. Renewal - Otherwise it picks a parent-id boundary near half the bytes. The split key is a PID prefix, so `_attr_` and the direct children of one parent stay together. - If the route is already `DualModeFineGrained` for that parent, the split key is a `(pid, name)` midpoint, excluding `_attr_`. -A jumbo candidate does **not** move the shard directory. `JumboIsolationPlanner` writes `ShardHealthState::JumboIsolated { dedicated_node, dominant_pid }` onto the route. The chosen node is the registered node with the fewest jumbo routes, then the fewest other routes. With only the bootstrap node registered, that node is this process. +A jumbo candidate does **not** move the shard directory. `JumboIsolationPlanner` writes `ShardHealthState::JumboIsolated { dedicated_node, dominant_pid }` onto the route. The chosen node is the registered node with the fewest jumbo routes, then the fewest other routes. With only the bootstrap node registered, that node is this process. That flag is detection. `reconcile_jumbo_placement` then writes `CELL_CONTROL_PLANE`. On one voter it records `LeaderOnDedicated` or `Blocked` and does not change the voter set. It transfers leadership only when the dedicated node is already a voter and this process is the leader. It replaces that node on another shard only when a node that is already a voter of some local shard can take the seat without lowering Raft fault tolerance. `DedicatedNodeNotShared` means that membership condition holds. It does not mean shard files moved to another machine. See [Scale control plane](./scale-control-plane-status.md). `enable_dual_mode_split` persists `split_mode = DualModeFineGrained` and `dual_mode_pid`. It does not itself copy keys. A later split uses the `(pid, name)` rule. The in-memory simulator (`CellLocalManager` in `control_plane.rs`) is a different type: its jumbo path returns `UnsplittableJumboShard` and its "scale to 3 voters" only edits a `BTreeMap`. Tests `T1`–`T6` exercise that simulator. @@ -136,7 +136,7 @@ Split plans are stored in `CELL_MANAGER_STATE`. Crash points covered by `split_c | RPC | Behavior in this tree | | :--- | :--- | | `RegisterNode` | Inserts `(node_id, grpc_addr)` into this cell's `CELL_MANAGER_STATE` | -| `StoreHeartbeat` | Does not install caller-supplied shard descriptors into the route cache. `metadbd` never sends this RPC | +| `StoreHeartbeat` | For a registered node, fsyncs liveness into `CELL_CONTROL_PLANE` when `monotonic_seq` is newer. The same sequence and body is a replay. A lower sequence or a different body at the same sequence is rejected and the stored record stays. Shard descriptors in the request are stored as annotations and are not installed as routes. An unregistered node is rejected. The maintenance loop sends this process's own record, without shard descriptors, about every 3 seconds | | `GetRoutes` | `cell_id = 0` lists every cached route. An unknown non-zero `cell_id` returns an error instead of an empty shard list | | `AllocateIdBlock` | Allocates from the local durable allocator | | `AllocSplitPlan` / `ActivateSplit` | Forwards to the local cell manager | diff --git a/docs/en/operations.md b/docs/en/operations.md index ed6a819..efa0bc5 100644 --- a/docs/en/operations.md +++ b/docs/en/operations.md @@ -97,7 +97,7 @@ What works inside one process: - More shards. Growth past `shard_split_threshold_bytes`, or `metadb-ctl shard split`, can add shard groups under the same `be/shards` directory. The parent keeps a left key range and the child boots as another 1-voter group on this node. Restart reopens both. - Dual-mode flag. `shard enable-dual-mode` marks one parent id. A later split of that shard may cut on `(pid, name)`. -- Jumbo flag. When one parent is more than 85% of `MetaTable` bytes on the shard, or the shard has a single parent, the route becomes `JumboIsolated`. The dedicated node id is chosen from nodes already registered in this cell. With one node, the flag names this process. No files are moved to another host. +- Jumbo flag. When one parent is more than 85% of `MetaTable` bytes on the shard, or the shard has a single parent, the route becomes `JumboIsolated`. The dedicated node id is chosen from nodes already registered in this cell. With one node, the flag names this process. No files are moved to another host. A placement record in `CELL_CONTROL_PLANE` says whether that node is already a voter and whether peer shards still list it. See [Scale control plane](./scale-control-plane-status.md). - In-process voters. `DurableCellManager::scale_out_replicas` can add learners and promote them when those node ids are registered **and** each address already serves `RaftTransportService` for that shard's group. `crates/metadb-raft/tests/multi_raft_failover_tests.rs` does this with three listeners in one test process and a basic KV state machine, not the metadata state machine, and not three `metadbd` processes. What does not work as an operator procedure: @@ -135,12 +135,12 @@ Variants are defined in `crates/metadb-core/src/error.rs`. gRPC methods usually - Role `all-in-one` only. `be`, `proxy`, `cell-manager`, and `global-manager` are rejected before listen. - A second all-in-one process can join the same cell with `[cluster] join`. It does not create a second cell. `RegisterCell` returns an error. -- `GetRoutes` fails closed for an unknown non-zero `cell_id`. `StoreHeartbeat` does not replace cached routes. +- `GetRoutes` fails closed for an unknown non-zero `cell_id`. `StoreHeartbeat` does not replace cached routes. A registered node's heartbeat is fsynced in `CELL_CONTROL_PLANE`. Shard ids inside that RPC stay annotations. - User names `.`, `..`, `/`, `\`, `_attr_`, empty, and NUL are rejected. A negative file size is rejected. A directory rename into its own descendant fails closed, including chains deeper than 1024. - The HLC saturates at the 48-bit physical ceiling instead of wrapping the logical counter. `Prepare2pc` follows `header.shard_id`, not the primary-key shard. - Quota cursor rows are written after the outbox lock is released, so a flush that already holds the memtable lock can still take the outbox lock. -- Jumbo isolation is a route flag plus a node id chosen from the local node map. It does not evict other shards from a disk. -- Heartbeats are an RPC with no sender in `metadbd`. `StoreHeartbeat` does not persist. +- Jumbo isolation is still not a move of shard files onto a dedicated disk. The route flag names a node. `CELL_CONTROL_PLANE` records whether a membership-safe leadership transfer or same-size voter replacement was committed. A one-voter cell does not change its voter set. +- Heartbeats are a 3-second liveness record. `metadbd` persists its own and sends it to the current leader when this process is not the leader. The sender does not include shard descriptors. The record does not schedule splits. - A non-empty shared secret authenticates Raft, the other three gRPC services, and the metrics listener with the same bearer. An empty secret is accepted only for loopback binds and leaves those listeners unauthenticated. A wildcard bind with an empty secret refuses to start. The process does not terminate TLS. - `memtable_size_bytes` seals and flushes the active memtable. `max_imm_memtables` caps queued immutable tables. Raft timer fields do not change runtime behavior through TOML. - `metadb-ctl bench` for `hotspot-create` and `bulk-ttl-delete` prints JSON lines: a header with `bench_pid`, then phase reports with attempted, succeeded, failed, and latency percentiles. The process exits non-zero unless every requested operation succeeds. `--workload mixed` or `--embedded` runs the in-process stress harness. `sql` prints the response as JSON and exits non-zero on an application error. @@ -196,7 +196,7 @@ These items are missing from the product, so this guide cannot describe a proced 1. A multi-process layout for `be`, `proxy`, `cell-manager`, and `global-manager`. 2. A second Cell. `RegisterCell` stays an error. Join reaches only the current leader; a follower does not forward it. -3. Placing a jumbo shard on its own machine and moving other shards off that machine. -4. Native TLS. This process does not terminate TLS. Config keys that ask for TLS or a certificate are rejected instead of serving plaintext. Put termination in an external proxy. Raft and metrics use the same bearer as the other services when a secret is set; that bearer is not mutual TLS. A heartbeat-driven control loop is not implemented. +3. Placing a jumbo shard on its own machine and moving other shard files off that disk. Leadership transfer and a same-size voter replacement exist only when the nodes are already voters and the change keeps Raft fault tolerance. A node that has not joined a shard is not added. +4. Native TLS. This process does not terminate TLS. Config keys that ask for TLS or a certificate are rejected instead of serving plaintext. Put termination in an external proxy. Raft and metrics use the same bearer as the other services when a secret is set; that bearer is not mutual TLS. The 3-second heartbeat records liveness. It does not drive splits, cell federation, or disk drain. 5. A Raft timer that operators can set and observe. 6. A checked-in service-level result for `metadb-ctl bench`. The command prints numbers for the machine you run it on. This repository does not record one. See [Tests and benches](./testing.md). diff --git a/docs/en/scale-control-plane-status.md b/docs/en/scale-control-plane-status.md new file mode 100644 index 0000000..7088229 --- /dev/null +++ b/docs/en/scale-control-plane-status.md @@ -0,0 +1,69 @@ +# Scale control plane: this increment and what is still missing + +[Overview](./README.md) · [Architecture](./architecture.md) · [Operations](./operations.md) + +This page is the evidence record for multi-cell routing, role separation, Jumbo shard placement, heartbeats, and membership safety. It describes the tree after the control-plane increment that added `CELL_CONTROL_PLANE`. It is not a first-ship pass and it is not a scale gate. Figures in arXiv:2610.32247 (including Baidu's 575-node BOS2 cluster and 1.848 trillion records) are Baidu production metrics. They are not results of this repository, and this change does not produce them. + +`Architecture.md` section 12 still says several of these subsystems are "Implemented & Tested". Where that matrix and this page disagree, follow this page and the code. Locale guides under `docs/{fr,de,ja,zh}` were not rewritten here. + +Root `Architecture.md` was left unchanged on purpose. Consolidating it with the locale guides is a separate documentation workstream. + +## What this increment does + +1. **Heartbeats are durable and are sent.** `StoreHeartbeat` for a registered node fsyncs `CELL_CONTROL_PLANE` (CRC32C frame, version 1). `monotonic_seq` must be non-zero. A lower sequence is rejected and the stored body stays. The same sequence and the same disk-free value and shard-id annotation is a replay and does not rewrite the timestamp. The same sequence with a different body is a conflict and does not overwrite. Shard descriptors in the RPC are stored only as `reported_shard_ids`. They are not copied into `CELL_MANAGER_STATE` or `CompositeMetaCache`. An unregistered node is rejected. A failed fsync leaves the previous record and returns an error. +2. **The process sends its own heartbeat.** The 250 ms maintenance loop persists a local heartbeat about every 3 seconds (`HEARTBEAT_INTERVAL_MS`). Disk free space is unknown on that record; a zero is not stored as a measurement. When this process is not the Raft leader, it sends that same sequence to the leader's control-plane address and retries the same sequence once. The sender does not attach shard descriptors. A lost response does not roll the local sequence back. The next interval uses a new sequence. +3. **Jumbo placement is a record plus a narrow Raft action.** `JumboIsolated` remains the detection flag from `JumboIsolationPlanner`. `reconcile_jumbo_placement` writes a placement record from live Raft voters: + - `Blocked` when the dedicated node is not already a voter, the shard has no leader, or a move was refused. No voter is added for a node that has only a registered address. + - `LeaderOnDedicated` when that node is the current leader and peer shards still list it, or when this process hosts no other shard. The second case is not evidence that a co-located shard was moved. + - `Recorded` when leadership transfer or a peer replacement is still outstanding. + - `DedicatedNodeNotShared` only when at least one other local shard exists and none of those shards currently has the dedicated node as a voter. + - `committed_moves` grows only after this process's own Raft call reaches that postcondition. A restart does not invent a move it cannot prove it committed. +4. **Membership changes from this path keep a majority.** `jumbo_membership_change_allowed` refuses an empty set, a drop in fault tolerance (`(n-1)/2`), and a new set whose overlap is not a majority of the old set. The peer replacement keeps the same voter count and uses a node that is already a voter of some local shard. Another jumbo shard's dedicated node is not used as that spare. Operator `scale_out_replicas` / `remove_voter` is unchanged and can still shrink on purpose. +5. **Leadership transfer uses a real Raft RPC.** `RaftTransportService.TransferLeader` carries OpenRaft's `TransferLeaderRequest` and the server calls `handle_transfer_leader`. The placement path calls `trigger().transfer_leader` only when this process is the leader and the target is already a voter. OpenRaft disables the leader lease when that call is submitted. If the target is not leader within 3 seconds, the move is not recorded as committed and the next attempt waits 30 seconds. A one-voter cell never submits it, because the dedicated node is either already the leader or not a voter. + +`RegisterCell` still returns an error. `open_and_serve` still rejects every role except `all-in-one`. + +## Implemented versus missing + +| Area | Evidence in this tree | Status | +| :--- | :--- | :--- | +| Multi-cell routing | `DurableGlobalManager::register_cell` is an in-process map. `open_and_serve` registers one cell over `[0x01, 0x04)`. `RegisterCell` returns "not implemented" and stores nothing (`grpc_services.rs`). `GetRoutes` for an unknown non-zero `cell_id` fails closed. | **Missing.** No durable cell directory, no cross-process range map, no forwarding between cells. | +| Role separation | `ServerRole` parses `be`, `proxy`, `cell-manager`, and `global-manager`. `open_and_serve` returns before listen for every role except `all-in-one` (`lib.rs`). | **Missing.** One process still hosts the global manager, the cell manager, the proxy, and the Raft groups. | +| Jumbo detection flag | `JumboIsolationPlanner` and `maybe_split_or_isolate_shard` persist `ShardHealthState::JumboIsolated` in `CELL_MANAGER_STATE`. | **Present, and it is only a flag.** It does not move files. | +| Jumbo leadership placement | `reconcile_jumbo_placement` plus `RaftTransportService.TransferLeader`. | **Code is present.** It runs only when the dedicated node is already a voter and this process is the leader. It was not executed against three voters in this change. | +| Jumbo peer drain / file migration | Same-size replacement is planned and calls the existing learner promotion or `change_membership` only when a proven spare keeps fault tolerance. | **Partial.** Uniform voter sets (the join path adds a node to every shard) have no spare, so the plan stays blocked. Shard directories are not copied to another host. | +| Heartbeat persistence | `CELL_CONTROL_PLANE`, `accept_remote_heartbeat`, `publish_local_heartbeat`. | **Present** for node liveness, sequence, optional reported disk free, and shard-id annotations. | +| Heartbeat sending | `PersistentMetaDbCluster::publish_control_heartbeat` from the maintenance loop. | **Present** as liveness to the current leader. It does not carry shard stats and it does not schedule splits. | +| Heartbeat-driven scheduling | Design text in `docs/designs/sharding_and_control_plane.md` §6.1. | **Missing.** Splits still run from the local maintenance tick. | +| Membership safety for operator scale-in | `plan_membership_voters`, `remove_voter`, joint-config handling in `uniform_voter_addrs`. | **Present, and it can shrink.** Scale-in to 2 or 1 voters is an explicit operator path. It is not a three-VM result. | +| Membership safety for jumbo moves | `jumbo_membership_change_allowed`. | **Present** for the jumbo path only. It does not change operator scale-in. | +| Raft majority on the data path | OpenRaft joint consensus via `ConfChangeOrchestrator`. | **Unchanged** by this increment. This page does not re-certify it. | +| 2PC lease / storage formats | `a48d038` ("Pin 2PC lease pre-images and reject an over-cap rename TTL") is not an ancestor of this branch. | **Not imported.** Lease and storage formats were not changed. | + +## Remaining backlog and dependencies + +These items block a scale gate. None of them is delivered by this change. + +1. **Second cell.** A durable global range table, a real `RegisterCell` that does not succeed until the new cell's manager is reachable, and routing that fails closed when the range is only partly published. Depends on role separation: today every process is its own global manager, so two processes do not share one cell map. +2. **Role separation.** `be`, `proxy`, `cell-manager`, and `global-manager` must each start only their own listeners and state. That work has to preserve the auth fail-closed rules owned by the auth/config workstream. This change does not trim subsystems. +3. **Jumbo file placement.** Moving a shard directory onto a dedicated disk, streaming its snapshot to a node that has not joined, and draining peer shards off that disk. The safe replacement in this tree cannot fire on the uniform voter sets `scale_out_replicas` creates, because there is no spare voter. Adding a voter that has not joined is intentionally refused here. +4. **Leadership transfer at three voters.** The RPC and the caller exist. A regression that boots three metadata voters, detects a jumbo shard, and observes the leader change was not run. Until that run exists, do not treat `committed_moves` as a demonstrated three-node result. Mixed versions are unsafe: OpenRaft disables the leader lease when `transfer_leader` is submitted, and a peer that does not implement `TransferLeader` makes that broadcast fail. +5. **Heartbeat as a scheduler.** Per-shard bytes, QPS, and disk free measured by this process, sent on a trusted channel, and used only as hints. The scheduler must keep using local Raft and LSM state for splits. Client descriptors must stay non-authoritative. A 3-second cell-wide heartbeat bus for tens of thousands of shards is not built. +6. **Global and cell managers on Raft.** `CELL_MANAGER_STATE` and `CELL_CONTROL_PLANE` are local files. They are not a replicated control-plane group. A follower's placement file is not the leader's file. +7. **2PC lease pre-images.** Commit `a48d038` is unreviewed and was not imported. Later lease work has to land on its own review. This increment does not depend on it and does not change the 3-second lease, the 60-second cap, or the intent/txn record layout. +8. **Operator status for the placement record.** There is no `metadb-ctl` field and no metrics series for `PlacementPhase`. `TriggerShardSplit` still reports `split_executed = false` for a jumbo shard even when a later leadership transfer is only recorded in `CELL_CONTROL_PLANE`. Health, metrics, and operator Raft timer configuration belong to another workstream and were not edited. +9. **Docs outside this English set.** `docs/{fr,de,ja,zh}` still describe the previous heartbeat and jumbo behavior in places. Root `Architecture.md` section 12 still marks the control plane and jumbo isolation as implemented. Those updates belong to documentation consolidation. +10. **Gates this page does not move.** No-ship stays in force. A first-ship gate is a separate bar from a scale gate (multi-cell, disaggregated roles, jumbo disk isolation, and a heartbeat bus that can carry a cell of 20k–30k shards). This increment is neither gate. CI workflows were not edited. The commands below were not run. + +## Validation not run + +Do not read this file as a test report. The following were not executed while the change was written: + +- `cargo test -p metadb-cluster --lib jumbo_placement` +- `cargo test -p metadb-cluster --lib control_plane_state` +- `cargo test -p metadb-cluster --test scale_control_plane_tests` +- `cargo test -p metadb-server --test control_plane_claim_tests` +- `cargo test --workspace --locked` +- Any benchmark, three-voter jumbo transfer, or multi-cell drill + +`crates/metadb-cluster/tests/scale_control_plane_tests.rs` and the heartbeat cases in `crates/metadb-server/tests/control_plane_claim_tests.rs` are the regression source. They cover sequence replay, conflict, a failed fsync, reload, a corrupt `CELL_CONTROL_PLANE` file, and a one-voter placement that must not change voter sets. They do not boot three voters. From 24f752fe6ebd617d94933c5c66b15feafec3f189 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 19:53:23 +0000 Subject: [PATCH 2/3] Stop automatic leadership transfer and keep control-plane state monotonic OpenRaft disables the leader lease before TransferLeader is known to succeed, and older peers do not implement that RPC. Jumbo maintenance no longer calls trigger().transfer_leader. Registration is not treated as capability. An already-correct leader is not recorded as this process's move. A voter replacement that reaches the planned set stays in committed_moves even when the route file persist fails. A control-plane rename that then fails the directory sync keeps the new state in memory so a later write cannot roll the sequence backward. Remote heartbeats may advance by at most 64 and a new sequence inside one second is rejected. They remain an unreplicated observation and do not schedule placement. Co-authored-by: RustFS --- crates/metadb-cluster/src/cell_manager.rs | 420 +++++++++++------- .../metadb-cluster/src/control_plane_state.rs | 48 ++ crates/metadb-cluster/src/jumbo_placement.rs | 106 +++-- crates/metadb-cluster/src/lib.rs | 12 +- .../tests/scale_control_plane_tests.rs | 70 ++- .../proto/metadb/v1/control_plane.proto | 4 + crates/metadb-raft/src/network.rs | 2 + crates/metadb-server/src/grpc_services.rs | 17 +- crates/metadb-server/src/lib.rs | 8 + .../tests/control_plane_claim_tests.rs | 5 + docs/en/architecture.md | 4 +- docs/en/operations.md | 6 +- docs/en/scale-control-plane-status.md | 24 +- 13 files changed, 519 insertions(+), 207 deletions(-) diff --git a/crates/metadb-cluster/src/cell_manager.rs b/crates/metadb-cluster/src/cell_manager.rs index 26195b9..0f0bd72 100644 --- a/crates/metadb-cluster/src/cell_manager.rs +++ b/crates/metadb-cluster/src/cell_manager.rs @@ -27,16 +27,17 @@ use metadb_storage::LsmEngineConfig; use metadb_tx::{RoutedShardHandle, TxStateMachineHandler}; use crate::control_plane_state::{ - decide_heartbeat, normalize_ids, unix_ms, HeartbeatDecision, HeartbeatWrite, - PersistedControlPlane, StoredHeartbeat, StoredPlacement, CONTROL_PLANE_FILE, + decide_heartbeat, normalize_ids, remote_heartbeat_is_too_soon, unix_ms, HeartbeatDecision, + HeartbeatWrite, PersistedControlPlane, StoredHeartbeat, StoredPlacement, CONTROL_PLANE_FILE, CONTROL_PLANE_VERSION, PLACEMENT_RETRY_MS, }; use crate::id_allocator::{AllocIdKind, DurableIdAllocator}; use crate::identity::{node_id_in_ha_range, ClusterIdentity}; use crate::jumbo::JumboIsolationPlanner; use crate::jumbo_placement::{ + automatic_leadership_transfer_allowed, executable_placement_actions, jumbo_membership_change_allowed, plan_jumbo_placement, CommittedMove, PlacementAction, - PlacementObservation, PlacementPhase, ShardVoters, + PlacementObservation, PlacementPhase, ShardVoters, AUTOMATIC_TRANSFER_DISABLED_REASON, }; use crate::meta_cache::{CompositeMetaCache, CompositeShardRoute}; use crate::shard::{ShardHealthState, ShardSplitMode}; @@ -149,6 +150,8 @@ pub struct DurableCellManager { control: Mutex, /// Test hook: the next `n` `CELL_CONTROL_PLANE` persists fail before touching disk. fail_control_persists: AtomicU32, + /// Test hook: the next `n` persists rename the file and then fail the directory sync. + fail_control_dirsync: AtomicU32, } impl DurableCellManager { @@ -292,6 +295,7 @@ impl DurableCellManager { instance_bindings: Arc::new(Mutex::new(BTreeMap::new())), control: Mutex::new(control_plane), fail_control_persists: AtomicU32::new(0), + fail_control_dirsync: AtomicU32::new(0), }); if let Err(error) = mgr.boot_local_shards().await { @@ -402,6 +406,7 @@ impl DurableCellManager { instance_bindings: Arc::new(Mutex::new(BTreeMap::new())), control: Mutex::new(control_plane), fail_control_persists: AtomicU32::new(0), + fail_control_dirsync: AtomicU32::new(0), })) } @@ -1921,6 +1926,19 @@ impl DurableCellManager { self.fail_control_persists.store(n, Ordering::Relaxed); } + /// The next `n` control-plane writes rename the file and then fail `sync_dir`. + pub fn testing_fail_next_control_dirsync(&self, n: u32) { + self.fail_control_dirsync.store(n, Ordering::Relaxed); + } + + /// Moves one stored heartbeat's observation time backward in memory only. + /// The sequence is unchanged. Tests use this to open the remote rate window. + pub fn testing_age_stored_heartbeat(&self, node_id: NodeId, earlier_by_ms: u64) { + if let Some(heartbeat) = self.control.lock().unwrap().heartbeats.get_mut(&node_id) { + heartbeat.observed_unix_ms = heartbeat.observed_unix_ms.saturating_sub(earlier_by_ms); + } + } + pub fn stored_heartbeat(&self, node_id: NodeId) -> Option { self.control .lock() @@ -2009,8 +2027,7 @@ impl DurableCellManager { let mut next = guard.clone(); next.heartbeats.insert(me, heartbeat.clone()); next.next_local_seq = seq.saturating_add(1); - self.persist_control(&next)?; - *guard = next; + self.store_control(&mut guard, next)?; Ok(heartbeat) } } @@ -2024,6 +2041,7 @@ impl DurableCellManager { seq: u64, disk_free_bytes: Option, reported_shard_ids: Vec, + instance_id: Option, ) -> Result<()> { node_id_in_ha_range(node_id)?; if node_id == self.host.node_id() { @@ -2039,6 +2057,13 @@ impl DurableCellManager { "node {node_id} is not registered; client shard descriptors are not applied to routes" ))); } + if let Some(bound) = state.node_instances.get(&node_id).copied() { + if instance_id != Some(bound) { + return Err(MetaDbError::ShardRoutingError(format!( + "heartbeat for node {node_id} does not carry the bound instance; registration is not a TransferLeader capability and this record is not a shard epoch" + ))); + } + } } let reported = normalize_ids(reported_shard_ids).map_err(MetaDbError::ShardRoutingError)?; let write = HeartbeatWrite { @@ -2055,11 +2080,22 @@ impl DurableCellManager { match decision { HeartbeatDecision::Replay(_) => Ok(()), HeartbeatDecision::Store(heartbeat) => { + if let Some(previous) = guard.heartbeats.get(&node_id) { + if remote_heartbeat_is_too_soon( + previous.observed_unix_ms, + write.observed_unix_ms, + write.seq, + previous.seq, + ) { + return Err(MetaDbError::ShardRoutingError( + "heartbeat rate limit; the stored record was kept. A heartbeat is not a scheduling epoch" + .to_string(), + )); + } + } let mut next = guard.clone(); next.heartbeats.insert(node_id, heartbeat); - self.persist_control(&next)?; - *guard = next; - Ok(()) + self.store_control(&mut guard, next) } } } @@ -2081,7 +2117,7 @@ impl DurableCellManager { .as_ref() .map(|record| record.committed_moves.clone()) .unwrap_or_default(); - let mut transfer_attempt = previous + let transfer_attempt = previous .as_ref() .map(|record| record.last_transfer_attempt_unix_ms) .unwrap_or(0); @@ -2111,7 +2147,27 @@ impl DurableCellManager { self.sync_route_voters_from_raft(shard.shard_id)?; } let decision = plan_jumbo_placement(&observation); - let Some(action) = decision.actions.first().cloned() else { + let actions = executable_placement_actions(&decision.actions); + if !automatic_leadership_transfer_allowed() + && decision + .actions + .iter() + .any(|action| matches!(action, PlacementAction::TransferLeadership { .. })) + { + let reason = + append_reason(&decision.blocked_reason, AUTOMATIC_TRANSFER_DISABLED_REASON); + return self.finish_placement(placement_record( + shard_id, + dominant_pid, + dedicated_node, + PlacementPhase::Blocked, + reason, + committed_moves, + transfer_attempt, + replace_attempt, + )); + } + let Some(action) = actions.first().cloned() else { return self.finish_placement(placement_record( shard_id, dominant_pid, @@ -2136,62 +2192,16 @@ impl DurableCellManager { )); } match action { - PlacementAction::TransferLeadership { - shard_id: target, - to, - } => { - let now = unix_ms(); - if transfer_attempt != 0 - && now.saturating_sub(transfer_attempt) < PLACEMENT_RETRY_MS - { - let reason = append_reason( - &decision.blocked_reason, - "leadership transfer is in cooldown and was not submitted again", - ); - return self.finish_placement(placement_record( - shard_id, - dominant_pid, - dedicated_node, - PlacementPhase::Recorded, - reason, - committed_moves, - transfer_attempt, - replace_attempt, - )); - } - transfer_attempt = now; - self.save_placement(&placement_record( - shard_id, - dominant_pid, - dedicated_node, - decision.phase, - decision.blocked_reason.clone(), - committed_moves.clone(), - transfer_attempt, - replace_attempt, - ))?; - let moved = self.transfer_leadership(target, to).await?; - if moved { - push_move( - &mut committed_moves, - CommittedMove::LeadershipTransferred { - shard_id: target, - to, - }, - ); - continue; - } - let reason = append_reason( - &decision.blocked_reason, - &format!( - "transfer_leader to {to} did not make that node the leader within 3s; the move is not recorded as committed" - ), - ); + PlacementAction::TransferLeadership { .. } => { + // Unreachable while automatic transfer is disabled. The filter + // above drops the variant. Do not call `trigger().transfer_leader`. + let reason = + append_reason(&decision.blocked_reason, AUTOMATIC_TRANSFER_DISABLED_REASON); return self.finish_placement(placement_record( shard_id, dominant_pid, dedicated_node, - PlacementPhase::Recorded, + PlacementPhase::Blocked, reason, committed_moves, transfer_attempt, @@ -2234,7 +2244,10 @@ impl DurableCellManager { replace_attempt, ))?; match self.replace_dedicated_voter(target, remove, add).await { - Ok(true) => { + ReplaceOutcome::NotProposed => {} + ReplaceOutcome::Committed { + route_persist_error, + } => { push_move( &mut committed_moves, CommittedMove::VoterReplaced { @@ -2243,13 +2256,31 @@ impl DurableCellManager { added: add, }, ); + let reason = match &route_persist_error { + Some(error) => format!( + "membership committed but the route record failed to persist: {error}; committed_moves keeps VoterReplaced" + ), + None => decision.blocked_reason.clone(), + }; + self.save_placement(&placement_record( + shard_id, + dominant_pid, + dedicated_node, + decision.phase, + reason, + committed_moves.clone(), + transfer_attempt, + replace_attempt, + ))?; + if let Some(error) = route_persist_error { + return Err(error); + } } - Ok(false) => {} - Err(error) => { + ReplaceOutcome::Rejected(error) => { let reason = append_reason( &decision.blocked_reason, &format!( - "peer voter replacement failed: {error}; voters were not reported as drained" + "peer voter replacement was not committed: {error}; no VoterReplaced was recorded" ), ); return self.finish_placement(placement_record( @@ -2342,94 +2373,112 @@ impl DurableCellManager { self.persist_voter_set(shard_id, &live, group.current_epoch()) } - async fn transfer_leadership(&self, shard_id: ShardId, to: NodeId) -> Result { - let (_, group, _) = self.lookup_local_handle(shard_id)?; - if group.current_leader() == Some(to) { - return Ok(true); - } - if group.current_leader() != Some(self.host.node_id()) { - return Ok(false); - } - let voters = group.uniform_voter_addrs()?; - if !voters.contains_key(&to) { - return Err(MetaDbError::ConsensusError(format!( - "refusing to transfer leadership of shard {shard_id} to node {to}; that node is not a voter" - ))); - } - group - .raft() - .trigger() - .transfer_leader(to) - .await - .map_err(|error| { - MetaDbError::ConsensusError(format!("transfer_leader({to}) failed: {error}")) - })?; - let deadline = tokio::time::Instant::now() + Duration::from_secs(3); - loop { - if group.current_leader() == Some(to) { - return Ok(true); - } - if tokio::time::Instant::now() >= deadline { - return Ok(false); - } - tokio::time::sleep(Duration::from_millis(20)).await; - } - } - - /// `Ok(true)` only after the committed voter set is the planned set. - /// `Ok(false)` means this process did not propose a change. + /// Does not call `trigger().transfer_leader`. An already-correct leader is not a + /// committed move. A matching voter set that this call did not propose is + /// [`ReplaceOutcome::NotProposed`]. async fn replace_dedicated_voter( &self, shard_id: ShardId, remove: NodeId, add: NodeId, - ) -> Result { - let (_, group, _) = self.lookup_local_handle(shard_id)?; + ) -> ReplaceOutcome { + let (_, group, _) = match self.lookup_local_handle(shard_id) { + Ok(handle) => handle, + Err(error) => return ReplaceOutcome::Rejected(error), + }; if group.current_leader() != Some(self.host.node_id()) { - return Ok(false); + return ReplaceOutcome::NotProposed; } - let current = group.uniform_voter_addrs()?; + let current = match group.uniform_voter_addrs() { + Ok(voters) => voters, + Err(error) => return ReplaceOutcome::Rejected(error), + }; let old: BTreeSet = current.keys().copied().collect(); if !old.contains(&remove) { - return Ok(false); + return ReplaceOutcome::NotProposed; } let mut proposed = old.clone(); proposed.remove(&remove); proposed.insert(add); - jumbo_membership_change_allowed(&old, &proposed).map_err(|refusal| { - MetaDbError::ConsensusError(format!( + if let Err(refusal) = jumbo_membership_change_allowed(&old, &proposed) { + return ReplaceOutcome::Rejected(MetaDbError::ConsensusError(format!( "refusing jumbo voter change on shard {shard_id}: {refusal:?}" - )) - })?; - if !self.node_is_proven_voter(add)? { - return Err(MetaDbError::ConsensusError(format!( + ))); + } + let proven = match self.node_is_proven_voter(add) { + Ok(proven) => proven, + Err(error) => return ReplaceOutcome::Rejected(error), + }; + if !proven { + return ReplaceOutcome::Rejected(MetaDbError::ConsensusError(format!( "refusing to add node {add} on shard {shard_id}; it is not already a voter of a local shard" ))); } - if current.contains_key(&add) { - ConfChangeOrchestrator::change_voters(group.raft(), proposed.clone()).await?; + let proposed_change = if current.contains_key(&add) { + ConfChangeOrchestrator::change_voters(group.raft(), proposed.clone()).await } else { - let addr = self.proven_voter_addr(add)?; - let min_matched = group.prepare_learner_snapshot().await?; - ConfChangeOrchestrator::add_learners_and_promote_voters( - group.raft(), - &[(add, addr)], - proposed.clone(), - 64, - Duration::from_secs(20), - min_matched, - ) - .await?; + match self.proven_voter_addr(add) { + Ok(addr) => match group.prepare_learner_snapshot().await { + Ok(min_matched) => { + ConfChangeOrchestrator::add_learners_and_promote_voters( + group.raft(), + &[(add, addr)], + proposed.clone(), + 64, + Duration::from_secs(20), + min_matched, + ) + .await + } + Err(error) => Err(error), + }, + Err(error) => Err(error), + } + }; + if let Err(error) = proposed_change { + return self.finish_replace_after_proposal(group.as_ref(), &proposed, error); } - let committed = group.wait_uniform_voter_addrs().await?; + match group.wait_uniform_voter_addrs().await { + Ok(committed) => self.committed_replace(shard_id, group.as_ref(), &proposed, committed), + Err(error) => self.finish_replace_after_proposal(group.as_ref(), &proposed, error), + } + } + + fn finish_replace_after_proposal( + &self, + group: &metadb_raft::ShardRaftGroup, + proposed: &BTreeSet, + error: MetaDbError, + ) -> ReplaceOutcome { + match group.uniform_voter_addrs() { + Ok(live) if live.keys().copied().collect::>() == *proposed => { + self.committed_replace(group.shard_id(), group, proposed, live) + } + _ => ReplaceOutcome::Rejected(error), + } + } + + fn committed_replace( + &self, + shard_id: ShardId, + group: &metadb_raft::ShardRaftGroup, + proposed: &BTreeSet, + committed: BTreeMap, + ) -> ReplaceOutcome { let committed_ids: BTreeSet = committed.keys().copied().collect(); - if committed_ids != proposed { - return Err(MetaDbError::ConsensusError(format!( - "shard {shard_id} committed voters {committed_ids:?} but the plan required {proposed:?}; the placement is not marked drained" + if committed_ids != *proposed { + return ReplaceOutcome::Rejected(MetaDbError::ConsensusError(format!( + "shard {shard_id} voters {committed_ids:?} are not the planned set {proposed:?}; no VoterReplaced was recorded" ))); } - self.persist_voter_set(shard_id, &committed, group.current_epoch())?; - Ok(true) + match self.persist_voter_set(shard_id, &committed, group.current_epoch()) { + Ok(()) => ReplaceOutcome::Committed { + route_persist_error: None, + }, + Err(error) => ReplaceOutcome::Committed { + route_persist_error: Some(error), + }, + } } fn node_is_proven_voter(&self, node_id: NodeId) -> Result { @@ -2478,25 +2527,51 @@ impl DurableCellManager { } let mut next = guard.clone(); next.placements.insert(record.shard_id, record.clone()); - self.persist_control(&next)?; - *guard = next; - Ok(()) + self.store_control(&mut guard, next) } - fn persist_control(&self, state: &PersistedControlPlane) -> Result<()> { + /// Installs `next` when the new file is the visible directory entry, including + /// when the directory fsync fails after rename. A later persist then continues + /// from that state instead of writing the previous sequence back over it. + fn store_control( + &self, + guard: &mut PersistedControlPlane, + next: PersistedControlPlane, + ) -> Result<()> { + match self.persist_control(&next) { + Ok(()) => { + *guard = next; + Ok(()) + } + Err(ControlPersistError::NotVisible(error)) => Err(error), + Err(ControlPersistError::VisibleDirSyncFailed(error)) => { + *guard = next; + Err(error) + } + } + } + + fn persist_control( + &self, + state: &PersistedControlPlane, + ) -> std::result::Result<(), ControlPersistError> { if state.version != CONTROL_PLANE_VERSION { - return Err(MetaDbError::CodecError(format!( - "{CONTROL_PLANE_FILE} version {} is not supported", - state.version + return Err(ControlPersistError::NotVisible(MetaDbError::CodecError( + format!( + "{CONTROL_PLANE_FILE} version {} is not supported", + state.version + ), ))); } if self.fail_control_persists.load(Ordering::Relaxed) > 0 { self.fail_control_persists.fetch_sub(1, Ordering::Relaxed); - return Err(MetaDbError::StorageIoError( - "injected CELL_CONTROL_PLANE persist failure".to_string(), + return Err(ControlPersistError::NotVisible( + MetaDbError::StorageIoError( + "injected CELL_CONTROL_PLANE persist failure".to_string(), + ), )); } - Self::write_control_file(&self.state_dir, state) + self.write_control_file(&self.state_dir, state) } fn load_control_plane(dir: &Path) -> Result { @@ -2518,19 +2593,26 @@ impl DurableCellManager { Ok(state) } - fn write_control_file(dir: &Path, state: &PersistedControlPlane) -> Result<()> { + fn write_control_file( + &self, + dir: &Path, + state: &PersistedControlPlane, + ) -> std::result::Result<(), ControlPersistError> { let _shard_set = if dir .file_name() .and_then(|name| name.to_str()) .is_some_and(|name| name.starts_with("cell_")) { let root = dir.parent().unwrap_or_else(|| Path::new(".")); - Some(metadb_raft::backup::lock_be_shard_set(&root.join("be"))?) + metadb_raft::backup::lock_be_shard_set(&root.join("be")) + .map(Some) + .map_err(ControlPersistError::NotVisible)? } else { None }; - let mut raw = - codec::serialize(state).map_err(|error| MetaDbError::CodecError(error.to_string()))?; + let mut raw = codec::serialize(state).map_err(|error| { + ControlPersistError::NotVisible(MetaDbError::CodecError(error.to_string())) + })?; append_crc32c_le(&mut raw); let tmp = dir.join(format!("{CONTROL_PLANE_FILE}.tmp")); let dst = dir.join(CONTROL_PLANE_FILE); @@ -2539,12 +2621,27 @@ impl DurableCellManager { .create(true) .write(true) .truncate(true) - .open(&tmp)?; - file.write_all(&raw)?; - file.sync_data()?; + .open(&tmp) + .map_err(|error| ControlPersistError::NotVisible(error.into()))?; + file.write_all(&raw) + .map_err(|error| ControlPersistError::NotVisible(error.into()))?; + file.sync_data() + .map_err(|error| ControlPersistError::NotVisible(error.into()))?; + } + fs::rename(&tmp, &dst).map_err(|error| ControlPersistError::NotVisible(error.into()))?; + if self.fail_control_dirsync.load(Ordering::Relaxed) > 0 { + self.fail_control_dirsync.fetch_sub(1, Ordering::Relaxed); + return Err(ControlPersistError::VisibleDirSyncFailed( + MetaDbError::StorageIoError( + "injected CELL_CONTROL_PLANE directory sync failure after rename".to_string(), + ), + )); } - fs::rename(&tmp, &dst)?; - sync_dir(dir)?; + sync_dir(dir).map_err(|error| { + ControlPersistError::VisibleDirSyncFailed(MetaDbError::StorageIoError(format!( + "CELL_CONTROL_PLANE directory sync failed after rename: {error}" + ))) + })?; Ok(()) } @@ -2600,6 +2697,27 @@ impl DurableCellManager { } } +#[allow(clippy::too_many_arguments)] +enum ControlPersistError { + /// The previous file is still the visible record. Memory must stay unchanged. + NotVisible(MetaDbError), + /// `rename` has published the new file. Memory must keep that state so a later + /// persist cannot write an older sequence over it. The directory fsync did not finish. + VisibleDirSyncFailed(MetaDbError), +} + +enum ReplaceOutcome { + /// This call did not propose a voter change. An already-matching set is observation. + NotProposed, + /// Raft's uniform voter set matches the plan. `route_persist_error` is set when + /// that fact did not reach `CELL_MANAGER_STATE`. + Committed { + route_persist_error: Option, + }, + /// No matching voter set was observed. Do not record `VoterReplaced`. + Rejected(MetaDbError), +} + #[allow(clippy::too_many_arguments)] fn placement_record( shard_id: ShardId, diff --git a/crates/metadb-cluster/src/control_plane_state.rs b/crates/metadb-cluster/src/control_plane_state.rs index f40bc99..251fea3 100644 --- a/crates/metadb-cluster/src/control_plane_state.rs +++ b/crates/metadb-cluster/src/control_plane_state.rs @@ -26,6 +26,19 @@ pub const CONTROL_PLANE_FILE: &str = "CELL_CONTROL_PLANE"; /// Upper bound on shard ids stored from one heartbeat. The ids are annotations. pub const MAX_REPORTED_SHARD_IDS: usize = 1_024; +/// Largest forward jump accepted from the stored sequence. A first record must +/// also sit inside `1..=MAX_HEARTBEAT_SEQ_ADVANCE`. `u64::MAX` cannot wedge the node. +pub const MAX_HEARTBEAT_SEQ_ADVANCE: u64 = 64; + +/// Minimum gap between two remote heartbeats that carry a new sequence. +pub const MIN_REMOTE_HEARTBEAT_INTERVAL_MS: u64 = 1_000; + +/// Heartbeats are an unreplicated local observation. They are not a shard epoch +/// and must not schedule splits, membership changes, or leadership transfer. +pub fn heartbeat_is_scheduling_truth() -> bool { + false +} + #[derive( Debug, Clone, PartialEq, Eq, Serialize, Deserialize, wincode::SchemaWrite, wincode::SchemaRead, )] @@ -146,6 +159,21 @@ pub fn decide_heartbeat( .to_string(), ); } + if let Some(previous) = existing { + if write.seq > previous.seq && write.seq - previous.seq > MAX_HEARTBEAT_SEQ_ADVANCE { + return Err(format!( + "heartbeat seq {} jumps {} past {}; the stored record was kept. A heartbeat is not a scheduling epoch", + write.seq, + write.seq - previous.seq, + previous.seq + )); + } + } else if write.seq > MAX_HEARTBEAT_SEQ_ADVANCE { + return Err(format!( + "initial heartbeat seq {} exceeds {MAX_HEARTBEAT_SEQ_ADVANCE}; the stored record was kept. A heartbeat is not a scheduling epoch", + write.seq + )); + } let stored = StoredHeartbeat { node_id: write.node_id, seq: write.seq, @@ -181,6 +209,18 @@ pub fn decide_heartbeat( Ok(HeartbeatDecision::Store(stored)) } +/// A new remote sequence inside the interval is rejected. An equal sequence is a +/// replay or a conflict and is not rate-limited here. +pub fn remote_heartbeat_is_too_soon( + previous_observed_unix_ms: u64, + now_ms: u64, + incoming_seq: u64, + stored_seq: u64, +) -> bool { + incoming_seq != stored_seq + && now_ms.saturating_sub(previous_observed_unix_ms) < MIN_REMOTE_HEARTBEAT_INTERVAL_MS +} + fn same_body(stored: &StoredHeartbeat, write: &HeartbeatWrite) -> bool { stored.disk_free_bytes == write.disk_free_bytes && stored.reported_shard_ids == write.reported_shard_ids @@ -234,6 +274,14 @@ mod tests { assert!(decide_heartbeat(Some(&next), &write(1, None, &[4])) .unwrap_err() .contains("stale")); + let poisoned = decide_heartbeat(Some(&next), &write(u64::MAX, None, &[4])).unwrap_err(); + assert!(poisoned.contains("jumps"), "{poisoned}"); + let initial = decide_heartbeat(None, &write(u64::MAX, None, &[])).unwrap_err(); + assert!(initial.contains("exceeds"), "{initial}"); + assert!(remote_heartbeat_is_too_soon(1_000, 1_500, 2, 1)); + assert!(!remote_heartbeat_is_too_soon(1_000, 1_500, 1, 1)); + assert!(!remote_heartbeat_is_too_soon(1_000, 3_000, 2, 1)); + assert!(!heartbeat_is_scheduling_truth()); } #[test] diff --git a/crates/metadb-cluster/src/jumbo_placement.rs b/crates/metadb-cluster/src/jumbo_placement.rs index 2773ac3..4dab7ee 100644 --- a/crates/metadb-cluster/src/jumbo_placement.rs +++ b/crates/metadb-cluster/src/jumbo_placement.rs @@ -1,9 +1,9 @@ //! Membership-safe Jumbo placement decisions. //! //! `JumboIsolated` on a route is a detection flag. It does not by itself move a replica. -//! This module plans the only moves this increment will attempt: -//! leadership transfer onto a node that is already a voter, and a same-size voter -//! replacement that keeps Raft fault tolerance and an old-majority overlap. +//! This module plans a same-size voter replacement that keeps Raft fault tolerance +//! and an old-majority overlap. Automatic leadership transfer is not planned: +//! OpenRaft disables the leader lease before peers answer `TransferLeader`. //! //! A plan that cannot do either is `Blocked` or `LeaderOnDedicated` with a reason. //! Neither of those is a completed eviction. @@ -36,8 +36,47 @@ pub struct PlacementObservation { pub reserved_dedicated_nodes: BTreeSet, } +/// OpenRaft 0.10 `trigger().transfer_leader` marks the transfer and disables the +/// leader lease before any peer answers `TransferLeader`. Older peers do not +/// implement that RPC. Registration in the node map is not proof that they do. +/// Automatic transfer stays off until a check that does not touch the lease can +/// show every current voter implements it. +pub const AUTOMATIC_LEADERSHIP_TRANSFER_ENABLED: bool = false; + +pub const AUTOMATIC_TRANSFER_DISABLED_REASON: &str = "automatic leadership transfer is disabled; peer TransferLeader capability is unknown, and OpenRaft disables the leader lease before the RPC is known to succeed. Node registration is not that capability"; + +pub fn automatic_leadership_transfer_allowed() -> bool { + AUTOMATIC_LEADERSHIP_TRANSFER_ENABLED +} + +/// A transfer poll shorter than the configured election timeout can return while +/// OpenRaft is still rejecting writes. Pull request #38 (`f55cc6cf`) loads +/// `election_timeout_max_ms`. This process does not start that poll. +pub fn transfer_poll_covers_election(poll_ms: u64, election_timeout_max_ms: u64) -> bool { + election_timeout_max_ms > 0 && poll_ms >= election_timeout_max_ms +} + +/// `committed_moves` records only a transfer this process initiated and then +/// observed on the target. An already-correct leader is observation, not our move. +pub fn leadership_move_recorded(initiated_transfer: bool, target_became_leader: bool) -> bool { + initiated_transfer && target_became_leader +} + +/// Drops leadership transfer unless [`automatic_leadership_transfer_allowed`] is true. +pub fn executable_placement_actions(actions: &[PlacementAction]) -> Vec { + actions + .iter() + .filter(|action| match action { + PlacementAction::TransferLeadership { .. } => automatic_leadership_transfer_allowed(), + PlacementAction::ReplaceDedicatedOnPeer { .. } => true, + }) + .cloned() + .collect() +} + /// One Raft action the executor may attempt. The planner never emits an action that /// drops fault tolerance or addresses a node that has not already joined a shard. +/// `TransferLeadership` is not executable while automatic transfer is disabled. #[derive(Debug, Clone, PartialEq, Eq)] pub enum PlacementAction { TransferLeadership { @@ -169,14 +208,8 @@ pub fn plan_jumbo_placement(obs: &PlacementObservation) -> PlacementDecision { let mut actions = Vec::new(); let leader_here = jumbo.leader == Some(obs.dedicated_node); - if !leader_here { - if jumbo.leader.is_none() { - return blocked("jumbo shard has no current leader; leadership was not transferred"); - } - actions.push(PlacementAction::TransferLeadership { - shard_id: jumbo.shard_id, - to: obs.dedicated_node, - }); + if !leader_here && jumbo.leader.is_none() { + return blocked("jumbo shard has no current leader; transfer_leader was not called"); } let mut reasons = Vec::new(); @@ -205,10 +238,16 @@ pub fn plan_jumbo_placement(obs: &PlacementObservation) -> PlacementDecision { .to_string(), ); } + if !leader_here { + reasons.push(AUTOMATIC_TRANSFER_DISABLED_REASON.to_string()); + } - let phase = if !leader_here && jumbo.leader.is_some() { - PlacementPhase::Recorded - } else if reasons.is_empty() && other_shards > 0 && leader_here { + let replace_pending = actions + .iter() + .any(|action| matches!(action, PlacementAction::ReplaceDedicatedOnPeer { .. })); + let phase = if !leader_here { + PlacementPhase::Blocked + } else if reasons.is_empty() && other_shards > 0 && !replace_pending { PlacementPhase::DedicatedNodeNotShared } else if leader_here { PlacementPhase::LeaderOnDedicated @@ -216,17 +255,6 @@ pub fn plan_jumbo_placement(obs: &PlacementObservation) -> PlacementDecision { PlacementPhase::Blocked }; - // A replacement that has not been applied yet is not the unshared condition. - let phase = if actions - .iter() - .any(|action| matches!(action, PlacementAction::ReplaceDedicatedOnPeer { .. })) - && phase == PlacementPhase::DedicatedNodeNotShared - { - PlacementPhase::LeaderOnDedicated - } else { - phase - }; - PlacementDecision { phase, blocked_reason: reasons.join("; "), @@ -347,23 +375,37 @@ mod tests { } #[test] - fn uniform_three_voters_transfer_leadership_and_refuse_to_shrink() { + fn uniform_three_voters_do_not_transfer_or_shrink() { let decision = plan_jumbo_placement(&obs( 2, vec![shard(1, &[1, 2, 3], Some(1)), shard(2, &[1, 2, 3], Some(1))], &[1, 2, 3], )); - assert_eq!(decision.phase, PlacementPhase::Recorded); - assert_eq!( - decision.actions, - vec![PlacementAction::TransferLeadership { shard_id: 1, to: 2 }] + assert_eq!(decision.phase, PlacementPhase::Blocked); + assert!( + decision + .actions + .iter() + .all(|action| !matches!(action, PlacementAction::TransferLeadership { .. })), + "{decision:?}" ); + assert!(executable_placement_actions(&decision.actions).is_empty()); assert!( - decision.blocked_reason.contains("fault tolerance") - || decision.blocked_reason.contains("proven voter"), + decision + .blocked_reason + .contains("automatic leadership transfer is disabled"), "{}", decision.blocked_reason ); + assert!(!automatic_leadership_transfer_allowed()); + assert!(!leadership_move_recorded(false, true)); + assert!(leadership_move_recorded(true, true)); + // #38 can set election_timeout_max_ms above a 3s poll. Covering the + // timeout is not enough to enable transfer. + assert!(!transfer_poll_covers_election(3_000, 5_000)); + assert!(transfer_poll_covers_election(5_000, 5_000)); + let forced = vec![PlacementAction::TransferLeadership { shard_id: 1, to: 2 }]; + assert!(executable_placement_actions(&forced).is_empty()); } #[test] diff --git a/crates/metadb-cluster/src/lib.rs b/crates/metadb-cluster/src/lib.rs index 7eb0cb1..d748aef 100644 --- a/crates/metadb-cluster/src/lib.rs +++ b/crates/metadb-cluster/src/lib.rs @@ -23,7 +23,10 @@ pub use cell_manager::{ SplitPlanRecord, SplitPlanState, }; pub use control_plane::{CellId, CellLocalManager, GlobalManager, MetaCache, ShardRoute}; -pub use control_plane_state::{StoredHeartbeat, StoredPlacement, HEARTBEAT_INTERVAL_MS}; +pub use control_plane_state::{ + heartbeat_is_scheduling_truth, StoredHeartbeat, StoredPlacement, HEARTBEAT_INTERVAL_MS, + MAX_HEARTBEAT_SEQ_ADVANCE, +}; pub use global_manager::DurableGlobalManager; pub use id_allocator::{ AllocIdKind, DurableIdAllocator, LocalIdBuffer, CELL_DIR_AFFINITY_BLOCK_SIZE, @@ -32,9 +35,10 @@ pub use id_allocator::{ pub use identity::{node_id_in_ha_range, ClusterIdentity, CLUSTER_IDENTITY_FILE}; pub use jumbo::JumboIsolationPlanner; pub use jumbo_placement::{ - fault_tolerance, jumbo_membership_change_allowed, plan_jumbo_placement, CommittedMove, - MembershipRefusal, PlacementAction, PlacementDecision, PlacementObservation, PlacementPhase, - ShardVoters, + automatic_leadership_transfer_allowed, executable_placement_actions, fault_tolerance, + jumbo_membership_change_allowed, leadership_move_recorded, plan_jumbo_placement, + transfer_poll_covers_election, CommittedMove, MembershipRefusal, PlacementAction, + PlacementDecision, PlacementObservation, PlacementPhase, ShardVoters, }; pub use meta_cache::{CompositeMetaCache, CompositeShardRoute}; pub use shard::{ diff --git a/crates/metadb-cluster/tests/scale_control_plane_tests.rs b/crates/metadb-cluster/tests/scale_control_plane_tests.rs index 5de18b2..5df83c5 100644 --- a/crates/metadb-cluster/tests/scale_control_plane_tests.rs +++ b/crates/metadb-cluster/tests/scale_control_plane_tests.rs @@ -57,24 +57,25 @@ async fn heartbeat_survives_reopen_and_a_lower_sequence_does_not_replace_it() { ); let second = cell.publish_local_heartbeat().unwrap(); assert_eq!(second.seq, 2); - let stale = cell.accept_remote_heartbeat(1, 1, None, vec![999]); + let stale = cell.accept_remote_heartbeat(1, 1, None, vec![999], None); assert!( stale.is_err(), "the local node does not accept its own remote heartbeat" ); cell.register_node(4, "127.0.0.1:4".to_string()).unwrap(); - cell.accept_remote_heartbeat(4, 3, Some(8), vec![999, 999]) + cell.accept_remote_heartbeat(4, 3, Some(8), vec![999, 999], None) .unwrap(); let peer = cell.stored_heartbeat(4).unwrap(); assert_eq!(peer.reported_shard_ids, vec![999]); assert!(cell.list_routes().iter().all(|route| route.shard_id != 999)); - let conflict = cell.accept_remote_heartbeat(4, 3, Some(9), vec![999]); + let conflict = cell.accept_remote_heartbeat(4, 3, Some(9), vec![999], None); assert!(conflict.unwrap_err().to_string().contains("conflicts")); assert_eq!(cell.stored_heartbeat(4).unwrap().disk_free_bytes, Some(8)); - let older = cell.accept_remote_heartbeat(4, 2, Some(8), vec![999]); + let older = cell.accept_remote_heartbeat(4, 2, Some(8), vec![999], None); assert!(older.unwrap_err().to_string().contains("stale")); + cell.testing_age_stored_heartbeat(4, 5_000); cell.testing_fail_next_control_persists(1); - let failed = cell.accept_remote_heartbeat(4, 4, Some(8), vec![999]); + let failed = cell.accept_remote_heartbeat(4, 4, Some(8), vec![999], None); assert!(failed.is_err()); assert_eq!(cell.stored_heartbeat(4).unwrap().seq, 3); @@ -108,6 +109,11 @@ async fn single_voter_jumbo_placement_does_not_change_membership() { assert_eq!(local.phase, PlacementPhase::LeaderOnDedicated); assert_ne!(local.phase, PlacementPhase::DedicatedNodeNotShared); assert!(local.committed_moves.is_empty(), "{local:?}"); + assert!( + !metadb_cluster::leadership_move_recorded(false, true), + "an already-correct leader is not this process's LeadershipTransferred" + ); + assert!(!metadb_cluster::automatic_leadership_transfer_allowed()); assert!( local.blocked_reason.contains("proven voter") || local.blocked_reason.contains("fault tolerance"), @@ -177,3 +183,57 @@ async fn a_corrupt_control_plane_file_refuses_to_open() { "{text}" ); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn directory_sync_failure_after_rename_keeps_the_new_sequence() { + let dir = tempdir().unwrap(); + let (host, cell) = open_cell(dir.path()).await; + assert_eq!(cell.publish_local_heartbeat().unwrap().seq, 1); + cell.testing_fail_next_control_dirsync(1); + let failed = cell.publish_local_heartbeat().unwrap_err(); + assert!(failed.to_string().contains("directory sync"), "{failed}"); + assert_eq!( + cell.stored_heartbeat(1).unwrap().seq, + 2, + "a renamed control file must stay in memory" + ); + assert_eq!(cell.publish_local_heartbeat().unwrap().seq, 3); + host.shutdown_all().await.unwrap(); + drop(cell); + drop(host); + + let (host, cell) = open_cell(dir.path()).await; + assert_eq!(cell.stored_heartbeat(1).unwrap().seq, 3); + host.shutdown_all().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn remote_heartbeat_rejects_a_poison_sequence_and_a_fast_repeat() { + let dir = tempdir().unwrap(); + let (host, cell) = open_cell(dir.path()).await; + cell.register_node(4, "127.0.0.1:4".to_string()).unwrap(); + cell.accept_remote_heartbeat(4, 1, None, Vec::new(), None) + .unwrap(); + let too_soon = cell + .accept_remote_heartbeat(4, 2, None, Vec::new(), None) + .unwrap_err(); + assert!(too_soon.to_string().contains("rate"), "{too_soon}"); + assert_eq!(cell.stored_heartbeat(4).unwrap().seq, 1); + let poisoned = cell + .accept_remote_heartbeat(4, u64::MAX, None, Vec::new(), None) + .unwrap_err(); + assert!( + poisoned.to_string().contains("jumps") || poisoned.to_string().contains("exceeds"), + "{poisoned}" + ); + assert_eq!(cell.stored_heartbeat(4).unwrap().seq, 1); + cell.testing_age_stored_heartbeat(4, 5_000); + cell.accept_remote_heartbeat(4, 2, None, Vec::new(), None) + .unwrap(); + assert_eq!(cell.stored_heartbeat(4).unwrap().seq, 2); + assert!(!metadb_cluster::heartbeat_is_scheduling_truth()); + assert!(!metadb_cluster::automatic_leadership_transfer_allowed()); + assert!(!metadb_cluster::leadership_move_recorded(false, true)); + assert!(!metadb_cluster::transfer_poll_covers_election(3_000, 5_000)); + host.shutdown_all().await.unwrap(); +} diff --git a/crates/metadb-proto/proto/metadb/v1/control_plane.proto b/crates/metadb-proto/proto/metadb/v1/control_plane.proto index bacb208..dc4c428 100644 --- a/crates/metadb-proto/proto/metadb/v1/control_plane.proto +++ b/crates/metadb-proto/proto/metadb/v1/control_plane.proto @@ -36,6 +36,10 @@ message StoreHeartbeatRequest { uint64 monotonic_seq = 5; // When false, disk_free_bytes is not a measurement and is stored as unknown. bool disk_free_known = 6; + // 16-byte big-endian instance id. Required only when that node id is already + // bound to an instance. Empty does not authenticate the caller. This is not a + // shard epoch and does not schedule placement. + bytes instance_id = 7; } message StoreHeartbeatResponse { diff --git a/crates/metadb-raft/src/network.rs b/crates/metadb-raft/src/network.rs index eda26d5..eebbe5d 100644 --- a/crates/metadb-raft/src/network.rs +++ b/crates/metadb-raft/src/network.rs @@ -459,6 +459,8 @@ impl RaftTransportService for MultiRaftTransportServer { } } + /// Same bearer interceptor as `Vote` and `AppendEntries`. This handler does not + /// decide to transfer; `DurableCellManager` does not call `trigger().transfer_leader`. async fn transfer_leader( &self, request: Request, diff --git a/crates/metadb-server/src/grpc_services.rs b/crates/metadb-server/src/grpc_services.rs index 1b552d5..2519648 100644 --- a/crates/metadb-server/src/grpc_services.rs +++ b/crates/metadb-server/src/grpc_services.rs @@ -1004,7 +1004,22 @@ impl ControlPlaneService for MetaDbGrpcService { } } let disk_free = req.disk_free_known.then_some(req.disk_free_bytes); - match cell.accept_remote_heartbeat(req.node_id, req.monotonic_seq, disk_free, reported) { + let instance_id = match metadb_proto::convert::decode_optional_u128_be(&req.instance_id) { + Ok(0) => None, + Ok(id) => Some(id), + Err(error) => { + return Ok(Response::new(StoreHeartbeatResponse { + error: Some(ErrorDetailProto::from(&error)), + })); + } + }; + match cell.accept_remote_heartbeat( + req.node_id, + req.monotonic_seq, + disk_free, + reported, + instance_id, + ) { Ok(()) => Ok(Response::new(StoreHeartbeatResponse { error: None })), Err(error) => Ok(Response::new(StoreHeartbeatResponse { error: Some(ErrorDetailProto::from(&error)), diff --git a/crates/metadb-server/src/lib.rs b/crates/metadb-server/src/lib.rs index f67f4bb..09f28cb 100644 --- a/crates/metadb-server/src/lib.rs +++ b/crates/metadb-server/src/lib.rs @@ -941,6 +941,14 @@ impl PersistentMetaDbCluster { disk_free_known: heartbeat.disk_free_bytes.is_some(), monotonic_seq: heartbeat.seq, shards: Vec::new(), + instance_id: { + let instance = self.cell_manager.node_instance_id(); + if instance == 0 { + Vec::new() + } else { + metadb_proto::convert::encode_u128_be(instance).to_vec() + } + }, }) .await .map_err(|error| { diff --git a/crates/metadb-server/tests/control_plane_claim_tests.rs b/crates/metadb-server/tests/control_plane_claim_tests.rs index 9637a33..b1efea9 100644 --- a/crates/metadb-server/tests/control_plane_claim_tests.rs +++ b/crates/metadb-server/tests/control_plane_claim_tests.rs @@ -19,6 +19,7 @@ fn heartbeat_request(seq: u64, node_id: u64, disk_free_bytes: u64) -> StoreHeart disk_free_bytes, monotonic_seq: seq, disk_free_known: true, + instance_id: Vec::new(), shards: vec![ShardHeartbeatStatsProto { descriptor: Some(ShardDescriptorProto { cell_id: 1, @@ -92,6 +93,7 @@ async fn control_plane_does_not_pretend_missing_topology_ops_succeeded() { disk_free_bytes: 1, monotonic_seq: 1, disk_free_known: true, + instance_id: Vec::new(), shards: vec![ShardHeartbeatStatsProto { descriptor: Some(ShardDescriptorProto { cell_id: 1, @@ -178,6 +180,9 @@ async fn control_plane_does_not_pretend_missing_topology_ops_succeeded() { .disk_free_bytes, Some(4) ); + cluster + .cell_manager() + .testing_age_stored_heartbeat(7, 5_000); cluster.cell_manager().testing_fail_next_control_persists(1); let failed = svc .store_heartbeat(Request::new(heartbeat_request(2, 7, 4))) diff --git a/docs/en/architecture.md b/docs/en/architecture.md index 5d4ff6e..5334b8f 100644 --- a/docs/en/architecture.md +++ b/docs/en/architecture.md @@ -125,7 +125,7 @@ A directory rename also holds one `DirRenameLease` in the ID allocator. Renewal - Otherwise it picks a parent-id boundary near half the bytes. The split key is a PID prefix, so `_attr_` and the direct children of one parent stay together. - If the route is already `DualModeFineGrained` for that parent, the split key is a `(pid, name)` midpoint, excluding `_attr_`. -A jumbo candidate does **not** move the shard directory. `JumboIsolationPlanner` writes `ShardHealthState::JumboIsolated { dedicated_node, dominant_pid }` onto the route. The chosen node is the registered node with the fewest jumbo routes, then the fewest other routes. With only the bootstrap node registered, that node is this process. That flag is detection. `reconcile_jumbo_placement` then writes `CELL_CONTROL_PLANE`. On one voter it records `LeaderOnDedicated` or `Blocked` and does not change the voter set. It transfers leadership only when the dedicated node is already a voter and this process is the leader. It replaces that node on another shard only when a node that is already a voter of some local shard can take the seat without lowering Raft fault tolerance. `DedicatedNodeNotShared` means that membership condition holds. It does not mean shard files moved to another machine. See [Scale control plane](./scale-control-plane-status.md). +A jumbo candidate does **not** move the shard directory. `JumboIsolationPlanner` writes `ShardHealthState::JumboIsolated { dedicated_node, dominant_pid }` onto the route. The chosen node is the registered node with the fewest jumbo routes, then the fewest other routes. With only the bootstrap node registered, that node is this process. That flag is detection. `reconcile_jumbo_placement` then writes `CELL_CONTROL_PLANE`. On one voter it records `LeaderOnDedicated` or `Blocked` and does not change the voter set. Automatic `transfer_leader` is not called: OpenRaft disables the leader lease before the peer answers, and this process cannot prove that older peers implement `TransferLeader`. A same-size voter replacement runs only when a node that is already a voter of some local shard can take the seat without lowering Raft fault tolerance. An already-correct leader is not recorded as this process's move. `DedicatedNodeNotShared` means that membership condition holds. It does not mean shard files moved to another machine. See [Scale control plane](./scale-control-plane-status.md). `enable_dual_mode_split` persists `split_mode = DualModeFineGrained` and `dual_mode_pid`. It does not itself copy keys. A later split uses the `(pid, name)` rule. The in-memory simulator (`CellLocalManager` in `control_plane.rs`) is a different type: its jumbo path returns `UnsplittableJumboShard` and its "scale to 3 voters" only edits a `BTreeMap`. Tests `T1`–`T6` exercise that simulator. @@ -136,7 +136,7 @@ Split plans are stored in `CELL_MANAGER_STATE`. Crash points covered by `split_c | RPC | Behavior in this tree | | :--- | :--- | | `RegisterNode` | Inserts `(node_id, grpc_addr)` into this cell's `CELL_MANAGER_STATE` | -| `StoreHeartbeat` | For a registered node, fsyncs liveness into `CELL_CONTROL_PLANE` when `monotonic_seq` is newer. The same sequence and body is a replay. A lower sequence or a different body at the same sequence is rejected and the stored record stays. Shard descriptors in the request are stored as annotations and are not installed as routes. An unregistered node is rejected. The maintenance loop sends this process's own record, without shard descriptors, about every 3 seconds | +| `StoreHeartbeat` | For a registered node, fsyncs liveness into `CELL_CONTROL_PLANE`. `monotonic_seq` must be non-zero and may advance by at most 64. The same sequence and body is a replay. A lower sequence, a larger jump, or a different body at the same sequence is rejected and the stored record stays. A new sequence sooner than 1 second after the previous observation is rejected. Shard descriptors are annotations, not routes, and this record does not schedule splits or membership changes. A bound node instance must be repeated; an address-only registration has no second check. The shared bearer is still the only credential. The maintenance loop sends this process's own record, without shard descriptors, about every 3 seconds | | `GetRoutes` | `cell_id = 0` lists every cached route. An unknown non-zero `cell_id` returns an error instead of an empty shard list | | `AllocateIdBlock` | Allocates from the local durable allocator | | `AllocSplitPlan` / `ActivateSplit` | Forwards to the local cell manager | diff --git a/docs/en/operations.md b/docs/en/operations.md index efa0bc5..0e3b850 100644 --- a/docs/en/operations.md +++ b/docs/en/operations.md @@ -139,8 +139,8 @@ Variants are defined in `crates/metadb-core/src/error.rs`. gRPC methods usually - User names `.`, `..`, `/`, `\`, `_attr_`, empty, and NUL are rejected. A negative file size is rejected. A directory rename into its own descendant fails closed, including chains deeper than 1024. - The HLC saturates at the 48-bit physical ceiling instead of wrapping the logical counter. `Prepare2pc` follows `header.shard_id`, not the primary-key shard. - Quota cursor rows are written after the outbox lock is released, so a flush that already holds the memtable lock can still take the outbox lock. -- Jumbo isolation is still not a move of shard files onto a dedicated disk. The route flag names a node. `CELL_CONTROL_PLANE` records whether a membership-safe leadership transfer or same-size voter replacement was committed. A one-voter cell does not change its voter set. -- Heartbeats are a 3-second liveness record. `metadbd` persists its own and sends it to the current leader when this process is not the leader. The sender does not include shard descriptors. The record does not schedule splits. +- Jumbo isolation is still not a move of shard files onto a dedicated disk. The route flag names a node. Automatic leadership transfer is disabled. `CELL_CONTROL_PLANE` records a same-size voter replacement only after this process observes the planned voter set. An already-correct leader is not listed as this process's move. A one-voter cell does not change its voter set. +- Heartbeats are a local liveness observation, not a shard epoch and not a split or membership input. `metadbd` persists its own about every 3 seconds and sends it to the current leader when this process is not the leader. The sender does not include shard descriptors. A remote sequence may advance by at most 64, and a new sequence inside 1 second is rejected, so one registered identity cannot pin the counter at `u64::MAX`. The shared bearer remains the only credential. - A non-empty shared secret authenticates Raft, the other three gRPC services, and the metrics listener with the same bearer. An empty secret is accepted only for loopback binds and leaves those listeners unauthenticated. A wildcard bind with an empty secret refuses to start. The process does not terminate TLS. - `memtable_size_bytes` seals and flushes the active memtable. `max_imm_memtables` caps queued immutable tables. Raft timer fields do not change runtime behavior through TOML. - `metadb-ctl bench` for `hotspot-create` and `bulk-ttl-delete` prints JSON lines: a header with `bench_pid`, then phase reports with attempted, succeeded, failed, and latency percentiles. The process exits non-zero unless every requested operation succeeds. `--workload mixed` or `--embedded` runs the in-process stress harness. `sql` prints the response as JSON and exits non-zero on an application error. @@ -196,7 +196,7 @@ These items are missing from the product, so this guide cannot describe a proced 1. A multi-process layout for `be`, `proxy`, `cell-manager`, and `global-manager`. 2. A second Cell. `RegisterCell` stays an error. Join reaches only the current leader; a follower does not forward it. -3. Placing a jumbo shard on its own machine and moving other shard files off that disk. Leadership transfer and a same-size voter replacement exist only when the nodes are already voters and the change keeps Raft fault tolerance. A node that has not joined a shard is not added. +3. Placing a jumbo shard on its own machine and moving other shard files off that disk. Automatic leadership transfer is disabled because OpenRaft drops the leader lease before peers answer, and older peers do not implement `TransferLeader`. A same-size voter replacement keeps fault tolerance and only adds a node that is already a voter. A node that has not joined a shard is not added. 4. Native TLS. This process does not terminate TLS. Config keys that ask for TLS or a certificate are rejected instead of serving plaintext. Put termination in an external proxy. Raft and metrics use the same bearer as the other services when a secret is set; that bearer is not mutual TLS. The 3-second heartbeat records liveness. It does not drive splits, cell federation, or disk drain. 5. A Raft timer that operators can set and observe. 6. A checked-in service-level result for `metadb-ctl bench`. The command prints numbers for the machine you run it on. This repository does not record one. See [Tests and benches](./testing.md). diff --git a/docs/en/scale-control-plane-status.md b/docs/en/scale-control-plane-status.md index 7088229..aef8fef 100644 --- a/docs/en/scale-control-plane-status.md +++ b/docs/en/scale-control-plane-status.md @@ -10,16 +10,15 @@ Root `Architecture.md` was left unchanged on purpose. Consolidating it with the ## What this increment does -1. **Heartbeats are durable and are sent.** `StoreHeartbeat` for a registered node fsyncs `CELL_CONTROL_PLANE` (CRC32C frame, version 1). `monotonic_seq` must be non-zero. A lower sequence is rejected and the stored body stays. The same sequence and the same disk-free value and shard-id annotation is a replay and does not rewrite the timestamp. The same sequence with a different body is a conflict and does not overwrite. Shard descriptors in the RPC are stored only as `reported_shard_ids`. They are not copied into `CELL_MANAGER_STATE` or `CompositeMetaCache`. An unregistered node is rejected. A failed fsync leaves the previous record and returns an error. +1. **Heartbeats are durable and are sent.** `StoreHeartbeat` for a registered node fsyncs `CELL_CONTROL_PLANE` (CRC32C frame, version 1). `monotonic_seq` must be non-zero and may move forward by at most 64, including the first record. A lower sequence is rejected and the stored body stays. The same sequence and the same disk-free value and shard-id annotation is a replay and does not rewrite the timestamp. The same sequence with a different body is a conflict and does not overwrite. A new remote sequence inside 1 second is rejected. Shard descriptors in the RPC are stored only as `reported_shard_ids`. They are not copied into `CELL_MANAGER_STATE` or `CompositeMetaCache`, and they do not schedule placement. An unregistered node is rejected. The shared bearer is still the only credential; a bound node instance must be repeated, and an address-only registration does not gain a second check. A failed fsync before rename leaves the previous record. If rename succeeds and the directory sync fails, memory keeps the new file so a later write cannot put an older sequence back. 2. **The process sends its own heartbeat.** The 250 ms maintenance loop persists a local heartbeat about every 3 seconds (`HEARTBEAT_INTERVAL_MS`). Disk free space is unknown on that record; a zero is not stored as a measurement. When this process is not the Raft leader, it sends that same sequence to the leader's control-plane address and retries the same sequence once. The sender does not attach shard descriptors. A lost response does not roll the local sequence back. The next interval uses a new sequence. 3. **Jumbo placement is a record plus a narrow Raft action.** `JumboIsolated` remains the detection flag from `JumboIsolationPlanner`. `reconcile_jumbo_placement` writes a placement record from live Raft voters: - - `Blocked` when the dedicated node is not already a voter, the shard has no leader, or a move was refused. No voter is added for a node that has only a registered address. - - `LeaderOnDedicated` when that node is the current leader and peer shards still list it, or when this process hosts no other shard. The second case is not evidence that a co-located shard was moved. - - `Recorded` when leadership transfer or a peer replacement is still outstanding. + - `Blocked` when the dedicated node is not already a voter, the shard has no leader, leadership is elsewhere (automatic transfer is off), or a voter change was refused. No voter is added for a node that has only a registered address. + - `LeaderOnDedicated` when that node is already the current leader and peer shards still list it, or when this process hosts no other shard. That observation is not a `LeadershipTransferred` move. - `DedicatedNodeNotShared` only when at least one other local shard exists and none of those shards currently has the dedicated node as a voter. - - `committed_moves` grows only after this process's own Raft call reaches that postcondition. A restart does not invent a move it cannot prove it committed. + - `committed_moves` gains `VoterReplaced` only after this process observes the planned uniform voter set. A route-file persist failure does not drop that entry or label the set as uncommitted. A restart does not invent a move. 4. **Membership changes from this path keep a majority.** `jumbo_membership_change_allowed` refuses an empty set, a drop in fault tolerance (`(n-1)/2`), and a new set whose overlap is not a majority of the old set. The peer replacement keeps the same voter count and uses a node that is already a voter of some local shard. Another jumbo shard's dedicated node is not used as that spare. Operator `scale_out_replicas` / `remove_voter` is unchanged and can still shrink on purpose. -5. **Leadership transfer uses a real Raft RPC.** `RaftTransportService.TransferLeader` carries OpenRaft's `TransferLeaderRequest` and the server calls `handle_transfer_leader`. The placement path calls `trigger().transfer_leader` only when this process is the leader and the target is already a voter. OpenRaft disables the leader lease when that call is submitted. If the target is not leader within 3 seconds, the move is not recorded as committed and the next attempt waits 30 seconds. A one-voter cell never submits it, because the dedicated node is either already the leader or not a voter. +5. **Automatic leadership transfer is disabled.** OpenRaft 0.10 `trigger().transfer_leader` marks the transfer and disables the leader lease before any peer answers. Older processes do not implement `RaftTransportService.TransferLeader`. This process cannot prove that capability without that lease-affecting call, and node registration is not proof. `reconcile_jumbo_placement` therefore does not call `trigger().transfer_leader`. The RPC handler remains so a peer that does send one is answered on the same bearer interceptor as `Vote`. A 3 second poll is not used. Pull request #38 (`f55cc6cf`) can set `election_timeout_max_ms` above 3 seconds; a poll that short would return while OpenRaft could still be rejecting writes. `transfer_poll_covers_election` records that comparison and does not enable the call. `committed_moves` does not gain `LeadershipTransferred` when the leader is already the dedicated node. `RegisterCell` still returns an error. `open_and_serve` still rejects every role except `all-in-one`. @@ -30,9 +29,9 @@ Root `Architecture.md` was left unchanged on purpose. Consolidating it with the | Multi-cell routing | `DurableGlobalManager::register_cell` is an in-process map. `open_and_serve` registers one cell over `[0x01, 0x04)`. `RegisterCell` returns "not implemented" and stores nothing (`grpc_services.rs`). `GetRoutes` for an unknown non-zero `cell_id` fails closed. | **Missing.** No durable cell directory, no cross-process range map, no forwarding between cells. | | Role separation | `ServerRole` parses `be`, `proxy`, `cell-manager`, and `global-manager`. `open_and_serve` returns before listen for every role except `all-in-one` (`lib.rs`). | **Missing.** One process still hosts the global manager, the cell manager, the proxy, and the Raft groups. | | Jumbo detection flag | `JumboIsolationPlanner` and `maybe_split_or_isolate_shard` persist `ShardHealthState::JumboIsolated` in `CELL_MANAGER_STATE`. | **Present, and it is only a flag.** It does not move files. | -| Jumbo leadership placement | `reconcile_jumbo_placement` plus `RaftTransportService.TransferLeader`. | **Code is present.** It runs only when the dedicated node is already a voter and this process is the leader. It was not executed against three voters in this change. | +| Jumbo leadership placement | `automatic_leadership_transfer_allowed` is false. The handler exists; maintenance does not call `trigger().transfer_leader`. | **Disabled.** Mixed-version capability is unknown. Registration is not a capability proof. | | Jumbo peer drain / file migration | Same-size replacement is planned and calls the existing learner promotion or `change_membership` only when a proven spare keeps fault tolerance. | **Partial.** Uniform voter sets (the join path adds a node to every shard) have no spare, so the plan stays blocked. Shard directories are not copied to another host. | -| Heartbeat persistence | `CELL_CONTROL_PLANE`, `accept_remote_heartbeat`, `publish_local_heartbeat`. | **Present** for node liveness, sequence, optional reported disk free, and shard-id annotations. | +| Heartbeat persistence | `CELL_CONTROL_PLANE`, `accept_remote_heartbeat`, `publish_local_heartbeat`. | **Present** as an unreplicated local observation. Sequence advance is at most 64. A new remote sequence inside 1 second is rejected. It is not a shard epoch and does not schedule placement. | | Heartbeat sending | `PersistentMetaDbCluster::publish_control_heartbeat` from the maintenance loop. | **Present** as liveness to the current leader. It does not carry shard stats and it does not schedule splits. | | Heartbeat-driven scheduling | Design text in `docs/designs/sharding_and_control_plane.md` §6.1. | **Missing.** Splits still run from the local maintenance tick. | | Membership safety for operator scale-in | `plan_membership_voters`, `remove_voter`, joint-config handling in `uniform_voter_addrs`. | **Present, and it can shrink.** Scale-in to 2 or 1 voters is an explicit operator path. It is not a three-VM result. | @@ -47,7 +46,7 @@ These items block a scale gate. None of them is delivered by this change. 1. **Second cell.** A durable global range table, a real `RegisterCell` that does not succeed until the new cell's manager is reachable, and routing that fails closed when the range is only partly published. Depends on role separation: today every process is its own global manager, so two processes do not share one cell map. 2. **Role separation.** `be`, `proxy`, `cell-manager`, and `global-manager` must each start only their own listeners and state. That work has to preserve the auth fail-closed rules owned by the auth/config workstream. This change does not trim subsystems. 3. **Jumbo file placement.** Moving a shard directory onto a dedicated disk, streaming its snapshot to a node that has not joined, and draining peer shards off that disk. The safe replacement in this tree cannot fire on the uniform voter sets `scale_out_replicas` creates, because there is no spare voter. Adding a voter that has not joined is intentionally refused here. -4. **Leadership transfer at three voters.** The RPC and the caller exist. A regression that boots three metadata voters, detects a jumbo shard, and observes the leader change was not run. Until that run exists, do not treat `committed_moves` as a demonstrated three-node result. Mixed versions are unsafe: OpenRaft disables the leader lease when `transfer_leader` is submitted, and a peer that does not implement `TransferLeader` makes that broadcast fail. +4. **Safe automatic leadership transfer.** Still missing. It needs a capability check that does not disable the leader lease, then a wait of at least the configured `election_timeout_max_ms` (#38, head `f55cc6cf`, not merged here). Until that exists, maintenance must keep the action disabled. 5. **Heartbeat as a scheduler.** Per-shard bytes, QPS, and disk free measured by this process, sent on a trusted channel, and used only as hints. The scheduler must keep using local Raft and LSM state for splits. Client descriptors must stay non-authoritative. A 3-second cell-wide heartbeat bus for tens of thousands of shards is not built. 6. **Global and cell managers on Raft.** `CELL_MANAGER_STATE` and `CELL_CONTROL_PLANE` are local files. They are not a replicated control-plane group. A follower's placement file is not the leader's file. 7. **2PC lease pre-images.** Commit `a48d038` is unreviewed and was not imported. Later lease work has to land on its own review. This increment does not depend on it and does not change the 3-second lease, the 60-second cap, or the intent/txn record layout. @@ -55,6 +54,13 @@ These items block a scale gate. None of them is delivered by this change. 9. **Docs outside this English set.** `docs/{fr,de,ja,zh}` still describe the previous heartbeat and jumbo behavior in places. Root `Architecture.md` section 12 still marks the control plane and jumbo isolation as implemented. Those updates belong to documentation consolidation. 10. **Gates this page does not move.** No-ship stays in force. A first-ship gate is a separate bar from a scale gate (multi-cell, disaggregated roles, jumbo disk isolation, and a heartbeat bus that can carry a cell of 20k–30k shards). This increment is neither gate. CI workflows were not edited. The commands below were not run. +## Overlap with other open pull requests + +This branch stays on `main` at `36d8e950926b9e1f34c43e3f377031ff54963a2a`. It does not merge or discard: + +- **#35** head `8b276d3714ef8aef02179d93baefb1cdb0a933e1` requires an explicit opt-in before an empty `shared_secret` serves. This PR does not change that rule. `TransferLeader` is registered on `RaftTransportService` with the same `BearerAuth` interceptor as `Vote` and `AppendEntries`. When #35 lands, the stricter empty-secret rule applies to this RPC because it shares that interceptor. This PR does not add an unauthenticated path around it. +- **#38** head `f55cc6cf653a475a41de6846bbf2d03d749acdca` is stacked on #35 and loads `[raft].election_timeout_min_ms` / `election_timeout_max_ms`. On this branch those fields still exist on `RaftNodeOptions` but TOML does not apply them. Automatic transfer is off, so this PR does not poll for 3 seconds against a longer election timeout. A later transfer attempt has to wait at least `election_timeout_max_ms` from that work. + ## Validation not run Do not read this file as a test report. The following were not executed while the change was written: From c4ef7b82a928c131703e23a44d57be76d909689b Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 20:14:21 +0000 Subject: [PATCH 3/3] Rate-limit heartbeat generation changes and pin the control-plane layout A same-sequence generation replacement was accepted inside the one-second window and rewrote CELL_CONTROL_PLANE. Every remote accept that changes the stored row now waits, including that replacement. An identical replay still does not write. The file body must match exactly one layout: the current version 1 with observation generations, or the previous version 1 without them. Both matching is rejected. Generation ids come from getrandom instead of /dev/urandom. Co-authored-by: RustFS --- Cargo.lock | 1 + crates/metadb-cluster/Cargo.toml | 1 + crates/metadb-cluster/src/cell_manager.rs | 12 +- .../metadb-cluster/src/control_plane_state.rs | 149 ++++++++++++++---- crates/metadb-cluster/src/identity.rs | 8 +- .../tests/scale_control_plane_tests.rs | 109 +++++++++++++ docs/en/operations.md | 2 +- docs/en/scale-control-plane-status.md | 2 +- 8 files changed, 237 insertions(+), 47 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index c87cddc..7076e98 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -838,6 +838,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" name = "metadb-cluster" version = "0.1.0" dependencies = [ + "getrandom", "metadb-core", "metadb-proto", "metadb-raft", diff --git a/crates/metadb-cluster/Cargo.toml b/crates/metadb-cluster/Cargo.toml index 603c00c..8efdbe7 100644 --- a/crates/metadb-cluster/Cargo.toml +++ b/crates/metadb-cluster/Cargo.toml @@ -19,6 +19,7 @@ tokio = { workspace = true } tonic = { workspace = true } tracing = { workspace = true } openraft = { workspace = true } +getrandom = "0.4.3" [dev-dependencies] tempfile = { workspace = true } diff --git a/crates/metadb-cluster/src/cell_manager.rs b/crates/metadb-cluster/src/cell_manager.rs index 3b07fc3..9f1bec8 100644 --- a/crates/metadb-cluster/src/cell_manager.rs +++ b/crates/metadb-cluster/src/cell_manager.rs @@ -27,9 +27,9 @@ use metadb_storage::LsmEngineConfig; use metadb_tx::{RoutedShardHandle, TxStateMachineHandler}; use crate::control_plane_state::{ - decide_heartbeat, decode_control_plane, normalize_ids, remote_heartbeat_is_too_soon, unix_ms, - HeartbeatDecision, HeartbeatWrite, PersistedControlPlane, StoredHeartbeat, StoredPlacement, - CONTROL_PLANE_FILE, CONTROL_PLANE_VERSION, PLACEMENT_RETRY_MS, + decide_heartbeat, decode_control_plane, normalize_ids, remote_state_change_is_too_soon, + unix_ms, HeartbeatDecision, HeartbeatWrite, PersistedControlPlane, StoredHeartbeat, + StoredPlacement, CONTROL_PLANE_FILE, CONTROL_PLANE_VERSION, PLACEMENT_RETRY_MS, }; use crate::id_allocator::{AllocIdKind, DurableIdAllocator}; use crate::identity::{node_id_in_ha_range, random_id, ClusterIdentity}; @@ -2092,14 +2092,12 @@ impl DurableCellManager { HeartbeatDecision::Replay(_) => Ok(()), HeartbeatDecision::Store(heartbeat) => { if let Some(previous) = guard.heartbeats.get(&node_id) { - if remote_heartbeat_is_too_soon( + if remote_state_change_is_too_soon( previous.observed_unix_ms, write.observed_unix_ms, - write.seq, - previous.seq, ) { return Err(MetaDbError::ShardRoutingError( - "heartbeat rate limit; the stored record was kept. A heartbeat is not a scheduling epoch" + "heartbeat rate limit; the stored record was kept, including a generation change. A heartbeat is not a scheduling epoch" .to_string(), )); } diff --git a/crates/metadb-cluster/src/control_plane_state.rs b/crates/metadb-cluster/src/control_plane_state.rs index 74fedd3..2e4cad9 100644 --- a/crates/metadb-cluster/src/control_plane_state.rs +++ b/crates/metadb-cluster/src/control_plane_state.rs @@ -10,7 +10,6 @@ use std::time::{SystemTime, UNIX_EPOCH}; use serde::{Deserialize, Serialize}; -use metadb_core::codec; use metadb_core::{InodeId, MetaDbError, NodeId, ShardId}; use crate::jumbo_placement::{CommittedMove, PlacementPhase}; @@ -231,41 +230,67 @@ fn stored_from_write(write: &HeartbeatWrite) -> StoredHeartbeat { } } -/// A new remote sequence inside the interval is rejected. An equal sequence is a -/// replay or a conflict and is not rate-limited here. -pub fn remote_heartbeat_is_too_soon( - previous_observed_unix_ms: u64, - now_ms: u64, - incoming_seq: u64, - stored_seq: u64, -) -> bool { - incoming_seq != stored_seq - && now_ms.saturating_sub(previous_observed_unix_ms) < MIN_REMOTE_HEARTBEAT_INTERVAL_MS +/// Every accepted remote heartbeat that changes the stored row is limited, +/// including a same-sequence generation replacement. An identical replay does +/// not call this. +pub fn remote_state_change_is_too_soon(previous_observed_unix_ms: u64, now_ms: u64) -> bool { + now_ms.saturating_sub(previous_observed_unix_ms) < MIN_REMOTE_HEARTBEAT_INTERVAL_MS } -/// Reads version 1 files written before `observation_generation` existed. -/// Those rows keep generation 0 until a real sender presents a generation. +/// Reads a `CELL_CONTROL_PLANE` body after the CRC32C trailer has been checked. +/// +/// The file frame is `body || crc32c_le`. This function sees only `body` and +/// requires one layout to consume every byte: +/// +/// - Current version 1 appends `observation_generation: u128` on the plane and +/// on each stored heartbeat. +/// - The previous version 1 body omits those two fields. It still decodes. +/// Missing generations stay 0 until a sender presents a non-zero generation. +/// +/// If both layouts consume the same bytes, the file is rejected. A heartbeat +/// is not a scheduling epoch. pub fn decode_control_plane( body: &[u8], ) -> std::result::Result { - if let Ok(state) = codec::deserialize::(body) { - if state.version != CONTROL_PLANE_VERSION { - return Err(MetaDbError::CodecError(format!( - "{CONTROL_PLANE_FILE} version {} is not supported", - state.version - ))); + let current = decode_exact::(body); + let legacy = decode_exact::(body); + match (current, legacy) { + (Ok(state), Err(_)) => { + if state.version != CONTROL_PLANE_VERSION { + return Err(MetaDbError::CodecError(format!( + "{CONTROL_PLANE_FILE} version {} is not supported", + state.version + ))); + } + Ok(state) } - return Ok(state); - } - let legacy: LegacyPersistedControlPlane = codec::deserialize(body) - .map_err(|error| MetaDbError::CodecError(format!("{CONTROL_PLANE_FILE}: {error}")))?; - if legacy.version != CONTROL_PLANE_VERSION { - return Err(MetaDbError::CodecError(format!( - "{CONTROL_PLANE_FILE} version {} is not supported", - legacy.version - ))); + (Err(_), Ok(legacy)) => { + if legacy.version != CONTROL_PLANE_VERSION { + return Err(MetaDbError::CodecError(format!( + "{CONTROL_PLANE_FILE} version {} is not supported", + legacy.version + ))); + } + Ok(upgrade_legacy(legacy)) + } + (Ok(_), Ok(_)) => Err(MetaDbError::CodecError(format!( + "{CONTROL_PLANE_FILE} matches both the current and the pre-generation layout" + ))), + (Err(error), Err(_)) => Err(MetaDbError::CodecError(format!( + "{CONTROL_PLANE_FILE}: {error}" + ))), } - Ok(PersistedControlPlane { +} + +fn decode_exact(body: &[u8]) -> wincode::ReadResult +where + T: for<'de> wincode::SchemaRead<'de, wincode::config::DefaultConfig, Dst = T>, +{ + wincode::config::deserialize_exact(body, wincode::config::DefaultConfig::default()) +} + +fn upgrade_legacy(legacy: LegacyPersistedControlPlane) -> PersistedControlPlane { + PersistedControlPlane { version: CONTROL_PLANE_VERSION, heartbeats: legacy .heartbeats @@ -288,10 +313,10 @@ pub fn decode_control_plane( next_local_seq: legacy.next_local_seq, placements: legacy.placements, observation_generation: 0, - }) + } } -#[derive(Debug, Deserialize, wincode::SchemaRead)] +#[derive(Debug, Deserialize, wincode::SchemaRead, wincode::SchemaWrite)] struct LegacyStoredHeartbeat { node_id: NodeId, seq: u64, @@ -301,7 +326,7 @@ struct LegacyStoredHeartbeat { local_hosted_shard_ids: Vec, } -#[derive(Debug, Deserialize, wincode::SchemaRead)] +#[derive(Debug, Deserialize, wincode::SchemaRead, wincode::SchemaWrite)] struct LegacyPersistedControlPlane { version: u32, heartbeats: BTreeMap, @@ -318,6 +343,7 @@ fn same_body(stored: &StoredHeartbeat, write: &HeartbeatWrite) -> bool { #[cfg(test)] mod tests { use super::*; + use metadb_core::codec; fn write(seq: u64, disk: Option, reported: &[u64]) -> HeartbeatWrite { HeartbeatWrite { @@ -397,12 +423,65 @@ mod tests { assert!(decide_heartbeat(Some(&recovered), &conflict) .unwrap_err() .contains("conflicts")); - assert!(remote_heartbeat_is_too_soon(1_000, 1_500, 2, 1)); - assert!(!remote_heartbeat_is_too_soon(1_000, 1_500, 1, 1)); - assert!(!remote_heartbeat_is_too_soon(1_000, 3_000, 2, 1)); + assert!(remote_state_change_is_too_soon(1_000, 1_500)); + assert!(!remote_state_change_is_too_soon(1_000, 3_000)); assert!(!heartbeat_is_scheduling_truth()); } + #[test] + fn control_plane_layouts_consume_exactly_one_body() { + let mut heartbeats = BTreeMap::new(); + heartbeats.insert( + 1, + StoredHeartbeat { + node_id: 1, + seq: 80, + observed_unix_ms: 9, + disk_free_bytes: None, + reported_shard_ids: Vec::new(), + local_hosted_shard_ids: vec![1], + observation_generation: 7, + }, + ); + let current = PersistedControlPlane { + version: CONTROL_PLANE_VERSION, + heartbeats, + next_local_seq: 81, + placements: BTreeMap::new(), + observation_generation: 7, + }; + let bytes = codec::serialize(¤t).unwrap(); + assert_eq!(decode_control_plane(&bytes).unwrap(), current); + assert!(decode_exact::(&bytes).is_err()); + + let legacy = LegacyPersistedControlPlane { + version: CONTROL_PLANE_VERSION, + heartbeats: BTreeMap::from([( + 1, + LegacyStoredHeartbeat { + node_id: 1, + seq: 4, + observed_unix_ms: 3, + disk_free_bytes: Some(8), + reported_shard_ids: Vec::new(), + local_hosted_shard_ids: Vec::new(), + }, + )]), + next_local_seq: 5, + placements: BTreeMap::new(), + }; + let legacy_bytes = codec::serialize(&legacy).unwrap(); + let upgraded = decode_control_plane(&legacy_bytes).unwrap(); + assert_eq!(upgraded.observation_generation, 0); + assert_eq!(upgraded.heartbeats[&1].seq, 4); + assert_eq!(upgraded.heartbeats[&1].observation_generation, 0); + assert!(decode_exact::(&legacy_bytes).is_err()); + + let mut extra = bytes.clone(); + extra.push(0xAA); + assert!(decode_control_plane(&extra).is_err()); + } + #[test] fn too_many_shard_annotations_are_rejected() { let ids = 0..(MAX_REPORTED_SHARD_IDS as u64 + 2); diff --git a/crates/metadb-cluster/src/identity.rs b/crates/metadb-cluster/src/identity.rs index 23f9ccb..834d09a 100644 --- a/crates/metadb-cluster/src/identity.rs +++ b/crates/metadb-cluster/src/identity.rs @@ -144,13 +144,15 @@ impl ClusterIdentity { } pub fn random_id() -> Result { + // `getrandom` 0.4 is already in this workspace. It uses the platform CSPRNG + // (including Windows) and does not open `/dev/urandom`. let mut bytes = [0u8; 16]; - let mut file = File::open("/dev/urandom")?; - file.read_exact(&mut bytes)?; + getrandom::fill(&mut bytes) + .map_err(|error| MetaDbError::StorageIoError(format!("secure random failed: {error}")))?; let id = u128::from_le_bytes(bytes); if id == 0 { return Err(MetaDbError::StorageIoError( - "urandom returned a zero identity".to_string(), + "secure random returned a zero identity".to_string(), )); } Ok(id) diff --git a/crates/metadb-cluster/tests/scale_control_plane_tests.rs b/crates/metadb-cluster/tests/scale_control_plane_tests.rs index 17df00b..60a117c 100644 --- a/crates/metadb-cluster/tests/scale_control_plane_tests.rs +++ b/crates/metadb-cluster/tests/scale_control_plane_tests.rs @@ -33,6 +33,29 @@ async fn open_cell(dir: &std::path::Path) -> (Arc, Arc (Arc, Arc) { + let cache = Arc::new(ShardedBlockCache::new(8 * 1024 * 1024)); + let clock = Arc::new(HybridLogicalClock::new()); + let host = Arc::new(ShardGroupHost::open(2, dir.join("be"), cache, clock).unwrap()); + let alloc = Arc::new(DurableIdAllocator::open(dir.join("alloc")).unwrap()); + let cell = DurableCellManager::open_or_bootstrap( + 1, + dir.join("cell_1"), + host.clone(), + "127.0.0.1:2".to_string(), + true, + 4 * 1024 * 1024 * 1024, + LsmEngineConfig::default(), + RaftNodeOptions::default(), + alloc, + Arc::new(CompositeMetaCache::new()), + ) + .await + .unwrap(); + cell.register_node(1, "127.0.0.1:1".to_string()).unwrap(); + (host, cell) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn heartbeat_survives_reopen_and_a_lower_sequence_does_not_replace_it() { let dir = tempdir().unwrap(); @@ -261,3 +284,89 @@ async fn empty_receiver_accepts_a_sender_sequence_above_64() { assert_eq!(recovered.seq, 1); host.shutdown_all().await.unwrap(); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn same_sequence_generation_spam_is_rate_limited_and_a_retired_generation_is_not_remembered() +{ + let dir = tempdir().unwrap(); + let (host, cell) = open_cell(dir.path()).await; + cell.register_node(4, "127.0.0.1:4".to_string()).unwrap(); + cell.accept_remote_heartbeat(4, 5, None, Vec::new(), None, 11) + .unwrap(); + let spam = cell + .accept_remote_heartbeat(4, 5, None, Vec::new(), None, 12) + .unwrap_err(); + assert!(spam.to_string().contains("rate"), "{spam}"); + assert_eq!(cell.stored_heartbeat(4).unwrap().observation_generation, 11); + cell.testing_age_stored_heartbeat(4, 5_000); + cell.accept_remote_heartbeat(4, 5, None, Vec::new(), None, 12) + .unwrap(); + assert_eq!(cell.stored_heartbeat(4).unwrap().observation_generation, 12); + cell.testing_age_stored_heartbeat(4, 5_000); + // No retired-generation set. A delayed older generation replaces the row + // once the rate window allows another state change. It does not schedule. + cell.accept_remote_heartbeat(4, 5, None, Vec::new(), None, 11) + .unwrap(); + assert_eq!(cell.stored_heartbeat(4).unwrap().observation_generation, 11); + assert!(!metadb_cluster::heartbeat_is_scheduling_truth()); + host.shutdown_all().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn sender_file_loss_remints_generation_and_restarts_the_sequence() { + let dir = tempdir().unwrap(); + let (host, cell) = open_cell(dir.path()).await; + let first = cell.publish_local_heartbeat().unwrap(); + assert_ne!(first.observation_generation, 0); + host.shutdown_all().await.unwrap(); + drop(cell); + drop(host); + std::fs::remove_file(dir.path().join("cell_1").join("CELL_CONTROL_PLANE")).unwrap(); + + let (host, cell) = open_cell(dir.path()).await; + let restarted = cell.publish_local_heartbeat().unwrap(); + assert_eq!(restarted.seq, 1); + assert_ne!( + restarted.observation_generation, + first.observation_generation + ); + assert_ne!(restarted.observation_generation, 0); + host.shutdown_all().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn receiver_file_loss_accepts_sender_sequence_above_64() { + let sender_dir = tempdir().unwrap(); + let (sender_host, sender) = open_cell(sender_dir.path()).await; + let mut published = sender.publish_local_heartbeat().unwrap(); + for _ in 0..64 { + published = sender.publish_local_heartbeat().unwrap(); + } + assert!(published.seq > 64, "{}", published.seq); + let generation = published.observation_generation; + let seq = published.seq; + sender_host.shutdown_all().await.unwrap(); + + let receiver_dir = tempdir().unwrap(); + let (host, cell) = open_receiver(receiver_dir.path()).await; + cell.accept_remote_heartbeat(1, seq, None, Vec::new(), None, generation) + .unwrap(); + assert_eq!(cell.stored_heartbeat(1).unwrap().seq, seq); + host.shutdown_all().await.unwrap(); + drop(cell); + drop(host); + std::fs::remove_file( + receiver_dir + .path() + .join("cell_1") + .join("CELL_CONTROL_PLANE"), + ) + .unwrap(); + + let (host, cell) = open_receiver(receiver_dir.path()).await; + cell.accept_remote_heartbeat(1, seq, None, Vec::new(), None, generation) + .unwrap(); + assert_eq!(cell.stored_heartbeat(1).unwrap().seq, seq); + assert!(cell.stored_heartbeat(1).unwrap().seq > 64); + host.shutdown_all().await.unwrap(); +} diff --git a/docs/en/operations.md b/docs/en/operations.md index 52e18b8..0add5c3 100644 --- a/docs/en/operations.md +++ b/docs/en/operations.md @@ -156,7 +156,7 @@ Variants are defined in `crates/metadb-core/src/error.rs`. gRPC methods usually - The HLC saturates at the 48-bit physical ceiling instead of wrapping the logical counter. `Prepare2pc` follows `header.shard_id`, not the primary-key shard. - Quota cursor rows are written after the outbox lock is released, so a flush that already holds the memtable lock can still take the outbox lock. - Jumbo isolation is still not a move of shard files onto a dedicated disk. The route flag names a node. Automatic leadership transfer is disabled. `CELL_CONTROL_PLANE` records a same-size voter replacement only after this process observes the planned voter set. An already-correct leader is not listed as this process's move. A one-voter cell does not change its voter set. -- Heartbeats are a local liveness observation, not a shard epoch and not a split or membership input. `metadbd` persists its own about every 3 seconds and sends it to the current leader when this process is not the leader. The sender does not include shard descriptors. Within one observation generation a remote sequence may advance by at most 64, and a new sequence inside 1 second is rejected. A receiver with no row, or a new observation generation after the sender's control file is recreated, accepts the sender's current sequence. That record still does not schedule placement. The shared bearer remains the only credential. +- Heartbeats are a local liveness observation, not a shard epoch and not a split or membership input. `metadbd` persists its own about every 3 seconds and sends it to the current leader when this process is not the leader. The sender does not include shard descriptors. Within one observation generation a remote sequence may advance by at most 64. Any accepted remote heartbeat that changes the stored row, including a same-sequence generation replacement, waits 1 second. An identical replay does not write. A receiver with no row, or a new observation generation after the sender's control file is recreated, accepts the sender's current sequence. A delayed older generation is not remembered; after the rate window it is just another replacement. The shared bearer can still overwrite that observation. That record still does not schedule placement. The shared bearer remains the only credential. - A secret that contains a non-whitespace character authenticates Raft, the other three gRPC services, and the metrics listener, including `/livez`, `/readyz`, and `/healthz`, with the same bearer. An empty secret does not start the process. `allow_unauthenticated = true` is the explicit exception for literal loopback IPs (`127.0.0.0/8` or `::1`) and still refuses a wildcard bind. The hostname `localhost` is not accepted for that exception. The bound socket is checked again after listen. A whitespace-only secret is rejected and is not compared as a bearer. The process does not terminate TLS. - `memtable_size_bytes` seals and flushes the active memtable. `max_imm_memtables` caps queued immutable tables. `[raft]` timers and `max_segment_bytes` apply when a group starts. They are not reloaded from a changed file, and the segment size does not rewrite segments already on disk. - `metadb-ctl bench` for `hotspot-create` and `bulk-ttl-delete` prints JSON lines: a header with `bench_pid`, then phase reports with attempted, succeeded, failed, and latency percentiles. The process exits non-zero unless every requested operation succeeds. `--workload mixed` or `--embedded` runs the in-process stress harness. `sql` prints the response as JSON and exits non-zero on an application error. diff --git a/docs/en/scale-control-plane-status.md b/docs/en/scale-control-plane-status.md index 441a76d..8ceca93 100644 --- a/docs/en/scale-control-plane-status.md +++ b/docs/en/scale-control-plane-status.md @@ -10,7 +10,7 @@ Root `Architecture.md` was left unchanged on purpose. Consolidating it with the ## What this increment does -1. **Heartbeats are durable and are sent.** `StoreHeartbeat` for a registered node fsyncs `CELL_CONTROL_PLANE` (CRC32C frame, version 1). Each sender file has an `observation_generation`. A receiver with no row accepts that generation's current sequence, even when it is above 64, so a leader change after many local publications is not a permanent rejection. The same generation rejects a forward jump above 64, a lower sequence, and a different body at the same sequence. A different generation, minted when the sender file is created again, is a new baseline at whatever sequence the sender now has. A new remote sequence inside 1 second is rejected, which also bounds generation flapping. These records are not copied into routes and do not schedule placement. An unregistered node is rejected. The shared bearer is still the only credential; a bound node instance must be repeated, and an address-only registration does not gain a second check. A failed fsync before rename leaves the previous record. If rename succeeds and the directory sync fails, memory keeps the new file so a later write cannot put an older sequence back. The sender does not roll back a sequence after a failed send. +1. **Heartbeats are durable and are sent.** `StoreHeartbeat` for a registered node fsyncs `CELL_CONTROL_PLANE` (CRC32C frame, version 1). Each sender file has an `observation_generation`. A receiver with no row accepts that generation's current sequence, even when it is above 64, so a leader change after many local publications is not a permanent rejection. The same generation rejects a forward jump above 64, a lower sequence, and a different body at the same sequence. A different generation, minted when the sender file is created again, is a new baseline at whatever sequence the sender now has. Every state-changing remote accept, including that replacement, waits 1 second. An identical replay does not write. This process does not keep a set of retired generations: after the rate window a delayed older generation replaces the row again. That is still not a scheduling input. The shared bearer can overwrite the observation and cannot make a later honest generation unreadable. These records are not copied into routes and do not schedule placement. An unregistered node is rejected. The shared bearer is still the only credential; a bound node instance must be repeated, and an address-only registration does not gain a second check. A failed fsync before rename leaves the previous record. If rename succeeds and the directory sync fails, memory keeps the new file so a later write cannot put an older sequence back. The sender does not roll back a sequence after a failed send. 2. **The process sends its own heartbeat.** The 250 ms maintenance loop persists a local heartbeat about every 3 seconds (`HEARTBEAT_INTERVAL_MS`). Disk free space is unknown on that record; a zero is not stored as a measurement. When this process is not the Raft leader, it sends that same sequence to the leader's control-plane address and retries the same sequence once. The sender does not attach shard descriptors. A lost response does not roll the local sequence back. The next interval uses a new sequence. 3. **Jumbo placement is a record plus a narrow Raft action.** `JumboIsolated` remains the detection flag from `JumboIsolationPlanner`. `reconcile_jumbo_placement` writes a placement record from live Raft voters: - `Blocked` when the dedicated node is not already a voter, the shard has no leader, leadership is elsewhere (automatic transfer is off), or a voter change was refused. No voter is added for a node that has only a registered address.