fix: defer reads from repartition targets until metadata is ready

Hide newly allocated targets until logical-region metadata synchronization completes. Refresh cached pending routes from authoritative metadata and stop staging entry when cache invalidation fails. Cover route persistence, allocation replay, rollback, stale caches, and failure paths.

Signed-off-by: WenyXu <wenymedia@gmail.com>
This commit is contained in:
WenyXu
2026-11-12 13:19:26 +00:00
parent ccd28f854e
commit c184c1bbd1
11 changed files with 359 additions and 53 deletions
+62
View File
@@ -228,7 +228,28 @@ pub enum WriteRoutePolicy {
IgnoreAllWrites,
}
// Presence, rather than the value, hides a newly allocated repartition target.
const REPARTITION_PENDING_READ: &str = "greptime:repartition-pending-read";
impl RegionRoute {
/// Whether allocation has published this target before its logical regions are ready.
/// Old routes without this attribute remain readable. Unknown values also remain hidden.
pub fn is_repartition_pending_read(&self) -> bool {
self.region.attrs.contains_key(REPARTITION_PENDING_READ)
}
/// Hides a newly allocated target until its logical regions have been synchronized.
pub fn set_repartition_pending_read(&mut self) {
self.region
.attrs
.insert(REPARTITION_PENDING_READ.to_string(), "true".to_string());
}
/// Makes a prepared target available to query planning.
pub fn clear_repartition_pending_read(&mut self) {
self.region.attrs.remove(REPARTITION_PENDING_READ);
}
/// Returns true if the region should ignore all writes.
pub fn is_ignore_all_writes(&self) -> bool {
matches!(
@@ -441,6 +462,47 @@ mod tests {
use super::*;
use crate::key::RegionRoleSet;
#[test]
fn test_repartition_pending_read_route_roundtrip() {
let fixture = include_bytes!(
"../../../../../tests/compatibility/metadata/repartition_readiness/route.json"
);
let frozen: RegionRoute = serde_json::from_slice(fixture).unwrap();
assert!(frozen.is_repartition_pending_read());
assert_eq!(frozen.region.id, RegionId::new(1, 2));
assert_eq!(frozen.region.attrs.get("unrelated").unwrap(), "retained");
assert_eq!(
serde_json::from_slice::<RegionRoute>(&serde_json::to_vec(&frozen).unwrap()).unwrap(),
frozen
);
let mut route = new_test_region_route(RegionId::new(1, 2));
assert!(!route.is_repartition_pending_read());
let legacy = serde_json::to_vec(&route).unwrap();
assert!(
!serde_json::from_slice::<RegionRoute>(&legacy)
.unwrap()
.is_repartition_pending_read()
);
route.set_repartition_pending_read();
route
.region
.attrs
.insert("other".into(), "preserved".into());
let encoded = serde_json::to_vec(&route).unwrap();
let mut decoded: RegionRoute = serde_json::from_slice(&encoded).unwrap();
assert_eq!(decoded, route);
assert!(decoded.is_repartition_pending_read());
decoded
.region
.attrs
.insert(REPARTITION_PENDING_READ.into(), "future-value".into());
assert!(decoded.is_repartition_pending_read());
decoded.clear_repartition_pending_read();
decoded.clear_repartition_pending_read();
assert!(!decoded.is_repartition_pending_read());
assert_eq!(decoded.region.attrs.get("other").unwrap(), "preserved");
}
fn new_test_region_route(region_id: RegionId) -> RegionRoute {
RegionRoute {
region: Region::new_test(region_id),
+19 -17
View File
@@ -1210,16 +1210,18 @@ mod tests {
#[test]
fn test_filter_allocated_region_routes() {
let table_id = 1024;
let region_routes = vec![
let mut region_routes = vec![
test_region_route(RegionId::new(table_id, 1), "a"),
test_region_route(RegionId::new(table_id, 2), "b"),
];
region_routes[1].set_repartition_pending_read();
let allocated_region_ids = HashSet::from([RegionId::new(table_id, 2)]);
let new_region_routes =
DeallocateRegion::generate_region_routes(&region_routes, &allocated_region_ids);
assert_eq!(new_region_routes.len(), 1);
assert!(!new_region_routes[0].is_repartition_pending_read());
assert_eq!(new_region_routes[0].region.id, RegionId::new(table_id, 1));
}
@@ -2164,14 +2166,14 @@ mod tests {
RegionId::new(table_id, 2),
&range_expr("x", 100, 200).as_json_str().unwrap(),
),
RegionRoute {
region: Region {
id: RegionId::new(table_id, 3),
partition_expr: range_expr("x", 50, 100).as_json_str().unwrap(),
..Default::default()
},
leader_peer: Some(Peer::empty(0)),
..Default::default()
{
let mut target = test_region_route(
RegionId::new(table_id, 3),
&range_expr("x", 50, 100).as_json_str().unwrap(),
);
target.leader_peer = Some(Peer::empty(0));
target.set_repartition_pending_read();
target
},
]
);
@@ -2549,14 +2551,14 @@ mod tests {
RegionId::new(table_id, 2),
&range_expr("x", 100, 200).as_json_str().unwrap(),
),
RegionRoute {
region: Region {
id: RegionId::new(table_id, 3),
partition_expr: range_expr("x", 50, 100).as_json_str().unwrap(),
..Default::default()
},
leader_peer: Some(Peer::empty(0)),
..Default::default()
{
let mut target = test_region_route(
RegionId::new(table_id, 3),
&range_expr("x", 50, 100).as_json_str().unwrap(),
);
target.leader_peer = Some(Peer::empty(0));
target.set_repartition_pending_read();
target
},
]
);
@@ -316,7 +316,11 @@ impl AllocateRegion {
let mut new_region_routes = region_routes.to_vec();
for new_allocated_region_id in new_allocated_region_ids {
if !region_ids.contains(&new_allocated_region_id.region.id) {
new_region_routes.push(new_allocated_region_id.clone());
// Physical allocation precedes metric logical-region synchronization.
// Keep the old sources readable until the group has prepared its targets.
let mut route = new_allocated_region_id.clone();
route.set_repartition_pending_read();
new_region_routes.push(route);
}
}
new_region_routes
@@ -631,6 +635,36 @@ mod tests {
test_region_wal_options,
};
#[test]
fn test_allocate_routes_hide_only_new_targets_and_resume_preserves_state() {
let source = RegionRoute {
region: common_meta::rpc::router::Region::new_test(RegionId::new(1, 0)),
..Default::default()
};
let target = RegionRoute {
region: common_meta::rpc::router::Region::new_test(RegionId::new(1, 1)),
..Default::default()
};
let allocated = AllocateRegion::generate_region_routes(
std::slice::from_ref(&source),
std::slice::from_ref(&target),
);
assert_eq!(allocated[0], source);
assert!(allocated[1].is_repartition_pending_read());
let restored: Vec<RegionRoute> =
serde_json::from_slice(&serde_json::to_vec(&allocated).unwrap()).unwrap();
assert_eq!(
AllocateRegion::generate_region_routes(&restored, std::slice::from_ref(&target)),
allocated
);
let mut prepared = restored;
prepared[1].clear_repartition_pending_read();
assert_eq!(
AllocateRegion::generate_region_routes(&prepared, &[target]),
prepared
);
}
fn create_region_descriptor(
table_id: TableId,
region_number: u32,
@@ -471,11 +471,15 @@ impl Context {
let ctx = common_meta::cache_invalidator::Context {
subject: Some(subject),
};
let _ = self
.cache_invalidator
self.cache_invalidator
.invalidate(&ctx, &[CacheIdent::TableId(table_id)])
.await;
Ok(())
.await
.map_err(BoxedError::new)
.context(error::RetryLaterWithSourceSnafu {
reason: format!(
"Failed to invalidate repartition routes for table {table_id}, group {group_id}"
),
})
}
/// Updates the table route.
@@ -53,11 +53,8 @@ impl State for UpdateMetadata {
// TODO(weny): If all metadata have already been updated, skip applying staging regions.
self.apply_staging_regions(ctx).await?;
if let Err(err) = ctx.invalidate_table_cache().await {
warn!(
"Failed to broadcast the invalidate table cache message during the apply staging regions, error: {err:?}"
);
};
// Do not enter staging after an explicitly failed invalidation broadcast.
ctx.invalidate_table_cache().await?;
ctx.update_update_metadata_elapsed(timer.elapsed());
Ok((Box::new(EnterStagingRegion), Status::executing(false)))
}
@@ -79,3 +76,74 @@ impl State for UpdateMetadata {
self
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use store_api::storage::RegionId;
use super::*;
use crate::handler::test_utils::FailingCacheInvalidator;
use crate::procedure::repartition::group::repartition_start::RepartitionStart;
use crate::procedure::repartition::plan::{SourceRegionDescriptor, TargetRegionDescriptor};
use crate::procedure::repartition::test_util::{
TestingEnv, new_persistent_context, range_expr, test_region_route,
};
#[tokio::test]
async fn test_pending_read_invalidation_failure_blocks_enter_staging() {
let env = TestingEnv::new();
let table_id = 1024;
let source_id = RegionId::new(table_id, 1);
let target_id = RegionId::new(table_id, 2);
let source_expr = range_expr("x", 0, 100);
let mut target = test_region_route(target_id, "");
target.set_repartition_pending_read();
env.create_physical_table_metadata(
table_id,
vec![
test_region_route(source_id, &source_expr.as_json_str().unwrap()),
target,
],
)
.await;
let persistent = new_persistent_context(
table_id,
vec![SourceRegionDescriptor::partitioned(
source_id,
source_expr.clone(),
)],
vec![TargetRegionDescriptor {
region_id: target_id,
partition_expr: range_expr("x", 0, 50),
}],
);
let mut ctx = env.create_context(persistent);
let procedure_ctx = TestingEnv::procedure_context();
RepartitionStart
.next(&mut ctx, &procedure_ctx)
.await
.unwrap();
let invalidator = Arc::new(FailingCacheInvalidator::default());
ctx.cache_invalidator = invalidator.clone();
let mut state = UpdateMetadata::ApplyStaging;
let error = state.next(&mut ctx, &procedure_ctx).await.unwrap_err();
assert!(matches!(
error,
crate::error::Error::RetryLaterWithSource { .. }
));
assert_eq!(invalidator.attempts(), 1);
let value = ctx.get_table_route_value().await.unwrap();
let routes = value.region_routes().unwrap();
assert_eq!(
routes[0].region.partition_expr,
source_expr.as_json_str().unwrap()
);
assert!(!routes[0].is_repartition_pending_read());
assert!(!routes[1].is_repartition_pending_read());
// Retrying the same persisted phase cannot advance while notification still fails.
assert!(state.next(&mut ctx, &procedure_ctx).await.is_err());
assert_eq!(invalidator.attempts(), 2);
}
}
@@ -57,6 +57,8 @@ impl UpdateMetadata {
.context(error::SerializePartitionExprSnafu)?;
// Set leader staging state and write route policy for the target region route.
region_route.set_leader_staging();
// Metric targets have completed SyncRegion before this transition.
region_route.clear_repartition_pending_read();
region_route.clear_ignore_all_writes();
}
@@ -138,7 +140,7 @@ mod tests {
fn test_generate_region_routes() {
let group_id = Uuid::new_v4();
let table_id = 1024;
let region_routes = vec![
let mut region_routes = vec![
RegionRoute {
region: Region {
id: RegionId::new(table_id, 1),
@@ -167,6 +169,8 @@ mod tests {
..Default::default()
},
];
region_routes[1].set_repartition_pending_read();
region_routes[2].set_repartition_pending_read();
let source_region = SourceRegionDescriptor::partitioned(
RegionId::new(table_id, 1),
range_expr("x", 0, 100),
@@ -184,6 +188,9 @@ mod tests {
&region_routes,
)
.unwrap();
assert!(!new_region_routes[0].is_repartition_pending_read());
assert!(!new_region_routes[1].is_repartition_pending_read());
assert!(new_region_routes[2].is_repartition_pending_read());
assert!(new_region_routes[0].is_leader_staging());
assert_eq!(
new_region_routes[0].region.partition_expr,
+24
View File
@@ -120,6 +120,30 @@ impl PartitionRuleManager {
}
}
/// Resolves a query route, refreshing allocation-time snapshots from metadata.
/// Cache invalidation is broadcast without a processing acknowledgment, so a
/// cached pending target must not stay hidden after synchronization completes.
pub async fn find_physical_read_route_with_id(
&self,
table_id: TableId,
) -> Result<(TableId, Arc<PhysicalTableRouteValue>)> {
let (physical_id, route) = self.find_physical_table_route_with_id(table_id).await?;
if route
.region_routes
.iter()
.any(|route| route.is_repartition_pending_read())
{
let (physical_id, route) = self
.table_route_manager
.get_physical_table_route(physical_id)
.await
.context(error::TableRouteManagerSnafu)?;
Ok((physical_id, Arc::new(route)))
} else {
Ok((physical_id, route))
}
}
pub async fn batch_find_region_routes(
&self,
table_ids: &[TableId],
+108 -25
View File
@@ -14,6 +14,7 @@
//! [ExtensionPlanner] implementation for distributed planner
use std::borrow::Cow;
use std::sync::Arc;
use ahash::HashMap;
@@ -272,11 +273,27 @@ impl DistExtensionPlanner {
let table_info = table.table_info();
let (physical_table_id, physical_table_route) = self
.partition_rule_manager
.find_physical_table_route_with_id(table_info.table_id())
.find_physical_read_route_with_id(table_info.table_id())
.await
.context(PartitionRuleManagerSnafu)?;
let all_regions = physical_table_route
.region_routes
// New repartition targets may be routed before their logical regions exist.
// Use the same visible routes for fallback scans and partition pruning.
let routes = &physical_table_route.region_routes;
let read_routes = if routes
.iter()
.any(|route| route.is_repartition_pending_read())
{
Cow::Owned(
routes
.iter()
.filter(|route| !route.is_repartition_pending_read())
.cloned()
.collect::<Vec<_>>(),
)
} else {
Cow::Borrowed(routes.as_slice())
};
let all_regions = read_routes
.iter()
.map(|r| RegionId::new(table_info.table_id(), r.region.id.region_number()))
.collect::<Vec<_>>();
@@ -331,20 +348,18 @@ impl DistExtensionPlanner {
};
// Get partition information for the table if partition rule manager is available
let partitions = match create_partitions_from_region_routes(
table_info.table_id(),
&physical_table_route.region_routes,
) {
Ok(partitions) => partitions,
Err(err) => {
common_telemetry::debug!(
"Failed to get partition information for table {}, using all regions: {:?}",
table_name,
err
);
return Ok(all_regions);
}
};
let partitions =
match create_partitions_from_region_routes(table_info.table_id(), &read_routes) {
Ok(partitions) => partitions,
Err(err) => {
common_telemetry::debug!(
"Failed to get partition information for table {}, using all regions: {:?}",
table_name,
err
);
return Ok(all_regions);
}
};
if partitions.is_empty() {
return Ok(all_regions);
}
@@ -549,10 +564,12 @@ mod tests {
use catalog::{CatalogManagerRef, RegisterTableRequest};
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
use common_meta::cache::new_table_route_cache;
use common_meta::key::TableMetadataManager;
use common_meta::key::table_route::TableRouteValue;
use common_meta::key::table_route::{TableRouteKey, TableRouteValue};
use common_meta::key::{MetadataKey, MetadataValue, TableMetadataManager};
use common_meta::kv_backend::KvBackendRef;
use common_meta::kv_backend::memory::MemoryKvBackend;
use common_meta::rpc::router::{Region, RegionRoute};
use common_meta::rpc::store::{DeleteRangeRequest, PutRequest};
use common_query::request::QueryRequest;
use common_recordbatch::SendableRecordBatchStream;
use datafusion::datasource::DefaultTableSource;
@@ -670,6 +687,20 @@ mod tests {
physical_partition_keys: Vec<usize>,
expressions: Vec<Option<PartitionExpr>>,
) -> (DistExtensionPlanner, LogicalPlan, TableName) {
let routes = expressions
.into_iter()
.enumerate()
.map(|(index, expression)| region_route(index as u32 + 1, expression))
.collect();
let (planner, plan, name, _) =
planner_and_plan_with_routes(physical_partition_keys, routes).await;
(planner, plan, name)
}
async fn planner_and_plan_with_routes(
physical_partition_keys: Vec<usize>,
routes: Vec<RegionRoute>,
) -> (DistExtensionPlanner, LogicalPlan, TableName, KvBackendRef) {
let logical_info = table_info(LOGICAL_TABLE_ID, "logical", &["host"], vec![0]);
let physical_info = table_info(
PHYSICAL_TABLE_ID,
@@ -695,11 +726,6 @@ mod tests {
let backend = Arc::new(MemoryKvBackend::default());
let metadata_manager = TableMetadataManager::new(backend.clone());
let routes = expressions
.into_iter()
.enumerate()
.map(|(index, expression)| region_route(index as u32 + 1, expression))
.collect();
metadata_manager
.create_table_metadata(
physical_info,
@@ -728,7 +754,7 @@ mod tests {
table_route_cache.clone(),
));
let partition_rule_manager = Arc::new(PartitionRuleManager::new(
backend,
backend.clone(),
table_route_cache,
partition_info_cache,
));
@@ -763,9 +789,66 @@ mod tests {
planner,
plan,
TableName::new(DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME, "logical"),
backend,
)
}
#[tokio::test]
async fn test_pending_repartition_targets_excluded_from_reads() {
let expression = Some(partition_col("host").lt(Value::String("z".into())));
let mut source = region_route(1, expression.clone());
source.set_leader_staging();
let mut target = region_route(2, expression);
target.set_repartition_pending_read();
// The metadata backend and route cache must preserve the pending marker.
let (planner, plan, name, backend) =
planner_and_plan_with_routes(vec![0], vec![source.clone(), target.clone()]).await;
assert_eq!(
planner.get_regions(&name, &plan).await.unwrap(),
vec![RegionId::new(LOGICAL_TABLE_ID, 1)]
);
let LogicalPlan::Filter(filter) = &plan else {
panic!("expected filtered test plan")
};
assert_eq!(
planner.get_regions(&name, &filter.input).await.unwrap(),
vec![RegionId::new(LOGICAL_TABLE_ID, 1)]
);
// Synchronization makes the target readable; a staging source remains readable throughout.
target.clear_repartition_pending_read();
// Deliberately do not invalidate the cached pending snapshot.
backend
.put(
PutRequest::new()
.with_key(TableRouteKey::new(PHYSICAL_TABLE_ID).to_bytes())
.with_value(
TableRouteValue::physical(vec![source, target])
.try_as_raw_value()
.unwrap(),
),
)
.await
.unwrap();
let mut visible = planner.get_regions(&name, &plan).await.unwrap();
visible.sort_unstable();
assert_eq!(
visible,
vec![
RegionId::new(LOGICAL_TABLE_ID, 1),
RegionId::new(LOGICAL_TABLE_ID, 2)
]
);
backend
.delete_range(
DeleteRangeRequest::new()
.with_key(TableRouteKey::new(PHYSICAL_TABLE_ID).to_bytes()),
)
.await
.unwrap();
// A failed authoritative refresh must not fall back to silently hiding targets.
assert!(planner.get_regions(&name, &plan).await.is_err());
}
fn physical_partition_expressions() -> Vec<Option<PartitionExpr>> {
vec![
Some(partition_col("host").lt(Value::String("m".into()))),
+6
View File
@@ -23,6 +23,12 @@ including exact integer counts, custom bounds, and NaN payloads:
cargo nextest run -p servers -E 'test(native_histogram_remote_read_wire_fixture)'
```
## Metadata fixtures
The [repartition route fixture](metadata/repartition_readiness/README.md) checks
allocation-time read readiness, old-route defaults, and attribute preservation.
It is exercised by `common-meta` and query route-cache tests.
## Object store WAL fixtures
Frozen objects of the object store WAL are checked byte for byte by the format tests of
@@ -0,0 +1,15 @@
# Repartition read-readiness route fixture
`route.json` freezes the existing JSON route envelope with the allocation-only
`greptime:repartition-pending-read` attribute. Its presence hides a newly allocated
target from query planning until metric logical-region synchronization completes.
Routes without the attribute remain readable; unknown values remain hidden.
The `common-meta` test `test_repartition_pending_read_route_roundtrip` checks this
fixture, old routes without the attribute, and unrelated-attribute preservation.
The query test `test_pending_repartition_targets_excluded_from_reads` also exercises
KV decoding and the route cache. SQL restart cases cannot pause this intermediate
procedure state reliably.
Older frontends preserve the attribute but do not honor it. Upgrade query frontends
before relying on this protection during concurrent reads and repartition.
@@ -0,0 +1 @@
{"region":{"id":4294967298,"name":"target","partition_expr":"","attrs":{"greptime:repartition-pending-read":"true","unrelated":"retained"}},"leader_peer":{"id":1,"addr":"datanode:4001"},"follower_peers":[],"leader_down_since":null}