From 5dec7b1986e4552d132e8120d9e907475a7cb98a Mon Sep 17 00:00:00 2001 From: jeremyhi Date: Fri, 20 Nov 2026 05:16:35 +0000 Subject: [PATCH] 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 * test(common-meta): freeze the region statistic encodings before the pending tails flag Signed-off-by: jeremyhi * fix(meta-srv): clarify the repartition pending tails errors and pin the flag encoding Signed-off-by: jeremyhi * fix(meta-srv): retry repartitions over pending WAL tails and pass sources without a report Signed-off-by: jeremyhi * docs(meta-srv): note the retained leader report in the repartition pre-check Signed-off-by: jeremyhi * fix(meta-srv): report pending repartition tails as region not ready and share is_false Signed-off-by: jeremyhi * style(meta-srv): order the repartition pre-check test imports Signed-off-by: jeremyhi --------- Signed-off-by: jeremyhi --- src/common/meta/src/datanode.rs | 51 +++++++++ src/common/meta/src/region_registry.rs | 2 + src/meta-srv/src/error.rs | 12 ++ src/meta-srv/src/gc/handler.rs | 1 + src/meta-srv/src/gc/mock.rs | 1 + .../handler/collect_leader_region_handler.rs | 10 +- src/meta-srv/src/handler/failure_handler.rs | 1 + .../src/handler/persist_stats_handler.rs | 1 + .../src/handler/region_lease_handler.rs | 1 + .../repartition/repartition_start.rs | 105 +++++++++++++++++- .../src/procedure/repartition/test_util.rs | 16 ++- src/meta-srv/src/procedure/test_util.rs | 23 ++-- src/meta-srv/src/region/flush_trigger.rs | 2 + src/meta-srv/src/selector/weight_compute.rs | 3 + src/metric-engine/src/utils.rs | 21 ++++ src/mito2/src/engine/tail_replay_test.rs | 16 +++ src/mito2/src/region.rs | 1 + src/standalone/src/information_extension.rs | 1 + src/store-api/src/lib.rs | 5 + src/store-api/src/region_engine.rs | 4 + tests/compatibility/README.md | 7 ++ .../region_statistic_pending_tails/README.md | 51 +++++++++ .../legacy_region_stat.json | 1 + .../legacy_region_statistic.json | 1 + 24 files changed, 325 insertions(+), 12 deletions(-) create mode 100644 tests/compatibility/wire/region_statistic_pending_tails/README.md create mode 100644 tests/compatibility/wire/region_statistic_pending_tails/legacy_region_stat.json create mode 100644 tests/compatibility/wire/region_statistic_pending_tails/legacy_region_statistic.json diff --git a/src/common/meta/src/datanode.rs b/src/common/meta/src/datanode.rs index ba4250238d7..b2c01629051 100644 --- a/src/common/meta/src/datanode.rs +++ b/src/common/meta/src/datanode.rs @@ -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, + /// 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(®ion); + 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(); diff --git a/src/common/meta/src/region_registry.rs b/src/common/meta/src/region_registry.rs index 8bef3f2d385..e4e2b4f755b 100644 --- a/src/common/meta/src/region_registry.rs +++ b/src/common/meta/src/region_registry.rs @@ -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)] diff --git a/src/meta-srv/src/error.rs b/src/meta-srv/src/error.rs index 692f440a5c5..6ab4b936cf8 100644 --- a/src/meta-srv/src/error.rs +++ b/src/meta-srv/src/error.rs @@ -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, + #[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 { .. } diff --git a/src/meta-srv/src/gc/handler.rs b/src/meta-srv/src/gc/handler.rs index ffcfa387c21..ed82095f0e0 100644 --- a/src/meta-srv/src/gc/handler.rs +++ b/src/meta-srv/src/gc/handler.rs @@ -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, } } diff --git a/src/meta-srv/src/gc/mock.rs b/src/meta-srv/src/gc/mock.rs index 04e70e8d3a7..64977980201 100644 --- a/src/meta-srv/src/gc/mock.rs +++ b/src/meta-srv/src/gc/mock.rs @@ -456,5 +456,6 @@ fn mock_region_stat( ingested_parquet_bytes: 0, query_cpu_time: 0, query_scanned_bytes: 0, + has_pending_tails: false, } } diff --git a/src/meta-srv/src/handler/collect_leader_region_handler.rs b/src/meta-srv/src/handler/collect_leader_region_handler.rs index 3ec3d8c69ca..1015ecc4300 100644 --- a/src/meta-srv/src/handler/collect_leader_region_handler.rs +++ b/src/meta-srv/src/handler/collect_leader_region_handler.rs @@ -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, }) ); } diff --git a/src/meta-srv/src/handler/failure_handler.rs b/src/meta-srv/src/handler/failure_handler.rs index 35c1d324e3c..05bdaba5257 100644 --- a/src/meta-srv/src/handler/failure_handler.rs +++ b/src/meta-srv/src/handler/failure_handler.rs @@ -111,6 +111,7 @@ mod tests { query_scanned_bytes: 0, min_timestamp: None, max_timestamp: None, + has_pending_tails: false, } } diff --git a/src/meta-srv/src/handler/persist_stats_handler.rs b/src/meta-srv/src/handler/persist_stats_handler.rs index f3d7c43452d..b0ecb5dd3cc 100644 --- a/src/meta-srv/src/handler/persist_stats_handler.rs +++ b/src/meta-srv/src/handler/persist_stats_handler.rs @@ -305,6 +305,7 @@ mod tests { metadata_topic_latest_entry_id: 200, min_timestamp: None, max_timestamp: None, + has_pending_tails: false, } } diff --git a/src/meta-srv/src/handler/region_lease_handler.rs b/src/meta-srv/src/handler/region_lease_handler.rs index 4f27b8f48e7..45351d41e2b 100644 --- a/src/meta-srv/src/handler/region_lease_handler.rs +++ b/src/meta-srv/src/handler/region_lease_handler.rs @@ -204,6 +204,7 @@ mod test { query_scanned_bytes: 0, min_timestamp: None, max_timestamp: None, + has_pending_tails: false, } } diff --git a/src/meta-srv/src/procedure/repartition/repartition_start.rs b/src/meta-srv/src/procedure/repartition/repartition_start.rs index 48ac603e684..c6438d6d869 100644 --- a/src/meta-srv/src/procedure/repartition/repartition_start.rs +++ b/src/meta-srv/src/procedure/repartition/repartition_start.rs @@ -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::>(); + 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) -> 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::()); + } + + #[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::()); + } } diff --git a/src/meta-srv/src/procedure/repartition/test_util.rs b/src/meta-srv/src/procedure/repartition/test_util.rs index 1fe3553286e..3bb7dfd72c2 100644 --- a/src/meta-srv/src/procedure/repartition/test_util.rs +++ b/src/meta-srv/src/procedure/repartition/test_util.rs @@ -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(procedure: &RepartitionProcedure) { assert!(procedure.state.as_any().is::()); } diff --git a/src/meta-srv/src/procedure/test_util.rs b/src/meta-srv/src/procedure/test_util.rs index 20b86bfc2d9..c75617e0727 100644 --- a/src/meta-srv/src/procedure/test_util.rs +++ b/src/meta-srv/src/procedure/test_util.rs @@ -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, ) -> 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); diff --git a/src/meta-srv/src/region/flush_trigger.rs b/src/meta-srv/src/region/flush_trigger.rs index 24d2d6d19d2..c3160933e5d 100644 --- a/src/meta-srv/src/region/flush_trigger.rs +++ b/src/meta-srv/src/region/flush_trigger.rs @@ -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, } } diff --git a/src/meta-srv/src/selector/weight_compute.rs b/src/meta-srv/src/selector/weight_compute.rs index eda2a0357ad..2f158512936 100644 --- a/src/meta-srv/src/selector/weight_compute.rs +++ b/src/meta-srv/src/selector/weight_compute.rs @@ -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() } diff --git a/src/metric-engine/src/utils.rs b/src/metric-engine/src/utils.rs index 43ec4a13586..8177e6d002b 100644 --- a/src/metric-engine/src/utils.rs +++ b/src/metric-engine/src/utils.rs @@ -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 diff --git a/src/mito2/src/engine/tail_replay_test.rs b/src/mito2/src/engine/tail_replay_test.rs index 69f373731eb..976d1b8c9d7 100644 --- a/src/mito2/src/engine/tail_replay_test.rs +++ b/src/mito2/src/engine/tail_replay_test.rs @@ -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); +} diff --git a/src/mito2/src/region.rs b/src/mito2/src/region.rs index c99f48d5a18..bf16ebf85f9 100644 --- a/src/mito2/src/region.rs +++ b/src/mito2/src/region.rs @@ -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(), } } diff --git a/src/standalone/src/information_extension.rs b/src/standalone/src/information_extension.rs index 083fabadeb8..424dfcad70c 100644 --- a/src/standalone/src/information_extension.rs +++ b/src/standalone/src/information_extension.rs @@ -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::>(); diff --git a/src/store-api/src/lib.rs b/src/store-api/src/lib.rs index 7d156388e98..99aefab3544 100644 --- a/src/store-api/src/lib.rs +++ b/src/store-api/src/lib.rs @@ -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 +} diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index 296b88998c3..8719416398c 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -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. diff --git a/tests/compatibility/README.md b/tests/compatibility/README.md index 45b80a75daf..063a9bc616b 100644 --- a/tests/compatibility/README.md +++ b/tests/compatibility/README.md @@ -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 diff --git a/tests/compatibility/wire/region_statistic_pending_tails/README.md b/tests/compatibility/wire/region_statistic_pending_tails/README.md new file mode 100644 index 00000000000..7b510ea3aac --- /dev/null +++ b/tests/compatibility/wire/region_statistic_pending_tails/README.md @@ -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(®ion); +std::fs::write("legacy_region_stat.json", serde_json::to_vec(&stat).unwrap()).unwrap(); +``` diff --git a/tests/compatibility/wire/region_statistic_pending_tails/legacy_region_stat.json b/tests/compatibility/wire/region_statistic_pending_tails/legacy_region_stat.json new file mode 100644 index 00000000000..e232f5bdacc --- /dev/null +++ b/tests/compatibility/wire/region_statistic_pending_tails/legacy_region_stat.json @@ -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} \ No newline at end of file diff --git a/tests/compatibility/wire/region_statistic_pending_tails/legacy_region_statistic.json b/tests/compatibility/wire/region_statistic_pending_tails/legacy_region_statistic.json new file mode 100644 index 00000000000..2a06f61acd9 --- /dev/null +++ b/tests/compatibility/wire/region_statistic_pending_tails/legacy_region_statistic.json @@ -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} \ No newline at end of file