From bde2a4aae1b0cd38f63a0772890fc71950265126 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 11:30:44 +0000 Subject: [PATCH 1/3] Rewrite a missing snapshot from the LSM or stop advertising a live voter. The segmented raft log is the write-ahead log until it is purged. After purge, a missing snapshot file is rebuilt from the LSM before the read returns. If the LSM cannot cover that purged prefix, cluster status returns snapshot unrecoverable instead of the cached voter set. Co-authored-by: RustFS --- crates/metadb-cluster/src/cell_manager.rs | 17 +++ crates/metadb-raft/src/group_host.rs | 31 +++++ crates/metadb-raft/src/state_machine.rs | 104 +++++++++++++-- .../tests/snapshot_read_path_tests.rs | 124 +++++++++++++++++- crates/metadb-server/src/grpc_services.rs | 22 +++- .../tests/snapshot_status_tests.rs | 63 +++++++++ docs/de/architecture.md | 2 +- docs/de/configuration.md | 4 +- docs/de/operations.md | 2 +- docs/designs/correctness_hardening.md | 2 +- docs/en/architecture.md | 2 +- docs/fr/architecture.md | 2 +- docs/fr/configuration.md | 4 +- docs/fr/operations.md | 2 +- docs/ja/architecture.md | 2 +- docs/ja/configuration.md | 4 +- docs/ja/operations.md | 2 +- docs/zh/architecture.md | 2 +- docs/zh/configuration.md | 4 +- docs/zh/operations.md | 2 +- 20 files changed, 363 insertions(+), 34 deletions(-) create mode 100644 crates/metadb-server/tests/snapshot_status_tests.rs diff --git a/crates/metadb-cluster/src/cell_manager.rs b/crates/metadb-cluster/src/cell_manager.rs index fd76af3..ce66823 100644 --- a/crates/metadb-cluster/src/cell_manager.rs +++ b/crates/metadb-cluster/src/cell_manager.rs @@ -971,6 +971,23 @@ impl DurableCellManager { Ok(()) } + /// Routes for cluster status. A local shard that cannot rebuild its snapshot + /// is not returned as a live voter; the caller gets an error instead. + pub fn routes_for_live_status(&self) -> Result> { + let routes = self.list_routes(); + for route in &routes { + if let Some(group) = self.host.get_group(route.shard_id) { + if let Some(reason) = group.storage_unrecoverable() { + return Err(MetaDbError::StorageIoError(format!( + "shard {} storage is unrecoverable, so it is not a live voter: {reason}", + route.shard_id + ))); + } + } + } + Ok(routes) + } + pub fn list_routes(&self) -> Vec { let mut routes: Vec = { let guard = self.state.lock().unwrap(); diff --git a/crates/metadb-raft/src/group_host.rs b/crates/metadb-raft/src/group_host.rs index a5bdad9..b97df45 100644 --- a/crates/metadb-raft/src/group_host.rs +++ b/crates/metadb-raft/src/group_host.rs @@ -10,6 +10,7 @@ use std::time::Duration; use openraft::async_runtime::watch::WatchReceiver; use openraft::errors::RaftError; +use openraft::storage::RaftStateMachine; use openraft::{BasicNode, Config}; use serde::{Deserialize, Serialize}; @@ -358,6 +359,33 @@ impl ShardRaftGroup { &self.state_machine } + /// `Some` when this process must not be reported as a live voter. + pub fn storage_unrecoverable(&self) -> Option { + self.state_machine.storage_unrecoverable() + } + + /// Rewrite a published snapshot that disappeared, or refuse to serve. + /// + /// A missing in-use snapshot used to stop RaftCore while cluster status + /// still answered from the cached voter set. Repair from the LSM when it + /// can cover the purged log. Otherwise leave an explicit unrecoverable + /// error so status and later reads do not pretend the voter is healthy. + pub async fn repair_published_snapshot(&self) -> Result<()> { + if let Some(reason) = self.storage_unrecoverable() { + return Err(MetaDbError::StorageIoError(format!( + "snapshot unrecoverable: {reason}" + ))); + } + if !self.state_machine.published_snapshot_missing() { + return Ok(()); + } + let mut state_machine = self.state_machine.clone(); + match state_machine.get_current_snapshot().await { + Ok(_) => Ok(()), + Err(error) => Err(MetaDbError::StorageIoError(error.to_string())), + } + } + pub fn engine(&self) -> Arc { self.state_machine.engine() } @@ -527,6 +555,7 @@ impl ShardRaftGroup { payload: Vec, deadline: tokio::time::Instant, ) -> Result { + self.repair_published_snapshot().await?; { let mut hook = self.testing_not_leader.lock().unwrap(); if hook.0 > 0 { @@ -703,6 +732,7 @@ impl ShardRaftGroup { &self, expected_epoch: ShardEpoch, ) -> Result<(ReadToken, SnapshotGuard)> { + self.repair_published_snapshot().await?; self.read_batcher .acquire_linearizable_guard(expected_epoch, &self.state_machine) .await @@ -718,6 +748,7 @@ impl ShardRaftGroup { expected_epoch: ShardEpoch, barrier_hlc: HlcTimestamp, ) -> Result<(ReadToken, SnapshotGuard)> { + self.repair_published_snapshot().await?; let _ = self.clock.update_checked(barrier_hlc)?; let token = self.read_batcher.linearizable_token(expected_epoch).await?; let snap = self.state_machine.acquire_snapshot( diff --git a/crates/metadb-raft/src/state_machine.rs b/crates/metadb-raft/src/state_machine.rs index 9712be3..94e5d3e 100644 --- a/crates/metadb-raft/src/state_machine.rs +++ b/crates/metadb-raft/src/state_machine.rs @@ -239,6 +239,9 @@ struct StateMachineShared { last_applied_hlc: RwLock, last_membership: RwLock>, frontier_tx: watch::Sender, + /// Set when a required snapshot cannot be rebuilt. Cluster status must not + /// keep reporting this process as a live voter after RaftCore has failed. + unrecoverable: Mutex>, } impl StateMachineShared { @@ -425,23 +428,45 @@ impl StateMachineShared { }) } + fn clear_unrecoverable(&self) { + *self.unrecoverable.lock().unwrap() = None; + } + + fn fail_unrecoverable(&self, reason: impl Into) -> io::Result { + let reason = reason.into(); + *self.unrecoverable.lock().unwrap() = Some(reason.clone()); + Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("snapshot unrecoverable: {reason}"), + )) + } + + /// True when this process has published a snapshot that is no longer a complete directory. + fn published_snapshot_missing(&self) -> bool { + let index = self.watermarks.snapshot_values().2; + if index == 0 { + return false; + } + let dir = self + .shard_dir + .join(format!("raft/snapshots/snap_{index:020}")); + !snapshot_dir_is_complete(&dir) + } + fn load_current_snapshot_sync( &self, ) -> io::Result>> { let snaps_root = self.shard_dir.join("raft/snapshots"); + let candidates = snapshot_candidates(&snaps_root); // A missing file used to return `NotFound`. OpenRaft maps that to // `StorageError { subject: Snapshot(None), verb: Read }` and stops RaftCore, - // after which every later read repeats the same error. Skip a broken - // directory and use the newest complete snapshot instead, including the - // `.bak` copy left by an in-progress replace. - for (_, snap_dir) in snapshot_candidates(&snaps_root) { - match load_snapshot_dir(&snap_dir) { - Ok(snapshot) => return Ok(Some(snapshot)), - Err(error) if error.kind() == io::ErrorKind::NotFound => { - tracing::warn!( - path = %snap_dir.display(), - "skipping raft snapshot directory with a missing file" - ); + // while the process kept answering cluster status from cached membership. + // Skip a broken directory, including a `.bak` left by an in-progress replace. + for (_, snap_dir) in &candidates { + match load_snapshot_dir(snap_dir) { + Ok(snapshot) => { + self.clear_unrecoverable(); + return Ok(Some(snapshot)); } Err(error) => { tracing::warn!( @@ -452,7 +477,51 @@ impl StateMachineShared { } } } - Ok(None) + + let applied = self + .last_applied_log_id + .read() + .unwrap() + .map(|id| id.index) + .unwrap_or(0); + let flushed = self + .current_engine() + .durable_checkpoint() + .flushed_raft_index; + let raft_dir = self.shard_dir.join("raft"); + let purged = crate::log_store::read_persisted_purged_index(&raft_dir).unwrap_or(0); + let snapshot_required = + purged > 0 || self.watermarks.snapshot_values().2 > 0 || !candidates.is_empty(); + // The segmented raft log is the WAL until it is purged. Before that, + // a missing snapshot file is not fatal: restart replays the log. + if !snapshot_required { + self.clear_unrecoverable(); + return Ok(None); + } + + // After purge, the LSM is the only remaining copy. Rewrite the snapshot + // from it before returning, so a live process does not keep serving + // with the snapshot file gone. + match self.build_snapshot_sync() { + Ok(snapshot) => { + let covered = snapshot + .meta + .last_log_id + .as_ref() + .map(|id| id.index) + .unwrap_or(0); + if purged > covered { + return self.fail_unrecoverable(format!( + "rebuilt snapshot index {covered} does not cover purged raft log {purged}. The segmented raft log is the WAL only until it is purged. A missing snapshot is rebuilt from the LSM. If that LSM is also missing, committed data is not reconstructed" + )); + } + self.clear_unrecoverable(); + Ok(Some(snapshot)) + } + Err(error) => self.fail_unrecoverable(format!( + "cannot rebuild a missing snapshot from the LSM ({error}). purged log index is {purged}, flushed LSM index is {flushed}, applied index is {applied}. The segmented raft log is the WAL only until it is purged. If the log and the LSM are both gone, committed data is not reconstructed" + )), + } } } @@ -758,6 +827,7 @@ impl ShardStateMachine { last_applied_hlc: RwLock::new(cp.flushed_max_hlc), last_membership: RwLock::new(initial_membership), frontier_tx, + unrecoverable: Mutex::new(None), }); Ok((Self { shared }, frontier_rx)) @@ -767,6 +837,16 @@ impl ShardStateMachine { self.shared.current_engine() } + /// Reason this process must not be advertised as a live voter. + pub fn storage_unrecoverable(&self) -> Option { + self.shared.unrecoverable.lock().unwrap().clone() + } + + /// The snapshot index already published in memory has no complete directory. + pub fn published_snapshot_missing(&self) -> bool { + self.shared.published_snapshot_missing() + } + pub fn handler(&self) -> &Arc { &self.shared.handler } diff --git a/crates/metadb-raft/tests/snapshot_read_path_tests.rs b/crates/metadb-raft/tests/snapshot_read_path_tests.rs index 853a69b..f08f776 100644 --- a/crates/metadb-raft/tests/snapshot_read_path_tests.rs +++ b/crates/metadb-raft/tests/snapshot_read_path_tests.rs @@ -116,8 +116,27 @@ async fn missing_snapshot_after_flush_and_purge_does_not_kill_reads() { let mut state_machine = group.state_machine().clone(); let loaded = state_machine.get_current_snapshot().await.unwrap(); assert!( - loaded.is_none(), - "a missing snapshot file must not be returned as a fatal read error" + loaded.is_some(), + "a live process must rewrite the missing snapshot from the LSM" + ); + assert!( + group.storage_unrecoverable().is_none(), + "a rebuilt snapshot must still be reported as a live voter" + ); + assert!( + shard_dir + .join("raft/snapshots") + .read_dir() + .unwrap() + .any(|entry| { + entry + .unwrap() + .file_name() + .to_str() + .unwrap_or("") + .starts_with("snap_") + }), + "rewrite must put a snapshot directory back on disk" ); assert_keys(&group).await; group.shutdown().await.unwrap(); @@ -133,3 +152,104 @@ async fn missing_snapshot_after_flush_and_purge_does_not_kill_reads() { assert_keys(&group).await; group.shutdown().await.unwrap(); } + +#[tokio::test] +async fn unpurged_raft_log_reconstructs_keys_without_a_snapshot() { + let dir = tempdir().unwrap(); + let shard_dir = dir.path().join("shards/00000000000000000001"); + let cache = Arc::new(ShardedBlockCache::new(4 * 1024 * 1024)); + let clock = Arc::new(HybridLogicalClock::new()); + { + let group = boot(&shard_dir, cache.clone(), clock.clone()).await; + let epoch = group.current_epoch(); + for name in ["alpha", "beta", "gamma"] { + let cmd = BasicKvCommand::Put { + key: MetaKey::child(1, name).encode(), + value: name.as_bytes().to_vec(), + }; + group + .propose(epoch, HlcTimestamp::ZERO, codec::serialize(&cmd).unwrap()) + .await + .unwrap(); + } + assert!( + group.log_store().retained_entry_count() > 0, + "the segmented log is the WAL until purge" + ); + let _ = fs::remove_dir_all(shard_dir.join("raft/snapshots")); + group.shutdown().await.unwrap(); + } + let group = boot(&shard_dir, cache, clock).await; + assert!( + group.storage_unrecoverable().is_none(), + "an unpurged log must not be reported as an unrecoverable voter" + ); + assert_keys(&group).await; + group.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn missing_lsm_and_snapshot_after_log_purge_is_not_a_live_voter() { + let dir = tempdir().unwrap(); + let shard_dir = dir.path().join("shards/00000000000000000001"); + let cache = Arc::new(ShardedBlockCache::new(4 * 1024 * 1024)); + let clock = Arc::new(HybridLogicalClock::new()); + let group = boot(&shard_dir, cache, clock).await; + let epoch = group.current_epoch(); + for name in ["alpha", "beta", "gamma"] { + let cmd = BasicKvCommand::Put { + key: MetaKey::child(1, name).encode(), + value: name.as_bytes().to_vec(), + }; + group + .propose(epoch, HlcTimestamp::ZERO, codec::serialize(&cmd).unwrap()) + .await + .unwrap(); + } + let purged = group.flush_snapshot_and_purge().await.unwrap(); + assert!(purged > 0); + assert_eq!(group.log_store().retained_entry_count(), 0); + + let mut removed_sst = 0usize; + for entry in fs::read_dir(shard_dir.join("lsm")).unwrap() { + let entry = entry.unwrap(); + let name = entry.file_name(); + let Some(name) = name.to_str() else { + continue; + }; + if name.ends_with(".sst") { + fs::remove_file(entry.path()).unwrap(); + removed_sst += 1; + } + } + assert!(removed_sst > 0, "flush did not create an SSTable to remove"); + let _ = fs::remove_dir_all(shard_dir.join("raft/snapshots")); + + let mut state_machine = group.state_machine().clone(); + let error = state_machine + .get_current_snapshot() + .await + .expect_err("missing LSM and snapshot must not look like a healthy snapshot"); + let message = error.to_string(); + assert!( + message.contains("snapshot unrecoverable"), + "missing durable copies must be an explicit error, not ENOENT: {message}" + ); + assert!( + message.contains("not reconstructed"), + "the error must say committed data is not reconstructed: {message}" + ); + let reason = group + .storage_unrecoverable() + .expect("cluster status must be able to see that this process is not a live voter"); + assert!(reason.contains("not reconstructed"), "{reason}"); + let read_error = match group.linearizable_read(group.current_epoch()).await { + Ok(_) => panic!("reads must not succeed once storage is unrecoverable"), + Err(error) => error, + }; + assert!( + read_error.to_string().contains("snapshot unrecoverable"), + "{read_error}" + ); + group.shutdown().await.unwrap(); +} diff --git a/crates/metadb-server/src/grpc_services.rs b/crates/metadb-server/src/grpc_services.rs index 49e0789..c972db5 100644 --- a/crates/metadb-server/src/grpc_services.rs +++ b/crates/metadb-server/src/grpc_services.rs @@ -1016,12 +1016,30 @@ impl ControlPlaneService for MetaDbGrpcService { }; let mut routes = Vec::new(); for cell in &cells { - routes.extend(cell.list_routes()); + match cell.routes_for_live_status() { + Ok(live) => routes.extend(live), + Err(error) => { + return Ok(Response::new(GetRoutesResponse { + error: Some(ErrorDetailProto::from(&error)), + shards: Vec::new(), + cluster_id: Vec::new(), + })); + } + } } (routes, cluster_id) } else if let Some(cell) = self.global_manager.get_cell(req.cell_id) { let cluster_id = cell.cluster_id(); - (cell.list_routes(), cluster_id) + match cell.routes_for_live_status() { + Ok(routes) => (routes, cluster_id), + Err(error) => { + return Ok(Response::new(GetRoutesResponse { + error: Some(ErrorDetailProto::from(&error)), + shards: Vec::new(), + cluster_id: Vec::new(), + })); + } + } } else { let e = MetaDbError::ShardRoutingError(format!("unknown cell {}", req.cell_id)); return Ok(Response::new(GetRoutesResponse { diff --git a/crates/metadb-server/tests/snapshot_status_tests.rs b/crates/metadb-server/tests/snapshot_status_tests.rs new file mode 100644 index 0000000..f44340c --- /dev/null +++ b/crates/metadb-server/tests/snapshot_status_tests.rs @@ -0,0 +1,63 @@ +//! A missing snapshot must not leave cluster status advertising a live voter. + +use std::fs; + +use metadb_core::ROOT_INODE_ID; +use metadb_server::{PersistentMetaDbCluster, ServerTomlConfig}; +use openraft::storage::RaftStateMachine; + +#[tokio::test] +async fn unrecoverable_snapshot_is_not_reported_as_a_live_voter() { + let dir = tempfile::tempdir().unwrap(); + let mut cfg = ServerTomlConfig::default(); + cfg.node.data_dir = dir.path().to_path_buf(); + cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.sharding.bootstrap_table_shards = false; + let (cluster, _address) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); + cluster + .tx_router() + .mkdir(ROOT_INODE_ID, "bucket", 100, 1, 0o755) + .await + .unwrap(); + cluster + .tx_router() + .create_file(100, "alpha.dat", 1001, 7, 1, 0o644, 4) + .await + .unwrap(); + + let (_, group, _) = cluster.cell_manager().lookup_local_handle(1).unwrap(); + let purged = group.flush_snapshot_and_purge().await.unwrap(); + assert!(purged > 0); + let live = cluster.cell_manager().routes_for_live_status().unwrap(); + assert!( + live.iter() + .any(|route| { route.shard_id == 1 && route.peers.values().any(|(_, voter)| *voter) }), + "a healthy shard is still a live voter" + ); + + let shard_dir = cluster.cell_manager().host().shard_dir(1); + let mut removed_sst = 0usize; + for entry in fs::read_dir(shard_dir.join("lsm")).unwrap() { + let entry = entry.unwrap(); + if entry.file_name().to_str().unwrap_or("").ends_with(".sst") { + fs::remove_file(entry.path()).unwrap(); + removed_sst += 1; + } + } + assert!(removed_sst > 0, "flush did not create an SSTable"); + let _ = fs::remove_dir_all(shard_dir.join("raft/snapshots")); + + let mut state_machine = group.state_machine().clone(); + let error = state_machine.get_current_snapshot().await.unwrap_err(); + assert!( + error.to_string().contains("snapshot unrecoverable"), + "{error}" + ); + let status = cluster.cell_manager().routes_for_live_status().unwrap_err(); + let status = status.to_string(); + assert!( + status.contains("not a live voter"), + "cluster status must not keep advertising voters after the snapshot and LSM are gone: {status}" + ); + cluster.shutdown().await.unwrap(); +} diff --git a/docs/de/architecture.md b/docs/de/architecture.md index e7e5b62..8073b95 100644 --- a/docs/de/architecture.md +++ b/docs/de/architecture.md @@ -82,7 +82,7 @@ Die Zustandsmaschine jedes Shards öffnet ein WAL-loses LSM unter `/be MVCC-Versionen leben `storage.mvcc_retention_ms` (Vorgabe 5.000) lang im Speicher. Ein koordinierter Flush versiegelt die Memtable, führt den Attribut-Aggregationshaken aus und schreibt eine L0-SSTable. Es gibt kein separates Nutzer-KV-WAL. Absturzrecovery ist das Raft-Log plus das LSM-Manifest. `LocalityCompactor` zählt Tombstones je 9-Byte-Präfix-Eimer und kompaktiert einen heißen Löschbereich, wenn sowohl `locality_tombstone_threshold` als auch `locality_tombstone_ratio` überschritten sind. `auto_locality_compaction` setzt `ServerTomlConfig::to_lsm_config` immer auf `true`; die TOML-Datei kann es nicht abschalten. -`storage.memtable_size_bytes` wird deserialisiert und nie gelesen. Die Flush-Größe kommt nicht aus diesem Feld. +`storage.memtable_size_bytes` is the active memtable flush threshold. `storage.max_imm_memtables` (default 4) is the immutable-table backpressure cap: a writer waits until an immutable table flushes instead of queueing another one. ## Raft diff --git a/docs/de/configuration.md b/docs/de/configuration.md index af567b0..33111b2 100644 --- a/docs/de/configuration.md +++ b/docs/de/configuration.md @@ -15,7 +15,7 @@ | `node.grpc_listen_addr` | `127.0.0.1:7800` | Ja. Bind-Adresse | | `node.metrics_listen_addr` | nicht gesetzt | Ja, nur wenn gesetzt. Eigener TCP-Listener. Eine Nicht-Loopback-Adresse verlangt ein nicht leeres Geheimnis | | `clock.max_clock_drift_ms` | `500` | Ja. `HybridLogicalClock::with_max_drift_ms` | -| `storage.memtable_size_bytes` | `33554432` (32 MiB) | **Nein.** Das Feld wird gespeichert und nie gelesen | +| `storage.memtable_size_bytes` | `33554432` (32 MiB) | Yes. Seals and flushes the active memtable once its accounted bytes reach this size. Values below 1 are treated as 1 | | `storage.block_cache_bytes` | `67108864` (64 MiB) | Ja. Gesamtbudget des 16-fachen Blockcaches | | `storage.mvcc_retention_ms` | `5000` | Ja | | `storage.bloom_bits_per_key` | `10` | Ja | @@ -31,7 +31,7 @@ Es gibt keine Tabelle `[raft]`. `ServerTomlConfig.raft_options` wird von serde ## Beispiel -Diese Datei entspricht den Vorgaben, außer einem ausdrücklichen Datenverzeichnis, einem Metrik-Port und einem Geheimnis. `memtable_size_bytes` steht hier, damit eine kopierte Konfiguration nicht überrascht; eine Änderung ändert das Flush-Verhalten nicht. +This file matches the defaults except for an explicit data directory, a metrics port, and a secret. `memtable_size_bytes` is the active memtable flush threshold. `max_imm_memtables` is the immutable-table backpressure cap. ```toml [node] diff --git a/docs/de/operations.md b/docs/de/operations.md index c7bde6c..ad71068 100644 --- a/docs/de/operations.md +++ b/docs/de/operations.md @@ -137,7 +137,7 @@ Die Varianten sind in `crates/metadb-core/src/error.rs` definiert. gRPC-Methoden - Jumbo-Isolation ist ein Routenflag plus eine Knotenkennung aus der lokalen Knotentabelle. Sie verdrängt andere Shards nicht von einer Platte. - Heartbeats sind ein RPC ohne Sender in `metadbd`. `StoreHeartbeat` speichert nicht dauerhaft. - Ein nicht leeres gemeinsames Geheimnis authentifiziert Raft, die drei anderen gRPC-Dienste und den Metrik-Listener mit demselben Bearer. Ein leeres Geheimnis wird nur für Loopback-Binds akzeptiert und lässt diese Listener unauthentifiziert. Ein Wildcard-Bind mit leerem Geheimnis verweigert den Start. Der Prozess beendet TLS nicht. -- `memtable_size_bytes` und alle Raft-Zeitgeberfelder ändern das Laufzeitverhalten über TOML nicht. +- `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` für `hotspot-create` und `bulk-ttl-delete` druckt JSON-Zeilen: einen Kopf mit `bench_pid`, dann Phasenberichte mit attempted, succeeded, failed und Latenzperzentilen. Der Prozess endet mit einem Fehler, wenn nicht jede angeforderte Operation gelingt. `--workload mixed` oder `--embedded` startet den prozessinternen Stress-Harness. `sql` druckt die Antwort als JSON und endet bei einem Anwendungsfehler mit einem Fehlerstatus. ## Dokumentationslücken diff --git a/docs/designs/correctness_hardening.md b/docs/designs/correctness_hardening.md index 544fce8..b2fd8f4 100644 --- a/docs/designs/correctness_hardening.md +++ b/docs/designs/correctness_hardening.md @@ -6,7 +6,7 @@ This change hardens acknowledged-write recovery, transaction migration, input va Recovery validates the entire unpurged committed log prefix, frame ordering and identity, and the durable vote/commit metadata before repairing files. Existing histories with missing `HARD_STATE` are rejected. A durable initialization marker also protects empty or fully purged stores from silently resetting their election identity. A fresh log has nothing to replay, so startup does not spend the recovery timeout before the first membership entry exists. -Snapshot installation requires a complete existing database image. It verifies required and duplicate filenames, the recovered checkpoint, LogId and membership, MANIFEST-to-SST metadata equality, and all data blocks before replacing live data. An empty or stale archive cannot create a new empty database and advance its advertised applied index. Snapshot publication syncs the temporary directory, renames it into place, and only then deletes the previous directory. A missing or unreadable snapshot directory is skipped. `get_current_snapshot` returns no snapshot instead of a fatal `Read Snapshot` error, and startup can rebuild one from the flushed LSM. Log purge stops at the newest complete snapshot directory, so a missing snapshot file does not also discard the log a restart still needs. +Snapshot installation requires a complete existing database image. It verifies required and duplicate filenames, the recovered checkpoint, LogId and membership, MANIFEST-to-SST metadata equality, and all data blocks before replacing live data. An empty or stale archive cannot create a new empty database and advance its advertised applied index. Snapshot publication syncs the temporary directory, renames it into place, and only then deletes the previous directory. A missing or unreadable snapshot directory is skipped. The segmented raft log is the write-ahead log only until it is purged. Before purge, a restart replays that log. After purge, the LSM is the remaining copy: the next snapshot read rewrites a missing snapshot from the LSM before returning. If that rebuild cannot cover the purged index, the error is `snapshot unrecoverable` and cluster status does not keep reporting the process as a live voter. Committed data is not reconstructed when the purged log, the snapshot file, and the LSM are all gone. A state-machine operation lock serializes complete apply operations, checkpoint creation, snapshot replacement, and read-cut acquisition. This favors correctness and can pause writers while a snapshot is built. A later optimization should pin immutable state under a shorter lock and stream it without weakening the atomic checkpoint boundary. diff --git a/docs/en/architecture.md b/docs/en/architecture.md index 672d1f1..ceee3fd 100644 --- a/docs/en/architecture.md +++ b/docs/en/architecture.md @@ -95,7 +95,7 @@ Each local shard is an `openraft` 0.10 group. The log is a segmented CRC32C file | `max_in_snapshot_log_to_keep` | 0 | | log segment size | 64 MiB | -Log purge is gated by `min(state_flushed_index, aux_outbox_durable_index, last_snapshot_index)` and by the newest complete snapshot directory. The 250 ms maintenance loop calls `flush_snapshot_and_purge` when a shard still retains log entries, unless a snapshot watermark is already at least `state_flushed_index` and fewer than 64 entries remain. An operator backup hold clamps that purge, and snapshot-directory deletion, until the hold is released or its wall-clock expiry passes. See [Operations](./operations.md#backup-and-restore). +Log purge is gated by `min(state_flushed_index, aux_outbox_durable_index, last_snapshot_index)` and by the newest complete snapshot directory. The segmented log is the write-ahead log until that purge. A missing published snapshot is rewritten from the LSM on the next read. If the LSM cannot cover the purged prefix, the shard is `snapshot unrecoverable` and is not reported as a live voter. The 250 ms maintenance loop calls `flush_snapshot_and_purge` when a shard still retains log entries, unless a snapshot watermark is already at least `state_flushed_index` and fewer than 64 entries remain. An operator backup hold clamps that purge, and snapshot-directory deletion, until the hold is released or its wall-clock expiry passes. See [Operations](./operations.md#backup-and-restore). `ConfChangeOrchestrator::add_learners_and_promote_voters` adds learners, waits until replication lag is at most 64 entries (default timeout 10 s, the value `scale_out_replicas` passes), then calls `change_membership`. The in-process test `test_online_1_to_3_voter_snapshot_promotion_and_leader_failover` does this with three tonic listeners and a basic KV state machine inside one OS process. It does not start `metadbd`. diff --git a/docs/fr/architecture.md b/docs/fr/architecture.md index eb7068e..27395fd 100644 --- a/docs/fr/architecture.md +++ b/docs/fr/architecture.md @@ -82,7 +82,7 @@ La machine d'état de chaque shard ouvre un LSM sans WAL dans `/be/sha Les versions MVCC vivent en mémoire pendant `storage.mvcc_retention_ms` (défaut 5 000). Un vidage coordonné scelle le memtable, exécute le crochet d'agrégation d'attributs et écrit une SSTable L0. Il n'y a pas de WAL KV utilisateur séparé. La reprise après plantage est le journal Raft plus le manifeste LSM. `LocalityCompactor` suit les tombstones par seau de préfixe de 9 octets et compacte un intervalle de suppression chaud lorsque `locality_tombstone_threshold` et `locality_tombstone_ratio` sont tous deux franchis. `auto_locality_compaction` est toujours mis à `true` par `ServerTomlConfig::to_lsm_config` ; le fichier TOML ne peut pas le désactiver. -`storage.memtable_size_bytes` est désérialisé et jamais lu. La taille de vidage ne vient pas de ce champ. +`storage.memtable_size_bytes` is the active memtable flush threshold. `storage.max_imm_memtables` (default 4) is the immutable-table backpressure cap: a writer waits until an immutable table flushes instead of queueing another one. ## Raft diff --git a/docs/fr/configuration.md b/docs/fr/configuration.md index a5e7851..30442b6 100644 --- a/docs/fr/configuration.md +++ b/docs/fr/configuration.md @@ -15,7 +15,7 @@ | `node.grpc_listen_addr` | `127.0.0.1:7800` | Oui. Adresse de liaison | | `node.metrics_listen_addr` | non défini | Oui, seulement s'il est défini. Écouteur TCP séparé. Une adresse non locale exige un secret non vide | | `clock.max_clock_drift_ms` | `500` | Oui. `HybridLogicalClock::with_max_drift_ms` | -| `storage.memtable_size_bytes` | `33554432` (32 Mio) | **Non.** Le champ est stocké et jamais lu | +| `storage.memtable_size_bytes` | `33554432` (32 MiB) | Yes. Seals and flushes the active memtable once its accounted bytes reach this size. Values below 1 are treated as 1 | | `storage.block_cache_bytes` | `67108864` (64 Mio) | Oui. Budget total du cache de blocs à 16 voies | | `storage.mvcc_retention_ms` | `5000` | Oui | | `storage.bloom_bits_per_key` | `10` | Oui | @@ -31,7 +31,7 @@ Il n'y a pas de table `[raft]`. `ServerTomlConfig.raft_options` est ignoré par ## Exemple -Ce fichier correspond aux valeurs par défaut, sauf un répertoire de données explicite, un port de métriques et un secret. `memtable_size_bytes` est montré pour qu'une configuration copiée ne surprenne pas ; le modifier ne change pas le comportement de vidage. +This file matches the defaults except for an explicit data directory, a metrics port, and a secret. `memtable_size_bytes` is the active memtable flush threshold. `max_imm_memtables` is the immutable-table backpressure cap. ```toml [node] diff --git a/docs/fr/operations.md b/docs/fr/operations.md index cd1125c..9bc4304 100644 --- a/docs/fr/operations.md +++ b/docs/fr/operations.md @@ -137,7 +137,7 @@ Les variantes sont définies dans `crates/metadb-core/src/error.rs`. Les méthod - L'isolation jumbo est un indicateur de route plus un identifiant de nœud choisi dans la table locale. Elle n'évince pas d'autres shards d'un disque. - Les battements de cœur sont un RPC sans émetteur dans `metadbd`. `StoreHeartbeat` ne persiste pas. - Un secret partagé non vide authentifie Raft, les trois autres services gRPC et l'écouteur de métriques avec le même bearer. Un secret vide n'est accepté que pour les liaisons en boucle locale et laisse ces écouteurs non authentifiés. Une liaison joker avec un secret vide refuse de démarrer. Le processus ne termine pas TLS. -- `memtable_size_bytes` et tous les champs de temporisation Raft ne changent pas le comportement d'exécution via le TOML. +- `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` pour `hotspot-create` et `bulk-ttl-delete` imprime des lignes JSON : un en-tête avec `bench_pid`, puis des rapports de phase avec attempted, succeeded, failed et des percentiles de latence. Le processus se termine en erreur si une opération demandée échoue. `--workload mixed` ou `--embedded` lance le harnais de stress dans le processus. `sql` imprime la réponse en JSON et se termine en erreur sur une erreur d'application. ## Lacunes de documentation diff --git a/docs/ja/architecture.md b/docs/ja/architecture.md index cc7595c..19776dc 100644 --- a/docs/ja/architecture.md +++ b/docs/ja/architecture.md @@ -82,7 +82,7 @@ MVCC の版は `storage.mvcc_retention_ms`(既定 5,000)のあいだメモリに留まります。協調フラッシュは memtable を封印し、属性集約フックを実行し、L0 SSTable を書きます。ユーザ KV 用の別 WAL はありません。クラッシュ回復は Raft ログと LSM マニフェストです。`LocalityCompactor` は 9 バイト接頭辞のバケットごとにトゥームストーンを追い、`locality_tombstone_threshold` と `locality_tombstone_ratio` の両方を超えたときにホットな削除範囲をコンパクトします。`ServerTomlConfig::to_lsm_config` は `auto_locality_compaction` を常に `true` にします。TOML では消せません。 -`storage.memtable_size_bytes` はデシリアライズされますが読まれません。フラッシュサイズはこの項目から取りません。 +`storage.memtable_size_bytes` is the active memtable flush threshold. `storage.max_imm_memtables` (default 4) is the immutable-table backpressure cap: a writer waits until an immutable table flushes instead of queueing another one. ## Raft diff --git a/docs/ja/configuration.md b/docs/ja/configuration.md index b9c1795..3177b97 100644 --- a/docs/ja/configuration.md +++ b/docs/ja/configuration.md @@ -15,7 +15,7 @@ | `node.grpc_listen_addr` | `127.0.0.1:7800` | する。バインドアドレス | | `node.metrics_listen_addr` | 未設定 | 設定されたときだけする。別の TCP リスナー。ループバック以外は空でないシークレットが必要 | | `clock.max_clock_drift_ms` | `500` | する。`HybridLogicalClock::with_max_drift_ms` | -| `storage.memtable_size_bytes` | `33554432`(32 MiB) | **しない。** フィールドは保持されるが読まれない | +| `storage.memtable_size_bytes` | `33554432` (32 MiB) | Yes. Seals and flushes the active memtable once its accounted bytes reach this size. Values below 1 are treated as 1 | | `storage.block_cache_bytes` | `67108864`(64 MiB) | する。16 分割ブロックキャッシュの合計予算 | | `storage.mvcc_retention_ms` | `5000` | する | | `storage.bloom_bits_per_key` | `10` | する | @@ -31,7 +31,7 @@ ## 例 -このファイルは、明示的なデータディレクトリ、メトリクスポート、シークレット以外は既定値です。`memtable_size_bytes` は、コピーした設定が驚かないように書いてあります。変えてもフラッシュの挙動は変わりません。 +This file matches the defaults except for an explicit data directory, a metrics port, and a secret. `memtable_size_bytes` is the active memtable flush threshold. `max_imm_memtables` is the immutable-table backpressure cap. ```toml [node] diff --git a/docs/ja/operations.md b/docs/ja/operations.md index 34cd004..6124043 100644 --- a/docs/ja/operations.md +++ b/docs/ja/operations.md @@ -137,7 +137,7 @@ metadb-ctl --endpoint 127.0.0.1:7800 sql \ - ジャンボ隔離はルートフラグと、ローカルノード表から選んだノード ID である。他のシャードをディスクから追い出すことはしない。 - ハートビートは RPC であり、`metadbd` に送信側はない。`StoreHeartbeat` は永続化しない。 - 空でない共有シークレットは、Raft、他の 3 つの gRPC サービス、およびメトリクスリスナーを同じベアラで認証する。空のシークレットはループバックのバインドだけを受け付け、それらのリスナーは無認証のままである。空のシークレットでのワイルドカードバインドは起動を拒否する。プロセスは TLS を終端しない。 -- `memtable_size_bytes` とすべての Raft タイマ項目は、TOML 経由で実行時の挙動を変えない。 +- `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. - `hotspot-create` と `bulk-ttl-delete` の `metadb-ctl bench` は JSON 行を印字する。`bench_pid` を含むヘッダのあと、attempted、succeeded、failed とレイテンシのパーセンタイルを持つフェーズ報告が続く。要求した操作がすべて成功しない限り、プロセスは非ゼロで終了する。`--workload mixed` または `--embedded` はプロセス内のストレステストを実行する。`sql` は応答を JSON で印字し、アプリケーションエラーでは非ゼロで終了する。 ## 文書化できない欠落 diff --git a/docs/zh/architecture.md b/docs/zh/architecture.md index b81add0..9473a66 100644 --- a/docs/zh/architecture.md +++ b/docs/zh/architecture.md @@ -82,7 +82,7 @@ MVCC 版本在内存中保留 `storage.mvcc_retention_ms`(默认 5,000)。协调刷盘封印 memtable,运行属性聚合钩子,并写出 L0 SSTable。没有单独的用户 KV WAL。崩溃恢复靠 Raft 日志加上 LSM 清单。`LocalityCompactor` 按 9 字节前缀桶跟踪墓碑,并在 `locality_tombstone_threshold` 与 `locality_tombstone_ratio` 同时越过时压缩热点删除范围。`ServerTomlConfig::to_lsm_config` 总是把 `auto_locality_compaction` 设为 `true`;TOML 文件不能关掉它。 -`storage.memtable_size_bytes` 会被反序列化,但从不读取。刷盘大小不取自该字段。 +`storage.memtable_size_bytes` is the active memtable flush threshold. `storage.max_imm_memtables` (default 4) is the immutable-table backpressure cap: a writer waits until an immutable table flushes instead of queueing another one. ## Raft diff --git a/docs/zh/configuration.md b/docs/zh/configuration.md index 6f19bae..339c1eb 100644 --- a/docs/zh/configuration.md +++ b/docs/zh/configuration.md @@ -15,7 +15,7 @@ | `node.grpc_listen_addr` | `127.0.0.1:7800` | 是。绑定地址 | | `node.metrics_listen_addr` | 未设置 | 仅在设置时应用。单独的 TCP 监听器。非环回地址要求非空密钥 | | `clock.max_clock_drift_ms` | `500` | 是。`HybridLogicalClock::with_max_drift_ms` | -| `storage.memtable_size_bytes` | `33554432`(32 MiB) | **否。** 字段被保存,从不读取 | +| `storage.memtable_size_bytes` | `33554432` (32 MiB) | Yes. Seals and flushes the active memtable once its accounted bytes reach this size. Values below 1 are treated as 1 | | `storage.block_cache_bytes` | `67108864`(64 MiB) | 是。16 路块缓存的总预算 | | `storage.mvcc_retention_ms` | `5000` | 是 | | `storage.bloom_bits_per_key` | `10` | 是 | @@ -31,7 +31,7 @@ ## 示例 -除了明确的数据目录、指标端口和密钥,这个文件与默认值一致。写出 `memtable_size_bytes` 是为了避免抄来的配置让人意外;改它不会改变刷盘行为。 +This file matches the defaults except for an explicit data directory, a metrics port, and a secret. `memtable_size_bytes` is the active memtable flush threshold. `max_imm_memtables` is the immutable-table backpressure cap. ```toml [node] diff --git a/docs/zh/operations.md b/docs/zh/operations.md index c563cf1..43ce3bf 100644 --- a/docs/zh/operations.md +++ b/docs/zh/operations.md @@ -137,7 +137,7 @@ metadb-ctl --endpoint 127.0.0.1:7800 sql \ - 巨型隔离是路由标志加上从本地节点表选出的节点标识。它不会把其他分片从磁盘上赶走。 - 心跳是一个 RPC,`metadbd` 里没有发送方。`StoreHeartbeat` 不持久化。 - 非空共享密钥用同一个持有者令牌认证 Raft、另外三个 gRPC 服务和指标监听器。空密钥只接受环回绑定,这些监听器不认证。通配绑定加上空密钥会拒绝启动。进程不终结 TLS。 -- `memtable_size_bytes` 和所有 Raft 计时字段不会通过 TOML 改变运行行为。 +- `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. - `hotspot-create` 和 `bulk-ttl-delete` 的 `metadb-ctl bench` 打印 JSON 行:先是带 `bench_pid` 的头,然后是包含 attempted、succeeded、failed 和延迟分位数的阶段报告。只要有一次请求的操作失败,进程就以非零状态退出。`--workload mixed` 或 `--embedded` 运行进程内的压力工具。`sql` 把响应打印成 JSON,遇到应用错误时以非零状态退出。 ## 文档缺口 From 46636fac30560a1e0ed4e463f3118d1de6a26afd Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 11:40:08 +0000 Subject: [PATCH 2/3] Check snapshot repair on forwarded writes and before publish. ClientWrite enters propose_local, so that path now repairs or rejects an unrecoverable snapshot. A loaded or rebuilt snapshot is kept only when its index covers the purged log, and healthy requests stat SNAPSHOT_META instead of decoding every SSTable. Co-authored-by: RustFS --- crates/metadb-raft/src/group_host.rs | 3 +- crates/metadb-raft/src/state_machine.rs | 120 +++++++++++++++--- .../tests/snapshot_read_path_tests.rs | 89 +++++++++++++ 3 files changed, 196 insertions(+), 16 deletions(-) diff --git a/crates/metadb-raft/src/group_host.rs b/crates/metadb-raft/src/group_host.rs index b97df45..36745e4 100644 --- a/crates/metadb-raft/src/group_host.rs +++ b/crates/metadb-raft/src/group_host.rs @@ -555,7 +555,6 @@ impl ShardRaftGroup { payload: Vec, deadline: tokio::time::Instant, ) -> Result { - self.repair_published_snapshot().await?; { let mut hook = self.testing_not_leader.lock().unwrap(); if hook.0 > 0 { @@ -632,6 +631,8 @@ impl ShardRaftGroup { caller_hlc: HlcTimestamp, payload: Vec, ) -> Result { + // Forwarded ClientWrite RPCs enter here and skip `propose_until`. + self.repair_published_snapshot().await?; let local_epoch = self.current_epoch(); if expected_epoch != local_epoch { return Err(MetaDbError::EpochMismatch { diff --git a/crates/metadb-raft/src/state_machine.rs b/crates/metadb-raft/src/state_machine.rs index 94e5d3e..c601d70 100644 --- a/crates/metadb-raft/src/state_machine.rs +++ b/crates/metadb-raft/src/state_machine.rs @@ -6,6 +6,7 @@ use std::fs::{self, File, OpenOptions}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, RwLock}; +use std::time::SystemTime; use openraft::entry::RaftEntry; use openraft::storage::{EntryResponder, RaftSnapshotBuilder, RaftStateMachine}; @@ -242,6 +243,15 @@ struct StateMachineShared { /// Set when a required snapshot cannot be rebuilt. Cluster status must not /// keep reporting this process as a live voter after RaftCore has failed. unrecoverable: Mutex>, + /// Last `SNAPSHOT_META` stat that passed a full completeness check. + /// Later requests compare this stat instead of decoding every SSTable. + snapshot_cache: Mutex>, +} + +struct PublishedSnapshotCache { + index: u64, + meta_len: u64, + meta_modified: Option, } impl StateMachineShared { @@ -417,7 +427,20 @@ impl StateMachineShared { // Persist SNAPSHOT_META's directory entry before publishing the snapshot. sync_dir(&tmp_dir).map_err(|e| io::Error::other(e.to_string()))?; + let purged = crate::log_store::read_persisted_purged_index(&self.shard_dir.join("raft")) + .unwrap_or(0); + let required = purged.max(self.watermarks.snapshot_values().2); + if snap_index < required { + let _ = fs::remove_dir_all(&tmp_dir); + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "refusing to publish snapshot index {snap_index}; it does not cover required index {required}" + ), + )); + } publish_snapshot_dir(&snaps_root, snap_index, &tmp_dir)?; + *self.snapshot_cache.lock().unwrap() = None; self.watermarks .advance_last_snapshot(checkpoint.flushed_raft_index); @@ -441,16 +464,60 @@ impl StateMachineShared { )) } - /// True when this process has published a snapshot that is no longer a complete directory. + /// True when the published snapshot directory is missing or no longer matches + /// the `SNAPSHOT_META` stat that last passed a full check. + /// + /// The common path is one metadata call. A changed or new meta file is + /// validated once and then cached, so a healthy request does not decode + /// every SSTable. fn published_snapshot_missing(&self) -> bool { let index = self.watermarks.snapshot_values().2; if index == 0 { return false; } - let dir = self + let meta_path = self .shard_dir - .join(format!("raft/snapshots/snap_{index:020}")); - !snapshot_dir_is_complete(&dir) + .join(format!("raft/snapshots/snap_{index:020}/SNAPSHOT_META")); + let Ok(info) = fs::metadata(&meta_path) else { + *self.snapshot_cache.lock().unwrap() = None; + return true; + }; + if !info.is_file() || info.len() <= 4 { + *self.snapshot_cache.lock().unwrap() = None; + return true; + } + let modified = info.modified().ok(); + if self + .snapshot_cache + .lock() + .unwrap() + .as_ref() + .is_some_and(|cached| { + cached.index == index + && cached.meta_len == info.len() + && cached.meta_modified == modified + }) + { + return false; + } + let complete = meta_path.parent().is_some_and(snapshot_dir_is_complete); + if complete { + *self.snapshot_cache.lock().unwrap() = Some(PublishedSnapshotCache { + index, + meta_len: info.len(), + meta_modified: modified, + }); + false + } else { + *self.snapshot_cache.lock().unwrap() = None; + true + } + } + + fn required_snapshot_index(&self) -> u64 { + let purged = crate::log_store::read_persisted_purged_index(&self.shard_dir.join("raft")) + .unwrap_or(0); + purged.max(self.watermarks.snapshot_values().2) } fn load_current_snapshot_sync( @@ -458,13 +525,38 @@ impl StateMachineShared { ) -> io::Result>> { let snaps_root = self.shard_dir.join("raft/snapshots"); let candidates = snapshot_candidates(&snaps_root); + let required = self.required_snapshot_index(); // A missing file used to return `NotFound`. OpenRaft maps that to // `StorageError { subject: Snapshot(None), verb: Read }` and stops RaftCore, // while the process kept answering cluster status from cached membership. - // Skip a broken directory, including a `.bak` left by an in-progress replace. - for (_, snap_dir) in &candidates { + // An older readable directory does not satisfy a higher purged or published index. + for (index, snap_dir) in &candidates { + if *index < required { + tracing::warn!( + path = %snap_dir.display(), + index, + required, + "skipping raft snapshot that does not cover the required index" + ); + continue; + } match load_snapshot_dir(snap_dir) { Ok(snapshot) => { + let covered = snapshot + .meta + .last_log_id + .as_ref() + .map(|id| id.index) + .unwrap_or(0); + if covered < required { + tracing::warn!( + path = %snap_dir.display(), + covered, + required, + "skipping raft snapshot whose log id is behind the required index" + ); + continue; + } self.clear_unrecoverable(); return Ok(Some(snapshot)); } @@ -488,20 +580,17 @@ impl StateMachineShared { .current_engine() .durable_checkpoint() .flushed_raft_index; - let raft_dir = self.shard_dir.join("raft"); - let purged = crate::log_store::read_persisted_purged_index(&raft_dir).unwrap_or(0); - let snapshot_required = - purged > 0 || self.watermarks.snapshot_values().2 > 0 || !candidates.is_empty(); // The segmented raft log is the WAL until it is purged. Before that, // a missing snapshot file is not fatal: restart replays the log. - if !snapshot_required { + if required == 0 { self.clear_unrecoverable(); return Ok(None); } // After purge, the LSM is the only remaining copy. Rewrite the snapshot // from it before returning, so a live process does not keep serving - // with the snapshot file gone. + // with the snapshot file gone. `build_snapshot_sync` refuses to publish + // a directory that does not cover `required`. match self.build_snapshot_sync() { Ok(snapshot) => { let covered = snapshot @@ -510,16 +599,16 @@ impl StateMachineShared { .as_ref() .map(|id| id.index) .unwrap_or(0); - if purged > covered { + if required > covered { return self.fail_unrecoverable(format!( - "rebuilt snapshot index {covered} does not cover purged raft log {purged}. The segmented raft log is the WAL only until it is purged. A missing snapshot is rebuilt from the LSM. If that LSM is also missing, committed data is not reconstructed" + "rebuilt snapshot index {covered} does not cover required index {required}. The segmented raft log is the WAL only until it is purged. A missing snapshot is rebuilt from the LSM. If that LSM is also missing, committed data is not reconstructed" )); } self.clear_unrecoverable(); Ok(Some(snapshot)) } Err(error) => self.fail_unrecoverable(format!( - "cannot rebuild a missing snapshot from the LSM ({error}). purged log index is {purged}, flushed LSM index is {flushed}, applied index is {applied}. The segmented raft log is the WAL only until it is purged. If the log and the LSM are both gone, committed data is not reconstructed" + "cannot rebuild a missing snapshot from the LSM ({error}). required index is {required}, flushed LSM index is {flushed}, applied index is {applied}. The segmented raft log is the WAL only until it is purged. If the log and the LSM are both gone, committed data is not reconstructed" )), } } @@ -828,6 +917,7 @@ impl ShardStateMachine { last_membership: RwLock::new(initial_membership), frontier_tx, unrecoverable: Mutex::new(None), + snapshot_cache: Mutex::new(None), }); Ok((Self { shared }, frontier_rx)) diff --git a/crates/metadb-raft/tests/snapshot_read_path_tests.rs b/crates/metadb-raft/tests/snapshot_read_path_tests.rs index f08f776..5fbca6b 100644 --- a/crates/metadb-raft/tests/snapshot_read_path_tests.rs +++ b/crates/metadb-raft/tests/snapshot_read_path_tests.rs @@ -253,3 +253,92 @@ async fn missing_lsm_and_snapshot_after_log_purge_is_not_a_live_voter() { ); group.shutdown().await.unwrap(); } + +#[tokio::test] +async fn forwarded_propose_local_rewrites_a_missing_snapshot() { + let dir = tempdir().unwrap(); + let shard_dir = dir.path().join("shards/00000000000000000001"); + let cache = Arc::new(ShardedBlockCache::new(4 * 1024 * 1024)); + let clock = Arc::new(HybridLogicalClock::new()); + let group = boot(&shard_dir, cache, clock).await; + let epoch = group.current_epoch(); + for name in ["alpha", "beta", "gamma"] { + let cmd = BasicKvCommand::Put { + key: MetaKey::child(1, name).encode(), + value: name.as_bytes().to_vec(), + }; + group + .propose(epoch, HlcTimestamp::ZERO, codec::serialize(&cmd).unwrap()) + .await + .unwrap(); + } + group.flush_snapshot_and_purge().await.unwrap(); + let published = group.watermarks().snapshot_values().2; + let meta = shard_dir.join(format!("raft/snapshots/snap_{published:020}/SNAPSHOT_META")); + fs::remove_file(&meta).unwrap(); + let cmd = BasicKvCommand::Put { + key: MetaKey::child(1, "delta").encode(), + value: b"delta".to_vec(), + }; + group + .propose_local(epoch, HlcTimestamp::ZERO, codec::serialize(&cmd).unwrap()) + .await + .unwrap(); + let rewritten = shard_dir + .join("raft/snapshots") + .read_dir() + .unwrap() + .any(|entry| { + entry + .ok() + .and_then(|entry| entry.file_name().into_string().ok()) + .is_some_and(|name| name.starts_with("snap_") && !name.contains('.')) + }); + assert!(rewritten, "propose_local must rewrite the missing snapshot"); + assert!(group.storage_unrecoverable().is_none()); + group.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn older_snapshot_does_not_satisfy_a_purged_prefix() { + let dir = tempdir().unwrap(); + let shard_dir = dir.path().join("shards/00000000000000000001"); + let cache = Arc::new(ShardedBlockCache::new(4 * 1024 * 1024)); + let clock = Arc::new(HybridLogicalClock::new()); + let group = boot(&shard_dir, cache, clock).await; + let epoch = group.current_epoch(); + for name in ["alpha", "beta", "gamma"] { + let cmd = BasicKvCommand::Put { + key: MetaKey::child(1, name).encode(), + value: name.as_bytes().to_vec(), + }; + group + .propose(epoch, HlcTimestamp::ZERO, codec::serialize(&cmd).unwrap()) + .await + .unwrap(); + } + let purged = group.flush_snapshot_and_purge().await.unwrap(); + assert!(purged > 1); + for entry in fs::read_dir(shard_dir.join("lsm")).unwrap() { + let entry = entry.unwrap(); + if entry.file_name().to_str().unwrap_or("").ends_with(".sst") { + fs::remove_file(entry.path()).unwrap(); + } + } + let _ = fs::remove_dir_all(shard_dir.join("raft/snapshots")); + metadb_raft::state_machine::write_complete_snapshot_marker(&shard_dir.join("raft"), 1).unwrap(); + + let mut state_machine = group.state_machine().clone(); + let first = state_machine.get_current_snapshot().await.unwrap_err(); + assert!( + first.to_string().contains("snapshot unrecoverable"), + "{first}" + ); + let second = state_machine.get_current_snapshot().await.unwrap_err(); + assert!( + second.to_string().contains("snapshot unrecoverable"), + "a later read must not accept the older snapshot: {second}" + ); + assert!(group.storage_unrecoverable().is_some()); + group.shutdown().await.unwrap(); +} From 2a1889c48e938601a79c7862c47036cdc643d362 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Thu, 19 Nov 2026 12:01:43 +0000 Subject: [PATCH 3/3] Fail closed on startup and status when a purged shard cannot be rebuilt. Open recomputes the snapshot before the group can serve, and cluster status repairs or rejects a missing snapshot without waiting for get_current_snapshot. After purge, reconstruction still depends on the LSM. A transient publish error does not latch the shard unrecoverable. Co-authored-by: RustFS --- crates/metadb-cluster/src/cell_manager.rs | 12 +- crates/metadb-raft/src/group_host.rs | 30 ++ crates/metadb-raft/src/state_machine.rs | 52 ++- .../tests/snapshot_read_path_tests.rs | 298 +++++++++++++++++- crates/metadb-server/src/lib.rs | 3 + .../tests/snapshot_status_tests.rs | 53 ++++ docs/de/architecture.md | 2 +- docs/de/configuration.md | 4 +- docs/de/operations.md | 2 +- docs/designs/correctness_hardening.md | 2 +- docs/en/architecture.md | 2 +- docs/fr/architecture.md | 2 +- docs/fr/configuration.md | 4 +- docs/fr/operations.md | 2 +- docs/ja/architecture.md | 2 +- docs/ja/configuration.md | 4 +- docs/ja/operations.md | 2 +- docs/zh/architecture.md | 2 +- docs/zh/configuration.md | 4 +- docs/zh/operations.md | 2 +- 20 files changed, 453 insertions(+), 31 deletions(-) diff --git a/crates/metadb-cluster/src/cell_manager.rs b/crates/metadb-cluster/src/cell_manager.rs index ce66823..ef26281 100644 --- a/crates/metadb-cluster/src/cell_manager.rs +++ b/crates/metadb-cluster/src/cell_manager.rs @@ -977,12 +977,14 @@ impl DurableCellManager { let routes = self.list_routes(); for route in &routes { if let Some(group) = self.host.get_group(route.shard_id) { - if let Some(reason) = group.storage_unrecoverable() { - return Err(MetaDbError::StorageIoError(format!( - "shard {} storage is unrecoverable, so it is not a live voter: {reason}", + // Probe the snapshot directory. The in-memory latch is still + // empty until something attempts repair. + group.ensure_published_snapshot_sync().map_err(|error| { + MetaDbError::StorageIoError(format!( + "shard {} storage is unrecoverable, so it is not a live voter: {error}", route.shard_id - ))); - } + )) + })?; } } Ok(routes) diff --git a/crates/metadb-raft/src/group_host.rs b/crates/metadb-raft/src/group_host.rs index 36745e4..157da61 100644 --- a/crates/metadb-raft/src/group_host.rs +++ b/crates/metadb-raft/src/group_host.rs @@ -218,6 +218,12 @@ impl ShardRaftGroup { let _ = raft.wait_for_recovery(Some(Duration::from_secs(5))).await; } + if let Some(reason) = state_machine.storage_unrecoverable() { + return Err(MetaDbError::StorageIoError(format!( + "snapshot unrecoverable: {reason}" + ))); + } + router.register_group(shard_id, raft.clone()); let read_batcher = Arc::new(ReadIndexBatcher::new(shard_id, raft.clone(), frontier_rx)); @@ -364,6 +370,30 @@ impl ShardRaftGroup { self.state_machine.storage_unrecoverable() } + /// Repair a missing published snapshot before cluster status returns. + /// + /// Status must not trust the in-memory latch alone. The files can disappear + /// before any `get_current_snapshot` call. + pub fn ensure_published_snapshot_sync(&self) -> Result<()> { + if let Some(reason) = self.storage_unrecoverable() { + return Err(MetaDbError::StorageIoError(format!( + "snapshot unrecoverable: {reason}" + ))); + } + if !self.state_machine.published_snapshot_missing() { + return Ok(()); + } + self.state_machine + .ensure_durable_snapshot() + .map_err(|error| MetaDbError::StorageIoError(error.to_string()))?; + if let Some(reason) = self.storage_unrecoverable() { + return Err(MetaDbError::StorageIoError(format!( + "snapshot unrecoverable: {reason}" + ))); + } + Ok(()) + } + /// Rewrite a published snapshot that disappeared, or refuse to serve. /// /// A missing in-use snapshot used to stop RaftCore while cluster status diff --git a/crates/metadb-raft/src/state_machine.rs b/crates/metadb-raft/src/state_machine.rs index c601d70..078a87f 100644 --- a/crates/metadb-raft/src/state_machine.rs +++ b/crates/metadb-raft/src/state_machine.rs @@ -607,9 +607,23 @@ impl StateMachineShared { self.clear_unrecoverable(); Ok(Some(snapshot)) } - Err(error) => self.fail_unrecoverable(format!( - "cannot rebuild a missing snapshot from the LSM ({error}). required index is {required}, flushed LSM index is {flushed}, applied index is {applied}. The segmented raft log is the WAL only until it is purged. If the log and the LSM are both gone, committed data is not reconstructed" - )), + Err(error) => { + let text = error.to_string(); + // A transient publish error must not stick. Latch only when the + // flushed LSM cannot cover the purged prefix, or the files + // needed to rebuild it are already gone. + let files_gone = text.contains("os error 2") + || text.contains("No such file") + || text.contains("does not cover required") + || text.contains("not found"); + if flushed < required || files_gone { + self.fail_unrecoverable(format!( + "cannot rebuild a missing snapshot from the LSM ({text}). required index is {required}, flushed LSM index is {flushed}, applied index is {applied}. After purge, reconstruction depends on the LSM. There is no fourth copy, so committed data is not reconstructed" + )) + } else { + Err(error) + } + } } } } @@ -869,12 +883,24 @@ impl ShardStateMachine { } } - let engine = Arc::new(LifecycleStorageEngine::open_lsm( + let engine = match LifecycleStorageEngine::open_lsm( shard_id, &lsm_dir, block_cache.clone(), lsm_config.clone(), - )?); + ) { + Ok(engine) => Arc::new(engine), + Err(error) => { + let purged = crate::log_store::read_persisted_purged_index(&shard_dir.join("raft")) + .unwrap_or(0); + if purged > 0 { + return Err(MetaDbError::StorageIoError(format!( + "snapshot unrecoverable: cannot open the LSM after the raft log was purged ({error}). committed data is not reconstructed" + ))); + } + return Err(error); + } + }; attach_flush_hook(&engine, &handler); let cp = engine.durable_checkpoint(); @@ -920,6 +946,17 @@ impl ShardStateMachine { snapshot_cache: Mutex::new(None), }); + // Rewrite a missing snapshot, or refuse to return a state machine that + // would serve an empty LSM over a purged log. + if let Err(error) = shared.load_current_snapshot_sync() { + return Err(MetaDbError::StorageIoError(error.to_string())); + } + if let Some(reason) = shared.unrecoverable.lock().unwrap().clone() { + return Err(MetaDbError::StorageIoError(format!( + "snapshot unrecoverable: {reason}" + ))); + } + Ok((Self { shared }, frontier_rx)) } @@ -937,6 +974,11 @@ impl ShardStateMachine { self.shared.published_snapshot_missing() } + /// Rebuild a required snapshot from the LSM, or record that it cannot be covered. + pub fn ensure_durable_snapshot(&self) -> io::Result<()> { + self.shared.load_current_snapshot_sync().map(|_| ()) + } + pub fn handler(&self) -> &Arc { &self.shared.handler } diff --git a/crates/metadb-raft/tests/snapshot_read_path_tests.rs b/crates/metadb-raft/tests/snapshot_read_path_tests.rs index 5fbca6b..380600f 100644 --- a/crates/metadb-raft/tests/snapshot_read_path_tests.rs +++ b/crates/metadb-raft/tests/snapshot_read_path_tests.rs @@ -1,14 +1,20 @@ //! A purged or missing Raft snapshot file must not stop the read path. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::sync::Arc; +use std::time::Duration; + +use tokio::net::TcpListener; +use tokio_stream::wrappers::TcpListenerStream; +use tonic::transport::Server; use metadb_core::codec; use metadb_core::{HlcTimestamp, HybridLogicalClock, MetaKey, ShardEpoch}; +use metadb_proto::raft_transport_service_server::RaftTransportServiceServer; use metadb_raft::{ - BasicKvApplyHandler, BasicKvCommand, ChannelPool, MultiRaftRouter, RaftNodeOptions, - ShardRaftGroup, ShardWatermarkTracker, + BasicKvApplyHandler, BasicKvCommand, ChannelPool, ConfChangeOrchestrator, MultiRaftRouter, + MultiRaftTransportServer, RaftNodeOptions, ShardRaftGroup, ShardWatermarkTracker, }; use metadb_storage::{LsmEngineConfig, ShardedBlockCache}; use openraft::storage::RaftStateMachine; @@ -342,3 +348,289 @@ async fn older_snapshot_does_not_satisfy_a_purged_prefix() { assert!(group.storage_unrecoverable().is_some()); group.shutdown().await.unwrap(); } + +#[tokio::test] +async fn restart_after_purged_log_missing_lsm_and_snapshot_is_unrecoverable_before_serving() { + let dir = tempdir().unwrap(); + let shard_dir = dir.path().join("shards/00000000000000000001"); + let cache = Arc::new(ShardedBlockCache::new(4 * 1024 * 1024)); + let clock = Arc::new(HybridLogicalClock::new()); + { + let group = boot(&shard_dir, cache.clone(), clock.clone()).await; + let epoch = group.current_epoch(); + for name in ["alpha", "beta", "gamma"] { + let cmd = BasicKvCommand::Put { + key: MetaKey::child(1, name).encode(), + value: name.as_bytes().to_vec(), + }; + group + .propose(epoch, HlcTimestamp::ZERO, codec::serialize(&cmd).unwrap()) + .await + .unwrap(); + } + let purged = group.flush_snapshot_and_purge().await.unwrap(); + assert!(purged > 0); + for entry in fs::read_dir(shard_dir.join("lsm")).unwrap() { + let entry = entry.unwrap(); + if entry.file_name().to_str().unwrap_or("").ends_with(".sst") { + fs::remove_file(entry.path()).unwrap(); + } + } + let _ = fs::remove_dir_all(shard_dir.join("raft/snapshots")); + group.shutdown().await.unwrap(); + } + + let watermarks = Arc::new(ShardWatermarkTracker::new(0, 0, 0)); + let handler = Arc::new(BasicKvApplyHandler::new( + ShardEpoch::initial(), + watermarks.clone(), + )); + let router = MultiRaftRouter::new(); + let started = ShardRaftGroup::start( + 1, + 1, + &shard_dir, + cache, + LsmEngineConfig::default(), + RaftNodeOptions::default(), + handler, + watermarks, + clock, + &router, + ChannelPool::default(), + ) + .await; + match started { + Err(error) => { + let text = error.to_string(); + assert!( + text.contains("snapshot unrecoverable"), + "restart must fail closed before serving: {text}" + ); + assert!( + text.contains("not reconstructed"), + "an empty replacement LSM must not be treated as a new shard: {text}" + ); + } + Ok(group) => { + let latched = group.storage_unrecoverable().is_some(); + let rejected = group + .propose_local( + group.current_epoch(), + HlcTimestamp::ZERO, + codec::serialize(&BasicKvCommand::Put { + key: MetaKey::child(1, "fresh").encode(), + value: b"nope".to_vec(), + }) + .unwrap(), + ) + .await + .is_err(); + let _ = group.shutdown().await; + assert!( + latched && rejected, + "restart must be unrecoverable and must not accept a write onto an empty LSM" + ); + } + } +} + +#[tokio::test] +async fn restart_rebuilds_snapshot_from_lsm_without_a_prior_live_read() { + let dir = tempdir().unwrap(); + let shard_dir = dir.path().join("shards/00000000000000000001"); + let cache = Arc::new(ShardedBlockCache::new(4 * 1024 * 1024)); + let clock = Arc::new(HybridLogicalClock::new()); + { + let group = boot(&shard_dir, cache.clone(), clock.clone()).await; + let epoch = group.current_epoch(); + for name in ["alpha", "beta", "gamma"] { + let cmd = BasicKvCommand::Put { + key: MetaKey::child(1, name).encode(), + value: name.as_bytes().to_vec(), + }; + group + .propose(epoch, HlcTimestamp::ZERO, codec::serialize(&cmd).unwrap()) + .await + .unwrap(); + } + group.flush_snapshot_and_purge().await.unwrap(); + let _ = fs::remove_dir_all(shard_dir.join("raft/snapshots")); + group.shutdown().await.unwrap(); + } + + let group = boot(&shard_dir, cache, clock).await; + let rewritten = fs::read_dir(shard_dir.join("raft/snapshots")) + .unwrap() + .flatten() + .any(|entry| { + let name = entry.file_name(); + let name = name.to_str().unwrap_or(""); + name.starts_with("snap_") && !name.contains('.') + }); + assert!( + rewritten, + "start must rewrite the snapshot from the LSM before a client read" + ); + assert!(group.storage_unrecoverable().is_none()); + assert_keys(&group).await; + group.shutdown().await.unwrap(); +} + +async fn spawn_transport(router: MultiRaftRouter) -> String { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + let svc = RaftTransportServiceServer::new(MultiRaftTransportServer::new(router)); + tokio::spawn(async move { + let _ = Server::builder() + .add_service(svc) + .serve_with_incoming(TcpListenerStream::new(listener)) + .await; + }); + addr +} + +async fn start_voter( + node_id: u64, + shard_dir: &std::path::Path, + router: &MultiRaftRouter, + cache: Arc, +) -> Arc { + let watermarks = Arc::new(ShardWatermarkTracker::new(0, 0, 0)); + let handler = Arc::new(BasicKvApplyHandler::new( + ShardEpoch::initial(), + watermarks.clone(), + )); + ShardRaftGroup::start( + 1, + node_id, + shard_dir, + cache, + LsmEngineConfig::default(), + RaftNodeOptions { + heartbeat_interval_ms: 80, + election_timeout_min_ms: 250, + election_timeout_max_ms: 450, + ..RaftNodeOptions::default() + }, + handler, + watermarks, + Arc::new(HybridLogicalClock::new()), + router, + ChannelPool::default(), + ) + .await + .unwrap() +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn learner_install_succeeds_after_leader_snapshot_file_deleted() { + let dir = tempdir().unwrap(); + let cache = Arc::new(ShardedBlockCache::new(4 * 1024 * 1024)); + let router1 = MultiRaftRouter::new(); + let router2 = MultiRaftRouter::new(); + let addr1 = spawn_transport(router1.clone()).await; + let addr2 = spawn_transport(router2.clone()).await; + let leader = start_voter(1, &dir.path().join("node1"), &router1, cache.clone()).await; + leader + .initialize_if_needed(BTreeMap::from([(1u64, addr1.clone())])) + .await + .unwrap(); + let epoch = leader.current_epoch(); + let cmd = BasicKvCommand::Put { + key: MetaKey::child(1, "alpha").encode(), + value: b"alpha".to_vec(), + }; + leader + .propose(epoch, HlcTimestamp::ZERO, codec::serialize(&cmd).unwrap()) + .await + .unwrap(); + let purged = leader.flush_snapshot_and_purge().await.unwrap(); + assert!(purged > 0); + let _ = fs::remove_dir_all(dir.path().join("node1/raft/snapshots")); + + let learner = start_voter(2, &dir.path().join("node2"), &router2, cache).await; + ConfChangeOrchestrator::add_learners_and_promote_voters( + leader.raft(), + &[(2, addr2)], + BTreeSet::from([1, 2]), + 64, + Duration::from_secs(10), + purged, + ) + .await + .expect("learner install must succeed after the leader rewrites its snapshot"); + let snap = learner + .state_machine() + .acquire_snapshot(learner.current_epoch(), purged, None) + .expect("installed learner state must be readable without being the leader"); + let key = MetaKey::child(1, "alpha").encode(); + assert_eq!( + learner.engine().get_with_snapshot(&key, &snap).unwrap(), + Some(b"alpha".to_vec()) + ); + leader.shutdown().await.unwrap(); + learner.shutdown().await.unwrap(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn learner_install_fails_closed_when_leader_is_unrecoverable() { + let dir = tempdir().unwrap(); + let cache = Arc::new(ShardedBlockCache::new(4 * 1024 * 1024)); + let router1 = MultiRaftRouter::new(); + let router2 = MultiRaftRouter::new(); + let addr1 = spawn_transport(router1.clone()).await; + let addr2 = spawn_transport(router2.clone()).await; + let leader = start_voter(1, &dir.path().join("node1"), &router1, cache.clone()).await; + leader + .initialize_if_needed(BTreeMap::from([(1u64, addr1)])) + .await + .unwrap(); + let epoch = leader.current_epoch(); + let cmd = BasicKvCommand::Put { + key: MetaKey::child(1, "alpha").encode(), + value: b"alpha".to_vec(), + }; + leader + .propose(epoch, HlcTimestamp::ZERO, codec::serialize(&cmd).unwrap()) + .await + .unwrap(); + leader.flush_snapshot_and_purge().await.unwrap(); + for entry in fs::read_dir(dir.path().join("node1/lsm")).unwrap() { + let entry = entry.unwrap(); + if entry.file_name().to_str().unwrap_or("").ends_with(".sst") { + fs::remove_file(entry.path()).unwrap(); + } + } + let _ = fs::remove_dir_all(dir.path().join("node1/raft/snapshots")); + let _learner = start_voter(2, &dir.path().join("node2"), &router2, cache).await; + let installed = ConfChangeOrchestrator::add_learners_and_promote_voters( + leader.raft(), + &[(2, addr2)], + BTreeSet::from([1, 2]), + 64, + Duration::from_secs(3), + 1, + ) + .await; + assert!( + installed.is_err(), + "an unrecoverable leader must not install a learner from a missing snapshot and LSM" + ); + let write = leader + .propose_local( + leader.current_epoch(), + HlcTimestamp::ZERO, + codec::serialize(&BasicKvCommand::Put { + key: MetaKey::child(1, "later").encode(), + value: b"no".to_vec(), + }) + .unwrap(), + ) + .await; + assert!( + write.is_err(), + "the leader must not keep accepting writes after it cannot rebuild the snapshot" + ); + leader.shutdown().await.ok(); +} diff --git a/crates/metadb-server/src/lib.rs b/crates/metadb-server/src/lib.rs index 273d52f..769f570 100644 --- a/crates/metadb-server/src/lib.rs +++ b/crates/metadb-server/src/lib.rs @@ -847,6 +847,9 @@ impl PersistentMetaDbCluster { // `.raftlog` retention follows the 3-watermark gate in production (metadbd's loop). for cell in self.global_manager.all_cells() { for (_, grp, _) in cell.local_shard_handles() { + // Rewrite a missing snapshot from the LSM without waiting for a + // client read. A purged log has no other copy. + let _ = grp.repair_published_snapshot().await; let retained = grp.log_store().retained_entry_count(); if retained == 0 { continue; diff --git a/crates/metadb-server/tests/snapshot_status_tests.rs b/crates/metadb-server/tests/snapshot_status_tests.rs index f44340c..f6bacb0 100644 --- a/crates/metadb-server/tests/snapshot_status_tests.rs +++ b/crates/metadb-server/tests/snapshot_status_tests.rs @@ -61,3 +61,56 @@ async fn unrecoverable_snapshot_is_not_reported_as_a_live_voter() { ); cluster.shutdown().await.unwrap(); } + +#[tokio::test] +async fn routes_for_live_status_detects_missing_snapshot_without_prior_get_current_snapshot() { + let dir = tempfile::tempdir().unwrap(); + let mut cfg = ServerTomlConfig::default(); + cfg.node.data_dir = dir.path().to_path_buf(); + cfg.node.grpc_listen_addr = "127.0.0.1:0".into(); + cfg.sharding.bootstrap_table_shards = false; + let (cluster, _address) = PersistentMetaDbCluster::open_and_serve(cfg).await.unwrap(); + cluster + .tx_router() + .mkdir(ROOT_INODE_ID, "bucket", 100, 1, 0o755) + .await + .unwrap(); + cluster + .tx_router() + .create_file(100, "alpha.dat", 1001, 7, 1, 0o644, 4) + .await + .unwrap(); + let (_, group, _) = cluster.cell_manager().lookup_local_handle(1).unwrap(); + group.flush_snapshot_and_purge().await.unwrap(); + let shard_dir = cluster.cell_manager().host().shard_dir(1); + let published = group.watermarks().snapshot_values().2; + let meta = shard_dir.join(format!("raft/snapshots/snap_{published:020}/SNAPSHOT_META")); + fs::remove_file(&meta).unwrap(); + assert!(!meta.is_file()); + + let live = cluster + .cell_manager() + .routes_for_live_status() + .expect("status must repair a missing snapshot from the LSM before advertising voters"); + assert!( + live.iter() + .any(|route| { route.shard_id == 1 && route.peers.values().any(|(_, voter)| *voter) }), + "a repaired shard remains a live voter" + ); + let rewritten = fs::read_dir(shard_dir.join("raft/snapshots")) + .unwrap() + .flatten() + .any(|entry| { + entry + .file_name() + .to_str() + .unwrap_or("") + .starts_with("snap_") + && !entry.file_name().to_str().unwrap_or("").contains('.') + }); + assert!( + rewritten, + "GetRoutes must not return voters while the published snapshot file is still gone" + ); + cluster.shutdown().await.unwrap(); +} diff --git a/docs/de/architecture.md b/docs/de/architecture.md index 8073b95..e7e5b62 100644 --- a/docs/de/architecture.md +++ b/docs/de/architecture.md @@ -82,7 +82,7 @@ Die Zustandsmaschine jedes Shards öffnet ein WAL-loses LSM unter `/be MVCC-Versionen leben `storage.mvcc_retention_ms` (Vorgabe 5.000) lang im Speicher. Ein koordinierter Flush versiegelt die Memtable, führt den Attribut-Aggregationshaken aus und schreibt eine L0-SSTable. Es gibt kein separates Nutzer-KV-WAL. Absturzrecovery ist das Raft-Log plus das LSM-Manifest. `LocalityCompactor` zählt Tombstones je 9-Byte-Präfix-Eimer und kompaktiert einen heißen Löschbereich, wenn sowohl `locality_tombstone_threshold` als auch `locality_tombstone_ratio` überschritten sind. `auto_locality_compaction` setzt `ServerTomlConfig::to_lsm_config` immer auf `true`; die TOML-Datei kann es nicht abschalten. -`storage.memtable_size_bytes` is the active memtable flush threshold. `storage.max_imm_memtables` (default 4) is the immutable-table backpressure cap: a writer waits until an immutable table flushes instead of queueing another one. +`storage.memtable_size_bytes` wird deserialisiert und nie gelesen. Die Flush-Größe kommt nicht aus diesem Feld. ## Raft diff --git a/docs/de/configuration.md b/docs/de/configuration.md index 33111b2..af567b0 100644 --- a/docs/de/configuration.md +++ b/docs/de/configuration.md @@ -15,7 +15,7 @@ | `node.grpc_listen_addr` | `127.0.0.1:7800` | Ja. Bind-Adresse | | `node.metrics_listen_addr` | nicht gesetzt | Ja, nur wenn gesetzt. Eigener TCP-Listener. Eine Nicht-Loopback-Adresse verlangt ein nicht leeres Geheimnis | | `clock.max_clock_drift_ms` | `500` | Ja. `HybridLogicalClock::with_max_drift_ms` | -| `storage.memtable_size_bytes` | `33554432` (32 MiB) | Yes. Seals and flushes the active memtable once its accounted bytes reach this size. Values below 1 are treated as 1 | +| `storage.memtable_size_bytes` | `33554432` (32 MiB) | **Nein.** Das Feld wird gespeichert und nie gelesen | | `storage.block_cache_bytes` | `67108864` (64 MiB) | Ja. Gesamtbudget des 16-fachen Blockcaches | | `storage.mvcc_retention_ms` | `5000` | Ja | | `storage.bloom_bits_per_key` | `10` | Ja | @@ -31,7 +31,7 @@ Es gibt keine Tabelle `[raft]`. `ServerTomlConfig.raft_options` wird von serde ## Beispiel -This file matches the defaults except for an explicit data directory, a metrics port, and a secret. `memtable_size_bytes` is the active memtable flush threshold. `max_imm_memtables` is the immutable-table backpressure cap. +Diese Datei entspricht den Vorgaben, außer einem ausdrücklichen Datenverzeichnis, einem Metrik-Port und einem Geheimnis. `memtable_size_bytes` steht hier, damit eine kopierte Konfiguration nicht überrascht; eine Änderung ändert das Flush-Verhalten nicht. ```toml [node] diff --git a/docs/de/operations.md b/docs/de/operations.md index ad71068..c7bde6c 100644 --- a/docs/de/operations.md +++ b/docs/de/operations.md @@ -137,7 +137,7 @@ Die Varianten sind in `crates/metadb-core/src/error.rs` definiert. gRPC-Methoden - Jumbo-Isolation ist ein Routenflag plus eine Knotenkennung aus der lokalen Knotentabelle. Sie verdrängt andere Shards nicht von einer Platte. - Heartbeats sind ein RPC ohne Sender in `metadbd`. `StoreHeartbeat` speichert nicht dauerhaft. - Ein nicht leeres gemeinsames Geheimnis authentifiziert Raft, die drei anderen gRPC-Dienste und den Metrik-Listener mit demselben Bearer. Ein leeres Geheimnis wird nur für Loopback-Binds akzeptiert und lässt diese Listener unauthentifiziert. Ein Wildcard-Bind mit leerem Geheimnis verweigert den Start. Der Prozess beendet TLS nicht. -- `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. +- `memtable_size_bytes` und alle Raft-Zeitgeberfelder ändern das Laufzeitverhalten über TOML nicht. - `metadb-ctl bench` für `hotspot-create` und `bulk-ttl-delete` druckt JSON-Zeilen: einen Kopf mit `bench_pid`, dann Phasenberichte mit attempted, succeeded, failed und Latenzperzentilen. Der Prozess endet mit einem Fehler, wenn nicht jede angeforderte Operation gelingt. `--workload mixed` oder `--embedded` startet den prozessinternen Stress-Harness. `sql` druckt die Antwort als JSON und endet bei einem Anwendungsfehler mit einem Fehlerstatus. ## Dokumentationslücken diff --git a/docs/designs/correctness_hardening.md b/docs/designs/correctness_hardening.md index b2fd8f4..fdc4417 100644 --- a/docs/designs/correctness_hardening.md +++ b/docs/designs/correctness_hardening.md @@ -6,7 +6,7 @@ This change hardens acknowledged-write recovery, transaction migration, input va Recovery validates the entire unpurged committed log prefix, frame ordering and identity, and the durable vote/commit metadata before repairing files. Existing histories with missing `HARD_STATE` are rejected. A durable initialization marker also protects empty or fully purged stores from silently resetting their election identity. A fresh log has nothing to replay, so startup does not spend the recovery timeout before the first membership entry exists. -Snapshot installation requires a complete existing database image. It verifies required and duplicate filenames, the recovered checkpoint, LogId and membership, MANIFEST-to-SST metadata equality, and all data blocks before replacing live data. An empty or stale archive cannot create a new empty database and advance its advertised applied index. Snapshot publication syncs the temporary directory, renames it into place, and only then deletes the previous directory. A missing or unreadable snapshot directory is skipped. The segmented raft log is the write-ahead log only until it is purged. Before purge, a restart replays that log. After purge, the LSM is the remaining copy: the next snapshot read rewrites a missing snapshot from the LSM before returning. If that rebuild cannot cover the purged index, the error is `snapshot unrecoverable` and cluster status does not keep reporting the process as a live voter. Committed data is not reconstructed when the purged log, the snapshot file, and the LSM are all gone. +Snapshot installation requires a complete existing database image. It verifies required and duplicate filenames, the recovered checkpoint, LogId and membership, MANIFEST-to-SST metadata equality, and all data blocks before replacing live data. An empty or stale archive cannot create a new empty database and advance its advertised applied index. Snapshot publication syncs the temporary directory, renames it into place, and only then deletes the previous directory. A missing or unreadable snapshot directory is skipped. The segmented raft log is the write-ahead log only until it is purged. Before purge, a restart replays that log. After purge, the LSM is the remaining copy; there is no fourth command log. Startup and the maintenance tick rewrite a missing snapshot from the LSM before the process serves or advertises voters. If the flushed LSM cannot cover the purged index, open and cluster status fail closed with `snapshot unrecoverable`. A transient snapshot-publish I/O error does not latch that state. Committed data is not reconstructed when the purged log, the snapshot file, and the LSM are all gone. A state-machine operation lock serializes complete apply operations, checkpoint creation, snapshot replacement, and read-cut acquisition. This favors correctness and can pause writers while a snapshot is built. A later optimization should pin immutable state under a shorter lock and stream it without weakening the atomic checkpoint boundary. diff --git a/docs/en/architecture.md b/docs/en/architecture.md index ceee3fd..eb29e3a 100644 --- a/docs/en/architecture.md +++ b/docs/en/architecture.md @@ -95,7 +95,7 @@ Each local shard is an `openraft` 0.10 group. The log is a segmented CRC32C file | `max_in_snapshot_log_to_keep` | 0 | | log segment size | 64 MiB | -Log purge is gated by `min(state_flushed_index, aux_outbox_durable_index, last_snapshot_index)` and by the newest complete snapshot directory. The segmented log is the write-ahead log until that purge. A missing published snapshot is rewritten from the LSM on the next read. If the LSM cannot cover the purged prefix, the shard is `snapshot unrecoverable` and is not reported as a live voter. The 250 ms maintenance loop calls `flush_snapshot_and_purge` when a shard still retains log entries, unless a snapshot watermark is already at least `state_flushed_index` and fewer than 64 entries remain. An operator backup hold clamps that purge, and snapshot-directory deletion, until the hold is released or its wall-clock expiry passes. See [Operations](./operations.md#backup-and-restore). +Log purge is gated by `min(state_flushed_index, aux_outbox_durable_index, last_snapshot_index)` and by the newest complete snapshot directory. The segmented log is the write-ahead log until that purge. After purge, the LSM is the only remaining copy. Startup and the 250 ms maintenance tick rewrite a missing snapshot from the LSM. If the flushed LSM cannot cover the purged prefix, open fails closed and cluster status does not report a live voter. There is no fourth copy of the command log. The 250 ms maintenance loop calls `flush_snapshot_and_purge` when a shard still retains log entries, unless a snapshot watermark is already at least `state_flushed_index` and fewer than 64 entries remain. An operator backup hold clamps that purge, and snapshot-directory deletion, until the hold is released or its wall-clock expiry passes. See [Operations](./operations.md#backup-and-restore). `ConfChangeOrchestrator::add_learners_and_promote_voters` adds learners, waits until replication lag is at most 64 entries (default timeout 10 s, the value `scale_out_replicas` passes), then calls `change_membership`. The in-process test `test_online_1_to_3_voter_snapshot_promotion_and_leader_failover` does this with three tonic listeners and a basic KV state machine inside one OS process. It does not start `metadbd`. diff --git a/docs/fr/architecture.md b/docs/fr/architecture.md index 27395fd..eb7068e 100644 --- a/docs/fr/architecture.md +++ b/docs/fr/architecture.md @@ -82,7 +82,7 @@ La machine d'état de chaque shard ouvre un LSM sans WAL dans `/be/sha Les versions MVCC vivent en mémoire pendant `storage.mvcc_retention_ms` (défaut 5 000). Un vidage coordonné scelle le memtable, exécute le crochet d'agrégation d'attributs et écrit une SSTable L0. Il n'y a pas de WAL KV utilisateur séparé. La reprise après plantage est le journal Raft plus le manifeste LSM. `LocalityCompactor` suit les tombstones par seau de préfixe de 9 octets et compacte un intervalle de suppression chaud lorsque `locality_tombstone_threshold` et `locality_tombstone_ratio` sont tous deux franchis. `auto_locality_compaction` est toujours mis à `true` par `ServerTomlConfig::to_lsm_config` ; le fichier TOML ne peut pas le désactiver. -`storage.memtable_size_bytes` is the active memtable flush threshold. `storage.max_imm_memtables` (default 4) is the immutable-table backpressure cap: a writer waits until an immutable table flushes instead of queueing another one. +`storage.memtable_size_bytes` est désérialisé et jamais lu. La taille de vidage ne vient pas de ce champ. ## Raft diff --git a/docs/fr/configuration.md b/docs/fr/configuration.md index 30442b6..a5e7851 100644 --- a/docs/fr/configuration.md +++ b/docs/fr/configuration.md @@ -15,7 +15,7 @@ | `node.grpc_listen_addr` | `127.0.0.1:7800` | Oui. Adresse de liaison | | `node.metrics_listen_addr` | non défini | Oui, seulement s'il est défini. Écouteur TCP séparé. Une adresse non locale exige un secret non vide | | `clock.max_clock_drift_ms` | `500` | Oui. `HybridLogicalClock::with_max_drift_ms` | -| `storage.memtable_size_bytes` | `33554432` (32 MiB) | Yes. Seals and flushes the active memtable once its accounted bytes reach this size. Values below 1 are treated as 1 | +| `storage.memtable_size_bytes` | `33554432` (32 Mio) | **Non.** Le champ est stocké et jamais lu | | `storage.block_cache_bytes` | `67108864` (64 Mio) | Oui. Budget total du cache de blocs à 16 voies | | `storage.mvcc_retention_ms` | `5000` | Oui | | `storage.bloom_bits_per_key` | `10` | Oui | @@ -31,7 +31,7 @@ Il n'y a pas de table `[raft]`. `ServerTomlConfig.raft_options` est ignoré par ## Exemple -This file matches the defaults except for an explicit data directory, a metrics port, and a secret. `memtable_size_bytes` is the active memtable flush threshold. `max_imm_memtables` is the immutable-table backpressure cap. +Ce fichier correspond aux valeurs par défaut, sauf un répertoire de données explicite, un port de métriques et un secret. `memtable_size_bytes` est montré pour qu'une configuration copiée ne surprenne pas ; le modifier ne change pas le comportement de vidage. ```toml [node] diff --git a/docs/fr/operations.md b/docs/fr/operations.md index 9bc4304..cd1125c 100644 --- a/docs/fr/operations.md +++ b/docs/fr/operations.md @@ -137,7 +137,7 @@ Les variantes sont définies dans `crates/metadb-core/src/error.rs`. Les méthod - L'isolation jumbo est un indicateur de route plus un identifiant de nœud choisi dans la table locale. Elle n'évince pas d'autres shards d'un disque. - Les battements de cœur sont un RPC sans émetteur dans `metadbd`. `StoreHeartbeat` ne persiste pas. - Un secret partagé non vide authentifie Raft, les trois autres services gRPC et l'écouteur de métriques avec le même bearer. Un secret vide n'est accepté que pour les liaisons en boucle locale et laisse ces écouteurs non authentifiés. Une liaison joker avec un secret vide refuse de démarrer. Le processus ne termine pas 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. +- `memtable_size_bytes` et tous les champs de temporisation Raft ne changent pas le comportement d'exécution via le TOML. - `metadb-ctl bench` pour `hotspot-create` et `bulk-ttl-delete` imprime des lignes JSON : un en-tête avec `bench_pid`, puis des rapports de phase avec attempted, succeeded, failed et des percentiles de latence. Le processus se termine en erreur si une opération demandée échoue. `--workload mixed` ou `--embedded` lance le harnais de stress dans le processus. `sql` imprime la réponse en JSON et se termine en erreur sur une erreur d'application. ## Lacunes de documentation diff --git a/docs/ja/architecture.md b/docs/ja/architecture.md index 19776dc..cc7595c 100644 --- a/docs/ja/architecture.md +++ b/docs/ja/architecture.md @@ -82,7 +82,7 @@ MVCC の版は `storage.mvcc_retention_ms`(既定 5,000)のあいだメモリに留まります。協調フラッシュは memtable を封印し、属性集約フックを実行し、L0 SSTable を書きます。ユーザ KV 用の別 WAL はありません。クラッシュ回復は Raft ログと LSM マニフェストです。`LocalityCompactor` は 9 バイト接頭辞のバケットごとにトゥームストーンを追い、`locality_tombstone_threshold` と `locality_tombstone_ratio` の両方を超えたときにホットな削除範囲をコンパクトします。`ServerTomlConfig::to_lsm_config` は `auto_locality_compaction` を常に `true` にします。TOML では消せません。 -`storage.memtable_size_bytes` is the active memtable flush threshold. `storage.max_imm_memtables` (default 4) is the immutable-table backpressure cap: a writer waits until an immutable table flushes instead of queueing another one. +`storage.memtable_size_bytes` はデシリアライズされますが読まれません。フラッシュサイズはこの項目から取りません。 ## Raft diff --git a/docs/ja/configuration.md b/docs/ja/configuration.md index 3177b97..b9c1795 100644 --- a/docs/ja/configuration.md +++ b/docs/ja/configuration.md @@ -15,7 +15,7 @@ | `node.grpc_listen_addr` | `127.0.0.1:7800` | する。バインドアドレス | | `node.metrics_listen_addr` | 未設定 | 設定されたときだけする。別の TCP リスナー。ループバック以外は空でないシークレットが必要 | | `clock.max_clock_drift_ms` | `500` | する。`HybridLogicalClock::with_max_drift_ms` | -| `storage.memtable_size_bytes` | `33554432` (32 MiB) | Yes. Seals and flushes the active memtable once its accounted bytes reach this size. Values below 1 are treated as 1 | +| `storage.memtable_size_bytes` | `33554432`(32 MiB) | **しない。** フィールドは保持されるが読まれない | | `storage.block_cache_bytes` | `67108864`(64 MiB) | する。16 分割ブロックキャッシュの合計予算 | | `storage.mvcc_retention_ms` | `5000` | する | | `storage.bloom_bits_per_key` | `10` | する | @@ -31,7 +31,7 @@ ## 例 -This file matches the defaults except for an explicit data directory, a metrics port, and a secret. `memtable_size_bytes` is the active memtable flush threshold. `max_imm_memtables` is the immutable-table backpressure cap. +このファイルは、明示的なデータディレクトリ、メトリクスポート、シークレット以外は既定値です。`memtable_size_bytes` は、コピーした設定が驚かないように書いてあります。変えてもフラッシュの挙動は変わりません。 ```toml [node] diff --git a/docs/ja/operations.md b/docs/ja/operations.md index 6124043..34cd004 100644 --- a/docs/ja/operations.md +++ b/docs/ja/operations.md @@ -137,7 +137,7 @@ metadb-ctl --endpoint 127.0.0.1:7800 sql \ - ジャンボ隔離はルートフラグと、ローカルノード表から選んだノード ID である。他のシャードをディスクから追い出すことはしない。 - ハートビートは RPC であり、`metadbd` に送信側はない。`StoreHeartbeat` は永続化しない。 - 空でない共有シークレットは、Raft、他の 3 つの gRPC サービス、およびメトリクスリスナーを同じベアラで認証する。空のシークレットはループバックのバインドだけを受け付け、それらのリスナーは無認証のままである。空のシークレットでのワイルドカードバインドは起動を拒否する。プロセスは 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. +- `memtable_size_bytes` とすべての Raft タイマ項目は、TOML 経由で実行時の挙動を変えない。 - `hotspot-create` と `bulk-ttl-delete` の `metadb-ctl bench` は JSON 行を印字する。`bench_pid` を含むヘッダのあと、attempted、succeeded、failed とレイテンシのパーセンタイルを持つフェーズ報告が続く。要求した操作がすべて成功しない限り、プロセスは非ゼロで終了する。`--workload mixed` または `--embedded` はプロセス内のストレステストを実行する。`sql` は応答を JSON で印字し、アプリケーションエラーでは非ゼロで終了する。 ## 文書化できない欠落 diff --git a/docs/zh/architecture.md b/docs/zh/architecture.md index 9473a66..b81add0 100644 --- a/docs/zh/architecture.md +++ b/docs/zh/architecture.md @@ -82,7 +82,7 @@ MVCC 版本在内存中保留 `storage.mvcc_retention_ms`(默认 5,000)。协调刷盘封印 memtable,运行属性聚合钩子,并写出 L0 SSTable。没有单独的用户 KV WAL。崩溃恢复靠 Raft 日志加上 LSM 清单。`LocalityCompactor` 按 9 字节前缀桶跟踪墓碑,并在 `locality_tombstone_threshold` 与 `locality_tombstone_ratio` 同时越过时压缩热点删除范围。`ServerTomlConfig::to_lsm_config` 总是把 `auto_locality_compaction` 设为 `true`;TOML 文件不能关掉它。 -`storage.memtable_size_bytes` is the active memtable flush threshold. `storage.max_imm_memtables` (default 4) is the immutable-table backpressure cap: a writer waits until an immutable table flushes instead of queueing another one. +`storage.memtable_size_bytes` 会被反序列化,但从不读取。刷盘大小不取自该字段。 ## Raft diff --git a/docs/zh/configuration.md b/docs/zh/configuration.md index 339c1eb..6f19bae 100644 --- a/docs/zh/configuration.md +++ b/docs/zh/configuration.md @@ -15,7 +15,7 @@ | `node.grpc_listen_addr` | `127.0.0.1:7800` | 是。绑定地址 | | `node.metrics_listen_addr` | 未设置 | 仅在设置时应用。单独的 TCP 监听器。非环回地址要求非空密钥 | | `clock.max_clock_drift_ms` | `500` | 是。`HybridLogicalClock::with_max_drift_ms` | -| `storage.memtable_size_bytes` | `33554432` (32 MiB) | Yes. Seals and flushes the active memtable once its accounted bytes reach this size. Values below 1 are treated as 1 | +| `storage.memtable_size_bytes` | `33554432`(32 MiB) | **否。** 字段被保存,从不读取 | | `storage.block_cache_bytes` | `67108864`(64 MiB) | 是。16 路块缓存的总预算 | | `storage.mvcc_retention_ms` | `5000` | 是 | | `storage.bloom_bits_per_key` | `10` | 是 | @@ -31,7 +31,7 @@ ## 示例 -This file matches the defaults except for an explicit data directory, a metrics port, and a secret. `memtable_size_bytes` is the active memtable flush threshold. `max_imm_memtables` is the immutable-table backpressure cap. +除了明确的数据目录、指标端口和密钥,这个文件与默认值一致。写出 `memtable_size_bytes` 是为了避免抄来的配置让人意外;改它不会改变刷盘行为。 ```toml [node] diff --git a/docs/zh/operations.md b/docs/zh/operations.md index 43ce3bf..c563cf1 100644 --- a/docs/zh/operations.md +++ b/docs/zh/operations.md @@ -137,7 +137,7 @@ metadb-ctl --endpoint 127.0.0.1:7800 sql \ - 巨型隔离是路由标志加上从本地节点表选出的节点标识。它不会把其他分片从磁盘上赶走。 - 心跳是一个 RPC,`metadbd` 里没有发送方。`StoreHeartbeat` 不持久化。 - 非空共享密钥用同一个持有者令牌认证 Raft、另外三个 gRPC 服务和指标监听器。空密钥只接受环回绑定,这些监听器不认证。通配绑定加上空密钥会拒绝启动。进程不终结 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. +- `memtable_size_bytes` 和所有 Raft 计时字段不会通过 TOML 改变运行行为。 - `hotspot-create` 和 `bulk-ttl-delete` 的 `metadb-ctl bench` 打印 JSON 行:先是带 `bench_pid` 的头,然后是包含 attempted、succeeded、failed 和延迟分位数的阶段报告。只要有一次请求的操作失败,进程就以非零状态退出。`--workload mixed` 或 `--embedded` 运行进程内的压力工具。`sql` 把响应打印成 JSON,遇到应用错误时以非零状态退出。 ## 文档缺口