mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
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:
+29
-16
@@ -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]
|
||||
|
||||
@@ -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);
|
||||
|
||||
+1
-3
@@ -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());
|
||||
}
|
||||
|
||||
|
||||
@@ -593,6 +593,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 }),
|
||||
@@ -610,6 +611,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,
|
||||
|
||||
@@ -1281,6 +1281,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() {
|
||||
|
||||
@@ -9074,3 +9074,131 @@ async fn test_time_windowed_seq_scan_keeps_files_with_disjoint_keys_together() {
|
||||
// Rows come out in `(ts, primary key)` order without sorting them.
|
||||
assert_eq!(vec!["a", "b", "c"], keys);
|
||||
}
|
||||
|
||||
#[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()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -923,6 +923,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,
|
||||
@@ -1873,6 +1881,7 @@ impl ErrorExt for Error {
|
||||
| InvalidPrimaryKeyRange { .. }
|
||||
| DecodePrimaryKeyRange { .. } => StatusCode::Internal,
|
||||
RegionBusy { .. } | EndStagingPending { .. } => StatusCode::RegionBusy,
|
||||
ReadRegionNotReady { .. } => StatusCode::RegionNotReady,
|
||||
GetSchemaMetadata { source, .. } => source.status_code(),
|
||||
Timeout { .. } => StatusCode::Cancelled,
|
||||
|
||||
@@ -1927,6 +1936,7 @@ impl ErrorExt for Error {
|
||||
|
||||
match self {
|
||||
PartitionExprVersionMismatch { .. }
|
||||
| ReadRegionNotReady { .. }
|
||||
| RegionNotFound { .. }
|
||||
| RegionClosed { .. }
|
||||
| RejectWriteInStaging { .. }
|
||||
|
||||
@@ -123,7 +123,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,
|
||||
@@ -132,7 +132,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
|
||||
|
||||
@@ -522,6 +522,7 @@ impl MergeScanLogicalPlan {
|
||||
pub struct MergeScanExec {
|
||||
table: TableName,
|
||||
regions: Vec<RegionId>,
|
||||
partition_versions: Arc<HashMap<RegionId, u64>>,
|
||||
plan: LogicalPlan,
|
||||
arrow_schema: ArrowSchemaRef,
|
||||
remote_schema: ArrowSchemaRef,
|
||||
@@ -613,6 +614,7 @@ impl MergeScanExec {
|
||||
Ok(Self {
|
||||
table,
|
||||
regions,
|
||||
partition_versions: Arc::default(),
|
||||
plan,
|
||||
arrow_schema,
|
||||
remote_schema,
|
||||
@@ -658,6 +660,12 @@ impl MergeScanExec {
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// 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
|
||||
@@ -687,6 +695,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();
|
||||
@@ -780,6 +789,12 @@ impl MergeScanExec {
|
||||
region_id,
|
||||
&captured_remote_dyn_filters,
|
||||
);
|
||||
if let Some(version) = partition_versions.get(®ion_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 {
|
||||
@@ -2166,6 +2181,7 @@ mod tests {
|
||||
select_target_calls: AtomicUsize,
|
||||
read_preferences: Mutex<Vec<ReadPreference>>,
|
||||
do_get_targets: Mutex<Vec<u64>>,
|
||||
versions: Mutex<Vec<(RegionId, Option<String>)>>,
|
||||
}
|
||||
|
||||
impl TestRegionQueryHandler {
|
||||
@@ -2610,6 +2626,19 @@ mod tests {
|
||||
request: common_query::request::QueryRequest,
|
||||
) -> crate::error::Result<common_recordbatch::SendableRecordBatchStream> {
|
||||
self.do_get_targets.lock().unwrap().push(target.peer().id);
|
||||
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)
|
||||
@@ -2727,6 +2756,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(
|
||||
|
||||
@@ -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;
|
||||
@@ -155,6 +155,12 @@ pub struct DistExtensionPlanner {
|
||||
enable_per_region_metrics: bool,
|
||||
}
|
||||
|
||||
struct RegionReadPlan {
|
||||
series_disjoint: bool,
|
||||
regions: Vec<RegionId>,
|
||||
partition_versions: HashMap<RegionId, u64>,
|
||||
}
|
||||
|
||||
impl DistExtensionPlanner {
|
||||
pub fn new(
|
||||
catalog_manager: CatalogManagerRef,
|
||||
@@ -213,14 +219,9 @@ impl ExtensionPlanner for DistExtensionPlanner {
|
||||
return fallback(optimized_plan).await;
|
||||
};
|
||||
|
||||
let (regions, series_disjoint) = match self.get_regions(&table_name, input_plan).await {
|
||||
Ok(regions) => regions,
|
||||
Err(error) if direct_raw => {
|
||||
return Err(error);
|
||||
}
|
||||
// Existing non-raw plans may still execute locally when no peers are found.
|
||||
Err(_) => 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();
|
||||
@@ -239,7 +240,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(),
|
||||
@@ -248,7 +249,8 @@ impl ExtensionPlanner for DistExtensionPlanner {
|
||||
merge_scan.remote_dyn_filter_producer_id(),
|
||||
self.enable_per_region_metrics,
|
||||
)?
|
||||
.with_raw_series_disjoint(series_disjoint)?;
|
||||
.with_raw_series_disjoint(region_plan.series_disjoint)?
|
||||
.with_partition_versions(region_plan.partition_versions);
|
||||
Ok(Some(Arc::new(merge_scan_plan) as _))
|
||||
}
|
||||
}
|
||||
@@ -261,12 +263,22 @@ impl DistExtensionPlanner {
|
||||
Ok(extractor.table_name)
|
||||
}
|
||||
|
||||
/// Selects the regions of the ordinary distributed plan.
|
||||
#[cfg(test)]
|
||||
async fn get_regions(
|
||||
&self,
|
||||
table_name: &TableName,
|
||||
logical_plan: &LogicalPlan,
|
||||
plan: &LogicalPlan,
|
||||
) -> Result<(Vec<RegionId>, bool)> {
|
||||
self.get_region_plan(table_name, plan)
|
||||
.await
|
||||
.map(|plan| (plan.regions, plan.series_disjoint))
|
||||
}
|
||||
|
||||
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.
|
||||
@@ -294,26 +306,42 @@ 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 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
|
||||
@@ -430,11 +458,14 @@ impl DistExtensionPlanner {
|
||||
.ok()
|
||||
.flatten()
|
||||
};
|
||||
physical_info.is_some_and(|info| {
|
||||
physical_regions_disjoint(&info, &read_routes, ®ions)
|
||||
})
|
||||
physical_info
|
||||
.is_some_and(|info| physical_regions_disjoint(&info, &read_routes, ®ions))
|
||||
};
|
||||
Ok((regions, series_disjoint))
|
||||
Ok(RegionReadPlan {
|
||||
regions,
|
||||
partition_versions,
|
||||
series_disjoint,
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolves the partition-column types that are safe to use for region pruning.
|
||||
@@ -791,8 +822,13 @@ mod tests {
|
||||
use table::table_name::TableName;
|
||||
use table::test_util::EmptyTable;
|
||||
|
||||
use super::{DistExtensionPlanner, physical_regions_disjoint};
|
||||
use super::{
|
||||
DistExtensionPlanner, ExtensionPlanner, MergeScanLogicalPlan, PhysicalPlanningContext,
|
||||
physical_regions_disjoint,
|
||||
};
|
||||
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;
|
||||
@@ -1019,7 +1055,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();
|
||||
@@ -1028,19 +1064,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(
|
||||
@@ -1072,6 +1116,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>> {
|
||||
|
||||
@@ -348,12 +348,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)]
|
||||
@@ -695,6 +713,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
@@ -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]
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in New Issue
Block a user