fix(metasrv): reserve repartition region numbers before creating regions (#10524)

* fix(metasrv): reserve repartition region numbers before creating regions

Signed-off-by: WenyXu <wenymedia@gmail.com>

* fix(metasrv): limit repartition changes to region number reservation

Signed-off-by: WenyXu <wenymedia@gmail.com>

* refactor: share repartition allocation targets

Signed-off-by: WenyXu <wenymedia@gmail.com>

* fix: reserve region numbers when resuming repartition after upgrade

Signed-off-by: WenyXu <wenymedia@gmail.com>

* test: bound waits for repartition create requests

Signed-off-by: WenyXu <wenymedia@gmail.com>

---------

Signed-off-by: WenyXu <wenymedia@gmail.com>
This commit is contained in:
Weny Xu
2026-11-19 15:42:30 +00:00
committed by GitHub
parent 66719b648f
commit ce7153de26
4 changed files with 362 additions and 33 deletions
+102 -1
View File
@@ -18,7 +18,7 @@ use std::sync::Arc;
use serde::{Deserialize, Deserializer, Serialize};
use snafu::{OptionExt, ResultExt, ensure};
use store_api::storage::{RegionId, RegionNumber};
use store_api::storage::{MAX_REGION_SEQ, RegionId, RegionNumber};
use table::metadata::TableId;
use crate::error::{
@@ -511,6 +511,43 @@ impl TableRouteManager {
.transpose()
}
/// Reserves a positive number of consecutive region numbers without publishing their routes.
/// On success, advances the high-water mark and route version and returns the first reserved number.
/// If the table route changed, returns `None`. Reload the route before retrying.
pub async fn try_reserve_region_numbers(
&self,
table_id: TableId,
current: &DeserializedValueWithBytes<TableRouteValue>,
count: usize,
) -> Result<Option<RegionNumber>> {
// The read path remaps peer addresses. Preserve the stored routes verbatim.
let TableRouteValue::Physical(mut route) =
TableRouteValue::try_from_raw_value(&current.bytes)?
else {
return UnexpectedLogicalRouteTableSnafu {
err_msg: format!("Cannot reserve region numbers for logical table {table_id}"),
}
.fail();
};
let previous = route.max_region_number;
let last = RegionNumber::try_from(count)
.ok()
.and_then(|count| previous.checked_add(count))
.filter(|last| previous < *last && *last <= MAX_REGION_SEQ)
.with_context(|| InvalidMetadataSnafu {
err_msg: format!(
"Cannot reserve {count} region numbers after {previous} for table {table_id}"
),
})?;
route.max_region_number = last;
route.version += 1;
let (txn, _) =
self.storage
.build_update_txn(table_id, current, &TableRouteValue::Physical(route))?;
let response = self.storage.kv_backend.txn(txn).await?;
Ok(response.succeeded.then_some(previous + 1))
}
/// Sets the staging state for a specific region.
///
/// Returns a [TableRouteNotFound](crate::error::Error::TableRouteNotFound) Error if:
@@ -950,6 +987,70 @@ mod tests {
assert_eq!(new_table_route.max_region_number, 3);
}
#[tokio::test]
async fn test_reserve_region_numbers() {
let table_id = 1024;
let kv = Arc::new(MemoryKvBackend::default());
let manager = TableRouteManager::new(kv.clone());
let storage = manager.table_route_storage();
let routes = vec![RegionRoute {
region: Region {
id: RegionId::new(table_id, MAX_REGION_SEQ - 3),
..Default::default()
},
..Default::default()
}];
let initial = TableRouteValue::physical(routes.clone());
let (txn, _) = storage.build_create_txn(table_id, &initial).unwrap();
assert!(kv.txn(txn).await.unwrap().succeeded);
let current = storage.get_with_raw_bytes(table_id).await.unwrap().unwrap();
assert!(
manager
.try_reserve_region_numbers(table_id, &current, 0)
.await
.is_err()
);
assert_eq!(
manager
.try_reserve_region_numbers(table_id, &current, 2)
.await
.unwrap(),
Some(MAX_REGION_SEQ - 2)
);
// Another reservation based on the same snapshot must not claim this range.
assert_eq!(
manager
.try_reserve_region_numbers(table_id, &current, 2)
.await
.unwrap(),
None
);
let current = storage.get_with_raw_bytes(table_id).await.unwrap().unwrap();
assert_eq!(current.region_routes().unwrap(), &routes);
assert_eq!(current.max_region_number().unwrap(), MAX_REGION_SEQ - 1);
assert_eq!(current.version().unwrap(), 1);
assert!(
manager
.try_reserve_region_numbers(table_id, &current, 2)
.await
.is_err()
);
assert_eq!(
manager
.try_reserve_region_numbers(table_id, &current, 1)
.await
.unwrap(),
Some(MAX_REGION_SEQ)
);
let current = storage.get_with_raw_bytes(table_id).await.unwrap().unwrap();
assert!(
manager
.try_reserve_region_numbers(table_id, &current, 1)
.await
.is_err()
);
}
#[test]
fn test_table_route_compatibility() {
let old_raw_v = r#"{"region_routes":[{"region":{"id":1,"name":"r1","partition":null,"attrs":{}},"leader_peer":{"id":2,"addr":"a2"},"follower_peers":[]},{"region":{"id":1,"name":"r1","partition":null,"attrs":{}},"leader_peer":{"id":2,"addr":"a2"},"follower_peers":[]}],"version":0}"#;
+163 -1
View File
@@ -58,7 +58,7 @@ use common_telemetry::{error, info, warn};
use partition::expr::PartitionExpr;
use serde::{Deserialize, Serialize};
use snafu::{OptionExt, ResultExt};
use store_api::storage::TableId;
use store_api::storage::{RegionNumber, TableId};
use table::table_name::TableName;
use crate::error::{self, Result};
@@ -327,6 +327,24 @@ impl Context {
Ok(table_route_value)
}
async fn reserve_region_numbers(
&self,
current: &DeserializedValueWithBytes<TableRouteValue>,
count: usize,
) -> Result<RegionNumber> {
let table_id = self.persistent_ctx.table_id;
self.table_metadata_manager
.table_route_manager()
.try_reserve_region_numbers(table_id, current, count)
.await
.context(error::TableMetadataManagerSnafu)?
.with_context(|| error::RetryLaterSnafu {
reason: format!(
"Table route changed while reserving region numbers for table {table_id}"
),
})
}
/// Retrieves the table info value for the given table id.
///
/// Retry:
@@ -2095,6 +2113,150 @@ mod tests {
);
}
#[tokio::test]
async fn test_repartition_after_partial_create_failure() {
check_partial_create_failure(false).await;
}
#[tokio::test]
async fn test_repartition_after_pre_upgrade_partial_create_failure() {
check_partial_create_failure(true).await;
}
async fn check_partial_create_failure(pre_upgrade: bool) {
use api::v1::region::region_request::Body;
use common_meta::key::MetadataKey;
use common_meta::key::table_route::TableRouteKey;
use common_meta::rpc::store::PutRequest;
let env = TestingEnv::new();
let table_id = 1024;
let source = range_expr("x", 0, 90);
let route = test_region_route(RegionId::new(table_id, 1), &source.as_json_str().unwrap());
env.create_physical_table_metadata_for_repartition(
table_id,
vec![route.clone()],
test_region_wal_options(&[1]),
)
.await;
let (tx, mut requests) = mpsc::channel(1);
let fail_once = AtomicBool::new(true);
let nodes = Arc::new(MockDatanodeManager::new(
DatanodeWatcher::new(tx).with_handler(move |_, request| {
if let Some(Body::Create(create)) = request.body
&& create.region_id == RegionId::new(table_id, 3).as_u64()
&& fail_once.swap(false, Ordering::SeqCst)
{
return error::UnexpectedSnafu {
err_msg: "injected create failure",
}
.fail();
}
Ok(api::region::RegionResponse::new(0))
}),
));
let new_split = || {
RepartitionProcedure::new(
RepartitionFrom::Partitioned {
exprs: vec![source.clone()],
target_partition_columns: None,
},
vec![
range_expr("x", 0, 30),
range_expr("x", 30, 60),
range_expr("x", 60, 90),
],
new_parent_context(&env, nodes.clone(), table_id),
)
};
let ctx = TestingEnv::procedure_context();
let mut first = new_split();
first.execute(&ctx).await.unwrap();
let original = first.context.get_table_route_value().await.unwrap();
first.execute(&ctx).await.unwrap();
let reserved = first.context.get_table_route_value().await.unwrap();
if pre_upgrade {
// Old BuildPlan persisted the same Execute checkpoint without updating the route.
env.kv_backend
.put(
PutRequest::new()
.with_key(TableRouteKey::new(table_id).to_bytes())
.with_value(original.get_raw_bytes()),
)
.await
.unwrap();
first =
RepartitionProcedure::from_json(&first.dump().unwrap(), |persistent_ctx| Context {
persistent_ctx,
..new_parent_context(&env, nodes.clone(), table_id)
})
.unwrap();
}
let observe_create = async {
// The one-slot channel holds the second create until we observe the first.
let (_, request) = requests.recv().await.unwrap();
let Some(Body::Create(create)) = request.body else {
panic!("expected create")
};
let current = new_split().context.get_table_route_value().await.unwrap();
assert_eq!(current.max_region_number().unwrap(), 3);
assert_eq!(current.version().unwrap(), reserved.version().unwrap());
RegionId::from_u64(create.region_id).region_number()
};
let create_timeout = Duration::from_secs(5);
let (result, first_number) = tokio::time::timeout(create_timeout, async {
tokio::join!(first.execute(&ctx), observe_create)
})
.await
.expect("first split timed out waiting for a create request");
assert!(!result.unwrap_err().is_retry_later());
let (_, request) = requests.try_recv().unwrap();
let Some(Body::Create(create)) = request.body else {
panic!("expected create")
};
let mut creates = [
first_number,
RegionId::from_u64(create.region_id).region_number(),
];
creates.sort_unstable();
assert_eq!(creates, [2, 3]);
first.rollback(&ctx).await.unwrap();
assert_eq!(
current_parent_region_routes(&first.context).await,
vec![route]
);
assert_eq!(
first
.context
.get_table_route_value()
.await
.unwrap()
.max_region_number()
.unwrap(),
3
);
let mut second = new_split();
second.execute(&ctx).await.unwrap();
second.execute(&ctx).await.unwrap();
let (result, _) = tokio::time::timeout(create_timeout, async {
tokio::join!(second.execute(&ctx), requests.recv())
})
.await
.expect("second split timed out waiting for a create request");
result.unwrap();
assert_parent_state::<Dispatch>(&second);
let numbers: Vec<_> = current_parent_region_routes(&second.context)
.await
.iter()
.map(|route| route.region.id.region_number())
.collect();
assert_eq!(numbers, [1, 4, 5]);
}
#[tokio::test]
async fn test_repartition_procedure_flow_split_failed_and_full_rollback() {
let env = TestingEnv::new();
@@ -101,13 +101,22 @@ impl BuildPlan {
async fn next(
&mut self,
ctx: &mut Context,
_procedure_ctx: &ProcedureContext,
procedure_ctx: &ProcedureContext,
) -> Result<(Box<dyn State>, Status)> {
let timer = Instant::now();
let table_id = ctx.persistent_ctx.table_id;
let table_lock = TableLock::Write(table_id).into();
let _guard = procedure_ctx.provider.acquire_lock(&table_lock).await;
let table_route_value = ctx.get_table_route_value().await?;
let mut next_region_number =
AllocateRegion::get_next_region_number(table_route_value.max_region_number().unwrap());
let to_allocate = AllocateRegion::count_regions_to_allocate(&self.plan_entries);
// A crash before the plan is persisted can leave a gap, but no datanode
// can create a region until its number has been durably reserved.
let mut next_region_number = if to_allocate > 0 {
ctx.reserve_region_numbers(&table_route_value, to_allocate)
.await?
} else {
0
};
// Converts allocation plan to repartition plan.
let repartition_plan_entries = AllocateRegion::convert_to_repartition_plans(
@@ -117,14 +126,13 @@ impl BuildPlan {
table_route_value.region_routes().unwrap(),
)?;
let plan_count = repartition_plan_entries.len();
let to_allocate = AllocateRegion::count_regions_to_allocate(&repartition_plan_entries);
info!(
"Repartition allocate regions start, table_id: {}, groups: {}, regions_to_allocate: {}",
table_id, plan_count, to_allocate
);
// If no region to allocate, directly dispatch the plan.
if AllocateRegion::count_regions_to_allocate(&repartition_plan_entries) == 0 {
if to_allocate == 0 {
ctx.persistent_ctx.plans = repartition_plan_entries;
ctx.update_allocate_region_elapsed(timer.elapsed());
return Ok((Box::new(Dispatch), Status::executing(true)));
@@ -189,9 +197,23 @@ impl ExecutePlan {
.context(error::AllocateRegionRoutesSnafu { table_id })?;
new_allocated_region_routes.extend(routes);
}
// Older Execute checkpoints can contain region numbers that Build did not reserve.
let table_route_value = ctx.get_table_route_value().await?;
let current = table_route_value
.max_region_number()
.context(error::TableMetadataManagerSnafu)?;
if let Some(required) = allocate_regions
.iter()
.map(|r| r.region_id.region_number())
.max()
&& required > current
{
ctx.reserve_region_numbers(&table_route_value, (required - current) as usize)
.await?;
}
let skip_wal = table_info_value.table_info.meta.options.skip_wal;
let allocate_noop = if skip_wal {
let table_route_value = ctx.get_table_route_value().await?;
let region_wal_options =
get_region_wal_options(&ctx.table_metadata_manager, &table_route_value, table_id)
.await
@@ -410,18 +432,13 @@ impl AllocateRegion {
}
/// Calculates the total number of regions that need to be allocated.
fn count_regions_to_allocate(repartition_plan_entries: &[RepartitionPlanEntry]) -> usize {
repartition_plan_entries
fn count_regions_to_allocate(plan_entries: &[AllocationPlanEntry]) -> usize {
plan_entries
.iter()
.map(|p| p.allocated_region_ids.len())
.map(|plan| plan.targets_to_allocate().len())
.sum()
}
/// Gets the next region number from the physical table route.
fn get_next_region_number(max_region_number: RegionNumber) -> RegionNumber {
max_region_number + 1
}
async fn allocate_regions(
node_manager: &NodeManagerRef,
raw_table_info: &TableInfo,
@@ -897,7 +914,6 @@ mod tests {
#[test]
fn test_count_regions_to_allocate() {
let table_id = 1024;
let mut next_region_number = 10;
let plan_entries = vec![
create_allocation_plan_entry(table_id, &[1], &[(0, 50), (50, 100)]), // 1 allocation
@@ -905,15 +921,7 @@ mod tests {
create_allocation_plan_entry(table_id, &[4], &[(200, 250), (250, 300)]), // 1 allocation
];
let repartition_plans = AllocateRegion::convert_to_repartition_plans(
table_id,
&mut next_region_number,
&plan_entries,
&create_current_region_routes(table_id, &[1, 2, 3, 4]),
)
.unwrap();
let count = AllocateRegion::count_regions_to_allocate(&repartition_plans);
let count = AllocateRegion::count_regions_to_allocate(&plan_entries);
assert_eq!(count, 2);
}
@@ -960,6 +968,56 @@ mod tests {
assert!(!result[1].1.is_empty());
}
#[tokio::test]
async fn test_build_plan_reserves_numbers_before_region_creation() {
let env = TestingEnv::new();
let table_id = 1024;
let routes = create_current_region_routes(table_id, &[1]);
env.create_physical_table_metadata_for_repartition(
table_id,
routes.clone(),
test_region_wal_options(&[1]),
)
.await;
let mut ctx = new_parent_context(&env, Arc::new(MockDatanodeManager::new(())), table_id);
let mut build = BuildPlan {
plan_entries: vec![create_allocation_plan_entry(
table_id,
&[1],
&[(0, 50), (50, 100), (100, 150)],
)],
};
// Replaying Build after a crash before the procedure checkpoint only
// skips numbers. Neither attempt has published routes or created regions.
for first in [2, 4] {
build
.next(&mut ctx, &TestingEnv::procedure_context())
.await
.unwrap();
assert_eq!(
ctx.persistent_ctx.plans[0].allocated_region_ids,
[
RegionId::new(table_id, first),
RegionId::new(table_id, first + 1),
]
);
let current = ctx.get_table_route_value().await.unwrap();
assert_eq!(current.region_routes().unwrap(), &routes);
assert_eq!(current.max_region_number().unwrap(), first + 1);
}
let previous = ctx.get_table_route_value().await.unwrap();
let mut build = BuildPlan {
plan_entries: vec![create_allocation_plan_entry(table_id, &[1], &[(0, 100)])],
};
let (next, _) = build
.next(&mut ctx, &TestingEnv::procedure_context())
.await
.unwrap();
assert!(next.as_any().is::<Dispatch>());
let current = ctx.get_table_route_value().await.unwrap();
assert_eq!(previous.get_raw_bytes(), current.get_raw_bytes());
}
#[tokio::test]
async fn test_execute_plan_uses_latest_table_route_after_lock() {
let env = TestingEnv::new();
+15 -7
View File
@@ -165,6 +165,15 @@ pub struct AllocationPlanEntry {
pub transition_map: Vec<Vec<usize>>,
}
impl AllocationPlanEntry {
/// Returns the target partitions that need a new region.
pub(super) fn targets_to_allocate(&self) -> impl ExactSizeIterator<Item = &PartitionExpr> {
self.target_partition_exprs
.iter()
.skip(self.source_regions.len())
}
}
/// A plan entry for the dispatch phase after region allocation,
/// with concrete source and target region descriptors.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -216,20 +225,19 @@ impl RepartitionPlanEntry {
pub fn convert_allocation_plan_to_repartition_plan(
table_id: TableId,
next_region_number: &mut RegionNumber,
AllocationPlanEntry {
plan: &AllocationPlanEntry,
) -> RepartitionPlanEntry {
let AllocationPlanEntry {
group_id,
source_regions,
target_partition_exprs,
transition_map,
..
}: &AllocationPlanEntry,
) -> RepartitionPlanEntry {
} = plan;
match source_regions.len().cmp(&target_partition_exprs.len()) {
Ordering::Less => {
// requires to allocate regions
let pending_allocate_target_partition_exprs = target_partition_exprs
.iter()
.skip(source_regions.len())
let pending_allocate_target_partition_exprs = plan
.targets_to_allocate()
.map(|target_partition_expr| {
let desc = TargetRegionDescriptor {
region_id: RegionId::new(table_id, *next_region_number),