Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
159 changes: 155 additions & 4 deletions crates/metadb-raft/src/group_host.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,12 @@ where
configs.into_iter().flatten().collect()
}

/// Tuning parameters for OpenRaft timers and snapshot policies.
#[derive(Debug, Clone)]
/// Tuning parameters for OpenRaft timers and the segmented log.
///
/// Loaded from the `[raft]` table. Unknown keys in that table fail parsing.
/// The values are read once at process start and are not reloaded while Raft is running.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields, default)]
pub struct RaftNodeOptions {
pub heartbeat_interval_ms: u64,
pub election_timeout_min_ms: u64,
Expand All @@ -64,6 +68,63 @@ impl Default for RaftNodeOptions {
}
}

impl RaftNodeOptions {
/// Checks the same OpenRaft timer inequalities `ShardRaftGroup::start` applies,
/// plus a non-zero segment size. A zero segment would open a new file on every append.
pub fn validate(&self) -> Result<()> {
if self.max_segment_bytes == 0 {
return Err(MetaDbError::CodecError(
"invalid [raft] options: max_segment_bytes must be at least 1".to_string(),
));
}
Config {
cluster_name: "metadb-raft-options".to_string(),
heartbeat_interval: self.heartbeat_interval_ms,
election_timeout_min: self.election_timeout_min_ms,
election_timeout_max: self.election_timeout_max_ms,
max_in_snapshot_log_to_keep: self.max_in_snapshot_log_to_keep,
purge_batch_size: 256,
..Default::default()
}
.validate()
.map(|_| ())
.map_err(|error| {
MetaDbError::CodecError(format!(
"invalid [raft] options: {error}. election_timeout_min_ms must be greater than heartbeat_interval_ms and less than election_timeout_max_ms"
))
})
}
}

/// `replay_state` values stored on a shard group.
pub(crate) const REPLAY_NOT_REQUIRED: u8 = 0;
pub(crate) const REPLAY_CAUGHT_UP: u8 = 1;
pub(crate) const REPLAY_WAITING: u8 = 2;

/// Startup replay is still incomplete when the wait timed out and the state
/// machine has not applied the committed or purged index captured at open.
pub fn replay_still_pending(state: u8, target: u64, applied_index: Option<u64>) -> bool {
if state != REPLAY_WAITING {
return false;
}
match applied_index {
Some(index) => index < target,
None => true,
}
}

/// Facts a readiness probe may use. No addresses, paths, or log payloads.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ShardServeView {
pub leader_known: bool,
pub applied: bool,
pub voter: bool,
pub recovery_pending: bool,
pub storage_unrecoverable: bool,
pub stopped: bool,
pub fatal: bool,
}

/// Parks `client_write` callers inside `propose` until a failure test releases them.
///
/// Production leaves the gate unarmed, so `enter` returns immediately. A test arms it,
Expand Down Expand Up @@ -174,6 +235,9 @@ pub struct ShardRaftGroup {
testing_epoch_mismatch: std::sync::atomic::AtomicU32,
testing_log_discarded: std::sync::atomic::AtomicU32,
testing_read_quorum: std::sync::atomic::AtomicU32,
replay_state: std::sync::atomic::AtomicU8,
replay_target: std::sync::atomic::AtomicU64,
stopped: AtomicBool,
}

