mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-26 12:44:10 +00:00
fix(metric): route logical table writes by internal table id (#10366)
* fix(metric): pass logical table identity to partition evaluation Signed-off-by: WenyXu <wenymedia@gmail.com> * test(metric): cover table-id repartition routing across storage formats Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(partition): validate logical routing inputs Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(metric): retain table ids for physical batch routing Signed-off-by: WenyXu <wenymedia@gmail.com> * refactor(partition): simplify table-id routing paths Separate context dispatch, routing input construction and column conversion into private methods while preserving the scalar payload path. Reuse the existing table-id constant and shared IPC decoding in tests. Keep correctly routed requests intact when their partition version is unchanged. Update existing retry coverage to use stale versions for rerouting and verify unchanged bulk requests preserve alignment and ownership. Signed-off-by: WenyXu <wenymedia@gmail.com> * fix(servers): validate table-id column row count Report mismatched logical table identities before Arrow column construction, document batch and row ordering requirements, and remove the unreachable batch skip. Extend the existing conversion test and clarify the partition evaluation context contract. Signed-off-by: WenyXu <wenymedia@gmail.com> --------- Signed-off-by: WenyXu <wenymedia@gmail.com>
This commit is contained in:
Generated
+1
@@ -15564,6 +15564,7 @@ dependencies = [
|
||||
"opentelemetry-proto",
|
||||
"operator",
|
||||
"otel-arrow-rust",
|
||||
"partition",
|
||||
"paste",
|
||||
"pipeline",
|
||||
"plugins",
|
||||
|
||||
@@ -246,7 +246,8 @@ mod tests {
|
||||
use mito2::sst::parquet::metadata::MetadataLoader;
|
||||
use mito2::sst::parquet::reader::MetadataCacheMetrics;
|
||||
use store_api::metric_engine_consts::{
|
||||
METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY, PRIMARY_KEY_ENCODING,
|
||||
DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_ENGINE_NAME, PHYSICAL_TABLE_METADATA_KEY,
|
||||
PRIMARY_KEY_ENCODING,
|
||||
};
|
||||
use store_api::mito_engine_options::EXPERIMENTAL_SST_FLOAT_FIELD_ENCODING;
|
||||
use store_api::path_utils::table_dir;
|
||||
@@ -519,6 +520,23 @@ mod tests {
|
||||
physical_batch.column_by_name("job").is_some(),
|
||||
retain_partition_columns
|
||||
);
|
||||
let physical_batch = if retain_partition_columns {
|
||||
// The batcher retains identity for routing; sparse storage still uses the
|
||||
// identity encoded in __primary_key, including after WAL recovery.
|
||||
let mut fields = physical_batch.schema().fields().to_vec();
|
||||
fields.push(Arc::new(Field::new(
|
||||
DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
|
||||
DataType::UInt32,
|
||||
false,
|
||||
)));
|
||||
let mut columns = physical_batch.columns().to_vec();
|
||||
columns.push(Arc::new(datatypes::arrow::array::UInt32Array::from(vec![
|
||||
logical_region_id.table_id(); physical_batch.num_rows()
|
||||
])));
|
||||
RecordBatch::try_new(Arc::new(ArrowSchema::new(fields)), columns).unwrap()
|
||||
} else {
|
||||
physical_batch
|
||||
};
|
||||
let request = build_bulk_request(physical_region_id, physical_batch, skip_wal);
|
||||
let response = env
|
||||
.metric()
|
||||
|
||||
@@ -686,6 +686,7 @@ mod tests {
|
||||
use partition::expr;
|
||||
use partition::manager::{PartitionRuleManager, PartitionRuleManagerRef};
|
||||
use partition::multi_dim::MultiDimPartitionRule;
|
||||
use partition::partition::PartitionEvalContext;
|
||||
use store_api::metric_engine_consts;
|
||||
|
||||
use super::*;
|
||||
@@ -777,6 +778,96 @@ mod tests {
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_physical_bulk_retry_preserves_per_row_table_ids() {
|
||||
use datatypes::arrow::array::UInt32Array;
|
||||
|
||||
let table_info = build_sparse_table_info();
|
||||
let batch = build_sparse_batch();
|
||||
let mut fields = batch.schema().fields().to_vec();
|
||||
fields.push(Arc::new(Field::new(
|
||||
metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
|
||||
DataType::UInt32,
|
||||
false,
|
||||
)));
|
||||
let mut columns = batch.columns().to_vec();
|
||||
columns.push(Arc::new(UInt32Array::from(vec![42, 43, 44, 45, 46])));
|
||||
let batch = RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap();
|
||||
// Initially no partition uses table id, but the payload must retain it.
|
||||
let initial = TablePartitioner {
|
||||
table_id: 1,
|
||||
rule: Arc::new(MultiDimPartitionRule::try_new(vec![], vec![1], vec![], false).unwrap()),
|
||||
versions: HashMap::from([(1, Some(PartitionExprVersion { value: 1 }))]),
|
||||
};
|
||||
let requests = initial
|
||||
.partition_bulk_insert_requests(batch.clone(), None, false)
|
||||
.unwrap();
|
||||
assert_eq!(requests.len(), 1);
|
||||
let refreshed = TablePartitioner {
|
||||
table_id: 1,
|
||||
rule: Arc::new(
|
||||
MultiDimPartitionRule::try_new(
|
||||
vec![metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME.to_string()],
|
||||
vec![1, 2],
|
||||
vec![
|
||||
expr::col(metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME)
|
||||
.lt(DataValue::UInt32(44)),
|
||||
expr::col(metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME)
|
||||
.gt_eq(DataValue::UInt32(44)),
|
||||
],
|
||||
true,
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
versions: HashMap::from([
|
||||
(1, Some(PartitionExprVersion { value: 2 })),
|
||||
(2, Some(PartitionExprVersion { value: 2 })),
|
||||
]),
|
||||
};
|
||||
assert_eq!(
|
||||
refreshed.rule.eval_context(),
|
||||
PartitionEvalContext::FromPayload
|
||||
);
|
||||
let request = build_request(Body::BulkInsert(requests[0].clone()));
|
||||
let mut plain = refreshed
|
||||
.rebuild_write_requests(request.clone(), &table_info)
|
||||
.unwrap();
|
||||
plain.sort_by_key(|r| match r.body.as_ref().unwrap() {
|
||||
Body::BulkInsert(b) => b.region_id,
|
||||
_ => unreachable!(),
|
||||
});
|
||||
let mut tracked = refreshed
|
||||
.rebuild_tracked_write_requests(request, &table_info, Some(vec![0, 1, 2, 3, 4]))
|
||||
.unwrap();
|
||||
tracked.sort_by_key(|(r, _)| match r.body.as_ref().unwrap() {
|
||||
Body::BulkInsert(b) => b.region_id,
|
||||
_ => unreachable!(),
|
||||
});
|
||||
assert_eq!(plain.len(), 2);
|
||||
assert_eq!(tracked.len(), 2);
|
||||
for (index, (request, owners)) in tracked.into_iter().enumerate() {
|
||||
assert_eq!(request.body, plain[index].body);
|
||||
let Some(Body::BulkInsert(request)) = request.body else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!(
|
||||
request.region_id,
|
||||
RegionId::new(1, index as u32 + 1).as_u64()
|
||||
);
|
||||
assert_eq!(
|
||||
request.partition_expr_version,
|
||||
Some(PartitionExprVersion { value: 2 })
|
||||
);
|
||||
let Some(bulk_insert_request::Body::ArrowIpc(ipc)) = request.body else {
|
||||
unreachable!()
|
||||
};
|
||||
let decoded = decode_ipc(&ipc);
|
||||
let (offset, len) = if index == 0 { (0, 2) } else { (2, 3) };
|
||||
assert_eq!(decoded, batch.slice(offset, len));
|
||||
assert_eq!(owners, Some((offset..offset + len).collect()));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_partition_tags_use_physical_table_metadata() {
|
||||
let backend = Arc::new(MemoryKvBackend::new());
|
||||
@@ -909,10 +1000,7 @@ mod tests {
|
||||
let Some(bulk_insert_request::Body::ArrowIpc(ipc)) = bulk.body else {
|
||||
unreachable!()
|
||||
};
|
||||
let actual = FlightDecoder::try_from_schema_bytes(&ipc.schema)
|
||||
.unwrap()
|
||||
.try_decode_record_batch(&ipc.data_header, &ipc.payload)
|
||||
.unwrap();
|
||||
let actual = decode_ipc(&ipc);
|
||||
let mask = if RegionId::from_u64(bulk.region_id).region_number() == 1 {
|
||||
vec![true, false, true, true, true]
|
||||
} else {
|
||||
@@ -1024,6 +1112,473 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
const CONTEXT_PHYSICAL_ID: TableId = 1025;
|
||||
|
||||
/// Physical routes of a table repartitioned by the internal table id.
|
||||
fn context_regions() -> Vec<(RegionNumber, Option<expr::PartitionExpr>)> {
|
||||
let column = || expr::col(metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME);
|
||||
vec![
|
||||
(0, Some(column().lt(DataValue::Int64(1029)))),
|
||||
(
|
||||
1,
|
||||
Some(
|
||||
column()
|
||||
.gt_eq(DataValue::Int64(1029))
|
||||
.and(column().lt(DataValue::UInt64(1031))),
|
||||
),
|
||||
),
|
||||
(2, Some(column().gt_eq(DataValue::UInt64(1031)))),
|
||||
]
|
||||
}
|
||||
|
||||
/// A logical table created before its physical table was repartitioned: its own
|
||||
/// schema and partition metadata know nothing about the internal table id.
|
||||
fn logical_metric_table_info(table_id: TableId) -> TableInfo {
|
||||
let mut table_info = test_util::new_test_table_info(
|
||||
table_id,
|
||||
&format!("logical_{table_id}"),
|
||||
[0].into_iter(),
|
||||
);
|
||||
table_info.meta.engine = metric_engine_consts::METRIC_ENGINE_NAME.to_string();
|
||||
table_info.meta.partition_key_indices.clear();
|
||||
table_info.meta.options.extra_options.insert(
|
||||
metric_engine_consts::LOGICAL_TABLE_METADATA_KEY.to_string(),
|
||||
CONTEXT_PHYSICAL_ID.to_string(),
|
||||
);
|
||||
table_info
|
||||
}
|
||||
|
||||
async fn create_context_fixture(
|
||||
regions: Vec<(RegionNumber, Option<expr::PartitionExpr>)>,
|
||||
logical_table_ids: &[TableId],
|
||||
) -> PartitionRuleManagerRef {
|
||||
let backend = Arc::new(MemoryKvBackend::new());
|
||||
let routes = test_new_table_route_cache(backend.clone());
|
||||
let partitions = test_new_partition_info_cache(routes.clone());
|
||||
let manager = Arc::new(PartitionRuleManager::new(
|
||||
backend.clone(),
|
||||
routes,
|
||||
partitions,
|
||||
));
|
||||
let metadata = TableMetadataManager::new(backend);
|
||||
|
||||
let routes = regions
|
||||
.into_iter()
|
||||
.map(|(region, expression)| RegionRoute {
|
||||
region: Region {
|
||||
id: RegionId::new(CONTEXT_PHYSICAL_ID, region),
|
||||
partition_expr: expression
|
||||
.map(|expr| expr.as_json_str().unwrap())
|
||||
.unwrap_or_default(),
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
metadata
|
||||
.create_table_metadata(
|
||||
test_util::new_test_table_info(
|
||||
CONTEXT_PHYSICAL_ID,
|
||||
"physical_context",
|
||||
[0].into_iter(),
|
||||
),
|
||||
TableRouteValue::physical(routes),
|
||||
Default::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
for table_id in logical_table_ids {
|
||||
metadata
|
||||
.create_table_metadata(
|
||||
logical_metric_table_info(*table_id),
|
||||
TableRouteValue::logical(CONTEXT_PHYSICAL_ID),
|
||||
Default::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
manager
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_logical_context_routes_rows_deletes_and_retries() {
|
||||
let logical_ids = [1028u32, 1029, 1030, 1031, 4_000_000_000];
|
||||
let manager = create_context_fixture(context_regions(), &logical_ids).await;
|
||||
for (table_id, expected_region) in [
|
||||
(1028, 0u32),
|
||||
(1029, 1),
|
||||
(1030, 1),
|
||||
(1031, 2),
|
||||
(4_000_000_000, 2),
|
||||
] {
|
||||
let table_info = logical_metric_table_info(table_id);
|
||||
let partitioner = TablePartitioner::try_new(&manager, &table_info)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
partitioner.rule.partition_columns(),
|
||||
&[metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME]
|
||||
);
|
||||
assert_eq!(
|
||||
partitioner.rule.eval_context(),
|
||||
PartitionEvalContext::WithTableId { table_id }
|
||||
);
|
||||
assert_eq!(partitioner.versions.len(), 3);
|
||||
let version = partitioner.version(expected_region);
|
||||
|
||||
let rows = build_rows(&[1, 20, 70]);
|
||||
let expected_rows = rows.clone();
|
||||
let pointer = rows.rows.as_ptr();
|
||||
let inserts = partitioner.partition_insert_requests(rows, true).unwrap();
|
||||
assert_eq!(inserts.len(), 1);
|
||||
assert_eq!(
|
||||
inserts[0].region_id,
|
||||
RegionId::new(table_id, expected_region).as_u64()
|
||||
);
|
||||
assert_eq!(inserts[0].partition_expr_version, version);
|
||||
let inserted = inserts[0].rows.as_ref().unwrap();
|
||||
assert_eq!(inserted, &expected_rows);
|
||||
assert_eq!(inserted.rows.as_ptr(), pointer);
|
||||
|
||||
let deletes = partitioner
|
||||
.partition_delete_requests(expected_rows.clone())
|
||||
.unwrap();
|
||||
assert_eq!(deletes.len(), 1);
|
||||
assert_eq!(deletes[0].region_id, inserts[0].region_id);
|
||||
assert_eq!(deletes[0].partition_expr_version, version);
|
||||
assert_eq!(deletes[0].rows.as_ref().unwrap(), &expected_rows);
|
||||
|
||||
// The manager route and the operator route come from the same snapshot.
|
||||
let split_input = expected_rows.clone();
|
||||
let split_pointer = split_input.rows.as_ptr();
|
||||
let splits = manager.split_rows(&table_info, split_input).await.unwrap();
|
||||
assert_eq!(splits.len(), 1);
|
||||
let (region, (split_rows, split_version)) = splits.iter().next().unwrap();
|
||||
assert_eq!(*region, expected_region);
|
||||
assert_eq!(split_rows.rows.as_ptr(), split_pointer);
|
||||
assert_eq!(split_version, &version.map(|version| version.value));
|
||||
|
||||
for insert in [true, false] {
|
||||
// A leader change can reuse a correctly routed request with the same version.
|
||||
let request = if insert {
|
||||
build_request(Body::Inserts(InsertRequests {
|
||||
requests: inserts.clone(),
|
||||
}))
|
||||
} else {
|
||||
build_request(Body::Deletes(DeleteRequests {
|
||||
requests: deletes.clone(),
|
||||
}))
|
||||
};
|
||||
let pointer = row_request_parts(&request).2.rows.as_ptr();
|
||||
let rebuilt = partitioner
|
||||
.rebuild_write_requests(request, &table_info)
|
||||
.unwrap();
|
||||
assert_eq!(rebuilt.len(), 1);
|
||||
let (region_id, rebuilt_version, rebuilt_rows) = row_request_parts(&rebuilt[0]);
|
||||
assert_eq!(region_id, RegionId::new(table_id, expected_region).as_u64());
|
||||
assert_eq!(rebuilt_version, version.map(|v| v.value));
|
||||
assert_eq!(rebuilt_rows, &expected_rows);
|
||||
assert_eq!(rebuilt_rows.rows.as_ptr(), pointer);
|
||||
|
||||
// Repartitioning replaces the old catch-all expression while retaining region 0.
|
||||
let old_expr = expr::col(metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME)
|
||||
.gt_eq(DataValue::UInt32(0))
|
||||
.as_json_str()
|
||||
.unwrap();
|
||||
for stale_version in [
|
||||
None,
|
||||
Some(common_base::hash::partition_expr_version(Some(&old_expr))),
|
||||
] {
|
||||
let mut stale =
|
||||
build_row_request(expected_rows.clone(), insert, 0, stale_version);
|
||||
match stale.body.as_mut().unwrap() {
|
||||
Body::Inserts(inserts) => {
|
||||
inserts.requests[0].region_id = RegionId::new(table_id, 0).as_u64()
|
||||
}
|
||||
Body::Deletes(deletes) => {
|
||||
deletes.requests[0].region_id = RegionId::new(table_id, 0).as_u64()
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
let rebuilt = partitioner
|
||||
.rebuild_write_requests(stale, &table_info)
|
||||
.unwrap();
|
||||
assert_eq!(rebuilt.len(), 1);
|
||||
let (region_id, rebuilt_version, rebuilt_rows) = row_request_parts(&rebuilt[0]);
|
||||
assert_eq!(region_id, RegionId::new(table_id, expected_region).as_u64());
|
||||
assert_eq!(rebuilt_version, version.map(|version| version.value));
|
||||
assert_eq!(rebuilt_rows, &expected_rows);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_logical_context_missing_payload_partition_column() {
|
||||
for with_table_id in [false, true] {
|
||||
let regions = [
|
||||
expr::col("a").lt(DataValue::Int32(10)),
|
||||
expr::col("a").gt_eq(DataValue::Int32(10)),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(region, expr)| {
|
||||
let expr = if with_table_id {
|
||||
expr.and(
|
||||
expr::col(metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME)
|
||||
.eq(DataValue::UInt32(1029)),
|
||||
)
|
||||
} else {
|
||||
expr
|
||||
};
|
||||
(region as RegionNumber, Some(expr))
|
||||
})
|
||||
.collect();
|
||||
let manager = create_context_fixture(regions, &[1029]).await;
|
||||
// The logical schema declares a; only the payload omits it.
|
||||
let table_info = logical_metric_table_info(1029);
|
||||
let partitioner = TablePartitioner::try_new(&manager, &table_info)
|
||||
.await
|
||||
.unwrap();
|
||||
let rows = Rows {
|
||||
schema: vec![api::v1::helper::tag_column_schema(
|
||||
"b",
|
||||
ColumnDataType::Int32,
|
||||
)],
|
||||
rows: vec![Row {
|
||||
values: vec![ValueData::I32Value(7).into()],
|
||||
}],
|
||||
};
|
||||
let inserts = partitioner
|
||||
.partition_insert_requests(rows.clone(), true)
|
||||
.unwrap();
|
||||
assert_eq!(inserts.len(), 1);
|
||||
assert_eq!(inserts[0].region_id, RegionId::new(1029, 0).as_u64());
|
||||
assert_eq!(inserts[0].rows.as_ref(), Some(&rows));
|
||||
|
||||
let batch = RecordBatch::try_new(
|
||||
Arc::new(Schema::new(vec![Field::new("b", DataType::Int32, false)])),
|
||||
vec![Arc::new(Int32Array::from(vec![7]))],
|
||||
)
|
||||
.unwrap();
|
||||
let (schema, data_header, payload) =
|
||||
flight::record_batch_to_ipc(batch.clone()).unwrap();
|
||||
let original = ArrowIpc {
|
||||
schema,
|
||||
data_header,
|
||||
payload,
|
||||
};
|
||||
let requests = partitioner
|
||||
.partition_bulk_insert_requests(batch, Some(original.clone()), true)
|
||||
.unwrap();
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert_eq!(requests[0].region_id, inserts[0].region_id);
|
||||
assert_eq!(
|
||||
requests[0].body,
|
||||
Some(bulk_insert_request::Body::ArrowIpc(original))
|
||||
);
|
||||
|
||||
let mut stale = requests[0].clone();
|
||||
stale.region_id = RegionId::new(1029, 1).as_u64();
|
||||
let rebuilt = partitioner
|
||||
.rebuild_write_requests(build_request(Body::BulkInsert(stale)), &table_info)
|
||||
.unwrap();
|
||||
assert_eq!(rebuilt.len(), 1);
|
||||
assert_eq!(rebuilt[0].body, Some(Body::BulkInsert(requests[0].clone())));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_logical_context_routes_whole_batch() {
|
||||
let manager = create_context_fixture(context_regions(), &[1029]).await;
|
||||
let table_info = logical_metric_table_info(1029);
|
||||
let partitioner = TablePartitioner::try_new(&manager, &table_info)
|
||||
.await
|
||||
.unwrap();
|
||||
let batch = RecordBatch::try_new(
|
||||
Arc::new(Schema::new(vec![Field::new("a", DataType::Int32, false)])),
|
||||
vec![Arc::new(Int32Array::from(vec![1, 20, 70]))],
|
||||
)
|
||||
.unwrap();
|
||||
let (schema, data_header, payload) = flight::record_batch_to_ipc(batch.clone()).unwrap();
|
||||
let original = ArrowIpc {
|
||||
schema,
|
||||
data_header,
|
||||
payload,
|
||||
};
|
||||
|
||||
let requests = partitioner
|
||||
.partition_bulk_insert_requests(batch.clone(), Some(original.clone()), true)
|
||||
.unwrap();
|
||||
assert_eq!(requests.len(), 1);
|
||||
assert_eq!(requests[0].region_id, RegionId::new(1029, 1).as_u64());
|
||||
assert_eq!(requests[0].partition_expr_version, partitioner.version(1));
|
||||
// The whole batch belongs to one region, so the caller's IPC is reused.
|
||||
let Some(bulk_insert_request::Body::ArrowIpc(ipc)) = requests[0].body.as_ref() else {
|
||||
unreachable!()
|
||||
};
|
||||
assert_eq!(ipc.schema, original.schema);
|
||||
assert_eq!(ipc.data_header, original.data_header);
|
||||
assert_eq!(ipc.payload, original.payload);
|
||||
|
||||
// Unchanged routing keeps schema alignment and ownership without rebuilding IPC.
|
||||
let mut unchanged = requests[0].clone();
|
||||
unchanged.aligned_schema_version = Some(AlignedSchemaVersion {
|
||||
schema_version: 123,
|
||||
});
|
||||
let request = build_request(Body::BulkInsert(unchanged));
|
||||
let rebuilt = partitioner
|
||||
.rebuild_write_requests(request.clone(), &table_info)
|
||||
.unwrap();
|
||||
assert_eq!(rebuilt, vec![request.clone()]);
|
||||
let owners = vec![0, 1, 2];
|
||||
let owners_pointer = owners.as_ptr();
|
||||
let tracked = partitioner
|
||||
.rebuild_tracked_write_requests(request.clone(), &table_info, Some(owners))
|
||||
.unwrap();
|
||||
assert_eq!(tracked.len(), 1);
|
||||
assert_eq!(tracked[0].0, request);
|
||||
assert_eq!(tracked[0].1.as_ref().unwrap(), &[0, 1, 2]);
|
||||
assert_eq!(tracked[0].1.as_ref().unwrap().as_ptr(), owners_pointer);
|
||||
|
||||
// Region 0 previously accepted all rows without a partition expression.
|
||||
for version in [None, Some(PartitionExprVersion { value: 0 })] {
|
||||
let mut stale = requests[0].clone();
|
||||
stale.region_id = RegionId::new(1029, 0).as_u64();
|
||||
stale.partition_expr_version = version;
|
||||
let stale = build_request(Body::BulkInsert(stale));
|
||||
let rebuilt = partitioner
|
||||
.rebuild_write_requests(stale.clone(), &table_info)
|
||||
.unwrap();
|
||||
assert_eq!(rebuilt.len(), 1);
|
||||
assert_eq!(rebuilt[0].body, Some(Body::BulkInsert(requests[0].clone())));
|
||||
let tracked = partitioner
|
||||
.rebuild_tracked_write_requests(stale, &table_info, Some(vec![0, 1, 2]))
|
||||
.unwrap();
|
||||
assert_eq!(tracked.len(), 1);
|
||||
assert_eq!(tracked[0].0.body, rebuilt[0].body);
|
||||
assert_eq!(tracked[0].1, Some(vec![0, 1, 2]));
|
||||
}
|
||||
|
||||
let tracked = partitioner
|
||||
.partition_tracked_bulk_insert_requests(batch, vec![0, 1, 2], true)
|
||||
.unwrap();
|
||||
assert_eq!(tracked.len(), 1);
|
||||
assert_eq!(tracked[0].0.region_id, RegionId::new(1029, 1).as_u64());
|
||||
assert_eq!(tracked[0].1, vec![0, 1, 2]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_logical_context_routes_mixed_partition_columns() {
|
||||
let column = || expr::col(metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME);
|
||||
let manager = create_context_fixture(
|
||||
vec![
|
||||
(0, Some(column().lt(DataValue::Int64(1029)))),
|
||||
(
|
||||
1,
|
||||
Some(
|
||||
column()
|
||||
.gt_eq(DataValue::Int64(1029))
|
||||
.and(expr::col("a").lt(DataValue::Int32(10))),
|
||||
),
|
||||
),
|
||||
(
|
||||
2,
|
||||
Some(
|
||||
column()
|
||||
.gt_eq(DataValue::Int64(1029))
|
||||
.and(expr::col("a").gt_eq(DataValue::Int32(10))),
|
||||
),
|
||||
),
|
||||
],
|
||||
&[1028, 1029],
|
||||
)
|
||||
.await;
|
||||
for (table_id, expected) in [
|
||||
(1028, vec![(0, vec![1, 20])]),
|
||||
(1029, vec![(1, vec![1]), (2, vec![20])]),
|
||||
] {
|
||||
let table_info = logical_metric_table_info(table_id);
|
||||
let partitioner = TablePartitioner::try_new(&manager, &table_info)
|
||||
.await
|
||||
.unwrap();
|
||||
let rows = build_rows(&[1, 20]);
|
||||
let inserts = partitioner
|
||||
.partition_insert_requests(rows.clone(), false)
|
||||
.unwrap();
|
||||
assert_eq!(inserts.len(), expected.len());
|
||||
let deletes = partitioner.partition_delete_requests(rows).unwrap();
|
||||
for (region, values) in &expected {
|
||||
let region_id = RegionId::new(table_id, *region).as_u64();
|
||||
let inserted = inserts.iter().find(|r| r.region_id == region_id).unwrap();
|
||||
assert_eq!(inserted.rows.as_ref().unwrap(), &build_rows(values));
|
||||
assert_eq!(
|
||||
deletes
|
||||
.iter()
|
||||
.find(|r| r.region_id == region_id)
|
||||
.unwrap()
|
||||
.rows,
|
||||
inserted.rows
|
||||
);
|
||||
}
|
||||
let batch = RecordBatch::try_from_iter([(
|
||||
"a",
|
||||
Arc::new(Int32Array::from(vec![1, 20])) as datatypes::arrow::array::ArrayRef,
|
||||
)])
|
||||
.unwrap();
|
||||
let requests = partitioner
|
||||
.partition_tracked_bulk_insert_requests(batch, vec![0, 1], false)
|
||||
.unwrap();
|
||||
assert_eq!(requests.len(), expected.len());
|
||||
for (request, owners) in requests {
|
||||
let region = RegionId::from_u64(request.region_id).region_number();
|
||||
let values = &expected
|
||||
.iter()
|
||||
.find(|(number, _)| *number == region)
|
||||
.unwrap()
|
||||
.1;
|
||||
let Some(bulk_insert_request::Body::ArrowIpc(ipc)) = request.body else {
|
||||
unreachable!()
|
||||
};
|
||||
let decoded = decode_ipc(&ipc);
|
||||
assert_eq!(decoded.num_columns(), 1);
|
||||
let actual = decoded
|
||||
.column(0)
|
||||
.as_any()
|
||||
.downcast_ref::<Int32Array>()
|
||||
.unwrap();
|
||||
assert_eq!(actual.values().as_ref(), values.as_slice());
|
||||
assert_eq!(
|
||||
owners,
|
||||
values
|
||||
.iter()
|
||||
.map(|value| if *value == 1 { 0 } else { 1 })
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
// The old unpartitioned region remains, but its expression has changed.
|
||||
let mut stale = build_row_request(build_rows(&[1, 20]), true, 0, Some(0));
|
||||
let Some(Body::Inserts(inserts)) = stale.body.as_mut() else {
|
||||
unreachable!()
|
||||
};
|
||||
inserts.requests[0].region_id = RegionId::new(table_id, 0).as_u64();
|
||||
let rebuilt = partitioner
|
||||
.rebuild_write_requests(stale, &table_info)
|
||||
.unwrap();
|
||||
assert_eq!(rebuilt.len(), expected.len());
|
||||
for request in rebuilt {
|
||||
let (id, _, rows) = row_request_parts(&request);
|
||||
let values = &expected
|
||||
.iter()
|
||||
.find(|(region, _)| RegionId::new(table_id, *region).as_u64() == id)
|
||||
.unwrap()
|
||||
.1;
|
||||
assert_eq!(rows, &build_rows(values));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn create_fixture() -> (PartitionRuleManagerRef, TableInfoCache) {
|
||||
let backend = Arc::new(MemoryKvBackend::new());
|
||||
let manager = test_util::create_partition_rule_manager(backend.clone()).await;
|
||||
@@ -1043,6 +1598,13 @@ mod tests {
|
||||
(manager, cache)
|
||||
}
|
||||
|
||||
fn decode_ipc(ipc: &ArrowIpc) -> RecordBatch {
|
||||
FlightDecoder::try_from_schema_bytes(&ipc.schema)
|
||||
.unwrap()
|
||||
.try_decode_record_batch(&ipc.data_header, &ipc.payload)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn build_request(body: Body) -> RegionRequest {
|
||||
RegionRequest {
|
||||
header: Some(RegionRequestHeader {
|
||||
@@ -1252,10 +1814,7 @@ mod tests {
|
||||
let Some(bulk_insert_request::Body::ArrowIpc(ipc)) = bulk.body else {
|
||||
panic!("expected Arrow IPC")
|
||||
};
|
||||
let batch = FlightDecoder::try_from_schema_bytes(&ipc.schema)
|
||||
.unwrap()
|
||||
.try_decode_record_batch(&ipc.data_header, &ipc.payload)
|
||||
.unwrap();
|
||||
let batch = decode_ipc(&ipc);
|
||||
assert_eq!(batch.num_rows(), 1);
|
||||
let values = batch
|
||||
.column(0)
|
||||
@@ -1416,10 +1975,7 @@ mod tests {
|
||||
let Some(bulk_insert_request::Body::ArrowIpc(ipc)) = &request.body else {
|
||||
panic!("expected Arrow IPC")
|
||||
};
|
||||
let payload = FlightDecoder::try_from_schema_bytes(&ipc.schema)
|
||||
.unwrap()
|
||||
.try_decode_record_batch(&ipc.data_header, &ipc.payload)
|
||||
.unwrap();
|
||||
let payload = decode_ipc(ipc);
|
||||
let actual_rows = payload
|
||||
.column(0)
|
||||
.as_any()
|
||||
|
||||
@@ -97,11 +97,6 @@ fn new_test_table_info_with_columns(
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn new_physical_test_table_info(table_id: u32, table_name: &str) -> TableInfo {
|
||||
new_test_table_info_with_columns(table_id, table_name, test_column_schemas(true), vec![0, 2])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn new_logical_test_table_info(table_id: u32, table_name: &str) -> TableInfo {
|
||||
new_test_table_info_with_columns(table_id, table_name, test_column_schemas(false), vec![0])
|
||||
@@ -279,96 +274,110 @@ async fn test_partition_expr_version_cache() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_logical_split_rows_rejects_physical_only_partition_column() {
|
||||
let kv_backend = Arc::new(common_meta::kv_backend::memory::MemoryKvBackend::new());
|
||||
let table_metadata_manager = TableMetadataManager::new(kv_backend.clone());
|
||||
let table_route_cache = test_new_table_route_cache(kv_backend.clone());
|
||||
let partition_info_cache = test_new_partition_info_cache(table_route_cache.clone());
|
||||
let partition_manager =
|
||||
PartitionRuleManager::new(kv_backend, table_route_cache, partition_info_cache);
|
||||
let physical_table_info = new_physical_test_table_info(1024, "physical");
|
||||
let logical_table_info = new_logical_test_table_info(1025, "logical");
|
||||
assert_eq!(
|
||||
vec!["a", "b"],
|
||||
physical_table_info
|
||||
.meta
|
||||
.partition_column_names()
|
||||
.map(|name| name.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(
|
||||
vec!["a"],
|
||||
logical_table_info
|
||||
.meta
|
||||
.partition_column_names()
|
||||
.map(|name| name.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
for missing_column in ["b", "__tsid"] {
|
||||
let kv_backend = Arc::new(common_meta::kv_backend::memory::MemoryKvBackend::new());
|
||||
let table_metadata_manager = TableMetadataManager::new(kv_backend.clone());
|
||||
let table_route_cache = test_new_table_route_cache(kv_backend.clone());
|
||||
let partition_info_cache = test_new_partition_info_cache(table_route_cache.clone());
|
||||
let partition_manager =
|
||||
PartitionRuleManager::new(kv_backend, table_route_cache, partition_info_cache);
|
||||
let mut physical_columns = test_column_schemas(true);
|
||||
physical_columns[2].name = missing_column.to_string();
|
||||
let physical_table_info =
|
||||
new_test_table_info_with_columns(1024, "physical", physical_columns, vec![0, 2]);
|
||||
let mut logical_table_info = new_logical_test_table_info(1025, "logical");
|
||||
logical_table_info.meta.engine =
|
||||
store_api::metric_engine_consts::METRIC_ENGINE_NAME.to_string();
|
||||
logical_table_info.meta.options.extra_options.insert(
|
||||
store_api::metric_engine_consts::LOGICAL_TABLE_METADATA_KEY.to_string(),
|
||||
"1024".to_string(),
|
||||
);
|
||||
assert_eq!(
|
||||
vec!["a", missing_column],
|
||||
physical_table_info
|
||||
.meta
|
||||
.partition_column_names()
|
||||
.map(|name| name.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(
|
||||
vec!["a"],
|
||||
logical_table_info
|
||||
.meta
|
||||
.partition_column_names()
|
||||
.map(|name| name.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
|
||||
table_metadata_manager
|
||||
.create_table_metadata(
|
||||
physical_table_info,
|
||||
TableRouteValue::physical(vec![RegionRoute {
|
||||
region: Region {
|
||||
id: 1.into(),
|
||||
name: "r1".to_string(),
|
||||
attrs: BTreeMap::new(),
|
||||
partition_expr: PartitionExpr::new(
|
||||
Operand::Expr(PartitionExpr::new(
|
||||
Operand::Column("a".to_string()),
|
||||
RestrictedOp::GtEq,
|
||||
Operand::Value(datatypes::value::Value::Int32(10)),
|
||||
)),
|
||||
RestrictedOp::And,
|
||||
Operand::Expr(PartitionExpr::new(
|
||||
Operand::Column("b".to_string()),
|
||||
RestrictedOp::Lt,
|
||||
Operand::Value(datatypes::value::Value::Int32(50)),
|
||||
)),
|
||||
)
|
||||
.as_json_str()
|
||||
.unwrap(),
|
||||
table_metadata_manager
|
||||
.create_table_metadata(
|
||||
physical_table_info,
|
||||
TableRouteValue::physical(vec![RegionRoute {
|
||||
region: Region {
|
||||
id: 1.into(),
|
||||
name: "r1".to_string(),
|
||||
attrs: BTreeMap::new(),
|
||||
partition_expr: PartitionExpr::new(
|
||||
Operand::Expr(PartitionExpr::new(
|
||||
Operand::Column("a".to_string()),
|
||||
RestrictedOp::GtEq,
|
||||
Operand::Value(datatypes::value::Value::Int32(10)),
|
||||
)),
|
||||
RestrictedOp::And,
|
||||
Operand::Expr(PartitionExpr::new(
|
||||
Operand::Column(missing_column.to_string()),
|
||||
RestrictedOp::Lt,
|
||||
Operand::Value(datatypes::value::Value::Int32(50)),
|
||||
)),
|
||||
)
|
||||
.as_json_str()
|
||||
.unwrap(),
|
||||
},
|
||||
leader_peer: Some(Peer::new(1, "")),
|
||||
follower_peers: vec![],
|
||||
leader_state: None,
|
||||
leader_down_since: None,
|
||||
write_route_policy: None,
|
||||
}]),
|
||||
new_test_region_wal_options(vec![1]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
table_metadata_manager
|
||||
.create_table_metadata(
|
||||
logical_table_info.clone(),
|
||||
TableRouteValue::logical(1024),
|
||||
new_test_region_wal_options(vec![]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let error = partition_manager
|
||||
.find_table_partition_rule(&logical_table_info)
|
||||
.await
|
||||
.err()
|
||||
.expect("Physical-only partition columns must be rejected");
|
||||
assert!(
|
||||
matches!(error, partition::error::Error::UndefinedColumn { ref column, .. } if column == missing_column)
|
||||
);
|
||||
|
||||
let error = partition_manager
|
||||
.split_rows(
|
||||
&logical_table_info,
|
||||
Rows {
|
||||
schema: vec![tag_column_schema("a", ColumnDataType::Int32)],
|
||||
rows: vec![Row {
|
||||
values: vec![ValueData::I32Value(100).into()],
|
||||
}],
|
||||
},
|
||||
leader_peer: Some(Peer::new(1, "")),
|
||||
follower_peers: vec![],
|
||||
leader_state: None,
|
||||
leader_down_since: None,
|
||||
write_route_policy: None,
|
||||
}]),
|
||||
new_test_region_wal_options(vec![1]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
table_metadata_manager
|
||||
.create_table_metadata(
|
||||
logical_table_info.clone(),
|
||||
TableRouteValue::logical(1024),
|
||||
new_test_region_wal_options(vec![]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (partition_rule, _) = partition_manager
|
||||
.find_table_partition_rule(&logical_table_info)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(&["a"], partition_rule.partition_columns());
|
||||
|
||||
let error = partition_manager
|
||||
.split_rows(
|
||||
&logical_table_info,
|
||||
Rows {
|
||||
schema: vec![tag_column_schema("a", ColumnDataType::Int32)],
|
||||
rows: vec![Row {
|
||||
values: vec![ValueData::I32Value(100).into()],
|
||||
}],
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error,
|
||||
partition::error::Error::UndefinedColumn { ref column, .. } if column == "b"
|
||||
));
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error,
|
||||
partition::error::Error::UndefinedColumn { ref column, .. } if column == missing_column
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -101,6 +101,13 @@ pub enum Error {
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Invalid partition input, reason: {}", reason))]
|
||||
InvalidPartitionInput {
|
||||
reason: String,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Invalid DeleteRequest, reason: {}", reason))]
|
||||
InvalidDeleteRequest {
|
||||
reason: String,
|
||||
@@ -266,6 +273,7 @@ impl ErrorExt for Error {
|
||||
|
||||
Error::RegionKeysSize { .. }
|
||||
| Error::InvalidInsertRequest { .. }
|
||||
| Error::InvalidPartitionInput { .. }
|
||||
| Error::InvalidDeleteRequest { .. } => StatusCode::InvalidArguments,
|
||||
|
||||
Error::ConvertScalarValue { .. }
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use api::v1::Rows;
|
||||
@@ -22,6 +22,9 @@ use common_meta::kv_backend::KvBackendRef;
|
||||
use common_meta::peer::Peer;
|
||||
use common_meta::rpc::router::{self, RegionRoute};
|
||||
use snafu::{OptionExt, ResultExt};
|
||||
use store_api::metric_engine_consts::{
|
||||
DATA_SCHEMA_TABLE_ID_COLUMN_NAME, LOGICAL_TABLE_METADATA_KEY, METRIC_ENGINE_NAME,
|
||||
};
|
||||
use store_api::storage::{RegionId, RegionNumber};
|
||||
use table::metadata::{TableId, TableInfo};
|
||||
|
||||
@@ -29,6 +32,7 @@ use crate::cache::{CachedPartitionInfo, PartitionInfoCacheRef, PhysicalPartition
|
||||
use crate::error::{FindLeaderSnafu, Result};
|
||||
use crate::expr::PartitionExpr;
|
||||
use crate::multi_dim::MultiDimPartitionRule;
|
||||
use crate::partition::PartitionEvalContext;
|
||||
use crate::splitter::RowSplitter;
|
||||
use crate::{PartitionRuleRef, error};
|
||||
|
||||
@@ -192,12 +196,6 @@ impl PartitionRuleManager {
|
||||
&self,
|
||||
table_info: &TableInfo,
|
||||
) -> Result<(PartitionRuleRef, HashMap<RegionNumber, Option<u64>>)> {
|
||||
let partition_columns = table_info
|
||||
.meta
|
||||
.partition_column_names()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let partition_info = self
|
||||
.find_physical_partition_info(table_info.table_id())
|
||||
.await?;
|
||||
@@ -225,12 +223,12 @@ impl PartitionRuleManager {
|
||||
.filter(|partition| partition.partition_expr.is_none())
|
||||
.map(|partition| partition.id.region_number()),
|
||||
);
|
||||
let partition_rule = Arc::new(MultiDimPartitionRule::try_new(
|
||||
partition_columns,
|
||||
regions,
|
||||
exprs,
|
||||
false,
|
||||
)?) as _;
|
||||
let (partition_columns, eval_context) =
|
||||
Self::resolve_partition_columns_and_context(table_info, &exprs)?;
|
||||
let partition_rule = Arc::new(
|
||||
MultiDimPartitionRule::try_new(partition_columns, regions, exprs, false)?
|
||||
.with_eval_context(eval_context),
|
||||
) as _;
|
||||
Ok((partition_rule, partition_versions))
|
||||
}
|
||||
|
||||
@@ -276,6 +274,50 @@ impl PartitionRuleManager {
|
||||
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Resolves all expression inputs, including identity supplied outside the payload.
|
||||
fn resolve_partition_columns_and_context(
|
||||
table_info: &TableInfo,
|
||||
exprs: &[PartitionExpr],
|
||||
) -> Result<(Vec<String>, PartitionEvalContext)> {
|
||||
if table_info.meta.engine != METRIC_ENGINE_NAME
|
||||
|| !table_info
|
||||
.meta
|
||||
.options
|
||||
.extra_options
|
||||
.contains_key(LOGICAL_TABLE_METADATA_KEY)
|
||||
{
|
||||
let columns = table_info.meta.partition_column_names().cloned().collect();
|
||||
return Ok((columns, PartitionEvalContext::FromPayload));
|
||||
}
|
||||
|
||||
// Catalog maps only physical partition columns present in the logical schema.
|
||||
// The routing context can additionally supply __table_id.
|
||||
let mut columns = HashSet::new();
|
||||
for expr in exprs {
|
||||
expr.collect_column_names(&mut columns);
|
||||
}
|
||||
let mut columns: Vec<_> = columns.into_iter().collect();
|
||||
// Keep rule snapshots deterministic despite collecting names in a HashSet.
|
||||
columns.sort_unstable();
|
||||
for column in &columns {
|
||||
if column != DATA_SCHEMA_TABLE_ID_COLUMN_NAME
|
||||
&& table_info
|
||||
.meta
|
||||
.schema
|
||||
.column_schema_by_name(column)
|
||||
.is_none()
|
||||
{
|
||||
return error::UndefinedColumnSnafu { column }.fail();
|
||||
}
|
||||
}
|
||||
Ok((
|
||||
columns,
|
||||
PartitionEvalContext::WithTableId {
|
||||
table_id: table_info.table_id(),
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates partitions from region routes.
|
||||
|
||||
+233
-10
@@ -22,15 +22,19 @@ use datafusion_common::tree_node::{Transformed, TreeNode};
|
||||
use datafusion_expr::{ColumnarValue, Expr};
|
||||
use datafusion_physical_expr::PhysicalExpr;
|
||||
use datatypes::arrow;
|
||||
use datatypes::arrow::array::{Array, BooleanArray, BooleanBufferBuilder, RecordBatch};
|
||||
use datatypes::arrow::array::{
|
||||
Array, BooleanArray, BooleanBufferBuilder, NullArray, RecordBatch, UInt32Array,
|
||||
};
|
||||
use datatypes::arrow::buffer::BooleanBuffer;
|
||||
use datatypes::arrow::compute::prep_null_mask_filter;
|
||||
use datatypes::arrow::datatypes::{Field, Schema};
|
||||
use datatypes::arrow::datatypes::{DataType as ArrowDataType, Field, Schema};
|
||||
use datatypes::arrow::record_batch::RecordBatchOptions;
|
||||
use datatypes::data_type::DataType as _;
|
||||
use datatypes::prelude::Value;
|
||||
use datatypes::vectors::{Helper, VectorRef};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use store_api::metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME;
|
||||
use store_api::storage::RegionNumber;
|
||||
|
||||
use crate::PartitionRule;
|
||||
@@ -38,7 +42,7 @@ use crate::checker::PartitionChecker;
|
||||
use crate::error::{self, Result, UndefinedColumnSnafu};
|
||||
use crate::expr::{Operand, PartitionExpr, RestrictedOp, plan_physical_expr};
|
||||
use crate::function::IcebergHash;
|
||||
use crate::partition::RegionMask;
|
||||
use crate::partition::{PartitionEvalContext, RegionMask};
|
||||
|
||||
/// The default region number when no partition exprs are matched.
|
||||
const DEFAULT_REGION: RegionNumber = 0;
|
||||
@@ -76,6 +80,10 @@ pub struct MultiDimPartitionRule {
|
||||
/// Cache of physical expressions.
|
||||
#[serde(skip)]
|
||||
physical_expr_cache: RwLock<PhysicalExprCache>,
|
||||
/// Write-local routing context; not persisted. Deserialization defaults to
|
||||
/// [`PartitionEvalContext::FromPayload`].
|
||||
#[serde(skip)]
|
||||
eval_context: PartitionEvalContext,
|
||||
}
|
||||
|
||||
impl MultiDimPartitionRule {
|
||||
@@ -101,6 +109,7 @@ impl MultiDimPartitionRule {
|
||||
regions,
|
||||
exprs,
|
||||
physical_expr_cache: RwLock::new(None),
|
||||
eval_context: PartitionEvalContext::FromPayload,
|
||||
};
|
||||
|
||||
if check_exprs {
|
||||
@@ -111,6 +120,12 @@ impl MultiDimPartitionRule {
|
||||
Ok(rule)
|
||||
}
|
||||
|
||||
/// Attaches write-local table identity without changing persisted partition expressions.
|
||||
pub(crate) fn with_eval_context(mut self, context: PartitionEvalContext) -> Self {
|
||||
self.eval_context = context;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn exprs(&self) -> &[PartitionExpr] {
|
||||
&self.exprs
|
||||
}
|
||||
@@ -124,14 +139,10 @@ impl MultiDimPartitionRule {
|
||||
}
|
||||
);
|
||||
|
||||
for (region_index, expr) in self.exprs.iter().enumerate() {
|
||||
if self.evaluate_expr(expr, values)? {
|
||||
return Ok(self.regions[region_index]);
|
||||
}
|
||||
match self.eval_context {
|
||||
PartitionEvalContext::FromPayload => self.find_region_from_payload(values),
|
||||
PartitionEvalContext::WithTableId { .. } => self.find_region_with_context(values),
|
||||
}
|
||||
|
||||
// return the default region number
|
||||
Ok(DEFAULT_REGION)
|
||||
}
|
||||
|
||||
fn evaluate_expr(&self, expr: &PartitionExpr, values: &[Value]) -> Result<bool> {
|
||||
@@ -260,6 +271,8 @@ impl MultiDimPartitionRule {
|
||||
&self,
|
||||
record_batch: &RecordBatch,
|
||||
) -> Result<HashMap<RegionNumber, RegionMask>> {
|
||||
let routing_batch = self.build_routing_batch(record_batch)?;
|
||||
let record_batch = routing_batch.as_ref().unwrap_or(record_batch);
|
||||
let num_rows = record_batch.num_rows();
|
||||
if self.regions.len() == 1 {
|
||||
return Ok([(
|
||||
@@ -369,6 +382,96 @@ impl MultiDimPartitionRule {
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// Finds a region using the supplied scalar partition values.
|
||||
fn find_region_from_payload(&self, values: &[Value]) -> Result<RegionNumber> {
|
||||
for (region_index, expr) in self.exprs.iter().enumerate() {
|
||||
if self.evaluate_expr(expr, values)? {
|
||||
return Ok(self.regions[region_index]);
|
||||
}
|
||||
}
|
||||
|
||||
// return the default region number
|
||||
Ok(DEFAULT_REGION)
|
||||
}
|
||||
|
||||
/// Evaluates one row through the same context-aware batch path as bulk writes.
|
||||
fn find_region_with_context(&self, values: &[Value]) -> Result<RegionNumber> {
|
||||
let mut fields = Vec::new();
|
||||
let mut arrays = Vec::new();
|
||||
for (name, value) in self.partition_columns.iter().zip(values) {
|
||||
if name == DATA_SCHEMA_TABLE_ID_COLUMN_NAME {
|
||||
continue;
|
||||
}
|
||||
let vector =
|
||||
Helper::try_from_row_into_vector(std::slice::from_ref(value), &value.data_type())
|
||||
.context(error::ConvertToVectorSnafu)?;
|
||||
let array = vector.to_arrow_array();
|
||||
fields.push(Field::new(name, array.data_type().clone(), true));
|
||||
arrays.push(array);
|
||||
}
|
||||
let batch = RecordBatch::try_new_with_options(
|
||||
Arc::new(Schema::new(fields)),
|
||||
arrays,
|
||||
&RecordBatchOptions::new().with_row_count(Some(1)),
|
||||
)
|
||||
.context(error::ComputeArrowKernelSnafu)?;
|
||||
let masks = self.split_record_batch(&batch)?;
|
||||
masks
|
||||
.into_iter()
|
||||
.find(|(_, mask)| !mask.select_none())
|
||||
.map(|(region, _)| region)
|
||||
.context(error::UnexpectedSnafu {
|
||||
err_msg: "No partition selected the row",
|
||||
})
|
||||
}
|
||||
|
||||
/// Supplies contextual identity and missing payload inputs for complete expressions.
|
||||
/// Other partition columns remain in the batch, so mixed-column predicates use
|
||||
/// the same evaluator as predicates over table id alone.
|
||||
fn build_routing_batch(&self, record_batch: &RecordBatch) -> Result<Option<RecordBatch>> {
|
||||
let PartitionEvalContext::WithTableId { table_id } = self.eval_context else {
|
||||
return Ok(None);
|
||||
};
|
||||
let needs_inputs = self.partition_columns.iter().any(|name| {
|
||||
name == DATA_SCHEMA_TABLE_ID_COLUMN_NAME || record_batch.column_by_name(name).is_none()
|
||||
});
|
||||
if !needs_inputs {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
// Materialize only the routing input. The original write payload stays logical.
|
||||
let mut fields = Vec::with_capacity(record_batch.num_columns() + 1);
|
||||
let mut columns = Vec::with_capacity(record_batch.num_columns() + 1);
|
||||
for (field, column) in record_batch
|
||||
.schema()
|
||||
.fields()
|
||||
.iter()
|
||||
.zip(record_batch.columns())
|
||||
{
|
||||
if field.name() != DATA_SCHEMA_TABLE_ID_COLUMN_NAME {
|
||||
fields.push(field.clone());
|
||||
columns.push(column.clone());
|
||||
}
|
||||
}
|
||||
for name in &self.partition_columns {
|
||||
if name == DATA_SCHEMA_TABLE_ID_COLUMN_NAME {
|
||||
fields.push(Arc::new(Field::new(name, ArrowDataType::UInt32, false)));
|
||||
columns.push(Arc::new(UInt32Array::from(vec![
|
||||
table_id;
|
||||
record_batch.num_rows()
|
||||
])));
|
||||
} else if record_batch.column_by_name(name).is_none() {
|
||||
// The manager validates these columns against the logical schema.
|
||||
// Omitted payload columns retain row routing's NULL semantics.
|
||||
fields.push(Arc::new(Field::new(name, ArrowDataType::Null, true)));
|
||||
columns.push(Arc::new(NullArray::new(record_batch.num_rows())));
|
||||
}
|
||||
}
|
||||
RecordBatch::try_new(Arc::new(Schema::new(fields)), columns)
|
||||
.map(Some)
|
||||
.context(error::ComputeArrowKernelSnafu)
|
||||
}
|
||||
|
||||
fn plan_physical_exprs(&self, input_schema: Arc<Schema>) -> Result<PhysicalPartitionExprs> {
|
||||
let mut hashes = BTreeSet::new();
|
||||
for expr in &self.exprs {
|
||||
@@ -478,6 +581,10 @@ fn columnar_value_to_boolean_array(
|
||||
}
|
||||
|
||||
impl PartitionRule for MultiDimPartitionRule {
|
||||
fn eval_context(&self) -> PartitionEvalContext {
|
||||
self.eval_context
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
@@ -506,6 +613,122 @@ mod tests {
|
||||
use crate::error::{self, Error};
|
||||
use crate::expr::col;
|
||||
|
||||
#[test]
|
||||
fn test_partition_eval_context() {
|
||||
use datatypes::arrow::array::Int32Array;
|
||||
|
||||
use crate::splitter::RowSplitter;
|
||||
|
||||
let column = || col(DATA_SCHEMA_TABLE_ID_COLUMN_NAME);
|
||||
let hash = || Operand::IcebergHash(IcebergHash::new(DATA_SCHEMA_TABLE_ID_COLUMN_NAME));
|
||||
let hash_boundary = IcebergHash::evaluate_value(&Value::UInt32(1029)).unwrap();
|
||||
for exprs in [
|
||||
vec![
|
||||
column().lt(Value::Int64(1029)),
|
||||
column()
|
||||
.gt_eq(Value::UInt64(1029))
|
||||
.and(col("a").lt(Value::Int32(10))),
|
||||
column()
|
||||
.gt_eq(Value::Int64(1029))
|
||||
.and(col("a").gt_eq(Value::Int32(10))),
|
||||
],
|
||||
vec![
|
||||
hash().lt(hash_boundary.clone()),
|
||||
hash()
|
||||
.gt_eq(hash_boundary.clone())
|
||||
.and(col("a").lt(Value::Int32(10))),
|
||||
hash()
|
||||
.gt_eq(hash_boundary)
|
||||
.and(col("a").gt_eq(Value::Int32(10))),
|
||||
],
|
||||
] {
|
||||
let rule = MultiDimPartitionRule::try_new(
|
||||
vec![DATA_SCHEMA_TABLE_ID_COLUMN_NAME.into(), "a".into()],
|
||||
vec![0, 1, 2],
|
||||
exprs,
|
||||
false,
|
||||
)
|
||||
.unwrap();
|
||||
let batch = RecordBatch::try_from_iter([
|
||||
(
|
||||
DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
|
||||
Arc::new(UInt32Array::from(vec![1029, 1029])) as arrow::array::ArrayRef,
|
||||
),
|
||||
(
|
||||
"a",
|
||||
Arc::new(Int32Array::from(vec![1, 20])) as arrow::array::ArrayRef,
|
||||
),
|
||||
])
|
||||
.unwrap();
|
||||
let ordinary = rule.split_record_batch(&batch).unwrap();
|
||||
let serialized = serde_json::to_string(&rule).unwrap();
|
||||
let rule = rule.with_eval_context(PartitionEvalContext::WithTableId { table_id: 1029 });
|
||||
assert_eq!(serde_json::to_string(&rule).unwrap(), serialized);
|
||||
let logical = rule
|
||||
.split_record_batch(&batch.project(&[1]).unwrap())
|
||||
.unwrap();
|
||||
for region in [1, 2] {
|
||||
assert_eq!(logical[®ion].array(), ordinary[®ion].array());
|
||||
assert_eq!(logical[®ion].selected_rows(), 1);
|
||||
}
|
||||
assert_eq!(
|
||||
rule.find_region(&[Value::Null, Value::Int32(1)]).unwrap(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
rule.find_region(&[Value::UInt32(0), Value::Int32(20)])
|
||||
.unwrap(),
|
||||
2
|
||||
);
|
||||
let spoofed = RecordBatch::try_from_iter([
|
||||
(
|
||||
DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
|
||||
Arc::new(UInt32Array::from(vec![0, 0])) as arrow::array::ArrayRef,
|
||||
),
|
||||
("a", batch.column(1).clone()),
|
||||
])
|
||||
.unwrap();
|
||||
let masks = rule.split_record_batch(&spoofed).unwrap();
|
||||
assert_eq!(masks[&1].array(), logical[&1].array());
|
||||
assert_eq!(masks[&2].array(), logical[&2].array());
|
||||
assert!(
|
||||
rule.split_record_batch(&batch.slice(0, 0))
|
||||
.unwrap()
|
||||
.values()
|
||||
.all(|mask| mask.select_none())
|
||||
);
|
||||
let rows = api::v1::Rows {
|
||||
schema: vec![api::v1::helper::tag_column_schema(
|
||||
"a",
|
||||
api::v1::ColumnDataType::Int32,
|
||||
)],
|
||||
rows: vec![
|
||||
api::v1::Row {
|
||||
values: vec![api::v1::value::ValueData::I32Value(1).into()],
|
||||
},
|
||||
api::v1::Row {
|
||||
values: vec![api::v1::value::ValueData::I32Value(20).into()],
|
||||
},
|
||||
],
|
||||
};
|
||||
let expected = rows.clone();
|
||||
let rule = Arc::new(rule);
|
||||
let missing = api::v1::Rows {
|
||||
schema: vec![],
|
||||
rows: vec![api::v1::Row { values: vec![] }],
|
||||
};
|
||||
let splits = RowSplitter::new(rule.clone())
|
||||
.split(missing.clone())
|
||||
.unwrap();
|
||||
// Partition comparisons order NULL before non-NULL values.
|
||||
assert_eq!(splits[&1], missing);
|
||||
let splits = RowSplitter::new(rule).split(rows).unwrap();
|
||||
assert_eq!(splits[&1].rows, vec![expected.rows[0].clone()]);
|
||||
assert_eq!(splits[&2].rows, vec![expected.rows[1].clone()]);
|
||||
assert_eq!(splits[&1].schema, expected.schema);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_find_region() {
|
||||
// PARTITION ON COLUMNS (b) (
|
||||
|
||||
@@ -20,20 +20,46 @@ use std::sync::Arc;
|
||||
use datatypes::arrow::array::{BooleanArray, RecordBatch};
|
||||
use datatypes::prelude::Value;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use store_api::storage::RegionNumber;
|
||||
use store_api::storage::{RegionNumber, TableId};
|
||||
|
||||
use crate::error::Result;
|
||||
|
||||
pub type PartitionRuleRef = Arc<dyn PartitionRule>;
|
||||
|
||||
/// Supplies additional inputs when evaluating a write's physical partition expressions.
|
||||
/// The variants describe input sources, not whether the original write targets a logical table.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum PartitionEvalContext {
|
||||
/// Reads partition values directly from the payload.
|
||||
/// Physical metric batches combining logical tables use this variant: their payload
|
||||
/// carries a per-row `__table_id` column that is retained across routing retries.
|
||||
#[default]
|
||||
FromPayload,
|
||||
/// Supplies one table id for every row, overriding any payload `__table_id` value.
|
||||
/// Used for single-logical-table writes whose payload omits internal columns.
|
||||
/// Other partition values still come from the payload; omitted columns declared
|
||||
/// in the logical schema are evaluated as NULL. Already-converted physical metric
|
||||
/// batches carry per-row identities and use [`Self::FromPayload`] instead.
|
||||
WithTableId { table_id: TableId },
|
||||
}
|
||||
|
||||
pub trait PartitionRule: Sync + Send {
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
|
||||
fn partition_columns(&self) -> &[String];
|
||||
|
||||
/// Additional inputs for evaluating physical partition expressions during write routing.
|
||||
/// Defaults to [`PartitionEvalContext::FromPayload`]. Override when routing needs
|
||||
/// inputs supplied outside the write payload.
|
||||
fn eval_context(&self) -> PartitionEvalContext {
|
||||
PartitionEvalContext::FromPayload
|
||||
}
|
||||
|
||||
/// Finds the target region by the partition values.
|
||||
///
|
||||
/// Note that the `values` should have the same length as the `partition_columns`.
|
||||
/// With [`PartitionEvalContext::WithTableId`], the context supplies `__table_id`;
|
||||
/// the value in its payload slot is ignored.
|
||||
fn find_region(&self, values: &[Value]) -> Result<RegionNumber>;
|
||||
|
||||
/// Split the record batch into multiple regions by the partition values.
|
||||
|
||||
@@ -13,14 +13,22 @@
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
|
||||
use api::helper;
|
||||
use api::v1::{ColumnSchema, Row, Rows};
|
||||
use datatypes::arrow::array::ArrayRef;
|
||||
use datatypes::arrow::datatypes::{Field, Schema};
|
||||
use datatypes::arrow::record_batch::{RecordBatch, RecordBatchOptions};
|
||||
use datatypes::data_type::{ConcreteDataType, DataType};
|
||||
use datatypes::value::Value;
|
||||
use snafu::{OptionExt, ResultExt};
|
||||
use store_api::metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME;
|
||||
use store_api::storage::RegionNumber;
|
||||
|
||||
use crate::PartitionRuleRef;
|
||||
use crate::error::Result;
|
||||
use crate::error::{self, Result};
|
||||
use crate::partition::PartitionEvalContext;
|
||||
|
||||
pub struct RowSplitter {
|
||||
partition_rule: PartitionRuleRef,
|
||||
@@ -80,6 +88,18 @@ impl<'a> SplitReadRowHelper<'a> {
|
||||
|
||||
fn split_rows(mut self) -> Result<HashMap<RegionNumber, Rows>> {
|
||||
let regions = self.split_to_regions()?;
|
||||
if regions.len() == 1
|
||||
&& let Some((®ion, indices)) = regions.iter().next()
|
||||
&& indices.len() == self.rows.len()
|
||||
{
|
||||
return Ok(HashMap::from([(
|
||||
region,
|
||||
Rows {
|
||||
schema: self.schema,
|
||||
rows: self.rows,
|
||||
},
|
||||
)]));
|
||||
}
|
||||
let request_splits = regions
|
||||
.into_iter()
|
||||
.map(|(region_number, row_indexes)| {
|
||||
@@ -99,6 +119,14 @@ impl<'a> SplitReadRowHelper<'a> {
|
||||
}
|
||||
|
||||
fn split_to_regions(&self) -> Result<HashMap<RegionNumber, Vec<usize>>> {
|
||||
match self.partition_rule.eval_context() {
|
||||
PartitionEvalContext::FromPayload => self.split_rows_from_payload(),
|
||||
PartitionEvalContext::WithTableId { .. } => self.split_rows_with_context(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Routes payload values row by row without materializing Arrow arrays.
|
||||
fn split_rows_from_payload(&self) -> Result<HashMap<RegionNumber, Vec<usize>>> {
|
||||
let mut regions_row_indexes: HashMap<RegionNumber, Vec<usize>> = HashMap::new();
|
||||
for (row_idx, values) in self.iter_partition_values().enumerate() {
|
||||
let region_number = self.partition_rule.find_region(&values)?;
|
||||
@@ -111,6 +139,80 @@ impl<'a> SplitReadRowHelper<'a> {
|
||||
Ok(regions_row_indexes)
|
||||
}
|
||||
|
||||
/// Routes complete expressions through the batch evaluator with contextual inputs.
|
||||
fn split_rows_with_context(&self) -> Result<HashMap<RegionNumber, Vec<usize>>> {
|
||||
let batch = self.build_routing_batch()?;
|
||||
Ok(self
|
||||
.partition_rule
|
||||
.split_record_batch(&batch)?
|
||||
.into_iter()
|
||||
.filter(|(_, mask)| !mask.select_none())
|
||||
.map(|(region, mask)| (region, mask.array().values().set_indices().collect()))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Converts present payload partition columns; the evaluator supplies missing inputs.
|
||||
fn build_routing_batch(&self) -> Result<RecordBatch> {
|
||||
let mut fields = Vec::new();
|
||||
let mut arrays = Vec::new();
|
||||
for (name, index) in self
|
||||
.partition_rule
|
||||
.partition_columns()
|
||||
.iter()
|
||||
.zip(&self.partition_cols_indexes)
|
||||
{
|
||||
if name == DATA_SCHEMA_TABLE_ID_COLUMN_NAME {
|
||||
continue;
|
||||
}
|
||||
let Some(index) = *index else {
|
||||
continue;
|
||||
};
|
||||
let array = self.build_partition_column_array(index)?;
|
||||
fields.push(Field::new(name, array.data_type().clone(), true));
|
||||
arrays.push(array);
|
||||
}
|
||||
RecordBatch::try_new_with_options(
|
||||
Arc::new(Schema::new(fields)),
|
||||
arrays,
|
||||
&RecordBatchOptions::new().with_row_count(Some(self.rows.len())),
|
||||
)
|
||||
.context(error::ComputeArrowKernelSnafu)
|
||||
}
|
||||
|
||||
/// Converts one payload partition column, validating its type and row values.
|
||||
fn build_partition_column_array(&self, index: usize) -> Result<ArrayRef> {
|
||||
let column = &self.schema[index];
|
||||
let data_type = helper::ColumnDataTypeWrapper::try_new(
|
||||
column.datatype,
|
||||
column.datatype_extension.clone(),
|
||||
)
|
||||
.map_err(|err| {
|
||||
error::InvalidPartitionInputSnafu {
|
||||
reason: err.to_string(),
|
||||
}
|
||||
.build()
|
||||
})?;
|
||||
let mut builder = ConcreteDataType::from(data_type).create_mutable_vector(self.rows.len());
|
||||
for row in &self.rows {
|
||||
let value =
|
||||
row.values
|
||||
.get(index)
|
||||
.with_context(|| error::InvalidPartitionInputSnafu {
|
||||
reason: format!(
|
||||
"Missing value for partition column {}",
|
||||
column.column_name
|
||||
),
|
||||
})?;
|
||||
builder
|
||||
.try_push_value_ref(&helper::pb_value_to_value_ref(
|
||||
value,
|
||||
column.datatype_extension.as_ref(),
|
||||
))
|
||||
.context(error::ConvertToVectorSnafu)?;
|
||||
}
|
||||
Ok(builder.to_vector().to_arrow_array())
|
||||
}
|
||||
|
||||
fn iter_partition_values(&'a self) -> impl Iterator<Item = Vec<Value>> + 'a {
|
||||
self.rows.iter().map(|row| {
|
||||
self.partition_cols_indexes
|
||||
@@ -278,6 +380,38 @@ mod tests {
|
||||
unimplemented!()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_invalid_logical_partition_input() {
|
||||
use common_error::ext::ErrorExt;
|
||||
use common_error::status_code::StatusCode;
|
||||
|
||||
let rule = crate::multi_dim::MultiDimPartitionRule::try_new(
|
||||
vec!["a".to_string()],
|
||||
vec![0],
|
||||
vec![crate::expr::col("a").gt_eq(Value::Int32(0))],
|
||||
false,
|
||||
)
|
||||
.unwrap()
|
||||
.with_eval_context(PartitionEvalContext::WithTableId { table_id: 1025 });
|
||||
let splitter = RowSplitter::new(Arc::new(rule));
|
||||
for (datatype, values) in [
|
||||
(-1, vec![ValueData::I32Value(1).into()]),
|
||||
(ColumnDataType::Int32 as i32, vec![]),
|
||||
] {
|
||||
let mut column = tag_column_schema("a", ColumnDataType::Int32);
|
||||
column.datatype = datatype;
|
||||
let error = splitter
|
||||
.split(Rows {
|
||||
schema: vec![column],
|
||||
rows: vec![api::v1::Row { values }],
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, error::Error::InvalidPartitionInput { .. }));
|
||||
assert_eq!(error.status_code(), StatusCode::InvalidArguments);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_writer_splitter() {
|
||||
let rows = mock_rows();
|
||||
|
||||
@@ -306,8 +306,9 @@ async fn flush_batch_physical_tracked(
|
||||
)?;
|
||||
|
||||
// 4. Concatenate all modified batches (all share the same physical schema)
|
||||
let combined_batch = batch_convert::concat_modified_batches(&modified_batches)?;
|
||||
// 5. Split by physical partition rule and send to regions
|
||||
let combined_batch = batch_convert::concat_modified_batches(&modified_batches, table_batches)?;
|
||||
// 5. Use the physical rule with FromPayload context: the combined batch carries
|
||||
// each row's logical table id, rather than one identity for the whole batch.
|
||||
let physical_table_id = physical_table_info.table_id();
|
||||
let row_count = table_batches
|
||||
.iter()
|
||||
|
||||
@@ -16,13 +16,15 @@ use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use arrow::array::UInt32Array;
|
||||
use arrow::compute::concat_batches;
|
||||
use arrow::datatypes::{DataType as ArrowDataType, Schema as ArrowSchema};
|
||||
use arrow::datatypes::{DataType as ArrowDataType, Field, Schema as ArrowSchema};
|
||||
use arrow::record_batch::RecordBatch;
|
||||
use common_query::prelude::{greptime_timestamp, greptime_value};
|
||||
use metric_engine::batch_modifier::{TagColumnInfo, modify_batch_sparse};
|
||||
use smallvec::SmallVec;
|
||||
use snafu::{OptionExt, ResultExt, ensure};
|
||||
use store_api::metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME;
|
||||
use table::metadata::TableId;
|
||||
|
||||
use crate::error;
|
||||
@@ -194,7 +196,9 @@ pub(in crate::batcher::logical_table) fn columns_taxonomy(
|
||||
/// Transforms logical table batches into physical format (sparse primary key encoding).
|
||||
///
|
||||
/// It identifies tag columns and essential columns (timestamp, value) for each logical batch
|
||||
/// and applies sparse primary key modification.
|
||||
/// and applies sparse primary key modification. On success, each input batch has
|
||||
/// one corresponding output batch, preserving table/batch order and each batch's
|
||||
/// row count and row order.
|
||||
pub(in crate::batcher::logical_table) fn transform_logical_batches_to_physical(
|
||||
table_batches: &[TableBatch],
|
||||
name_to_ids: &HashMap<String, u32>,
|
||||
@@ -221,10 +225,6 @@ pub(in crate::batcher::logical_table) fn transform_logical_batches_to_physical(
|
||||
)?;
|
||||
|
||||
columns_taxonomy_elapsed += start.elapsed();
|
||||
if tag_columns.is_empty() && essential_col_indices.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let modified = {
|
||||
let start = Instant::now();
|
||||
// The schema of modified batch is: __primary_key, timestamp, value, other partition columns...
|
||||
@@ -260,15 +260,43 @@ pub(in crate::batcher::logical_table) fn transform_logical_batches_to_physical(
|
||||
|
||||
/// Concatenates all modified batches into a single large batch.
|
||||
///
|
||||
/// All modified batches share the same physical schema.
|
||||
/// All modified batches share the same physical schema. They must correspond
|
||||
/// one-to-one to the batches in `table_batches`, in table/batch order, preserving
|
||||
/// each batch's row count and row order. A per-row table-id column lets the physical rule use
|
||||
/// [`FromPayload`](partition::partition::PartitionEvalContext::FromPayload) even
|
||||
/// when the batch contains several logical tables.
|
||||
pub(in crate::batcher::logical_table) fn concat_modified_batches(
|
||||
modified_batches: &[RecordBatch],
|
||||
table_batches: &[TableBatch],
|
||||
) -> Result<RecordBatch> {
|
||||
let combined_schema = modified_batches[0].schema();
|
||||
let _timer = PENDING_ROWS_BATCH_FLUSH_STAGE_ELAPSED
|
||||
.with_label_values(&["flush_physical_concat_all"])
|
||||
.start_timer();
|
||||
concat_batches(&combined_schema, modified_batches).context(error::ArrowSnafu)
|
||||
let combined = concat_batches(&combined_schema, modified_batches).context(error::ArrowSnafu)?;
|
||||
// Build one array after concatenation instead of allocating one per logical batch.
|
||||
// Always retain it in the IPC payload: a retry can introduce table-id partitioning.
|
||||
let mut table_ids = Vec::with_capacity(combined.num_rows());
|
||||
for table in table_batches {
|
||||
for batch in &table.batches {
|
||||
table_ids.extend(std::iter::repeat_n(table.table_id, batch.batch.num_rows()));
|
||||
}
|
||||
}
|
||||
ensure!(
|
||||
table_ids.len() == combined.num_rows(),
|
||||
error::InternalSnafu {
|
||||
err_msg: "Logical table ids do not match combined rows",
|
||||
}
|
||||
);
|
||||
let mut fields = combined.schema().fields().to_vec();
|
||||
fields.push(Arc::new(Field::new(
|
||||
DATA_SCHEMA_TABLE_ID_COLUMN_NAME,
|
||||
ArrowDataType::UInt32,
|
||||
false,
|
||||
)));
|
||||
let mut columns = combined.columns().to_vec();
|
||||
columns.push(Arc::new(UInt32Array::from(table_ids)));
|
||||
RecordBatch::try_new(Arc::new(ArrowSchema::new(fields)), columns).context(error::ArrowSnafu)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -283,7 +311,8 @@ mod tests {
|
||||
use smallvec::SmallVec;
|
||||
|
||||
use crate::batcher::logical_table::batch_convert::{
|
||||
TableBatch, columns_taxonomy, transform_logical_batches_to_physical,
|
||||
TableBatch, columns_taxonomy, concat_modified_batches,
|
||||
transform_logical_batches_to_physical,
|
||||
};
|
||||
use crate::batcher::logical_table::test_util::mock_aligned_tag_batch;
|
||||
use crate::error::Error;
|
||||
@@ -577,6 +606,13 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(2, modified.len());
|
||||
|
||||
let err = concat_modified_batches(&modified, &table_batches[..1]).unwrap_err();
|
||||
assert!(
|
||||
matches!(&err, Error::Internal { err_msg }
|
||||
if err_msg == "Logical table ids do not match combined rows"),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -386,6 +386,68 @@ mod tests {
|
||||
assert_eq!(histogram.get_sample_count(), before + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_physical_batch_routes_each_logical_table_id() {
|
||||
use arrow::array::UInt32Array;
|
||||
use datatypes::value::Value;
|
||||
use partition::expr::col;
|
||||
use partition::multi_dim::MultiDimPartitionRule;
|
||||
use partition::partition::PartitionEvalContext;
|
||||
use store_api::metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME;
|
||||
|
||||
use crate::batcher::logical_table::test_util::mock_aligned_tag_batch;
|
||||
|
||||
let tables = [10, 20].map(|table_id| TableBatch {
|
||||
table_name: format!("metric_{table_id}"),
|
||||
table_id,
|
||||
batches: vec![mock_aligned_tag_batch("host", "node", 1000, 1.0)],
|
||||
row_count: 1,
|
||||
});
|
||||
// Keep identity even when the rule at conversion time does not reference it.
|
||||
let modified = batch_convert::transform_logical_batches_to_physical(
|
||||
&tables,
|
||||
&HashMap::from([("host".to_string(), 1)]),
|
||||
&HashSet::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let combined = batch_convert::concat_modified_batches(&modified, &tables).unwrap();
|
||||
let rule = MultiDimPartitionRule::try_new(
|
||||
vec![DATA_SCHEMA_TABLE_ID_COLUMN_NAME.to_string()],
|
||||
vec![1, 2],
|
||||
vec![
|
||||
col(DATA_SCHEMA_TABLE_ID_COLUMN_NAME).lt(Value::UInt32(15)),
|
||||
col(DATA_SCHEMA_TABLE_ID_COLUMN_NAME).gt_eq(Value::UInt32(15)),
|
||||
],
|
||||
true,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(rule.eval_context(), PartitionEvalContext::FromPayload);
|
||||
let planned = plan_region_batches(combined.clone(), 1024, &rule).unwrap();
|
||||
assert_eq!(planned.len(), 2);
|
||||
for batch in planned {
|
||||
let index = batch.region_id.region_number() as usize - 1;
|
||||
let request = encode_region_write_request(batch, false, &HashMap::new()).unwrap();
|
||||
let Some(region_request::Body::BulkInsert(request)) = request.body else {
|
||||
panic!("expected bulk insert")
|
||||
};
|
||||
let Some(bulk_insert_request::Body::ArrowIpc(ipc)) = request.body else {
|
||||
panic!("expected IPC")
|
||||
};
|
||||
let decoded = FlightDecoder::try_from_schema_bytes(&ipc.schema)
|
||||
.unwrap()
|
||||
.try_decode_record_batch(&ipc.data_header, &ipc.payload)
|
||||
.unwrap();
|
||||
assert_eq!(decoded, combined.slice(index, 1));
|
||||
let ids = decoded
|
||||
.column_by_name(DATA_SCHEMA_TABLE_ID_COLUMN_NAME)
|
||||
.unwrap()
|
||||
.as_any()
|
||||
.downcast_ref::<UInt32Array>()
|
||||
.unwrap();
|
||||
assert_eq!(ids.values().as_ref(), &[tables[index].table_id]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_plan_region_batches_preserves_partition_columns_through_encoding() {
|
||||
let logical_batch = RecordBatch::try_new(
|
||||
@@ -419,7 +481,8 @@ mod tests {
|
||||
&HashSet::from(["host"]),
|
||||
)
|
||||
.unwrap();
|
||||
let combined_batch = batch_convert::concat_modified_batches(&modified).unwrap();
|
||||
let combined_batch =
|
||||
batch_convert::concat_modified_batches(&modified, &table_batches).unwrap();
|
||||
assert!(combined_batch.column_by_name("host").is_some());
|
||||
assert!(combined_batch.column_by_name("zone").is_none());
|
||||
let expected = combined_batch.clone();
|
||||
@@ -436,10 +499,10 @@ mod tests {
|
||||
assert_eq!(2, planned_batches.len());
|
||||
assert_eq!(RegionId::new(1024, 1), planned_batches[0].region_id);
|
||||
assert_eq!(1, planned_batches[0].num_rows());
|
||||
assert_eq!(4, planned_batches[0].batch.num_columns());
|
||||
assert_eq!(5, planned_batches[0].batch.num_columns());
|
||||
assert_eq!(RegionId::new(1024, 2), planned_batches[1].region_id);
|
||||
assert_eq!(1, planned_batches[1].num_rows());
|
||||
assert_eq!(4, planned_batches[1].batch.num_columns());
|
||||
assert_eq!(5, planned_batches[1].batch.num_columns());
|
||||
|
||||
let partition_versions = HashMap::from([(1, Some(7)), (2, Some(8))]);
|
||||
for (index, planned) in planned_batches.into_iter().enumerate() {
|
||||
|
||||
@@ -109,6 +109,7 @@ mysql_async = { version = "0.37", default-features = false, features = [
|
||||
opentelemetry-proto.workspace = true
|
||||
operator = { workspace = true, features = ["testing"] }
|
||||
otel-arrow-rust.workspace = true
|
||||
partition.workspace = true
|
||||
paste.workspace = true
|
||||
plugins.workspace = true
|
||||
promql = { workspace = true, features = ["test-utils"] }
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -27,16 +27,20 @@ use common_test_util::recordbatch::check_output_stream;
|
||||
use common_test_util::temp_dir::{TempDir, create_temp_dir};
|
||||
use common_wal::config::DatanodeWalConfig;
|
||||
use datatypes::arrow::array::AsArray;
|
||||
use datatypes::value::Value;
|
||||
use frontend::instance::Instance;
|
||||
use meta_srv::gc::{self, BatchGcProcedure, GcSchedulerOptions, GcTickerRef};
|
||||
use meta_srv::metasrv::Metasrv;
|
||||
use mito2::gc::GcConfig;
|
||||
use partition::expr::{PartitionExpr, RestrictedOp};
|
||||
use partition::function::IcebergHash;
|
||||
use servers::error::Result as ServerResult;
|
||||
use servers::query_handler::sql::SqlQueryHandler;
|
||||
use session::Session;
|
||||
use session::context::{Channel, QueryContext, QueryContextRef};
|
||||
use sqlx::Row;
|
||||
use store_api::codec::PrimaryKeyEncoding;
|
||||
use store_api::metric_engine_consts::{DATA_SCHEMA_TABLE_ID_COLUMN_NAME, METRIC_DATA_REGION_GROUP};
|
||||
use store_api::storage::{RegionId, TableId};
|
||||
use tests_integration::cluster::{GreptimeDbCluster, GreptimeDbClusterBuilder};
|
||||
use tests_integration::test_util::{
|
||||
@@ -45,6 +49,26 @@ use tests_integration::test_util::{
|
||||
};
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
/// Each partition/format combination uses its own cluster and test timeout.
|
||||
#[macro_export]
|
||||
macro_rules! table_id_partition_tests {
|
||||
($service:ident, $(($name:ident, $mixed:expr, $hashed:expr, $flat:expr, $encoding:ident)),+ $(,)?) => {
|
||||
$(
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn $name() {
|
||||
let store_type = tests_integration::test_util::StorageType::$service;
|
||||
if store_type.test_on() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
$crate::repartition::test_partition_unpartitioned_metric_by_table_id(
|
||||
store_type, $mixed, $hashed, $flat,
|
||||
store_api::codec::PrimaryKeyEncoding::$encoding,
|
||||
).await;
|
||||
}
|
||||
}
|
||||
)+
|
||||
};
|
||||
}
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! repartition_tests {
|
||||
($($service:ident),*) => {
|
||||
@@ -110,6 +134,14 @@ macro_rules! repartition_tests {
|
||||
}
|
||||
}
|
||||
|
||||
$crate::table_id_partition_tests! { $service,
|
||||
(test_partition_unpartitioned_metric_by_table_id_primary_key_sparse, false, false, false, Sparse),
|
||||
(test_partition_unpartitioned_metric_by_table_id_and_host_primary_key_sparse, true, false, false, Sparse),
|
||||
(test_partition_unpartitioned_metric_by_table_id_hash_primary_key_sparse, false, true, false, Sparse),
|
||||
(test_partition_unpartitioned_metric_by_table_id_hash_and_host_flat_dense, true, true, true, Dense),
|
||||
(test_partition_unpartitioned_metric_by_table_id_hash_and_host_primary_key_sparse, true, true, false, Sparse),
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn [< test_repartition_metric_flat_sparse >]() {
|
||||
let store_type = tests_integration::test_util::StorageType::$service;
|
||||
@@ -1507,6 +1539,516 @@ ORDER BY partition_ordinal_position;",
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
/// Verifies table-id repartitioning, optionally with user columns and hash expressions.
|
||||
pub async fn test_partition_unpartitioned_metric_by_table_id(
|
||||
store_type: StorageType,
|
||||
mixed: bool,
|
||||
hashed: bool,
|
||||
flat_format: bool,
|
||||
primary_key_encoding: PrimaryKeyEncoding,
|
||||
) {
|
||||
info!(
|
||||
"test_partition_unpartitioned_metric_by_table_id: store_type: {:?}",
|
||||
store_type
|
||||
);
|
||||
let cluster_name = "test_partition_unpartitioned_metric_by_table_id";
|
||||
let (store_config, _guard) = get_test_store_config(&store_type);
|
||||
let datanodes = 3u64;
|
||||
let mut builder = GreptimeDbClusterBuilder::new(cluster_name).await;
|
||||
if matches!(store_type, StorageType::File) {
|
||||
let home_dir = create_temp_dir("test_partition_unpartitioned_metric_by_table_id_data_home");
|
||||
builder = builder.with_shared_home_dir(Arc::new(home_dir));
|
||||
}
|
||||
|
||||
let cluster = builder
|
||||
.with_datanodes(datanodes as u32)
|
||||
.with_store_config(store_config)
|
||||
.with_datanode_wal_config(DatanodeWalConfig::Noop)
|
||||
.with_metasrv_gc_config(GcSchedulerOptions {
|
||||
enable: true,
|
||||
gc_cooldown_period: Duration::from_nanos(1),
|
||||
..Default::default()
|
||||
})
|
||||
.with_datanode_gc_config(GcConfig {
|
||||
enable: true,
|
||||
lingering_time: Some(Duration::from_secs(0)),
|
||||
unknown_file_lingering_time: Duration::from_secs(0),
|
||||
..Default::default()
|
||||
})
|
||||
.build(true)
|
||||
.await;
|
||||
|
||||
let query_ctx = QueryContext::arc();
|
||||
let instance = cluster.fe_instance();
|
||||
|
||||
let sst_format = if flat_format { "flat" } else { "primary_key" };
|
||||
let primary_key_encoding = match primary_key_encoding {
|
||||
PrimaryKeyEncoding::Dense => "dense",
|
||||
PrimaryKeyEncoding::Sparse => "sparse",
|
||||
};
|
||||
let sql = format!(
|
||||
r#"
|
||||
CREATE TABLE `partition_table_id_metric_phy`(
|
||||
`ts` TIMESTAMP TIME INDEX,
|
||||
`val` DOUBLE,
|
||||
`host` STRING PRIMARY KEY
|
||||
) ENGINE = metric
|
||||
WITH (
|
||||
"physical_metric_table" = "true",
|
||||
"sst_format" = "{sst_format}",
|
||||
"primary_key_encoding" = "{primary_key_encoding}"
|
||||
);
|
||||
"#
|
||||
);
|
||||
run_sql(instance, &sql, query_ctx.clone()).await.unwrap();
|
||||
|
||||
for logical in [
|
||||
"partition_table_id_metric_low",
|
||||
"partition_table_id_metric_high",
|
||||
] {
|
||||
let sql = format!(
|
||||
r#"
|
||||
CREATE TABLE `{logical}`(
|
||||
`ts` TIMESTAMP TIME INDEX,
|
||||
`val` DOUBLE,
|
||||
`host` STRING PRIMARY KEY
|
||||
) ENGINE = metric
|
||||
WITH (
|
||||
"on_physical_table" = "partition_table_id_metric_phy"
|
||||
);
|
||||
"#
|
||||
);
|
||||
run_sql(instance, &sql, query_ctx.clone()).await.unwrap();
|
||||
}
|
||||
|
||||
run_sql(
|
||||
instance,
|
||||
r#"
|
||||
CREATE TABLE partition_table_id_metric_null_host (
|
||||
ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY
|
||||
) ENGINE = metric WITH ("on_physical_table" = "partition_table_id_metric_phy")
|
||||
"#,
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
run_sql(
|
||||
instance,
|
||||
"INSERT INTO partition_table_id_metric_null_host (ts, val) VALUES (0, 98)",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
if mixed {
|
||||
run_sql(
|
||||
instance,
|
||||
r#"CREATE TABLE partition_table_id_metric_no_host (
|
||||
ts TIMESTAMP TIME INDEX, val DOUBLE
|
||||
) ENGINE = metric WITH ("on_physical_table" = "partition_table_id_metric_phy")"#,
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let sql = r#"
|
||||
INSERT INTO `partition_table_id_metric_low` (`host`, `ts`, `val`) VALUES
|
||||
('a_host', '2022-01-01 00:00:00', 1);
|
||||
"#;
|
||||
run_sql(instance, sql, query_ctx.clone()).await.unwrap();
|
||||
let sql = r#"
|
||||
INSERT INTO `partition_table_id_metric_high` (`host`, `ts`, `val`) VALUES
|
||||
('a_host', '2022-01-01 00:00:00', 10);
|
||||
"#;
|
||||
run_sql(instance, sql, query_ctx.clone()).await.unwrap();
|
||||
|
||||
let low_table_id = get_table_id(&cluster.metasrv, "partition_table_id_metric_low").await;
|
||||
let high_table_id = get_table_id(&cluster.metasrv, "partition_table_id_metric_high").await;
|
||||
assert!(low_table_id < high_table_id);
|
||||
|
||||
// Exercise repartition of persisted data in each SST/primary-key format.
|
||||
run_sql(
|
||||
instance,
|
||||
"ADMIN flush_table('partition_table_id_metric_phy')",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let (operand, boundary) = if hashed {
|
||||
let Value::Int32(boundary) =
|
||||
IcebergHash::evaluate_value(&Value::UInt32(high_table_id)).unwrap()
|
||||
else {
|
||||
panic!("expected an INT hash for the logical table id");
|
||||
};
|
||||
("iceberg_hash(__table_id)", i64::from(boundary))
|
||||
} else {
|
||||
(DATA_SCHEMA_TABLE_ID_COLUMN_NAME, i64::from(high_table_id))
|
||||
};
|
||||
let partition_columns = if mixed {
|
||||
"`__table_id`, `host`"
|
||||
} else {
|
||||
"`__table_id`"
|
||||
};
|
||||
let expressions = if mixed {
|
||||
format!(
|
||||
"{operand} < {boundary}, {operand} >= {boundary} AND host < 'm', {operand} >= {boundary} AND host >= 'm'"
|
||||
)
|
||||
} else {
|
||||
format!("{operand} < {boundary}, {operand} >= {boundary}")
|
||||
};
|
||||
let sql = format!(
|
||||
"ALTER TABLE partition_table_id_metric_phy PARTITION ON COLUMNS ({partition_columns}) ({expressions})"
|
||||
);
|
||||
run_sql(instance, &sql, query_ctx.clone()).await.unwrap();
|
||||
// Refresh routes synchronously so the checks exercise the new partitions.
|
||||
instance.cache_invalidator().invalidate_all().unwrap();
|
||||
|
||||
let logical_table = instance
|
||||
.catalog_manager()
|
||||
.table("greptime", "public", "partition_table_id_metric_high", None)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let partition_columns = logical_table
|
||||
.table_info()
|
||||
.meta
|
||||
.partition_column_names()
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(partition_columns, if mixed { vec!["host"] } else { vec![] });
|
||||
assert_eq!(
|
||||
logical_table
|
||||
.partition_rules()
|
||||
.unwrap()
|
||||
.extra_phy_cols_not_in_logical_table,
|
||||
vec![DATA_SCHEMA_TABLE_ID_COLUMN_NAME]
|
||||
);
|
||||
|
||||
if mixed {
|
||||
// A missing schema column cannot be supplied by the table identity context.
|
||||
assert_sql_err_eq(
|
||||
instance,
|
||||
"INSERT INTO partition_table_id_metric_no_host (ts, val) VALUES (1000, 99)",
|
||||
"Undefined column: host",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await;
|
||||
run_sql(
|
||||
instance,
|
||||
"DROP TABLE partition_table_id_metric_no_host",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
for (logical, expected) in [
|
||||
(
|
||||
"partition_table_id_metric_low",
|
||||
"+-----+\n| val |\n+-----+\n| 1.0 |\n+-----+",
|
||||
),
|
||||
(
|
||||
"partition_table_id_metric_high",
|
||||
"+------+\n| val |\n+------+\n| 10.0 |\n+------+",
|
||||
),
|
||||
] {
|
||||
let result = run_sql(
|
||||
instance,
|
||||
&format!("SELECT val FROM `{logical}` WHERE host = 'a_host'"),
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
check_output_stream(result.data, expected).await;
|
||||
}
|
||||
|
||||
{
|
||||
// Hash predicates cannot always prune reads, so visible rows alone do not prove
|
||||
// correct routing. Observe writes on the actual data-region leaders as well.
|
||||
let physical_id = get_table_id(&cluster.metasrv, "partition_table_id_metric_phy").await;
|
||||
let (_, physical_route) = cluster
|
||||
.metasrv
|
||||
.table_metadata_manager()
|
||||
.table_route_manager()
|
||||
.get_physical_table_route(physical_id)
|
||||
.await
|
||||
.unwrap();
|
||||
let written_bytes = || {
|
||||
physical_route
|
||||
.region_routes
|
||||
.iter()
|
||||
.map(|route| {
|
||||
let datanode =
|
||||
&cluster.datanode_instances[&route.leader_peer.as_ref().unwrap().id];
|
||||
let data_region = RegionId::with_group_and_seq(
|
||||
physical_id,
|
||||
METRIC_DATA_REGION_GROUP,
|
||||
route.region.id.region_sequence(),
|
||||
);
|
||||
let stats = datanode
|
||||
.region_server()
|
||||
.mito_engine()
|
||||
.unwrap()
|
||||
.get_region_statistic(data_region)
|
||||
.unwrap();
|
||||
(route.region.id, stats.written_bytes)
|
||||
})
|
||||
.collect::<BTreeMap<_, _>>()
|
||||
};
|
||||
// The high table is exactly on the >= boundary. Its two hosts target both
|
||||
// host partitions when mixed, and the single >= partition otherwise.
|
||||
let expected_regions = physical_route
|
||||
.region_routes
|
||||
.iter()
|
||||
.filter(|route| {
|
||||
PartitionExpr::from_json_str(&route.region.partition_expr)
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.op
|
||||
!= RestrictedOp::Lt
|
||||
})
|
||||
.map(|route| route.region.id)
|
||||
.collect::<BTreeSet<_>>();
|
||||
assert_eq!(expected_regions.len(), if mixed { 2 } else { 1 });
|
||||
let before = written_bytes();
|
||||
run_sql(instance,
|
||||
"INSERT INTO partition_table_id_metric_high (host, ts, val) VALUES ('c_host', '2022-01-02 00:00:00', 30), ('z_host', '2022-01-02 00:00:00', 40)",
|
||||
query_ctx.clone()).await.unwrap();
|
||||
let actual_regions = written_bytes()
|
||||
.into_iter()
|
||||
.filter_map(|(region, bytes)| (bytes > before[®ion]).then_some(region))
|
||||
.collect::<BTreeSet<_>>();
|
||||
assert_eq!(
|
||||
actual_regions, expected_regions,
|
||||
"writes must reach the physical expression's regions"
|
||||
);
|
||||
run_sql(
|
||||
instance,
|
||||
"ADMIN flush_table('partition_table_id_metric_phy')",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let result = run_sql(
|
||||
instance,
|
||||
"SELECT host, val FROM partition_table_id_metric_high WHERE host IN ('c_host', 'z_host') ORDER BY host",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
check_output_stream(
|
||||
result.data,
|
||||
"\
|
||||
+--------+------+
|
||||
| host | val |
|
||||
+--------+------+
|
||||
| c_host | 30.0 |
|
||||
| z_host | 40.0 |
|
||||
+--------+------+",
|
||||
)
|
||||
.await;
|
||||
run_sql(
|
||||
instance,
|
||||
"DELETE FROM partition_table_id_metric_high WHERE host IN ('c_host', 'z_host')",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let sql = r#"
|
||||
INSERT INTO `partition_table_id_metric_low` (`host`, `ts`, `val`) VALUES
|
||||
('b_host', '2022-01-02 00:00:00', 2);
|
||||
"#;
|
||||
run_sql(instance, sql, query_ctx.clone()).await.unwrap();
|
||||
let sql = r#"
|
||||
INSERT INTO `partition_table_id_metric_high` (`host`, `ts`, `val`) VALUES
|
||||
('b_host', '2022-01-02 00:00:00', 20);
|
||||
"#;
|
||||
run_sql(instance, sql, query_ctx.clone()).await.unwrap();
|
||||
for logical in [
|
||||
"partition_table_id_metric_low",
|
||||
"partition_table_id_metric_high",
|
||||
] {
|
||||
let result = run_sql(
|
||||
instance,
|
||||
&format!("SELECT host FROM `{logical}` WHERE host = 'b_host'"),
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let expected = "\
|
||||
+--------+
|
||||
| host |
|
||||
+--------+
|
||||
| b_host |
|
||||
+--------+";
|
||||
check_output_stream(result.data, expected).await;
|
||||
}
|
||||
|
||||
run_sql(
|
||||
instance,
|
||||
"ADMIN flush_table('partition_table_id_metric_phy')",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
run_sql(
|
||||
instance,
|
||||
"INSERT INTO partition_table_id_metric_null_host (ts, val) VALUES (1000, 99)",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
run_sql(
|
||||
instance,
|
||||
"ADMIN flush_table('partition_table_id_metric_phy')",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let output = run_sql(
|
||||
instance,
|
||||
"SELECT val FROM partition_table_id_metric_null_host WHERE ts = 1000",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
check_output_stream(
|
||||
output.data,
|
||||
"+------+\n| val |\n+------+\n| 99.0 |\n+------+",
|
||||
)
|
||||
.await;
|
||||
let output = run_sql(
|
||||
instance,
|
||||
"SELECT val FROM partition_table_id_metric_null_host ORDER BY ts",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
check_output_stream(
|
||||
output.data,
|
||||
"+------+\n| val |\n+------+\n| 98.0 |\n| 99.0 |\n+------+",
|
||||
)
|
||||
.await;
|
||||
|
||||
// Logical tables created after repartition must inherit usable routing metadata.
|
||||
run_sql(
|
||||
instance,
|
||||
r#"
|
||||
CREATE TABLE partition_table_id_metric_new (
|
||||
ts TIMESTAMP TIME INDEX, val DOUBLE, host STRING PRIMARY KEY
|
||||
) ENGINE = metric WITH ("on_physical_table" = "partition_table_id_metric_phy")
|
||||
"#,
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
run_sql(
|
||||
instance,
|
||||
"INSERT INTO partition_table_id_metric_new (host, ts, val) VALUES ('new_host', 1000, 100)",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let output = run_sql(
|
||||
instance,
|
||||
"SELECT val FROM partition_table_id_metric_new",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
check_output_stream(
|
||||
output.data,
|
||||
"+-------+\n| val |\n+-------+\n| 100.0 |\n+-------+",
|
||||
)
|
||||
.await;
|
||||
run_sql(
|
||||
instance,
|
||||
"DELETE FROM partition_table_id_metric_new WHERE host = 'new_host'",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let output = run_sql(
|
||||
instance,
|
||||
"SELECT count(*) AS n FROM partition_table_id_metric_new",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
check_output_stream(output.data, "+---+\n| n |\n+---+\n| 0 |\n+---+").await;
|
||||
|
||||
let sql = r#"
|
||||
DELETE FROM `partition_table_id_metric_low` WHERE `host` = 'a_host';
|
||||
"#;
|
||||
run_sql(instance, sql, query_ctx.clone()).await.unwrap();
|
||||
|
||||
let result = run_sql(
|
||||
instance,
|
||||
"SELECT * FROM `partition_table_id_metric_low` ORDER BY `host`",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let expected = "\
|
||||
+--------+---------------------+-----+
|
||||
| host | ts | val |
|
||||
+--------+---------------------+-----+
|
||||
| b_host | 2022-01-02T00:00:00 | 2.0 |
|
||||
+--------+---------------------+-----+";
|
||||
check_output_stream(result.data, expected).await;
|
||||
|
||||
let result = run_sql(
|
||||
instance,
|
||||
"SELECT * FROM `partition_table_id_metric_high` ORDER BY `host`",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let expected = "\
|
||||
+--------+---------------------+------+
|
||||
| host | ts | val |
|
||||
+--------+---------------------+------+
|
||||
| a_host | 2022-01-01T00:00:00 | 10.0 |
|
||||
| b_host | 2022-01-02T00:00:00 | 20.0 |
|
||||
+--------+---------------------+------+";
|
||||
check_output_stream(result.data, expected).await;
|
||||
|
||||
let result = run_sql(
|
||||
instance,
|
||||
"\
|
||||
SELECT count(*) AS partition_count \
|
||||
FROM information_schema.partitions \
|
||||
WHERE table_name = 'partition_table_id_metric_phy';",
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let count = if mixed { 3 } else { 2 };
|
||||
let expected = format!(
|
||||
"+-----------------+\n| partition_count |\n+-----------------+\n| {count} |\n+-----------------+"
|
||||
);
|
||||
check_output_stream(result.data, &expected).await;
|
||||
|
||||
for table in [
|
||||
"partition_table_id_metric_new",
|
||||
"partition_table_id_metric_null_host",
|
||||
"partition_table_id_metric_low",
|
||||
"partition_table_id_metric_high",
|
||||
"partition_table_id_metric_phy",
|
||||
] {
|
||||
run_sql(
|
||||
instance,
|
||||
&format!("DROP TABLE `{table}`"),
|
||||
query_ctx.clone(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_table_id(metasrv: &Arc<Metasrv>, table_name: &str) -> TableId {
|
||||
metasrv
|
||||
.table_metadata_manager()
|
||||
|
||||
Reference in New Issue
Block a user