diff --git a/Cargo.lock b/Cargo.lock index 741cbe40bc8..b4eb237452d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10633,6 +10633,7 @@ version = "1.4.0-alpha.0" dependencies = [ "api", "common-base", + "common-cache", "common-error", "common-macro", "common-meta", diff --git a/src/partition/Cargo.toml b/src/partition/Cargo.toml index 43f6c8e792a..a0ad7468f1e 100644 --- a/src/partition/Cargo.toml +++ b/src/partition/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] api.workspace = true common-base.workspace = true +common-cache.workspace = true common-error.workspace = true common-macro.workspace = true common-meta.workspace = true diff --git a/src/partition/src/cache.rs b/src/partition/src/cache.rs index e070e1a2578..059f661d181 100644 --- a/src/partition/src/cache.rs +++ b/src/partition/src/cache.rs @@ -12,7 +12,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -use std::sync::Arc; +use std::collections::{BTreeSet, HashMap}; +use std::sync::{Arc, Weak}; + +use common_cache::SyncCache; +use datatypes::arrow::array::RecordBatch; +use datatypes::value::Value; use common_base::hash::partition_expr_version; use common_error::ext::BoxedError; @@ -21,7 +26,10 @@ use common_meta::instruction::CacheIdent; use common_meta::rpc::router::RegionRoute; use moka::future::Cache; use snafu::ResultExt; -use store_api::storage::{RegionId, TableId}; +use store_api::storage::{RegionId, RegionNumber, TableId}; + +use crate::multi_dim::MultiDimPartitionRule; +use crate::partition::{PartitionRule, PartitionRuleRef, RegionMask}; use crate::expr::PartitionExpr; use crate::manager::PartitionInfoWithVersion; @@ -126,6 +134,136 @@ pub fn new_partition_info_cache( ) } +/// Shared, bounded routing results. Snapshot identity fences late insertions after invalidation. +pub(crate) struct PartitionRoutingCache { + cache: SyncCache, +} + +#[derive(Clone, PartialEq, Eq, Hash)] +struct RoutingKey { + table_id: TableId, + values: Vec, +} + +#[derive(Clone)] +struct RoutingResult { + snapshot: Weak, + region: RegionNumber, +} + +impl PartitionRoutingCache { + pub(crate) fn new(capacity: u64) -> Self { + Self { + cache: SyncCache::new( + "partition_routing", + capacity, + |key: &RoutingKey, _: &RoutingResult| { + let bytes = key.values.iter().fold( + std::mem::size_of::() + std::mem::size_of::(), + |sum, value| { + sum.saturating_add(std::mem::size_of::()) + .saturating_add(value.as_value_ref().data_size()) + }, + ); + u32::try_from(bytes).unwrap_or(u32::MAX) + }, + |_, _, _| {}, + ), + } + } + + pub(crate) fn rule( + &self, + table_id: TableId, + snapshot: Arc, + ) -> crate::error::Result { + let mut names = BTreeSet::new(); + let mut regions = Vec::new(); + let mut expressions = Vec::new(); + for part in &snapshot.partitions { + if let Some(expr) = &part.partition_expr { + let mut columns = std::collections::HashSet::new(); + expr.collect_column_names(&mut columns); + names.extend(columns); + regions.push(part.id.region_number()); + expressions.push(expr.clone()); + } + } + regions.extend( + snapshot + .partitions + .iter() + .filter(|part| part.partition_expr.is_none()) + .map(|part| part.id.region_number()), + ); + let rule = MultiDimPartitionRule::try_new( + names.into_iter().collect(), + regions, + expressions, + false, + )?; + Ok(Arc::new(CachedPhysicalPartitionRule { + table_id, + snapshot, + rule, + cache: self.cache.clone(), + })) + } +} + +struct CachedPhysicalPartitionRule { + table_id: TableId, + snapshot: Arc, + rule: MultiDimPartitionRule, + cache: SyncCache, +} + +impl PartitionRule for CachedPhysicalPartitionRule { + fn as_any(&self) -> &dyn std::any::Any { + self + } + + fn partition_columns(&self) -> &[String] { + self.rule.partition_columns() + } + + fn find_region(&self, values: &[Value]) -> crate::error::Result { + // Large variable-width keys should not displace many useful small entries. + if values.iter().fold(0usize, |size, value| { + size.saturating_add(value.as_value_ref().data_size()) + }) > 8192 + { + return self.rule.find_region(values); + } + // Columns are deterministically ordered when building the rule from this snapshot. + let key = RoutingKey { + table_id: self.table_id, + values: values.to_vec(), + }; + if let Some(cached) = self.cache.get(&key) + && cached.snapshot.ptr_eq(&Arc::downgrade(&self.snapshot)) + { + return Ok(cached.region); + } + let region = self.rule.find_region(values)?; + self.cache.insert( + key, + RoutingResult { + snapshot: Arc::downgrade(&self.snapshot), + region, + }, + ); + Ok(region) + } + + fn split_record_batch( + &self, + batch: &RecordBatch, + ) -> crate::error::Result> { + self.rule.split_record_batch(batch) + } +} + #[cfg(test)] mod tests { use common_base::hash::partition_expr_version; @@ -171,4 +309,127 @@ mod tests { partitions[0].partition_expr_version ); } + fn routing_snapshot(region: u32) -> std::sync::Arc { + use crate::expr::col; + use datatypes::value::Value; + std::sync::Arc::new(super::PhysicalPartitionInfo { + partitions: vec![crate::manager::PartitionInfoWithVersion { + id: RegionId::new(42, region), + partition_expr: Some( + col("a") + .eq(Value::from("x")) + .and(col("b").gt_eq(Value::Int64(10))), + ), + partition_expr_version: None, + }], + }) + } + + #[test] + fn test_routing_cache_snapshot_fences_late_publication() { + use datatypes::value::Value; + let cache = super::PartitionRoutingCache::new(4096); + let old_snapshot = routing_snapshot(1); + let old = cache.rule(42, old_snapshot.clone()).unwrap(); + let new_snapshot = routing_snapshot(2); + let new = cache.rule(42, new_snapshot.clone()).unwrap(); + let values = [Value::from("x"), Value::Int64(10)]; + assert_eq!(old.partition_columns(), &["a", "b"]); + assert_eq!(old.find_region(&values).unwrap(), 1); + assert_eq!(new.find_region(&values).unwrap(), 2); + // An in-flight request can publish its old answer after replacement. + assert_eq!(old.find_region(&values).unwrap(), 1); + assert_eq!(new.find_region(&values).unwrap(), 2); + // Different physical tables cannot share a cached answer. + let other = cache.rule(43, routing_snapshot(3)).unwrap(); + assert_eq!(other.find_region(&values).unwrap(), 3); + assert_eq!( + new.find_region(&[Value::from("y"), Value::Int64(10)]) + .unwrap(), + 0 + ); + assert!(new.find_region(&[Value::from("x")]).is_err()); + drop(old); + assert_eq!(std::sync::Arc::strong_count(&old_snapshot), 1); + } + + #[test] + fn test_routing_cache_disabled_and_large_keys() { + use datatypes::value::Value; + let cache = super::PartitionRoutingCache::new(0); + let rule = cache.rule(42, routing_snapshot(1)).unwrap(); + assert_eq!( + rule.find_region(&[Value::from("x"), Value::Int64(11)]) + .unwrap(), + 1 + ); + cache.cache.run_pending_tasks(); + assert!( + cache + .cache + .get(&super::RoutingKey { + table_id: 42, + values: vec![Value::from("x"), Value::Int64(11)] + }) + .is_none() + ); + assert_eq!( + rule.find_region(&[Value::from("x".repeat(9000)), Value::Int64(11)]) + .unwrap(), + 0 + ); + } + + /// Identical rule and keys; compare interpretation with warm, shared routing results. + #[test] + #[ignore = "manual optimized routing benchmark"] + #[allow(clippy::print_stdout)] + fn bench_shared_partition_routing() { + use crate::expr::col; + use datatypes::value::Value; + for partitions in [19u32, 64, 128] { + let snapshot = std::sync::Arc::new(super::PhysicalPartitionInfo { + partitions: (0..partitions) + .map(|i| crate::manager::PartitionInfoWithVersion { + id: RegionId::new(42, i + 1), + partition_expr: Some( + col("key") + .gt_eq(Value::UInt32(i * 100)) + .and(col("key").lt(Value::UInt32((i + 1) * 100))), + ), + partition_expr_version: None, + }) + .collect(), + }); + let cache = super::PartitionRoutingCache::new(64 * 1024 * 1024); + let rule = cache.rule(42, snapshot).unwrap(); + let cached = rule + .as_any() + .downcast_ref::() + .unwrap(); + let keys: Vec<_> = (0..partitions * 100).map(|i| [Value::UInt32(i)]).collect(); + for key in &keys { + rule.find_region(key).unwrap(); + } + for round in 0..3 { + for use_cache in [false, true] { + let start = std::time::Instant::now(); + let mut checksum = 0u64; + for n in 0..200_000usize { + let key = std::hint::black_box(&keys[n % keys.len()]); + let result = if use_cache { + rule.find_region(key) + } else { + super::PartitionRule::find_region(&cached.rule, key) + }; + checksum += result.unwrap() as u64; + } + println!( + "routing partitions={partitions} round={round} cached={use_cache} elapsed_us={} checksum={checksum}", + start.elapsed().as_micros() + ); + } + } + } + } } diff --git a/src/partition/src/manager.rs b/src/partition/src/manager.rs index 6fc95fed558..8c4a8c9cd99 100644 --- a/src/partition/src/manager.rs +++ b/src/partition/src/manager.rs @@ -28,7 +28,9 @@ use store_api::metric_engine_consts::{ use store_api::storage::{RegionId, RegionNumber}; use table::metadata::{TableId, TableInfo}; -use crate::cache::{CachedPartitionInfo, PartitionInfoCacheRef, PhysicalPartitionInfo}; +use crate::cache::{ + CachedPartitionInfo, PartitionInfoCacheRef, PartitionRoutingCache, PhysicalPartitionInfo, +}; use crate::error::{FindLeaderSnafu, Result}; use crate::expr::PartitionExpr; use crate::multi_dim::MultiDimPartitionRule; @@ -46,6 +48,7 @@ pub struct PartitionRuleManager { table_route_manager: TableRouteManager, table_route_cache: TableRouteCacheRef, partition_info_cache: PartitionInfoCacheRef, + routing_cache: PartitionRoutingCache, } #[derive(Debug, Clone)] @@ -71,6 +74,7 @@ impl PartitionRuleManager { table_route_manager: TableRouteManager::new(kv_backend), table_route_cache, partition_info_cache, + routing_cache: PartitionRoutingCache::new(64 * 1024 * 1024), } } @@ -211,6 +215,16 @@ impl PartitionRuleManager { } } + /// Builds a payload rule sharing completed routing results with other requests. + /// The supplied physical snapshot owns column ordering and fences stale results. + pub fn cached_physical_partition_rule( + &self, + table_id: TableId, + snapshot: Arc, + ) -> Result { + self.routing_cache.rule(table_id, snapshot) + } + pub async fn batch_find_table_partitions( &self, table_ids: &[TableId],