feat(meta-srv): check pending WAL tails before a repartition starts (#10504)

* feat(meta-srv): check pending WAL tails of source regions before a repartition starts

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* test(common-meta): freeze the region statistic encodings before the pending tails flag

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* fix(meta-srv): clarify the repartition pending tails errors and pin the flag encoding

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* fix(meta-srv): retry repartitions over pending WAL tails and pass sources without a report

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* docs(meta-srv): note the retained leader report in the repartition pre-check

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* fix(meta-srv): report pending repartition tails as region not ready and share is_false

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

* style(meta-srv): order the repartition pre-check test imports

Signed-off-by: jeremyhi <fengjiachun@gmail.com>

---------

Signed-off-by: jeremyhi <fengjiachun@gmail.com>
This commit is contained in:
jeremyhi
2026-11-20 05:16:35 +00:00
committed by GitHub
parent 1ba656e345
commit 5dec7b1986
24 changed files with 325 additions and 12 deletions
+51
View File
@@ -130,6 +130,10 @@ pub struct RegionStat {
/// The latest timestamp of the region's current data, if it holds any.
#[serde(default)]
pub max_timestamp: Option<Timestamp>,
/// Whether the region still has WAL ranges to recover. Omitted from the serialized form
/// when false.
#[serde(default, skip_serializing_if = "store_api::is_false")]
pub has_pending_tails: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -347,6 +351,7 @@ impl From<&api::v1::meta::RegionStat> for RegionStat {
metadata_topic_latest_entry_id: region_stat.metadata_topic_latest_entry_id,
min_timestamp: region_stat.min_timestamp,
max_timestamp: region_stat.max_timestamp,
has_pending_tails: region_stat.has_pending_tails,
}
}
}
@@ -612,6 +617,7 @@ mod tests {
metadata_topic_latest_entry_id: 0,
min_timestamp: None,
max_timestamp: None,
has_pending_tails: false,
}],
..Default::default()
};
@@ -782,6 +788,51 @@ mod tests {
);
}
#[test]
fn test_has_pending_tails_wire() {
// Frozen encodings of a release without the field.
let legacy_statistic: &[u8] = include_bytes!(
"../../../../tests/compatibility/wire/region_statistic_pending_tails/legacy_region_statistic.json"
);
let legacy_stat: &[u8] = include_bytes!(
"../../../../tests/compatibility/wire/region_statistic_pending_tails/legacy_region_stat.json"
);
let statistic: RegionStatistic = serde_json::from_slice(legacy_statistic).unwrap();
assert!(!statistic.has_pending_tails);
// A false flag is not written, so the encoding stays as it was.
assert_eq!(serde_json::to_vec(&statistic).unwrap(), legacy_statistic);
let stat: RegionStat = serde_json::from_slice(legacy_stat).unwrap();
assert!(!stat.has_pending_tails);
assert_eq!(serde_json::to_vec(&stat).unwrap(), legacy_stat);
// A true flag is written under this key, which readers that support the flag decode;
// older readers ignore it.
let statistic = RegionStatistic {
has_pending_tails: true,
..statistic
};
let encoded = serde_json::to_value(&statistic).unwrap();
assert_eq!(encoded["has_pending_tails"], serde_json::Value::Bool(true));
let encoded = serde_json::to_value(RegionStat {
has_pending_tails: true,
..stat
})
.unwrap();
assert_eq!(encoded["has_pending_tails"], serde_json::Value::Bool(true));
// A true flag travels from the heartbeat extension to the stored statistic.
let mut region = api::v1::meta::RegionStat::default();
region.extensions.insert(
REGION_STATISTIC_KEY.to_string(),
serde_json::to_vec(&statistic).unwrap(),
);
let stat = RegionStat::from(&region);
assert!(stat.has_pending_tails);
let stored: RegionStat =
serde_json::from_slice(&serde_json::to_vec(&stat).unwrap()).unwrap();
assert_eq!(stored, stat);
}
#[test]
fn test_env_vars_round_trip() {
let mut vars = HashMap::new();
+2
View File
@@ -28,6 +28,8 @@ use crate::datanode::{RegionManifestInfo, RegionStat};
pub struct LeaderRegion {
pub datanode_id: u64,
pub manifest: LeaderRegionManifestInfo,
/// Whether the region still had WAL ranges to recover when it last reported.
pub has_pending_tails: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+12
View File
@@ -1082,6 +1082,16 @@ pub enum Error {
source: common_meta::error::Error,
},
#[snafu(display(
"Repartition cannot start while regions {:?} have pending WAL tails; wait for their replay to finish",
region_ids
))]
RepartitionPendingTails {
region_ids: Vec<RegionId>,
#[snafu(implicit)]
location: Location,
},
#[snafu(display(
"Repartition group {} source region missing, region id: {}",
group_id,
@@ -1236,6 +1246,7 @@ impl ErrorExt for Error {
| Error::PeerUnavailable { .. }
| Error::PusherNotFound { .. } => StatusCode::Unexpected,
Error::MailboxTimeout { .. } | Error::ExceededDeadline { .. } => StatusCode::Cancelled,
Error::RepartitionPendingTails { .. } => StatusCode::RegionNotReady,
Error::PruneTaskAlreadyRunning { .. }
| Error::DrainDatanodeRunning { .. }
| Error::RetryLater { .. }
@@ -1370,6 +1381,7 @@ impl ErrorExt for Error {
match self {
Error::RetryLater { .. }
| Error::RetryLaterWithSource { .. }
| Error::RepartitionPendingTails { .. }
| Error::MailboxTimeout { .. }
| Error::NoEnoughAvailableNode { .. }
| Error::NoLeader { .. }
+1
View File
@@ -502,5 +502,6 @@ fn dropped_region_stat(region_id: RegionId) -> RegionStat {
metadata_topic_latest_entry_id: 0,
min_timestamp: None,
max_timestamp: None,
has_pending_tails: false,
}
}
+1
View File
@@ -456,5 +456,6 @@ fn mock_region_stat(
ingested_parquet_bytes: 0,
query_cpu_time: 0,
query_scanned_bytes: 0,
has_pending_tails: false,
}
}
@@ -48,6 +48,7 @@ impl HeartbeatHandler for CollectLeaderRegionHandler {
let value = LeaderRegion {
datanode_id: current_stat.id,
manifest,
has_pending_tails: stat.has_pending_tails,
};
key_values.push((stat.id, value));
}
@@ -94,6 +95,7 @@ mod tests {
ingested_parquet_bytes: 0,
query_cpu_time: 0,
query_scanned_bytes: 0,
has_pending_tails: false,
}
}
@@ -106,7 +108,10 @@ mod tests {
stat: Some(Stat {
id: 1,
region_stats: vec![
new_region_stat(RegionId::new(1, 1), 1, RegionRole::Leader),
RegionStat {
has_pending_tails: true,
..new_region_stat(RegionId::new(1, 1), 1, RegionRole::Leader)
},
new_region_stat(RegionId::new(1, 2), 2, RegionRole::Follower),
],
addr: "127.0.0.1:0000".to_string(),
@@ -136,6 +141,7 @@ mod tests {
flushed_entry_id: 0,
topic_latest_entry_id: 0,
},
has_pending_tails: true,
})
);
@@ -168,6 +174,7 @@ mod tests {
flushed_entry_id: 0,
topic_latest_entry_id: 0,
},
has_pending_tails: false,
})
);
@@ -201,6 +208,7 @@ mod tests {
flushed_entry_id: 0,
topic_latest_entry_id: 0,
},
has_pending_tails: false,
})
);
}
@@ -111,6 +111,7 @@ mod tests {
query_scanned_bytes: 0,
min_timestamp: None,
max_timestamp: None,
has_pending_tails: false,
}
}
@@ -305,6 +305,7 @@ mod tests {
metadata_topic_latest_entry_id: 200,
min_timestamp: None,
max_timestamp: None,
has_pending_tails: false,
}
}
@@ -204,6 +204,7 @@ mod test {
query_scanned_bytes: 0,
min_timestamp: None,
max_timestamp: None,
has_pending_tails: false,
}
}
@@ -200,6 +200,7 @@ impl State for RepartitionStart {
if plans.is_empty() {
return Ok((Box::new(RepartitionEnd), Status::done()));
}
Self::ensure_no_pending_tails(ctx, &plans)?;
if ctx.persistent_ctx.partition_metadata_update.is_some() {
Ok((
@@ -220,6 +221,34 @@ impl State for RepartitionStart {
}
impl RepartitionStart {
/// Fails with a retryable error before any region is allocated or rerouted if a source
/// region of `plans` still had pending WAL tails when it last reported as leader, since
/// entering staging would then fail after the route change. Targets are the sources or new
/// regions, so only sources are checked. A source without a leader report to this metasrv
/// passes, and entering staging still refuses its pending tails. Registry entries are not
/// expired, so after a datanode restart the check uses the flag of the last report until
/// the reopened region reports as leader again.
fn ensure_no_pending_tails(ctx: &Context, plans: &[AllocationPlanEntry]) -> Result<()> {
let region_ids = plans
.iter()
.flat_map(|plan| plan.source_regions.iter().map(|source| source.region_id()));
let mut pending = ctx
.leader_region_registry
.batch_get(region_ids)
.into_iter()
.filter(|(_, leader)| leader.has_pending_tails)
.map(|(region_id, _)| region_id)
.collect::<Vec<_>>();
pending.sort_unstable();
ensure!(
pending.is_empty(),
error::RepartitionPendingTailsSnafu {
region_ids: pending
}
);
Ok(())
}
async fn prepare_from<'a>(&'a self, ctx: &mut Context) -> Result<&'a [PartitionExpr]> {
match &self.from {
RepartitionFrom::Partitioned {
@@ -474,6 +503,8 @@ impl RepartitionStart {
mod tests {
use std::sync::Arc;
use common_error::ext::ErrorExt;
use common_error::status_code::StatusCode;
use common_meta::ddl::test_util::datanode_handler::NaiveDatanodeHandler;
use common_meta::key::table_route::PhysicalTableRouteValue;
use common_meta::peer::Peer;
@@ -485,7 +516,8 @@ mod tests {
use super::*;
use crate::procedure::repartition::test_util::{
TestingEnv, new_parent_context, range_expr, test_region_route, test_region_wal_options,
TestingEnv, new_parent_context, range_expr, report_leader_regions, test_region_route,
test_region_wal_options,
};
fn physical_route(region_routes: Vec<RegionRoute>) -> PhysicalTableRouteValue {
@@ -878,4 +910,75 @@ mod tests {
);
assert!(ctx.persistent_ctx.partition_metadata_update.is_none());
}
/// Creates a table of regions 1 and 2 and a repartition that merges them.
async fn new_merge(env: &TestingEnv, table_id: u32) -> (Context, RepartitionStart) {
env.create_physical_table_metadata_for_repartition(
table_id,
vec![
test_region_route(
RegionId::new(table_id, 1),
&range_expr("x", 0, 50).as_json_str().unwrap(),
),
test_region_route(
RegionId::new(table_id, 2),
&range_expr("x", 50, 100).as_json_str().unwrap(),
),
],
test_region_wal_options(&[1, 2]),
)
.await;
let node_manager = Arc::new(MockDatanodeManager::new(NaiveDatanodeHandler));
let ctx = new_parent_context(env, node_manager, table_id);
let state = RepartitionStart::new(
RepartitionFrom::Partitioned {
exprs: vec![range_expr("x", 0, 50), range_expr("x", 50, 100)],
target_partition_columns: None,
},
vec![range_expr("x", 0, 100)],
);
(ctx, state)
}
#[tokio::test]
async fn test_repartition_start_retries_source_with_pending_tails() {
let env = TestingEnv::new();
let table_id = 1024;
let (mut ctx, mut state) = new_merge(&env, table_id).await;
report_leader_regions(&ctx, &[RegionId::new(table_id, 1)], false);
report_leader_regions(&ctx, &[RegionId::new(table_id, 2)], true);
let err = state
.next(&mut ctx, &TestingEnv::procedure_context())
.await
.unwrap_err();
assert!(err.is_retryable());
assert_eq!(StatusCode::RegionNotReady, err.status_code());
assert!(matches!(
&err,
error::Error::RepartitionPendingTails { region_ids, .. }
if region_ids == &[RegionId::new(table_id, 2)]
));
report_leader_regions(&ctx, &[RegionId::new(table_id, 2)], false);
let (next, _) = state
.next(&mut ctx, &TestingEnv::procedure_context())
.await
.unwrap();
assert!(next.as_any().is::<AllocateRegion>());
}
#[tokio::test]
async fn test_repartition_start_passes_unreported_source() {
let env = TestingEnv::new();
let table_id = 1024;
let (mut ctx, mut state) = new_merge(&env, table_id).await;
report_leader_regions(&ctx, &[RegionId::new(table_id, 1)], false);
let (next, _) = state
.next(&mut ctx, &TestingEnv::procedure_context())
.await
.unwrap();
assert!(next.as_any().is::<AllocateRegion>());
}
}
@@ -44,7 +44,7 @@ use crate::procedure::repartition::plan::{SourceRegionDescriptor, TargetRegionDe
use crate::procedure::repartition::{
Context as ParentContext, PersistentContext as ParentPersistentContext, RepartitionProcedure,
};
use crate::procedure::test_util::MailboxContext;
use crate::procedure::test_util::{MailboxContext, new_leader_region};
/// `TestingEnv` provides components during the tests.
pub struct TestingEnv {
@@ -232,6 +232,20 @@ pub fn new_parent_context(
)
}
/// Records `region_ids` as leader regions that reported to this metasrv, with
/// `has_pending_tails`, as their heartbeats do.
pub fn report_leader_regions(
ctx: &ParentContext,
region_ids: &[RegionId],
has_pending_tails: bool,
) {
let leaders = region_ids
.iter()
.map(|region_id| (*region_id, new_leader_region(0, has_pending_tails)))
.collect();
ctx.leader_region_registry.batch_put(leaders);
}
pub fn assert_parent_state<T: 'static>(procedure: &RepartitionProcedure) {
assert!(procedure.state.as_any().is::<T>());
}
+14 -9
View File
@@ -415,21 +415,26 @@ pub async fn new_wal_prune_metadata(
min_prunable_entry_id
}
/// Returns a mito leader region as datanode 1 reports it.
pub fn new_leader_region(flushed_entry_id: u64, has_pending_tails: bool) -> LeaderRegion {
LeaderRegion {
datanode_id: 1,
manifest: LeaderRegionManifestInfo::Mito {
manifest_version: 0,
flushed_entry_id,
topic_latest_entry_id: 0,
},
has_pending_tails,
}
}
pub async fn update_in_memory_region_flushed_entry_id(
leader_region_registry: &LeaderRegionRegistryRef,
region_entry_ids: HashMap<RegionId, u64>,
) -> Result<()> {
let mut key_values = Vec::with_capacity(region_entry_ids.len());
for (region_id, flushed_entry_id) in region_entry_ids {
let value = LeaderRegion {
datanode_id: 1,
manifest: LeaderRegionManifestInfo::Mito {
manifest_version: 0,
flushed_entry_id,
topic_latest_entry_id: 0,
},
};
key_values.push((region_id, value));
key_values.push((region_id, new_leader_region(flushed_entry_id, false)));
}
leader_region_registry.batch_put(key_values);
+2
View File
@@ -912,6 +912,7 @@ mod tests {
metadata_flushed_entry_id: metadata_replay_entry_id,
metadata_topic_latest_entry_id: 0,
},
has_pending_tails: false,
}
}
@@ -923,6 +924,7 @@ mod tests {
flushed_entry_id: replay_entry_id,
topic_latest_entry_id: 0,
},
has_pending_tails: false,
}
}
@@ -205,6 +205,7 @@ mod tests {
query_scanned_bytes: 0,
min_timestamp: None,
max_timestamp: None,
has_pending_tails: false,
}],
..Default::default()
}
@@ -240,6 +241,7 @@ mod tests {
query_scanned_bytes: 0,
min_timestamp: None,
max_timestamp: None,
has_pending_tails: false,
}],
..Default::default()
}
@@ -275,6 +277,7 @@ mod tests {
query_scanned_bytes: 0,
min_timestamp: None,
max_timestamp: None,
has_pending_tails: false,
}],
..Default::default()
}
+21
View File
@@ -90,6 +90,9 @@ fn merge_region_statistic(
// pin every metric region's minimum to the epoch.
min_timestamp: data_stat.min_timestamp,
max_timestamp: data_stat.max_timestamp,
// A repartition flushes the metadata region too, and that flush refuses pending
// tails, so the metadata region's tails count as well.
has_pending_tails: metadata_stat.has_pending_tails || data_stat.has_pending_tails,
}
}
@@ -168,6 +171,24 @@ mod tests {
);
}
#[test]
fn merge_region_statistic_has_pending_tails_of_either_region() {
for (metadata, data) in [(false, false), (true, false), (false, true), (true, true)] {
let metadata_stat = RegionStatistic {
has_pending_tails: metadata,
..Default::default()
};
let data_stat = RegionStatistic {
has_pending_tails: data,
..Default::default()
};
assert_eq!(
merge_region_statistic(&metadata_stat, &data_stat).has_pending_tails,
metadata || data
);
}
}
#[test]
fn merge_region_statistic_ignores_metadata_timestamps() {
// Metadata rows are written at timestamp 0; folding them in would report
+16
View File
@@ -2566,3 +2566,19 @@ async fn test_discard_reopens_after_crash_with_history_past_bound(
assert!(error.contains("does not hold the history"), "{error}");
}
}
#[tokio::test]
async fn test_region_statistic_reports_pending_tails() {
let region = TestRegion::new("tail-replay-statistic", false, None).await;
region
.reopen_with_tails(vec![own_tail(0, region.entries[1], UptoKind::Reported)])
.await;
let statistic = region.engine.region_statistic(region.region_id).unwrap();
assert!(statistic.has_pending_tails);
region.promote();
region.wait_until_replayed().await;
let statistic = region.engine.region_statistic(region.region_id).unwrap();
assert!(!statistic.has_pending_tails);
}
+1
View File
@@ -896,6 +896,7 @@ impl MitoRegion {
query_scanned_bytes,
min_timestamp: time_range.map(|(min, _)| min),
max_timestamp: time_range.map(|(_, max)| max),
has_pending_tails: version.has_pending_tails(),
}
}
@@ -143,6 +143,7 @@ impl InformationExtension for StandaloneInformationExtension {
query_scanned_bytes: region_stat.query_scanned_bytes,
min_timestamp: region_stat.min_timestamp,
max_timestamp: region_stat.max_timestamp,
has_pending_tails: region_stat.has_pending_tails,
}
})
.collect::<Vec<_>>();
+5
View File
@@ -33,3 +33,8 @@ pub mod storage;
pub type ManifestVersion = u64;
pub const MIN_VERSION: u64 = 0;
pub const MAX_VERSION: u64 = u64::MAX;
/// Returns whether `value` is false, for `skip_serializing_if` on a flag that defaults to false.
pub fn is_false(value: &bool) -> bool {
!*value
}
+4
View File
@@ -858,6 +858,10 @@ pub struct RegionStatistic {
pub data_topic_latest_entry_id: u64,
#[serde(default)]
pub metadata_topic_latest_entry_id: u64,
/// Whether the region still has WAL ranges to recover. Omitted from the serialized form
/// when false.
#[serde(default, skip_serializing_if = "crate::is_false")]
pub has_pending_tails: bool,
}
/// The manifest info of a region.
+7
View File
@@ -50,6 +50,13 @@ a region request discarding pending WAL tails stays at body field 24:
cargo nextest run -p store-api -E 'test(test_discard_pending_tails_request_wire)'
```
The [region statistic fixtures](wire/region_statistic_pending_tails/README.md) check that a
region statistic without pending tails decodes and encodes as before the flag existed:
```shell
cargo nextest run -p common-meta -E 'test(test_has_pending_tails_wire)'
```
## Object store WAL fixtures
Frozen objects of the object store WAL are checked byte for byte by the format tests of
@@ -0,0 +1,51 @@
# Region statistic compatibility
Two JSON fixtures written by the serializers at GreptimeDB commit
`48aa0ed3ae151f2a436b2a5295ce8cd10ece5a9d`, before the `has_pending_tails` field:
- `legacy_region_statistic.json`: a `store_api::region_engine::RegionStatistic`, as a datanode
puts it into the `__region_statistic` extension of a heartbeat region stat.
SHA-256: `e46a90c4596e38a3253c7d70c8878c1a101f111b79457f7b48b39a1561cfe6a5`.
- `legacy_region_stat.json`: the `common_meta::datanode::RegionStat` the metasrv derives from
that heartbeat region stat and stores in `DatanodeStatValue`.
SHA-256: `8ae052b52653cf3e20b7e5c8085846fb027e3daaaf506f610fd363d4cf24dfb4`.
Logical contents: region `4398046511105` (table `1024`, region number `1`), engine `mito`,
3 rows, a 1024-byte memtable, one 2048-byte SST, manifest version 5, flushed entry id 7.
Run the regression:
```shell
cargo nextest run -p common-meta -E 'test(test_has_pending_tails_wire)'
```
The test checks that both fixtures decode without pending tails and encode back to exactly the
same bytes, so a statistic without pending tails keeps the encoding of a release without the
field, and that a true flag travels from the heartbeat extension to the stored statistic.
## Reproduce the fixtures
At the commit above, run this in a test of `common_meta::datanode`:
```rust
let statistic = RegionStatistic {
num_rows: 3,
memtable_size: 1024,
sst_size: 2048,
sst_num: 1,
manifest: store_api::region_engine::RegionManifestInfo::mito(5, 7, 0),
..Default::default()
};
let statistic_json = serde_json::to_vec(&statistic).unwrap();
let mut region = api::v1::meta::RegionStat {
region_id: RegionId::new(1024, 1).as_u64(),
engine: "mito".to_string(),
..Default::default()
};
region
.extensions
.insert(REGION_STATISTIC_KEY.to_string(), statistic_json.clone());
std::fs::write("legacy_region_statistic.json", statistic_json).unwrap();
let stat = RegionStat::from(&region);
std::fs::write("legacy_region_stat.json", serde_json::to_vec(&stat).unwrap()).unwrap();
```
@@ -0,0 +1 @@
{"id":4398046511105,"rcus":0,"wcus":0,"approximate_bytes":0,"engine":"mito","role":"Leader","num_rows":3,"memtable_size":1024,"manifest_size":0,"sst_size":2048,"sst_num":1,"index_size":0,"region_manifest":{"Mito":{"manifest_version":5,"flushed_entry_id":7,"file_removed_cnt":0}},"written_bytes":0,"ingested_parquet_bytes":0,"query_cpu_time":0,"query_scanned_bytes":0,"data_topic_latest_entry_id":0,"metadata_topic_latest_entry_id":0,"min_timestamp":null,"max_timestamp":null}
@@ -0,0 +1 @@
{"num_rows":3,"memtable_size":1024,"wal_size":0,"manifest_size":0,"sst_size":2048,"sst_num":1,"index_size":0,"manifest":{"Mito":{"manifest_version":5,"flushed_entry_id":7,"file_removed_cnt":0}},"written_bytes":0,"ingested_parquet_bytes":0,"query_cpu_time":0,"query_scanned_bytes":0,"min_timestamp":null,"max_timestamp":null,"data_topic_latest_entry_id":0,"metadata_topic_latest_entry_id":0}