fix: fence reads across repartition data handoff

Reject query planning during repartition handoff and keep new targets pending until all manifests have been applied. Carry planned partition versions to datanodes and validate the pinned scan snapshot, including retiring merge sources. Preserve retryable read errors and cover cached routes, transport, metric mapping, and scope changes.

Signed-off-by: WenyXu <wenymedia@gmail.com>
This commit is contained in:
WenyXu
2026-11-18 06:42:40 +00:00
parent e833ce3bb8
commit 8fe217fa13
16 changed files with 503 additions and 81 deletions
+29 -16
View File
@@ -1307,22 +1307,35 @@ mod tests {
#[test]
fn test_from_tonic_status_with_retry_hint() {
let mut headers = HeaderMap::new();
headers.insert(
GREPTIME_DB_HEADER_ERROR_CODE,
HeaderValue::from(StatusCode::Internal as u32),
);
headers.insert(
GREPTIME_DB_HEADER_ERROR_RETRY_HINT,
HeaderValue::from_static(RetryHint::Retryable.as_str()),
);
let status =
Status::with_metadata(Code::Internal, "blabla", MetadataMap::from_headers(headers));
let actual: Error = status.into();
assert_eq!(actual.retry_hint(), RetryHint::Retryable);
assert!(actual.should_retry());
for (code, hint) in [
(StatusCode::Internal, RetryHint::Retryable),
(
StatusCode::RegionNotReady,
RetryHint::RetryAfterRouteRefresh,
),
] {
let mut headers = HeaderMap::new();
headers.insert(
GREPTIME_DB_HEADER_ERROR_CODE,
HeaderValue::from(code as u32),
);
headers.insert(
GREPTIME_DB_HEADER_ERROR_RETRY_HINT,
HeaderValue::from_static(hint.as_str()),
);
let status = Status::with_metadata(
common_error::status_code::status_to_tonic_code(code),
"blabla",
MetadataMap::from_headers(headers),
);
let actual: Error = status.into();
assert_eq!(actual.status_code(), code);
assert_eq!(actual.retry_hint(), hint);
assert!(actual.should_retry());
let stream_error = flight_stream_error("127.0.0.1:4001", actual);
assert_eq!(stream_error.status_code(), code);
assert_eq!(stream_error.retry_hint(), hint);
}
}
#[test]
+4 -4
View File
@@ -228,17 +228,17 @@ pub enum WriteRoutePolicy {
IgnoreAllWrites,
}
// Presence, rather than the value, hides a newly allocated repartition target.
// Presence, rather than the value, marks an incomplete repartition read handoff.
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.
/// Whether allocation has published this target before the read handoff completes.
/// Old routes without this attribute remain readable. Unknown values also mark a pending handoff.
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.
/// Marks a newly allocated target until the repartition read handoff completes.
pub fn set_repartition_pending_read(&mut self) {
self.region
.attrs
@@ -141,7 +141,7 @@ mod tests {
source_expr.as_json_str().unwrap()
);
assert!(!routes[0].is_repartition_pending_read());
assert!(!routes[1].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,8 +57,6 @@ 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();
}
@@ -189,7 +187,7 @@ mod tests {
)
.unwrap();
assert!(!new_region_routes[0].is_repartition_pending_read());
assert!(!new_region_routes[1].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!(
@@ -45,6 +45,8 @@ impl UpdateMetadata {
},
)?;
region_route.clear_leader_staging();
// Every target manifest and the retained source have completed their handoff.
region_route.clear_repartition_pending_read();
}
for source in sources {
@@ -153,6 +155,7 @@ mod tests {
..Default::default()
};
target_route.set_ignore_all_writes();
target_route.set_repartition_pending_read();
let new_region_routes = UpdateMetadata::exit_staging_region_routes(
group_id,
@@ -165,6 +168,7 @@ mod tests {
assert!(!new_region_routes[0].is_leader_staging());
assert!(new_region_routes[0].is_ignore_all_writes());
assert!(!new_region_routes[1].is_leader_staging());
assert!(!new_region_routes[1].is_repartition_pending_read());
assert!(new_region_routes[1].is_ignore_all_writes());
}
+2
View File
@@ -588,6 +588,7 @@ mod test {
// check explicit projection
let projection = Some(vec![0, 1, 2, 3, 4, 5, 6]);
let scan_req = ScanRequest {
expected_partition_expr_version: Some(42),
projection,
filters: vec![],
series_row_selector: Some(TimeSeriesRowSelector::LastRow { after_merge: true }),
@@ -605,6 +606,7 @@ mod test {
scan_req.projection.as_deref().unwrap(),
&[11, 10, 9, 8, 0, 1, 4]
);
assert_eq!(scan_req.expected_partition_expr_version, Some(42));
assert_eq!(scan_req.filters.len(), 1);
assert_eq!(
scan_req.series_row_selector,
+22
View File
@@ -1233,6 +1233,28 @@ impl EngineInner {
});
let version_data = region.version_control.current();
let version = version_data.version;
if let Some(planned_version) = request.expected_partition_expr_version {
// A retiring merge source can keep its old scope. Scope comparison alone
// cannot fence it, so reject reads during staging as well.
ensure!(
!region.is_staging_or_staged_edit() && !region.is_enter_staging(),
crate::error::ReadRegionNotReadySnafu {
region_id,
reason: "repartition is in progress".to_string(),
}
);
// Validate the pinned snapshot, not a separately loaded region metadata.
ensure!(
planned_version == version.metadata.partition_expr_version,
crate::error::ReadRegionNotReadySnafu {
region_id,
reason: format!(
"planned partition version {planned_version}, snapshot version {}",
version.metadata.partition_expr_version
),
}
);
}
version.ensure_no_pending_tails()?;
if request.snapshot_on_scan && request.memtable_max_sequence.is_none() {
+128
View File
@@ -5390,3 +5390,131 @@ fn scan_field_values(batches: &[common_recordbatch::RecordBatch]) -> Vec<f64> {
})
.collect()
}
#[tokio::test]
async fn test_planned_read_uses_pinned_partition_scope() {
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1024, 0);
let create = CreateRequestBuilder::new().build();
let schema = test_util::rows_schema(&create);
engine
.handle_request(region_id, RegionRequest::Create(create))
.await
.unwrap();
test_util::put_rows(
&engine,
region_id,
Rows {
schema,
rows: test_util::build_rows(0, 3),
},
)
.await;
test_util::flush_region(&engine, region_id, None).await;
let region = engine.get_region(region_id).unwrap();
let old_version = region.metadata().partition_expr_version;
let planned = ScanRequest {
expected_partition_expr_version: Some(old_version),
..Default::default()
};
let pinned = engine.scan_region(region_id, planned.clone()).unwrap();
let mut metadata = region.metadata().as_ref().clone();
let expr = partition::expr::col("field_0").lt(datatypes::value::Value::Float64(1.0.into()));
metadata.set_partition_expr(Some(expr.as_json_str().unwrap()));
let new_version = metadata.partition_expr_version;
assert_ne!(old_version, new_version);
region.version_control.alter_metadata(Arc::new(metadata));
let error = match engine.scan_region(region_id, planned) {
Err(error) => error,
Ok(_) => panic!("stale planned scope must fail"),
};
assert!(matches!(error, Error::ReadRegionNotReady { .. }));
assert_eq!(error.status_code(), StatusCode::RegionNotReady);
assert_eq!(
error.retry_hint(),
common_error::ext::RetryHint::RetryAfterRouteRefresh
);
// Opening the scanner later must retain the already validated old snapshot.
let old_batches =
RecordBatches::try_collect(pinned.scanner().await.unwrap().scan().await.unwrap())
.await
.unwrap();
assert_eq!(old_batches.iter().map(|b| b.num_rows()).sum::<usize>(), 3);
let current = engine
.scanner(
region_id,
ScanRequest {
expected_partition_expr_version: Some(new_version),
..Default::default()
},
)
.await
.unwrap();
let current_batches = RecordBatches::try_collect(current.scan().await.unwrap())
.await
.unwrap();
assert_eq!(
current_batches.iter().map(|b| b.num_rows()).sum::<usize>(),
1
);
assert!(
engine
.scan_region(region_id, ScanRequest::default())
.is_ok()
);
}
#[tokio::test]
async fn test_planned_read_rejects_retiring_merge_source() {
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
let region_id = RegionId::new(1024, 0);
engine
.handle_request(
region_id,
RegionRequest::Create(CreateRequestBuilder::new().build()),
)
.await
.unwrap();
let version = engine
.get_region(region_id)
.unwrap()
.metadata()
.partition_expr_version;
engine
.handle_request(
region_id,
RegionRequest::EnterStaging(store_api::region_request::EnterStagingRequest {
partition_directive:
store_api::region_request::StagingPartitionDirective::RejectAllWrites,
}),
)
.await
.unwrap();
assert_eq!(
engine
.get_region(region_id)
.unwrap()
.metadata()
.partition_expr_version,
version
);
let error = match engine.scan_region(
region_id,
ScanRequest {
expected_partition_expr_version: Some(version),
..Default::default()
},
) {
Err(error) => error,
Ok(_) => panic!("retiring source must reject a newly opened planned scan"),
};
assert!(matches!(error, Error::ReadRegionNotReady { .. }));
assert_eq!(error.status_code(), StatusCode::RegionNotReady);
assert!(
engine
.scan_region(region_id, ScanRequest::default())
.is_ok()
);
}
+10
View File
@@ -869,6 +869,14 @@ pub enum Error {
location: Location,
},
#[snafu(display("Region {} is not ready for the planned read: {}", region_id, reason))]
ReadRegionNotReady {
region_id: RegionId,
reason: String,
#[snafu(implicit)]
location: Location,
},
#[snafu(display(
"Partition expr version mismatch for region {}: request {}, expected {}",
region_id,
@@ -1812,6 +1820,7 @@ impl ErrorExt for Error {
| InvalidPrimaryKeyRange { .. }
| DecodePrimaryKeyRange { .. } => StatusCode::Internal,
RegionBusy { .. } | EndStagingPending { .. } => StatusCode::RegionBusy,
ReadRegionNotReady { .. } => StatusCode::RegionNotReady,
GetSchemaMetadata { source, .. } => source.status_code(),
Timeout { .. } => StatusCode::Cancelled,
@@ -1864,6 +1873,7 @@ impl ErrorExt for Error {
match self {
PartitionExprVersionMismatch { .. }
| ReadRegionNotReady { .. }
| RegionNotFound { .. }
| RegionClosed { .. }
| RejectWriteInStaging { .. }
+2 -2
View File
@@ -122,7 +122,7 @@ 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.
/// cached transition must not keep rejecting reads after the handoff completes.
pub async fn find_physical_read_route_with_id(
&self,
table_id: TableId,
@@ -131,7 +131,7 @@ impl PartitionRuleManager {
if route
.region_routes
.iter()
.any(|route| route.is_repartition_pending_read())
.any(|route| route.is_repartition_pending_read() || route.is_leader_staging())
{
let (physical_id, route) = self
.table_route_manager
+60 -2
View File
@@ -488,6 +488,7 @@ impl MergeScanLogicalPlan {
pub struct MergeScanExec {
table: TableName,
regions: Vec<RegionId>,
partition_versions: Arc<HashMap<RegionId, u64>>,
plan: LogicalPlan,
arrow_schema: ArrowSchemaRef,
region_query_handler: RegionQueryHandlerRef,
@@ -577,6 +578,7 @@ impl MergeScanExec {
Ok(Self {
table,
regions,
partition_versions: Arc::default(),
plan,
arrow_schema,
region_query_handler,
@@ -592,6 +594,12 @@ impl MergeScanExec {
})
}
/// Locks each scan to the partition scope selected by the planning snapshot.
pub(crate) fn with_partition_versions(mut self, versions: HashMap<RegionId, u64>) -> Self {
self.partition_versions = Arc::new(versions);
self
}
/// Conservative row-count upper bound for all selected regions.
///
/// This is not an expected cardinality: DataFusion receives it as an
@@ -621,6 +629,7 @@ impl MergeScanExec {
) -> Result<SendableRecordBatchStream> {
// prepare states to move
let regions = self.regions.clone();
let partition_versions = self.partition_versions.clone();
let region_query_handler = self.region_query_handler.clone();
let metric = MergeScanMetric::new(&self.metric);
let arrow_schema = self.arrow_schema.clone();
@@ -709,6 +718,12 @@ impl MergeScanExec {
region_id,
&captured_remote_dyn_filters,
);
if let Some(version) = partition_versions.get(&region_id) {
region_query_ctx.set_extension(
crate::dummy_catalog::EXPECTED_PARTITION_EXPR_VERSION_KEY,
version.to_string(),
);
}
if live_analyze_metrics {
let remote_query_id = region_query_ctx.remote_query_id().map(str::to_string);
if let Some(remote_query_id) = remote_query_id {
@@ -2077,6 +2092,7 @@ mod tests {
#[derive(Default)]
struct TestRegionQueryHandler {
responses: HashMap<RegionId, TestRegionResponse>,
versions: Mutex<Vec<(RegionId, Option<String>)>>,
}
impl TestRegionQueryHandler {
@@ -2093,7 +2109,10 @@ mod tests {
)
})
.collect();
Self { responses }
Self {
responses,
versions: Mutex::default(),
}
}
fn with_responses(
@@ -2117,7 +2136,10 @@ mod tests {
)
})
.collect();
Self { responses }
Self {
responses,
versions: Mutex::default(),
}
}
}
@@ -2512,6 +2534,19 @@ mod tests {
_target: &crate::region_query::RegionQueryTarget,
request: common_query::request::QueryRequest,
) -> crate::error::Result<common_recordbatch::SendableRecordBatchStream> {
self.versions.lock().unwrap().push((
request.region_id,
request
.header
.as_ref()
.and_then(|header| header.query_context.as_ref())
.and_then(|context| {
context
.extensions
.get(crate::dummy_catalog::EXPECTED_PARTITION_EXPR_VERSION_KEY)
})
.cloned(),
));
let response = self
.responses
.get(&request.region_id)
@@ -2629,6 +2664,29 @@ mod tests {
assert_eq!((a.value(0), b.value(0)), values);
}
#[tokio::test]
async fn test_merge_scan_sends_planned_partition_versions() {
let ids = [RegionId::new(1024, 1), RegionId::new(1024, 2)];
let batch = record_batch(
int64_schema(&["a", "b"]),
vec![
Arc::new(Int64Vector::from_slice([11])) as _,
Arc::new(Int64Vector::from_slice([12])) as _,
],
);
let handler = Arc::new(TestRegionQueryHandler::new(
ids.map(|id| (id, batch.clone())),
));
let exec =
merge_scan_exec_with_handler(ids.to_vec(), expected_int64_schema(), handler.clone(), 1)
.with_partition_versions(HashMap::from_iter([(ids[0], 41), (ids[1], 42)]));
collect_merge_scan(exec).await.unwrap();
assert_eq!(
*handler.versions.lock().unwrap(),
vec![(ids[0], Some("41".into())), (ids[1], Some("42".into()))]
);
}
#[tokio::test]
async fn qbs_merge_scan_remote_schema_identity_canonical_single_region() {
let batch = record_batch(
+155 -39
View File
@@ -14,13 +14,13 @@
//! [ExtensionPlanner] implementation for distributed planner
use std::borrow::Cow;
use std::sync::Arc;
use ahash::HashMap;
use arrow_schema::SortOptions;
use async_trait::async_trait;
use catalog::CatalogManagerRef;
use common_base::hash::partition_expr_version;
use common_catalog::consts::{DEFAULT_CATALOG_NAME, DEFAULT_SCHEMA_NAME};
use common_telemetry::debug;
use datafusion::catalog::Session;
@@ -151,6 +151,11 @@ pub struct DistExtensionPlanner {
enable_per_region_metrics: bool,
}
struct RegionReadPlan {
regions: Vec<RegionId>,
partition_versions: HashMap<RegionId, u64>,
}
impl DistExtensionPlanner {
pub fn new(
catalog_manager: CatalogManagerRef,
@@ -202,10 +207,9 @@ impl ExtensionPlanner for DistExtensionPlanner {
return fallback(optimized_plan).await;
};
let Ok(regions) = self.get_regions(&table_name, input_plan).await else {
// no peers found, going to execute them locally
return fallback(optimized_plan).await;
};
// A resolved table must not fall back to an unfenced local scan when its
// authoritative route cannot be read or is in transition.
let region_plan = self.get_region_plan(&table_name, input_plan).await?;
// TODO(ruihang): generate different execution plans for different variant merge operation
let schema = merge_scan.schema().as_arrow();
@@ -224,7 +228,7 @@ impl ExtensionPlanner for DistExtensionPlanner {
let merge_scan_plan = MergeScanExec::new(
session_state,
table_name,
regions,
region_plan.regions,
input_plan.clone(),
schema,
self.region_query_handler.clone(),
@@ -232,7 +236,8 @@ impl ExtensionPlanner for DistExtensionPlanner {
session.config().target_partitions(),
merge_scan.remote_dyn_filter_producer_id(),
self.enable_per_region_metrics,
)?;
)?
.with_partition_versions(region_plan.partition_versions);
Ok(Some(Arc::new(merge_scan_plan) as _))
}
}
@@ -245,11 +250,22 @@ impl DistExtensionPlanner {
Ok(extractor.table_name)
}
#[cfg(test)]
async fn get_regions(
&self,
table_name: &TableName,
logical_plan: &LogicalPlan,
plan: &LogicalPlan,
) -> Result<Vec<RegionId>> {
self.get_region_plan(table_name, plan)
.await
.map(|plan| plan.regions)
}
async fn get_region_plan(
&self,
table_name: &TableName,
logical_plan: &LogicalPlan,
) -> Result<RegionReadPlan> {
let mut extractor = TableScanExtractor::default();
let _ = logical_plan.visit(&mut extractor)?;
// Resolving by name again could bind an authorized scan to a replacement table.
@@ -276,26 +292,46 @@ impl DistExtensionPlanner {
.find_physical_read_route_with_id(table_info.table_id())
.await
.context(PartitionRuleManagerSnafu)?;
// 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
if routes
.iter()
.any(|route| route.is_repartition_pending_read())
.any(|route| route.is_repartition_pending_read() || route.is_leader_staging())
{
Cow::Owned(
routes
.iter()
.filter(|route| !route.is_repartition_pending_read())
.cloned()
.collect::<Vec<_>>(),
)
} else {
Cow::Borrowed(routes.as_slice())
return Err(DataFusionError::External(Box::new(
crate::error::RepartitionInProgressSnafu {
table_id: table_info.table_id(),
}
.build(),
)));
}
// IgnoreAllWrites is set on merge sources scheduled for deallocation. Their
// files can remain open after the new owner has become readable.
let read_routes = routes
.iter()
.filter(|route| !route.is_ignore_all_writes())
.cloned()
.collect::<Vec<_>>();
let partition_versions: HashMap<_, _> = read_routes
.iter()
.map(|route| {
let expr = route.region.partition_expr();
(
RegionId::new(table_info.table_id(), route.region.id.region_number()),
partition_expr_version(if expr.is_empty() {
None
} else {
Some(expr.as_str())
}),
)
})
.collect();
let planned = |regions| RegionReadPlan {
regions,
partition_versions: partition_versions.clone(),
};
let all_regions = read_routes
.iter()
.map(|r| RegionId::new(table_info.table_id(), r.region.id.region_number()))
.map(|route| RegionId::new(table_info.table_id(), route.region.id.region_number()))
.collect::<Vec<_>>();
let logical_partition_columns = partition_column_types(&table_info);
let partition_columns = logical_partition_columns
@@ -311,7 +347,7 @@ impl DistExtensionPlanner {
all_regions,
);
if partition_columns.is_empty() {
return Ok(all_regions);
return Ok(planned(all_regions));
}
// Extract predicates from logical plan
let partition_expressions = match PredicateExtractor::extract_partition_expressions(
@@ -326,12 +362,12 @@ impl DistExtensionPlanner {
table.table_info().table_id(),
err
);
return Ok(all_regions);
return Ok(planned(all_regions));
}
};
if partition_expressions.is_empty() {
return Ok(all_regions);
return Ok(planned(all_regions));
}
let Some(partition_column_types) = self
@@ -344,7 +380,7 @@ impl DistExtensionPlanner {
)
.await
else {
return Ok(all_regions);
return Ok(planned(all_regions));
};
// Get partition information for the table if partition rule manager is available
@@ -357,11 +393,11 @@ impl DistExtensionPlanner {
table_name,
err
);
return Ok(all_regions);
return Ok(planned(all_regions));
}
};
if partitions.is_empty() {
return Ok(all_regions);
return Ok(planned(all_regions));
}
// Apply region pruning based on partition rules
let pruned_regions = match ConstraintPruner::prune_regions(
@@ -376,7 +412,7 @@ impl DistExtensionPlanner {
table_name,
err
);
return Ok(all_regions);
return Ok(planned(all_regions));
}
};
@@ -388,7 +424,7 @@ impl DistExtensionPlanner {
pruned_regions.len()
);
Ok(pruned_regions)
Ok(planned(pruned_regions))
}
/// Resolves the partition-column types that are safe to use for region pruning.
@@ -588,8 +624,12 @@ mod tests {
use table::table_name::TableName;
use table::test_util::EmptyTable;
use super::DistExtensionPlanner;
use super::{
DistExtensionPlanner, ExtensionPlanner, MergeScanLogicalPlan, PhysicalPlanningContext,
};
use crate::region_query::{RegionQueryHandler, RegionQueryTarget};
use common_base::hash::partition_expr_version;
use datafusion_common::DataFusionError;
const LOGICAL_TABLE_ID: u32 = 1024;
const PHYSICAL_TABLE_ID: u32 = 2048;
@@ -794,7 +834,7 @@ mod tests {
}
#[tokio::test]
async fn test_pending_repartition_targets_excluded_from_reads() {
async fn test_repartition_transition_rejects_reads_until_handoff_complete() {
let expression = Some(partition_col("host").lt(Value::String("z".into())));
let mut source = region_route(1, expression.clone());
source.set_leader_staging();
@@ -803,19 +843,27 @@ mod tests {
// 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;
let error = planner.get_regions(&name, &plan).await.unwrap_err();
let DataFusionError::External(error) = error else {
panic!("expected retryable error")
};
let error = error.downcast_ref::<crate::error::Error>().unwrap();
use common_error::ext::ErrorExt;
assert_eq!(
planner.get_regions(&name, &plan).await.unwrap(),
vec![RegionId::new(LOGICAL_TABLE_ID, 1)]
error.status_code(),
common_error::status_code::StatusCode::RegionNotReady
);
assert_eq!(
error.retry_hint(),
common_error::ext::RetryHint::RetryAfterRouteRefresh
);
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.
assert!(planner.get_regions(&name, &filter.input).await.is_err());
// Only the completed handoff makes both scopes available.
target.clear_repartition_pending_read();
source.clear_leader_staging();
// Deliberately do not invalidate the cached pending snapshot.
backend
.put(
@@ -847,6 +895,74 @@ mod tests {
.unwrap();
// A failed authoritative refresh must not fall back to silently hiding targets.
assert!(planner.get_regions(&name, &plan).await.is_err());
let session = datafusion::execution::SessionStateBuilder::new()
.with_default_features()
.build();
let error = planner
.plan_extension(
&datafusion::physical_planner::DefaultPhysicalPlanner::default(),
&MergeScanLogicalPlan::new(plan, false),
&[],
&[],
&session,
&PhysicalPlanningContext::default(),
)
.await
.unwrap_err();
let DataFusionError::External(error) = error else {
panic!("route refresh failure must be preserved")
};
assert!(matches!(
error.downcast_ref::<crate::error::Error>(),
Some(crate::error::Error::PartitionRuleManager { .. })
));
}
#[tokio::test]
async fn test_repartition_merge_refresh_excludes_retired_source_and_locks_versions() {
let mut source = region_route(1, Some(partition_col("host").lt(Value::String("m".into()))));
source.set_ignore_all_writes();
source.set_leader_staging();
let mut target = region_route(2, Some(partition_col("host").lt(Value::String("z".into()))));
target.set_leader_staging();
let (planner, plan, name, backend) =
planner_and_plan_with_routes(vec![0], vec![source.clone(), target.clone()]).await;
// Pure merges do not allocate pending targets, but are still unsafe during staging.
assert!(planner.get_regions(&name, &plan).await.is_err());
source.clear_leader_staging();
target.clear_leader_staging();
let expected = partition_expr_version(Some(&target.region.partition_expr));
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 planned = planner.get_region_plan(&name, &plan).await.unwrap();
assert_eq!(planned.regions, vec![RegionId::new(LOGICAL_TABLE_ID, 2)]);
assert_eq!(planned.partition_versions.len(), 1);
assert_eq!(
planned.partition_versions[&RegionId::new(LOGICAL_TABLE_ID, 2)],
expected
);
// A later route change cannot silently give this old candidate set new versions.
backend
.delete_range(
DeleteRangeRequest::new()
.with_key(TableRouteKey::new(PHYSICAL_TABLE_ID).to_bytes()),
)
.await
.unwrap();
assert_eq!(
planned.partition_versions[&RegionId::new(LOGICAL_TABLE_ID, 2)],
expected
);
}
fn physical_partition_expressions() -> Vec<Option<PartitionExpr>> {
+44 -1
View File
@@ -337,12 +337,30 @@ impl DummyTableProviderFactory {
}
}
/// Internal FE-to-DN fence for the partition scope selected during planning.
pub(crate) const EXPECTED_PARTITION_EXPR_VERSION_KEY: &str =
"greptime:expected-partition-expr-version";
fn scan_request_from_query_context(
region_id: RegionId,
query_ctx: &QueryContext,
) -> Result<ScanRequest> {
let decision = decide_flow_scan(query_ctx, region_id)?;
Ok(build_scan_request(query_ctx, region_id, &decision))
let mut request = build_scan_request(query_ctx, region_id, &decision);
request.expected_partition_expr_version = query_ctx
.extension(EXPECTED_PARTITION_EXPR_VERSION_KEY)
.map(|value| {
value.parse::<u64>().map_err(|_| {
crate::error::InvalidQueryContextExtensionSnafu {
reason: format!(
"{EXPECTED_PARTITION_EXPR_VERSION_KEY} must be an unsigned integer"
),
}
.build()
})
})
.transpose()?;
Ok(request)
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -684,6 +702,31 @@ mod tests {
);
}
#[test]
fn test_partition_scope_fence_query_context_wire_roundtrip() {
let region_id = test_region_id();
let mut context = QueryContextBuilder::default().build();
assert_eq!(
scan_request_from_query_context(region_id, &context)
.unwrap()
.expected_partition_expr_version,
None
);
context.set_extension(super::EXPECTED_PARTITION_EXPR_VERSION_KEY, "42");
let wire: api::v1::QueryContext = (&context).into();
let restored = QueryContext::try_from(wire).unwrap();
assert_eq!(
scan_request_from_query_context(region_id, &restored)
.unwrap()
.expected_partition_expr_version,
Some(42)
);
for invalid in ["", "-1", "not-a-version", "18446744073709551616"] {
context.set_extension(super::EXPECTED_PARTITION_EXPR_VERSION_KEY, invalid);
assert!(scan_request_from_query_context(region_id, &context).is_err());
}
}
fn test_region_id() -> RegionId {
RegionId::new(1024, 1)
}
+26 -7
View File
@@ -361,6 +361,13 @@ pub enum Error {
location: Location,
},
#[snafu(display("Repartition is in progress for table {}; retry the query", table_id))]
RepartitionInProgress {
table_id: u32,
#[snafu(implicit)]
location: Location,
},
#[snafu(display("Invalid query context extension: {}", reason))]
InvalidQueryContextExtension {
reason: String,
@@ -443,7 +450,7 @@ impl ErrorExt for Error {
RegionQuery { source, .. } => source.status_code(),
TableMutation { source, .. } => source.status_code(),
MissingTableMutationHandler { .. } => StatusCode::Unexpected,
GetRegionMetadata { .. } => StatusCode::RegionNotReady,
GetRegionMetadata { .. } | RepartitionInProgress { .. } => StatusCode::RegionNotReady,
TableReadOnly { .. } => StatusCode::Unsupported,
GetFulltextOptions { source, .. }
@@ -462,6 +469,7 @@ impl ErrorExt for Error {
match self {
BuildBackend { source, .. } | ListObjects { source, .. } => source.retry_hint(),
GetRegionMetadata { .. } => RetryHint::Retryable,
RepartitionInProgress { .. } => RetryHint::RetryAfterRouteRefresh,
ParseFileFormat { source, .. } | InferSchema { source, .. } => source.retry_hint(),
Catalog { source, .. } => source.retry_hint(),
CreateRecordBatch { source, .. } => source.retry_hint(),
@@ -495,15 +503,26 @@ mod tests {
#[test]
fn test_datafusion_external_boxed_error_status_code() {
for status in [StatusCode::RequestOutdated, StatusCode::RegionNotReady] {
let error = Error::DataFusion {
error: DataFusionError::External(Box::new(BoxedError::new(PlainError::new(
"neutral error".to_string(),
status,
)))),
location: Location::default(),
};
assert_eq!(error.status_code(), status);
}
}
#[test]
fn test_repartition_error_preserves_datafusion_status() {
let source = RepartitionInProgressSnafu { table_id: 42_u32 }.build();
let error = Error::DataFusion {
error: DataFusionError::External(Box::new(BoxedError::new(PlainError::new(
"neutral error".to_string(),
StatusCode::RequestOutdated,
)))),
error: source.into(),
location: Location::default(),
};
assert_eq!(error.status_code(), StatusCode::RequestOutdated);
assert_eq!(error.status_code(), StatusCode::RegionNotReady);
}
#[test]
+11
View File
@@ -47,6 +47,9 @@ pub enum TimeSeriesDistribution {
#[derive(Default, Clone, Debug, PartialEq)]
pub struct ScanRequest {
/// Partition scope captured by distributed query planning. The engine validates
/// it against the same immutable metadata snapshot used by the scan.
pub expected_partition_expr_version: Option<u64>,
/// Optional projection information for the scan. `None` reads all root
/// columns.
pub projection: Option<Vec<usize>>,
@@ -117,6 +120,14 @@ impl Display for ScanRequest {
let mut delimiter = Delimiter::None;
write!(f, "ScanRequest {{ ")?;
if let Some(version) = self.expected_partition_expr_version {
write!(
f,
"{}expected_partition_expr_version: {}",
delimiter.as_str(),
version
)?;
}
if let Some(projection) = &self.projection {
write!(f, "{}projection: {:?}", delimiter.as_str(), projection)?;
}
@@ -1,15 +1,13 @@
# 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.
`greptime:repartition-pending-read` attribute. Its presence rejects new query planning until every target manifest and the retained source have completed the handoff.
Routes without the attribute remain readable; unknown values also mark a pending handoff.
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
The query test `test_repartition_transition_rejects_reads_until_handoff_complete` 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.
Older frontends preserve the attribute but do not honor it. Upgrade both query frontends and datanodes before relying on this protection during concurrent reads and repartition. New frontends send the partition version captured during planning; new datanodes check it against the pinned scan snapshot. Legacy requests without that version keep their previous behavior.