impl ShardRaftGroup {
Expand Down Expand Up @@ -238,9 +302,28 @@ impl ShardRaftGroup {
// Replay a committed tail into the WAL-less memtable before serving.
// A fresh log has no committed entry, and the recovery condition stays
// false until initialize, so waiting here only burns the timeout.
if log_store.has_committed_entries() {
// A timeout does not fail open: the group records the target index and
// stays unready until apply catches it.
let replay_target = log_store.committed_or_purged_index();
let replay_state = if let Some(target) = replay_target {
match raft.wait_for_recovery(Some(Duration::from_secs(5))).await {
Ok(_) => REPLAY_CAUGHT_UP,
Err(error) => {
tracing::warn!(
shard_id,
target,
error = %error,
"raft startup replay did not finish; this shard stays unready until the applied index catches the startup commit"
);
REPLAY_WAITING
}
}
} else if log_store.has_committed_entries() {
let _ = raft.wait_for_recovery(Some(Duration::from_secs(5))).await;
}
REPLAY_NOT_REQUIRED
} else {
REPLAY_NOT_REQUIRED
};

if let Some(reason) = state_machine.storage_unrecoverable() {
return Err(MetaDbError::StorageIoError(format!(
Expand All @@ -266,6 +349,9 @@ impl ShardRaftGroup {
testing_epoch_mismatch: std::sync::atomic::AtomicU32::new(0),
testing_log_discarded: std::sync::atomic::AtomicU32::new(0),
testing_read_quorum: std::sync::atomic::AtomicU32::new(0),
replay_state: std::sync::atomic::AtomicU8::new(replay_state),
replay_target: std::sync::atomic::AtomicU64::new(replay_target.unwrap_or(0)),
stopped: AtomicBool::new(false),
});
router.register_local_proposer(shard_id, group.clone());
Ok(group)
Expand Down Expand Up @@ -396,6 +482,32 @@ impl ShardRaftGroup {
&self.state_machine
}

/// Local facts for a readiness probe. The strings on an unrecoverable
/// snapshot stay inside the process; the view only carries a boolean.
pub fn serve_view(&self) -> ShardServeView {
let metrics = self.raft.metrics();
let snapshot = metrics.borrow_watched();
let applied_index = snapshot.last_applied.as_ref().map(|id| id.index);
let voter = snapshot
.membership_config
.membership()
.voter_ids()
.any(|id| id == self.node_id);
ShardServeView {
leader_known: snapshot.current_leader.is_some(),
applied: applied_index.is_some(),
voter,
recovery_pending: replay_still_pending(
self.replay_state.load(Ordering::Acquire),
self.replay_target.load(Ordering::Acquire),
applied_index,
),
storage_unrecoverable: self.storage_unrecoverable().is_some(),
stopped: self.stopped.load(Ordering::Acquire),
fatal: snapshot.running_state.is_err(),
}
}

/// `Some` when this process must not be reported as a live voter.
pub fn storage_unrecoverable(&self) -> Option<String> {
self.state_machine.storage_unrecoverable()
Expand Down Expand Up @@ -881,6 +993,7 @@ impl ShardRaftGroup {
}

pub async fn shutdown(&self) -> Result<()> {
self.stopped.store(true, Ordering::Release);
self.raft
.shutdown()
.await
Expand Down Expand Up @@ -1161,4 +1274,42 @@ mod tests {
let kept = normalize_discarded_legacy(&enveloped, discarded);
assert!(kept.is_retryable_write_consensus(), "{kept}");
}

#[test]
fn replay_pending_tracks_the_startup_commit_only() {
assert!(!replay_still_pending(REPLAY_NOT_REQUIRED, 10, None));
assert!(!replay_still_pending(REPLAY_CAUGHT_UP, 10, None));
assert!(replay_still_pending(REPLAY_WAITING, 10, None));
assert!(replay_still_pending(REPLAY_WAITING, 10, Some(9)));
assert!(!replay_still_pending(REPLAY_WAITING, 10, Some(10)));
assert!(!replay_still_pending(REPLAY_WAITING, 10, Some(11)));
}

#[test]
fn default_raft_options_match_the_openraft_inequalities() {
let options = RaftNodeOptions::default();
options.validate().expect("built-in defaults must start");
assert_eq!(options.heartbeat_interval_ms, 150);
assert_eq!(options.election_timeout_min_ms, 450);
assert_eq!(options.election_timeout_max_ms, 900);
assert_eq!(options.max_in_snapshot_log_to_keep, 0);
assert_eq!(options.max_segment_bytes, 64 * 1024 * 1024);
}

#[test]
fn raft_option_bounds_fail_before_a_group_starts() {
let mut options = RaftNodeOptions::default();
options.max_segment_bytes = 0;
assert!(options.validate().is_err());

options = RaftNodeOptions::default();
options.heartbeat_interval_ms = 450;
let heartbeat = options.validate().unwrap_err().to_string();
assert!(heartbeat.contains("invalid [raft] options"), "{heartbeat}");

options = RaftNodeOptions::default();
options.election_timeout_min_ms = 900;
options.election_timeout_max_ms = 900;
assert!(options.validate().is_err());
}
}
3 changes: 2 additions & 1 deletion crates/metadb-raft/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ pub use backup::{
};
pub use conf_change::{ConfChangeOrchestrator, DEFAULT_LEARNER_CATCHUP_THRESHOLD_ENTRIES};
pub use group_host::{
ProposalShutdownGate, RaftNodeOptions, RegistryShardState, ShardGroupHost, ShardRaftGroup,
replay_still_pending, ProposalShutdownGate, RaftNodeOptions, RegistryShardState,
ShardGroupHost, ShardRaftGroup, ShardServeView,
};
pub use log_store::SegmentedRaftLogStore;
pub use network::{
Expand Down
19 changes: 19 additions & 0 deletions crates/metadb-raft/src/log_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -789,6 +789,25 @@ impl SegmentedRaftLogStore {
|| !guard.entries.is_empty()
}

/// Commit or purge index that startup replay must apply before the shard can serve.
///
/// `None` when the store has neither. A non-empty uncommitted tail does not
/// count: those entries are not yet a committed prefix the state machine must replay.
pub fn committed_or_purged_index(&self) -> Option<u64> {
let guard = self.inner.lock().unwrap();
let committed = guard.hard_state.committed.as_ref().map(|id| id.index);
let purged = guard
.hard_state
.last_purged_log_id
.as_ref()
.map(|id| id.index);
match (committed, purged) {
(None, None) => None,
(Some(index), None) | (None, Some(index)) => Some(index),
(Some(committed), Some(purged)) => Some(committed.max(purged)),
}
}

/// Test hook. The next `n` append fsyncs fail and roll the in-memory log back.
pub fn testing_fail_next_syncs(&self, n: u32) {
self.inner.lock().unwrap().fail_syncs = n;
Expand Down
13 changes: 10 additions & 3 deletions crates/metadb-server/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,11 @@ pub struct ServerTomlConfig {
pub sharding: ShardingSection,
pub security: SecuritySection,
pub cluster: ClusterSection,
#[serde(skip)]
/// OpenRaft timers and the segmented-log size. The TOML table is `[raft]`.
///
/// Field names are not secret or TLS keys, so the security-key walk in
/// `from_toml_str` does not treat this table as an auth setting.
#[serde(default, rename = "raft")]
pub raft_options: RaftNodeOptions,
/// Overrides the 45-second join budget. `None` keeps that budget.
/// Not read from TOML; tests use it so a refused seed returns without waiting.
Expand All @@ -198,8 +202,11 @@ impl ServerTomlConfig {
let value: toml::Value = toml::from_str(s)
.map_err(|e| MetaDbError::CodecError(format!("invalid TOML config: {e}")))?;
reject_unsupported_security_keys(&value)?;
ServerTomlConfig::deserialize(value)
.map_err(|e| MetaDbError::CodecError(format!("invalid TOML config: {e}")))
let parsed = ServerTomlConfig::deserialize(value)
.map_err(|e| MetaDbError::CodecError(format!("invalid TOML config: {e}")))?;
// Timer checks only. This does not read or rewrite [security].
parsed.raft_options.validate()?;
Ok(parsed)
}

pub fn from_toml_file(path: impl AsRef<Path>) -> Result<Self> {
Expand Down
Loading