diff --git a/Cargo.lock b/Cargo.lock index 868a952b0ab..f9ea4e0b800 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1657,7 +1657,7 @@ dependencies = [ "maybe-owned", "rustix 1.0.7", "rustix-linux-procfs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "winx", ] @@ -6187,7 +6187,7 @@ dependencies = [ [[package]] name = "greptime-proto" version = "0.1.0" -source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=deb256cbdeac283f3946fb22f8b4e4b29656fd0c#deb256cbdeac283f3946fb22f8b4e4b29656fd0c" +source = "git+https://github.com/GreptimeTeam/greptime-proto.git?rev=9aa28f23abeea4f2b37ce14a74a583eb169e2fb0#9aa28f23abeea4f2b37ce14a74a583eb169e2fb0" dependencies = [ "prost 0.14.1", "prost-types 0.14.1", @@ -6799,7 +6799,7 @@ dependencies = [ "libc", "percent-encoding", "pin-project-lite", - "socket2 0.5.10", + "socket2 0.6.4", "tokio", "tower-service", "tracing", @@ -9377,7 +9377,7 @@ version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -11679,7 +11679,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac6c3320f9abac597dcbc668774ef006702672474aad53c6d596b62e487b40b1" dependencies = [ "heck 0.5.0", - "itertools 0.10.5", + "itertools 0.11.0", "log", "multimap", "once_cell", @@ -11727,7 +11727,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" dependencies = [ "anyhow", - "itertools 0.10.5", + "itertools 0.11.0", "proc-macro2", "quote", "syn 2.0.117", @@ -11740,7 +11740,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9120690fafc389a67ba3803df527d0ec9cbbc9cc45e4cc20b332996dfb672425" dependencies = [ "anyhow", - "itertools 0.10.5", + "itertools 0.11.0", "proc-macro2", "quote", "syn 2.0.117", @@ -13297,7 +13297,7 @@ dependencies = [ "security-framework 3.7.0", "security-framework-sys", "webpki-root-certs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -14220,7 +14220,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -14790,7 +14790,7 @@ dependencies = [ "cfg-if", "libc", "psm", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -15417,7 +15417,7 @@ dependencies = [ "getrandom 0.3.4", "once_cell", "rustix 1.0.7", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index d0e14064a79..6f9703a0339 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -164,7 +164,7 @@ fs2 = "0.4" fst = "0.4.7" futures = "0.3" futures-util = "0.3" -greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "deb256cbdeac283f3946fb22f8b4e4b29656fd0c" } +greptime-proto = { git = "https://github.com/GreptimeTeam/greptime-proto.git", rev = "9aa28f23abeea4f2b37ce14a74a583eb169e2fb0" } hdfs-native = "0.14.6" hex = "0.4" hostname = "0.4.0" diff --git a/src/api/src/region.rs b/src/api/src/region.rs index 79936629cd6..1d7f9b699c7 100644 --- a/src/api/src/region.rs +++ b/src/api/src/region.rs @@ -37,6 +37,8 @@ pub struct RegionResponse { pub metadata: Vec, /// Structured response for persisted sketch operations. pub sketch: Option, + /// Validated split points from one pinned statistics snapshot. + pub sketch_split: Option, } /// Successful entries and failed-entry errors indexed by input order. @@ -61,6 +63,7 @@ impl RegionResponse { extensions: region_response.extensions, metadata: region_response.metadata, sketch: region_response.sketch, + sketch_split: region_response.sketch_split, } } @@ -71,6 +74,7 @@ impl RegionResponse { extensions: Default::default(), metadata: Vec::new(), sketch: None, + sketch_split: None, } } @@ -81,6 +85,7 @@ impl RegionResponse { extensions: Default::default(), metadata, sketch: None, + sketch_split: None, } } } diff --git a/src/client/src/region.rs b/src/client/src/region.rs index 123f64030c3..98fd52f3e7e 100644 --- a/src/client/src/region.rs +++ b/src/client/src/region.rs @@ -169,6 +169,25 @@ impl RegionRequester { .await } + /// Generates and validates split points within one pinned SST snapshot. + pub async fn sketch_split( + &self, + request: api::v1::region::SketchSplitRequest, + ) -> Result { + self.handle_inner(RegionRequest { + header: Some(RegionRequestHeader { + tracing_context: TracingContext::from_current_span().to_w3c(), + ..Default::default() + }), + body: Some(region_request::Body::SketchSplit(request)), + }) + .await? + .sketch_split + .context(MissingFieldSnafu { + field: "sketch_split", + }) + } + async fn handle_sketch( &self, body: region_request::Body, @@ -769,6 +788,64 @@ mod tests { ); } + #[tokio::test] + async fn test_sketch_split_rpc_preserves_request_and_response() { + let server = RegionTestServer::start().await; + let requester = server.create_requester(ChannelConfig::default(), false, false); + let request = api::v1::region::SketchSplitRequest { + region_id: 42, + time_range: Some(api::v1::region::SketchTimeRange { + start: 1001, + end: 2001, + time_unit: api::v1::TimeUnit::Microsecond as i32, + }), + column: "__table_id".into(), + parts: 2, + initial_files: 128, + min_files: 512, + max_files: 2048, + seed: 42, + max_cdf_delta: 0.05, + min_partition_ratio: 0.7, + max_partition_ratio: 1.3, + }; + let expected = api::v1::region::SketchSplitResponse { + status: api::v1::region::SketchSplitStatus::Unstable as i32, + candidate_files: 10_000, + sampled_files: 2048, + proposal_files: 1024, + validation_files: 1024, + rounds: 5, + ..Default::default() + }; + let mut response = build_response(StatusCode::Success); + response.sketch_split = Some(expected.clone()); + server + .service + .responses + .lock() + .unwrap() + .push_back(Ok(response)); + assert_eq!( + requester.sketch_split(request.clone()).await.unwrap(), + expected + ); + assert_eq!( + server.service.requests.lock().unwrap()[0].0.body, + Some(region_request::Body::SketchSplit(request.clone())) + ); + server + .service + .responses + .lock() + .unwrap() + .push_back(Ok(build_response(StatusCode::Success))); + assert!( + requester.sketch_split(request).await.is_err(), + "missing dedicated response must not silently succeed" + ); + } + fn build_insert_request() -> RegionRequest { RegionRequest { header: Some(RegionRequestHeader { diff --git a/src/common/meta/src/ddl/test_util/datanode_handler.rs b/src/common/meta/src/ddl/test_util/datanode_handler.rs index ce2668dadf6..e22dad2a63d 100644 --- a/src/common/meta/src/ddl/test_util/datanode_handler.rs +++ b/src/common/meta/src/ddl/test_util/datanode_handler.rs @@ -40,6 +40,7 @@ impl MockDatanodeHandler for () { extensions: Default::default(), metadata: Vec::new(), sketch: None, + sketch_split: None, }) } diff --git a/src/datanode/src/region_server.rs b/src/datanode/src/region_server.rs index 5f53e18acbc..c9d394341a7 100644 --- a/src/datanode/src/region_server.rs +++ b/src/datanode/src/region_server.rs @@ -685,6 +685,7 @@ impl RegionServer { extensions, metadata: Vec::new(), sketch: None, + sketch_split: None, }) } @@ -1152,6 +1153,12 @@ impl RegionServer { let failed_requests_cnt = crate::metrics::REGION_SERVER_REQUEST_FAILURE_COUNT .with_label_values(&[request.as_ref()]); let request = match request { + region_request::Body::SketchSplit(request) => { + return self + .handle_sketch_split_rpc(request) + .await + .inspect_err(|_| failed_requests_cnt.inc()); + } region_request::Body::SketchStat(request) => { return self .handle_sketch_rpc(request, false) @@ -1197,6 +1204,7 @@ impl RegionServer { extensions: response.extensions, metadata: response.metadata, sketch: None, + sketch_split: None, failures: Vec::new(), }) } @@ -1347,6 +1355,7 @@ fn encode_batch_write_response(result: BatchRegionResponse) -> Reg }), metadata: Vec::new(), sketch: None, + sketch_split: None, affected_rows: result.affected_rows as _, extensions: result.extensions, failures: result @@ -1967,6 +1976,7 @@ impl RegionServerInner { extensions: result.extensions, metadata: Vec::new(), sketch: None, + sketch_split: None, }) } Err(err) => { @@ -2076,6 +2086,7 @@ impl RegionServerInner { extensions: result.extensions, metadata: Vec::new(), sketch: None, + sketch_split: None, }) } Err(err) => { diff --git a/src/datanode/src/region_server/sketch.rs b/src/datanode/src/region_server/sketch.rs index bc30fc7ddd1..3a4c79d2622 100644 --- a/src/datanode/src/region_server/sketch.rs +++ b/src/datanode/src/region_server/sketch.rs @@ -17,7 +17,9 @@ use common_error::ext::BoxedError; use snafu::{OptionExt, ResultExt}; use store_api::region_engine::RegionEngineRef; -use store_api::sketch::{SketchReader, SketchRequest, SketchResponse}; +use store_api::sketch::{ + SketchReader, SketchRequest, SketchResponse, SketchSplitRequest, SketchSplitResponse, +}; use store_api::storage::RegionId; use crate::error::SketchReaderUnavailableSnafu; @@ -50,6 +52,15 @@ impl RegionSketchReader { self.reader()?.query(self.region_id, request).await } + /// Searches for split points and validates them within one engine snapshot. + pub async fn split( + &self, + request: SketchSplitRequest, + ) -> std::result::Result { + request.validate()?; + self.reader()?.split(self.region_id, request).await + } + fn reader(&self) -> std::result::Result<&dyn SketchReader, BoxedError> { self.engine .sketch_reader() @@ -61,6 +72,35 @@ impl RegionSketchReader { } impl crate::region_server::RegionServer { + pub(crate) async fn handle_sketch_split_rpc( + &self, + request: api::v1::region::SketchSplitRequest, + ) -> servers::error::Result { + let response = async { + let region_id = RegionId::from_u64(request.region_id); + let request = SketchSplitRequest::try_from(request)?; + let reader = self + .sketch_reader(region_id) + .map_err(BoxedError::new)? + .context(SketchReaderUnavailableSnafu { region_id }) + .map_err(BoxedError::new)?; + let response = reader.split(request).await?; + api::v1::region::SketchSplitResponse::try_from(response) + } + .await + .context(servers::error::ExecuteGrpcRequestSnafu)?; + Ok(api::v1::region::RegionResponse { + header: Some(api::v1::ResponseHeader { + status: Some(api::v1::Status { + status_code: common_error::status_code::StatusCode::Success as _, + ..Default::default() + }), + }), + sketch_split: Some(response), + ..Default::default() + }) + } + pub(crate) async fn handle_sketch_rpc( &self, request: api::v1::region::SketchRequest, diff --git a/src/meta-srv/src/procedure/utils.rs b/src/meta-srv/src/procedure/utils.rs index e14f74caf14..277a25a038f 100644 --- a/src/meta-srv/src/procedure/utils.rs +++ b/src/meta-srv/src/procedure/utils.rs @@ -363,6 +363,7 @@ pub mod mock { extensions: Default::default(), metadata: Vec::new(), sketch: None, + sketch_split: None, failures: Vec::new(), }) } diff --git a/src/metric-engine/src/engine.rs b/src/metric-engine/src/engine.rs index a8fc9f724e7..2d974aab420 100644 --- a/src/metric-engine/src/engine.rs +++ b/src/metric-engine/src/engine.rs @@ -182,6 +182,7 @@ impl RegionEngine for MetricEngine { extensions: extension_return_value, metadata: Vec::new(), sketch: None, + sketch_split: None, }) } BatchRegionDdlRequest::Alter(requests) => { @@ -197,6 +198,7 @@ impl RegionEngine for MetricEngine { extensions: extension_return_value, metadata: Vec::new(), sketch: None, + sketch_split: None, }) } BatchRegionDdlRequest::Drop(requests) => { @@ -340,6 +342,7 @@ impl RegionEngine for MetricEngine { extensions: extension_return_value, metadata: Vec::new(), sketch: None, + sketch_split: None, }) } @@ -675,6 +678,7 @@ impl MetricEngine { extensions, metadata: Vec::new(), sketch: None, + sketch_split: None, }) } } diff --git a/src/metric-engine/src/engine/read.rs b/src/metric-engine/src/engine/read.rs index ae564b68c54..7d9e6fb2161 100644 --- a/src/metric-engine/src/engine/read.rs +++ b/src/metric-engine/src/engine/read.rs @@ -24,7 +24,9 @@ use snafu::{OptionExt, ResultExt}; use store_api::metadata::{ColumnMetadata, RegionMetadataBuilder, RegionMetadataRef}; use store_api::metric_engine_consts::DATA_SCHEMA_TABLE_ID_COLUMN_NAME; use store_api::region_engine::{RegionEngine, RegionScannerRef}; -use store_api::sketch::{SketchReader, SketchRequest, SketchResponse}; +use store_api::sketch::{ + SketchReader, SketchRequest, SketchResponse, SketchSplitRequest, SketchSplitResponse, +}; use store_api::storage::{RegionId, ScanRequest, SequenceNumber}; use crate::engine::{MetricEngine, MetricEngineInner}; @@ -56,6 +58,17 @@ impl SketchReader for MetricEngine { .query(utils::to_data_region_id(region_id), request) .await } + + async fn split( + &self, + region_id: RegionId, + request: SketchSplitRequest, + ) -> std::result::Result { + request.validate()?; + self.physical_sketch_reader(region_id)? + .split(utils::to_data_region_id(region_id), request) + .await + } } impl MetricEngine { @@ -399,6 +412,104 @@ mod test { self, TestEnv, alter_logical_region_add_tag_columns, create_logical_region_request, }; + #[tokio::test] + async fn test_split_sketch_forwarding() { + use common_base::Plugins; + use common_time::Timestamp; + use mito2::sst::index::sketch_reader::{ + SketchReadContext, SketchReadHandler, SketchReadHandlerRef, + }; + use store_api::sketch::{SketchSplitStatus, SketchTimeRange}; + + #[derive(Debug)] + struct SplitHandler { + region_id: RegionId, + request: SketchSplitRequest, + } + + #[async_trait::async_trait] + impl SketchReadHandler for SplitHandler { + async fn stat( + &self, + _: &SketchReadContext<'_>, + _: &SketchRequest, + ) -> std::result::Result { + panic!("split must not issue a stat request") + } + + async fn query( + &self, + _: &SketchReadContext<'_>, + _: &SketchRequest, + ) -> std::result::Result { + panic!("split must not issue a generic query") + } + + async fn split( + &self, + context: &SketchReadContext<'_>, + request: &SketchSplitRequest, + ) -> std::result::Result { + assert_eq!(context.metadata.region_id, self.region_id); + assert_eq!(request, &self.request); + assert_eq!(context.files.iter().count(), 0); + Ok(SketchSplitResponse { + status: SketchSplitStatus::EmptyWindow, + points: vec![], + candidate_files: 0, + sampled_files: 0, + proposal_files: 0, + validation_files: 0, + rounds: 0, + gaps: vec![], + }) + } + } + + let physical_region = RegionId::new(1, 2); + let request = SketchSplitRequest { + time_range: SketchTimeRange { + start: Timestamp::new_millisecond(0), + end: Timestamp::new_millisecond(300_000), + }, + column: DATA_SCHEMA_TABLE_ID_COLUMN_NAME.to_string(), + parts: 8, + initial_files: 128, + min_files: 512, + max_files: 2048, + seed: 42, + max_cdf_delta: 0.05, + min_partition_ratio: 0.7, + max_partition_ratio: 1.3, + }; + let plugins = Plugins::new(); + plugins.insert::(Arc::new(SplitHandler { + region_id: utils::to_data_region_id(physical_region), + request: request.clone(), + })); + let mut mito_env = mito2::test_util::TestEnv::new().await; + let mito = mito_env + .create_engine_with_plugins(Default::default(), plugins) + .await; + let env = TestEnv::with_mito_engine(mito_env, mito); + env.create_physical_region(physical_region, &TestEnv::default_table_dir(), vec![]) + .await; + let response = SketchReader::split(&env.metric(), physical_region, request.clone()) + .await + .unwrap(); + assert_eq!(response.status, SketchSplitStatus::EmptyWindow); + let logical_region = env.default_logical_region_id(); + env.create_logical_region(physical_region, logical_region) + .await; + assert_eq!( + SketchReader::split(&env.metric(), logical_region, request) + .await + .unwrap_err() + .status_code(), + StatusCode::Unsupported + ); + } + struct ScannerDisplay<'a>(&'a dyn store_api::region_engine::RegionScanner); impl fmt::Display for ScannerDisplay<'_> { diff --git a/src/mito2/AGENTS.md b/src/mito2/AGENTS.md index c59941c3dbb..2139c4e188e 100644 --- a/src/mito2/AGENTS.md +++ b/src/mito2/AGENTS.md @@ -81,7 +81,8 @@ Task-specific cancellation preserves other pending manual work when no DDL is pending. DDL cancellation retains its existing scheduling fence and priority. Sketch reads use the optional `SketchReader` capability (`engine/sketch.rs`). -`stat` and `query` independently prepare a fresh SST snapshot via `build_sketch_read`; +`stat`, `query`, and `split` independently prepare a fresh SST snapshot via +`build_sketch_read`; split proposal and validation rounds retain that one snapshot. `sst/index/sketch_reader.rs` defines the injected `SketchReadHandler` contract. The Region-bound application handle does not retain a snapshot between calls. diff --git a/src/mito2/src/engine/sketch.rs b/src/mito2/src/engine/sketch.rs index 45d82d34039..0ecebd2160e 100644 --- a/src/mito2/src/engine/sketch.rs +++ b/src/mito2/src/engine/sketch.rs @@ -18,7 +18,10 @@ use async_trait::async_trait; use common_error::ext::BoxedError; use snafu::OptionExt; use store_api::metadata::RegionMetadataRef; -use store_api::sketch::{SketchReader, SketchRequest, SketchResponse}; +use store_api::sketch::{ + SketchReader, SketchRequest, SketchResponse, SketchSplitRequest, SketchSplitResponse, + SketchTimeRange, +}; use store_api::storage::RegionId; use crate::engine::MitoEngine; @@ -33,7 +36,8 @@ impl SketchReader for MitoEngine { region_id: RegionId, request: SketchRequest, ) -> Result { - let prepared = self.build_sketch_read(region_id, &request)?; + request.validate()?; + let prepared = self.build_sketch_read(region_id, request.time_range)?; prepared.handler.stat(&prepared.context(), &request).await } @@ -42,18 +46,28 @@ impl SketchReader for MitoEngine { region_id: RegionId, request: SketchRequest, ) -> Result { - let prepared = self.build_sketch_read(region_id, &request)?; + request.validate()?; + let prepared = self.build_sketch_read(region_id, request.time_range)?; prepared.handler.query(&prepared.context(), &request).await } + + async fn split( + &self, + region_id: RegionId, + request: SketchSplitRequest, + ) -> Result { + request.validate()?; + let prepared = self.build_sketch_read(region_id, request.time_range)?; + prepared.handler.split(&prepared.context(), &request).await + } } impl MitoEngine { fn build_sketch_read( &self, region_id: RegionId, - request: &SketchRequest, + time_range: SketchTimeRange, ) -> Result, BoxedError> { - request.validate()?; let region = self .find_region(region_id) .context(RegionNotFoundSnafu { region_id }) @@ -67,7 +81,7 @@ impl MitoEngine { }) .map_err(BoxedError::new)?; let version = region.version(); - let files = SketchReadFiles::new(version.ssts.clone(), request.time_range); + let files = SketchReadFiles::new(version.ssts.clone(), time_range); let manager = region .access_layer .build_puffin_manager() @@ -115,6 +129,34 @@ mod tests { use super::*; use crate::test_util::TestEnv; + #[tokio::test] + async fn test_invalid_split_request_precedes_region_lookup() { + let mut env = TestEnv::new().await; + let engine = env.create_engine(Default::default()).await; + let request = SketchSplitRequest { + time_range: SketchTimeRange { + start: Timestamp::new_millisecond(0), + end: Timestamp::new_millisecond(300_000), + }, + column: "value".to_string(), + parts: 2, + initial_files: 128, + min_files: 512, + max_files: 2048, + seed: 42, + max_cdf_delta: f64::NAN, + min_partition_ratio: 0.7, + max_partition_ratio: 1.3, + }; + assert_eq!( + SketchReader::split(&engine, RegionId::new(1, 1), request) + .await + .unwrap_err() + .status_code(), + StatusCode::InvalidArguments + ); + } + #[tokio::test] async fn test_invalid_request_precedes_region_lookup() { let mut env = TestEnv::new().await; diff --git a/src/mito2/src/sst/index/sketch_reader.rs b/src/mito2/src/sst/index/sketch_reader.rs index 8922522b890..a560730b45d 100644 --- a/src/mito2/src/sst/index/sketch_reader.rs +++ b/src/mito2/src/sst/index/sketch_reader.rs @@ -18,9 +18,12 @@ use std::fmt::Debug; use std::sync::Arc; use async_trait::async_trait; -use common_error::ext::BoxedError; +use common_error::ext::{BoxedError, PlainError}; +use common_error::status_code::StatusCode; use store_api::metadata::RegionMetadataRef; -use store_api::sketch::{SketchRequest, SketchResponse, SketchTimeRange}; +use store_api::sketch::{ + SketchRequest, SketchResponse, SketchSplitRequest, SketchSplitResponse, SketchTimeRange, +}; use crate::sst::file::FileHandle; use crate::sst::index::puffin_manager::SstPuffinManager; @@ -83,6 +86,18 @@ pub trait SketchReadHandler: Send + Sync + Debug { context: &SketchReadContext<'_>, request: &SketchRequest, ) -> Result; + + /// Proposes and validates split points using this call's pinned file snapshot. + async fn split( + &self, + _context: &SketchReadContext<'_>, + _request: &SketchSplitRequest, + ) -> Result { + Err(BoxedError::new(PlainError::new( + "sketch split search is unsupported".to_string(), + StatusCode::Unsupported, + ))) + } } /// Plugin registration type shared by engine bootstrap and the read entry point. diff --git a/src/operator/src/write_dispatcher.rs b/src/operator/src/write_dispatcher.rs index 8492d48789f..227dd392b3b 100644 --- a/src/operator/src/write_dispatcher.rs +++ b/src/operator/src/write_dispatcher.rs @@ -361,6 +361,7 @@ impl WriteDispatcher { extensions: response.extensions, metadata: Vec::new(), sketch: None, + sketch_split: None, })]; attempts.extend(response.failures.into_iter().map(|(_, error)| { WriteAttempt::Failed { @@ -446,6 +447,7 @@ impl WriteDispatcher { extensions: response.extensions, metadata: Vec::new(), sketch: None, + sketch_split: None, }), ), ); diff --git a/src/store-api/src/region_engine.rs b/src/store-api/src/region_engine.rs index 9b8624157ad..e669b55cfff 100644 --- a/src/store-api/src/region_engine.rs +++ b/src/store-api/src/region_engine.rs @@ -1548,6 +1548,7 @@ pub trait RegionEngine: Send + Sync { extensions, metadata: Vec::new(), sketch: None, + sketch_split: None, }) } diff --git a/src/store-api/src/region_request.rs b/src/store-api/src/region_request.rs index 744d43f2b7f..8636424a778 100644 --- a/src/store-api/src/region_request.rs +++ b/src/store-api/src/region_request.rs @@ -204,12 +204,12 @@ impl RegionRequest { reason: "ListMetadata request should be handled separately by RegionServer", } .fail(), - region_request::Body::SketchStat(_) | region_request::Body::SketchQuery(_) => { - UnexpectedSnafu { - reason: "Sketch requests must be handled separately by RegionServer", - } - .fail() + region_request::Body::SketchStat(_) + | region_request::Body::SketchQuery(_) + | region_request::Body::SketchSplit(_) => UnexpectedSnafu { + reason: "Sketch requests must be handled separately by RegionServer", } + .fail(), region_request::Body::RemoteDynFilter(_) => UnexpectedSnafu { reason: "RemoteDynFilter request should be handled separately by RegionServer", } diff --git a/src/store-api/src/sketch.rs b/src/store-api/src/sketch.rs index 60250dbbd89..c975f9dd7f5 100644 --- a/src/store-api/src/sketch.rs +++ b/src/store-api/src/sketch.rs @@ -110,6 +110,108 @@ impl SketchRequest { } } +/// Proposes and validates split points within one pinned SST snapshot. +/// File limits count unique files across the proposal and validation samples together. +#[derive(Debug, Clone, PartialEq)] +pub struct SketchSplitRequest { + pub time_range: SketchTimeRange, + pub column: String, + /// Desired number of partitions, including both outermost partitions. + pub parts: u32, + /// Total files selected for the first sampling round. + pub initial_files: u32, + /// Minimum total files before a sampled result may be accepted. + pub min_files: u32, + /// Maximum total unique files read across all sampling rounds. + pub max_files: u32, + pub seed: u64, + /// Maximum allowed CDF disagreement; this is not a statistical confidence bound. + pub max_cdf_delta: f64, + /// Minimum partition mass relative to the ideal mass of `1 / parts`. + pub min_partition_ratio: f64, + /// Maximum partition mass relative to the ideal mass of `1 / parts`. + pub max_partition_ratio: f64, +} + +impl SketchSplitRequest { + /// Validates controls before taking a snapshot or reading index files. + pub fn validate(&self) -> Result<(), BoxedError> { + let reason = if self.time_range.start >= self.time_range.end { + Some("sketch time range must have start before end") + } else if self.column.trim().is_empty() { + Some("sketch split request must select a column") + } else if !(2..=64).contains(&self.parts) { + Some("sketch split partition count must be in 2..=64") + } else if self.initial_files == 0 + || self.initial_files > self.min_files + || self.min_files > self.max_files + { + Some("sketch split file limits must satisfy 0 < initial <= min <= max") + } else if !self.max_cdf_delta.is_finite() || !(0.0..=1.0).contains(&self.max_cdf_delta) { + Some("sketch split CDF delta must be finite and in [0, 1]") + } else if !self.min_partition_ratio.is_finite() + || self.min_partition_ratio <= 0.0 + || self.min_partition_ratio > 1.0 + { + Some("sketch split minimum partition ratio must be finite and in (0, 1]") + } else if !self.max_partition_ratio.is_finite() || self.max_partition_ratio < 1.0 { + Some("sketch split maximum partition ratio must be finite and at least 1") + } else { + None + }; + match reason { + Some(reason) => Err(BoxedError::new(PlainError::new( + reason.to_string(), + StatusCode::InvalidArguments, + ))), + None => Ok(()), + } + } +} + +/// A split boundary and its strict-less-than ranks in the two samples. +#[derive(Debug, Clone, PartialEq)] +pub struct SketchSplitPoint { + pub value: Value, + pub candidate_rank: f64, + /// Absent for a census, which does not manufacture an independent validation sample. + pub validation_rank: Option, +} + +/// Outcome of a bounded split-point search; only validated or census points are actionable. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SketchSplitStatus { + /// Both samples satisfy the requested stability and partition-mass controls. + Validated, + /// Every candidate file was read and the requested partition-mass controls hold. + Census, + /// Sampling exhausted its file budget without satisfying the controls. + Unstable, + /// The available distribution cannot produce the requested partition masses. + Infeasible, + /// Missing or incompatible summaries prevent validation. + MissingCoverage, + /// No represented rows are available in the requested window. + EmptyWindow, +} + +/// Split-point result and the actual file work performed in one snapshot. +#[derive(Debug, Clone, PartialEq)] +pub struct SketchSplitResponse { + pub status: SketchSplitStatus, + pub points: Vec, + /// Number of unique files eligible before sampling. + pub candidate_files: u64, + /// Total unique files read, equal to proposal_files plus validation_files. + pub sampled_files: u64, + /// Files used to propose boundaries; includes all files for a census. + pub proposal_files: u64, + /// Disjoint files used to evaluate boundaries; zero for a census. + pub validation_files: u64, + pub rounds: u32, + pub gaps: Vec, +} + /// Coverage of one whole time bucket and one query across the selected physical files. /// Whole means contained in the requested range, not that every file has statistics. #[derive(Debug, Clone, PartialEq, Eq)] @@ -215,6 +317,18 @@ pub trait SketchReader: Send + Sync { region_id: RegionId, request: SketchRequest, ) -> Result; + + /// Proposes and validates split points without changing snapshots between rounds. + async fn split( + &self, + _region_id: RegionId, + _request: SketchSplitRequest, + ) -> Result { + Err(BoxedError::new(PlainError::new( + "sketch split search is unsupported".to_string(), + StatusCode::Unsupported, + ))) + } } #[cfg(test)] @@ -235,6 +349,122 @@ mod tests { } } + fn split_request() -> SketchSplitRequest { + SketchSplitRequest { + time_range: request().time_range, + column: "value".to_string(), + parts: 2, + initial_files: 128, + min_files: 512, + max_files: 2048, + seed: 42, + max_cdf_delta: 0.05, + min_partition_ratio: 0.7, + max_partition_ratio: 1.3, + } + } + + #[test] + fn test_validate_split_request() { + let valid = split_request(); + assert!(valid.validate().is_ok()); + for (initial_files, min_files, max_files, accepted) in [ + (1, 1, 1, true), + (100_000, 100_000, 100_000, true), + (0, 512, 2048, false), + (513, 512, 2048, false), + (128, 2049, 2048, false), + (128, 512, u32::MAX, true), + ] { + let request = SketchSplitRequest { + initial_files, + min_files, + max_files, + ..valid.clone() + }; + assert_eq!(request.validate().is_ok(), accepted, "{request:?}"); + } + for (parts, accepted) in [(1, false), (2, true), (64, true), (65, false)] { + let request = SketchSplitRequest { + parts, + ..valid.clone() + }; + assert_eq!(request.validate().is_ok(), accepted, "{request:?}"); + } + for value in [f64::NAN, f64::NEG_INFINITY, f64::INFINITY, -0.1, 1.1] { + let request = SketchSplitRequest { + max_cdf_delta: value, + ..valid.clone() + }; + assert_eq!( + request.validate().unwrap_err().status_code(), + StatusCode::InvalidArguments + ); + } + for value in [0.0, 1.0] { + assert!( + SketchSplitRequest { + max_cdf_delta: value, + ..valid.clone() + } + .validate() + .is_ok() + ); + } + for value in [f64::NAN, f64::NEG_INFINITY, f64::INFINITY, 0.0, -0.1, 1.1] { + assert!( + SketchSplitRequest { + min_partition_ratio: value, + ..valid.clone() + } + .validate() + .is_err() + ); + } + for value in [f64::NAN, f64::NEG_INFINITY, f64::INFINITY, 0.9] { + assert!( + SketchSplitRequest { + max_partition_ratio: value, + ..valid.clone() + } + .validate() + .is_err() + ); + } + assert!( + SketchSplitRequest { + min_partition_ratio: 1.0, + max_partition_ratio: 1.0, + ..valid.clone() + } + .validate() + .is_ok() + ); + for column in ["", " "] { + assert!( + SketchSplitRequest { + column: column.to_string(), + ..valid.clone() + } + .validate() + .is_err() + ); + } + for end in [valid.time_range.start, Timestamp::new_nanosecond(1_000_999)] { + assert!( + SketchSplitRequest { + time_range: SketchTimeRange { + end, + ..valid.time_range + }, + ..valid.clone() + } + .validate() + .is_err() + ); + } + } + #[test] fn test_validate_sampling_limit() { for (max_files, valid) in [(0, false), (1, true), (100_000, true), (100_001, false)] { diff --git a/src/store-api/src/sketch/proto.rs b/src/store-api/src/sketch/proto.rs index e93613d2ae2..97ad3e273ac 100644 --- a/src/store-api/src/sketch/proto.rs +++ b/src/store-api/src/sketch/proto.rs @@ -24,7 +24,8 @@ use datatypes::value::Value; use crate::sketch::{ ColumnSketchResult, SketchBucket, SketchGap, SketchGapReason, SketchQuery, SketchRequest, - SketchResponse, SketchSample, SketchSampling, SketchTimeRange, SketchValue, + SketchResponse, SketchSample, SketchSampling, SketchSplitPoint, SketchSplitRequest, + SketchSplitResponse, SketchSplitStatus, SketchTimeRange, SketchValue, }; use crate::storage::{FileId, RegionId}; @@ -263,32 +264,7 @@ impl TryFrom for pb::SketchResponse { }) }) .collect::>()?; - let gaps = result - .gaps - .into_iter() - .map(|gap| pb::SketchGap { - source_region_id: gap.source_region_id.as_u64(), - file_id: gap.file_id.as_bytes().to_vec(), - index_version: gap.index_version, - reason: match gap.reason { - SketchGapReason::NotConfigured => { - pb::SketchGapReason::NotConfigured as i32 - } - SketchGapReason::MissingIndex => { - pb::SketchGapReason::MissingIndex as i32 - } - SketchGapReason::LegacyFormat => { - pb::SketchGapReason::LegacyFormat as i32 - } - SketchGapReason::ScopeMismatch => { - pb::SketchGapReason::ScopeMismatch as i32 - } - SketchGapReason::Incompatible => { - pb::SketchGapReason::Incompatible as i32 - } - }, - }) - .collect(); + let gaps = result.gaps.into_iter().map(Into::into).collect(); Ok(pb::ColumnSketchResult { column_name: result.column_name, column_id: result.column_id, @@ -338,30 +314,7 @@ impl TryFrom for SketchResponse { let gaps = result .gaps .into_iter() - .map(|gap| { - let reason = match pb::SketchGapReason::try_from(gap.reason) - .map_err(|_| invalid("unknown gap reason"))? - { - pb::SketchGapReason::NotConfigured => SketchGapReason::NotConfigured, - pb::SketchGapReason::MissingIndex => SketchGapReason::MissingIndex, - pb::SketchGapReason::LegacyFormat => SketchGapReason::LegacyFormat, - pb::SketchGapReason::ScopeMismatch => SketchGapReason::ScopeMismatch, - pb::SketchGapReason::Incompatible => SketchGapReason::Incompatible, - pb::SketchGapReason::Unspecified => { - return Err(invalid("unspecified gap reason")); - } - }; - Ok(SketchGap { - source_region_id: RegionId::from_u64(gap.source_region_id), - file_id: FileId::from_bytes( - gap.file_id - .try_into() - .map_err(|_| invalid("file UUID must be 16 bytes"))?, - ), - index_version: gap.index_version, - reason, - }) - }) + .map(TryInto::try_into) .collect::>()?; Ok(ColumnSketchResult { column_name: result.column_name, @@ -399,6 +352,225 @@ impl TryFrom for SketchResponse { } } +impl TryFrom for SketchSplitRequest { + type Error = BoxedError; + + fn try_from(request: pb::SketchSplitRequest) -> Result { + let request = Self { + time_range: request + .time_range + .ok_or_else(|| invalid("missing sketch split time range"))? + .try_into()?, + column: request.column, + parts: request.parts, + initial_files: request.initial_files, + min_files: request.min_files, + max_files: request.max_files, + seed: request.seed, + max_cdf_delta: request.max_cdf_delta, + min_partition_ratio: request.min_partition_ratio, + max_partition_ratio: request.max_partition_ratio, + }; + request.validate()?; + Ok(request) + } +} + +impl SketchSplitRequest { + /// Converts a validated split request to the region wire representation. + pub fn into_proto(self, region_id: RegionId) -> Result { + self.validate()?; + Ok(pb::SketchSplitRequest { + region_id: region_id.as_u64(), + time_range: Some(self.time_range.try_into()?), + column: self.column, + parts: self.parts, + initial_files: self.initial_files, + min_files: self.min_files, + max_files: self.max_files, + seed: self.seed, + max_cdf_delta: self.max_cdf_delta, + min_partition_ratio: self.min_partition_ratio, + max_partition_ratio: self.max_partition_ratio, + }) + } +} + +impl From for pb::SketchGap { + fn from(gap: SketchGap) -> Self { + Self { + source_region_id: gap.source_region_id.as_u64(), + file_id: gap.file_id.as_bytes().to_vec(), + index_version: gap.index_version, + reason: match gap.reason { + SketchGapReason::NotConfigured => pb::SketchGapReason::NotConfigured, + SketchGapReason::MissingIndex => pb::SketchGapReason::MissingIndex, + SketchGapReason::LegacyFormat => pb::SketchGapReason::LegacyFormat, + SketchGapReason::ScopeMismatch => pb::SketchGapReason::ScopeMismatch, + SketchGapReason::Incompatible => pb::SketchGapReason::Incompatible, + } as i32, + } + } +} + +impl TryFrom for SketchGap { + type Error = BoxedError; + + fn try_from(gap: pb::SketchGap) -> Result { + let reason = match pb::SketchGapReason::try_from(gap.reason) + .map_err(|_| invalid("unknown gap reason"))? + { + pb::SketchGapReason::NotConfigured => SketchGapReason::NotConfigured, + pb::SketchGapReason::MissingIndex => SketchGapReason::MissingIndex, + pb::SketchGapReason::LegacyFormat => SketchGapReason::LegacyFormat, + pb::SketchGapReason::ScopeMismatch => SketchGapReason::ScopeMismatch, + pb::SketchGapReason::Incompatible => SketchGapReason::Incompatible, + pb::SketchGapReason::Unspecified => return Err(invalid("unspecified gap reason")), + }; + Ok(Self { + source_region_id: RegionId::from_u64(gap.source_region_id), + file_id: FileId::from_bytes( + gap.file_id + .try_into() + .map_err(|_| invalid("file UUID must be 16 bytes"))?, + ), + index_version: gap.index_version, + reason, + }) + } +} + +impl TryFrom for SketchSplitResponse { + type Error = BoxedError; + + fn try_from(response: pb::SketchSplitResponse) -> Result { + let status = match pb::SketchSplitStatus::try_from(response.status) + .map_err(|_| invalid("unknown sketch split status"))? + { + pb::SketchSplitStatus::Unspecified => { + return Err(invalid("unspecified sketch split status")); + } + pb::SketchSplitStatus::Validated => SketchSplitStatus::Validated, + pb::SketchSplitStatus::Census => SketchSplitStatus::Census, + pb::SketchSplitStatus::Unstable => SketchSplitStatus::Unstable, + pb::SketchSplitStatus::Infeasible => SketchSplitStatus::Infeasible, + pb::SketchSplitStatus::MissingCoverage => SketchSplitStatus::MissingCoverage, + pb::SketchSplitStatus::EmptyWindow => SketchSplitStatus::EmptyWindow, + }; + let response = Self { + status, + points: response + .points + .into_iter() + .map(|point| { + Ok(SketchSplitPoint { + value: decode_value(point.value)?, + candidate_rank: point.candidate_rank, + validation_rank: point.validation_rank, + }) + }) + .collect::>()?, + candidate_files: response.candidate_files, + sampled_files: response.sampled_files, + proposal_files: response.proposal_files, + validation_files: response.validation_files, + rounds: response.rounds, + gaps: response + .gaps + .into_iter() + .map(TryInto::try_into) + .collect::>()?, + }; + validate_split_response(&response)?; + Ok(response) + } +} + +impl TryFrom for pb::SketchSplitResponse { + type Error = BoxedError; + + fn try_from(response: SketchSplitResponse) -> Result { + validate_split_response(&response)?; + Ok(Self { + status: match response.status { + SketchSplitStatus::Validated => pb::SketchSplitStatus::Validated, + SketchSplitStatus::Census => pb::SketchSplitStatus::Census, + SketchSplitStatus::Unstable => pb::SketchSplitStatus::Unstable, + SketchSplitStatus::Infeasible => pb::SketchSplitStatus::Infeasible, + SketchSplitStatus::MissingCoverage => pb::SketchSplitStatus::MissingCoverage, + SketchSplitStatus::EmptyWindow => pb::SketchSplitStatus::EmptyWindow, + } as i32, + points: response + .points + .into_iter() + .map(|point| pb::SketchSplitPoint { + value: Some(helper::to_grpc_value(point.value)), + candidate_rank: point.candidate_rank, + validation_rank: point.validation_rank, + }) + .collect(), + candidate_files: response.candidate_files, + sampled_files: response.sampled_files, + proposal_files: response.proposal_files, + validation_files: response.validation_files, + rounds: response.rounds, + gaps: response.gaps.into_iter().map(Into::into).collect(), + }) + } +} + +fn validate_split_response(response: &SketchSplitResponse) -> Result<(), BoxedError> { + let actionable = matches!( + response.status, + SketchSplitStatus::Validated | SketchSplitStatus::Census + ); + if response + .proposal_files + .checked_add(response.validation_files) + != Some(response.sampled_files) + || response.sampled_files > response.candidate_files + || (response.sampled_files > 0 && response.rounds == 0) + || response.points.len() > 63 + || (actionable + && (response.points.is_empty() + || !response.gaps.is_empty() + || response.proposal_files == 0)) + || (!actionable && !response.points.is_empty()) + || (response.status == SketchSplitStatus::Validated && response.validation_files == 0) + || (response.status == SketchSplitStatus::Census + && (response.validation_files != 0 + || response.sampled_files != response.candidate_files)) + { + return Err(invalid("inconsistent sketch split outcome or file counts")); + } + for point in &response.points { + if point.value.is_null() + || !point.candidate_rank.is_finite() + || !(0.0..1.0).contains(&point.candidate_rank) + || point.candidate_rank == 0.0 + || point + .validation_rank + .is_some_and(|rank| !rank.is_finite() || rank <= 0.0 || rank >= 1.0) + || point.validation_rank.is_some() != (response.status == SketchSplitStatus::Validated) + { + return Err(invalid("invalid sketch split point")); + } + } + for pair in response.points.windows(2) { + // Value ordering requires matching variants; check the type first to avoid a panic. + if pair[0].value.data_type() != pair[1].value.data_type() + || pair[0].value >= pair[1].value + || pair[0].candidate_rank >= pair[1].candidate_rank + || matches!((pair[0].validation_rank, pair[1].validation_rank), (Some(a), Some(b)) if a >= b) + { + return Err(invalid( + "sketch split points must have increasing values and ranks", + )); + } + } + Ok(()) +} + fn decode_value(value: Option) -> Result { use v1::value::ValueData; let value = value.ok_or_else(|| invalid("missing query value"))?; @@ -435,6 +607,127 @@ fn invalid(reason: &str) -> BoxedError { mod tests { use super::*; + fn split_request() -> SketchSplitRequest { + SketchSplitRequest { + time_range: SketchTimeRange { + start: Timestamp::new_microsecond(1001), + end: Timestamp::new_microsecond(2001), + }, + column: "__table_id".into(), + parts: 2, + initial_files: 128, + min_files: 512, + max_files: 2048, + seed: 42, + max_cdf_delta: 0.05, + min_partition_ratio: 0.7, + max_partition_ratio: 1.3, + } + } + + fn split_response() -> SketchSplitResponse { + SketchSplitResponse { + status: SketchSplitStatus::Validated, + points: vec![SketchSplitPoint { + value: Value::UInt32(100_000), + candidate_rank: 0.48, + validation_rank: Some(0.51), + }], + candidate_files: 10_000, + sampled_files: 512, + proposal_files: 256, + validation_files: 256, + rounds: 3, + gaps: vec![], + } + } + + #[test] + fn split_wire_request_roundtrip_and_validation() { + let request = split_request(); + let wire = request.clone().into_proto(RegionId::new(42, 3)).unwrap(); + assert_eq!(wire.region_id, RegionId::new(42, 3).as_u64()); + assert_eq!(SketchSplitRequest::try_from(wire.clone()).unwrap(), request); + let mut missing = wire.clone(); + missing.time_range = None; + assert!(SketchSplitRequest::try_from(missing).is_err()); + let mut invalid_delta = wire.clone(); + invalid_delta.max_cdf_delta = f64::NAN; + assert!(SketchSplitRequest::try_from(invalid_delta).is_err()); + let mut invalid_limits = wire; + invalid_limits.max_files = 128; + assert!(SketchSplitRequest::try_from(invalid_limits).is_err()); + } + + #[test] + fn split_wire_response_rejects_inconsistent_outcomes() { + let response = split_response(); + let wire = pb::SketchSplitResponse::try_from(response.clone()).unwrap(); + assert_eq!( + SketchSplitResponse::try_from(wire.clone()).unwrap(), + response + ); + for status in [0, 100] { + let mut invalid = wire.clone(); + invalid.status = status; + assert!(SketchSplitResponse::try_from(invalid).is_err()); + } + let mut invalid = wire.clone(); + invalid.sampled_files += 1; + assert!(SketchSplitResponse::try_from(invalid).is_err()); + let mut invalid = wire.clone(); + invalid.points[0].candidate_rank = f64::NAN; + assert!(SketchSplitResponse::try_from(invalid).is_err()); + let mut invalid = wire.clone(); + invalid.points[0].validation_rank = None; + assert!(SketchSplitResponse::try_from(invalid).is_err()); + let mut invalid = wire.clone(); + invalid.status = pb::SketchSplitStatus::Unstable as i32; + assert!(SketchSplitResponse::try_from(invalid).is_err()); + let mut invalid = wire.clone(); + invalid.points[0].value = None; + assert!(SketchSplitResponse::try_from(invalid).is_err()); + let mut invalid = wire.clone(); + invalid.points.push(pb::SketchSplitPoint { + value: Some(helper::to_grpc_value(Value::Int64(200_000))), + candidate_rank: 0.7, + validation_rank: Some(0.7), + }); + assert!( + SketchSplitResponse::try_from(invalid).is_err(), + "different value variants must not panic" + ); + let mut census = response.clone(); + census.status = SketchSplitStatus::Census; + census.candidate_files = census.sampled_files; + census.proposal_files = census.sampled_files; + census.validation_files = 0; + census.points[0].validation_rank = None; + assert_eq!( + SketchSplitResponse::try_from( + pb::SketchSplitResponse::try_from(census.clone()).unwrap() + ) + .unwrap(), + census + ); + let mut missing = response; + missing.status = SketchSplitStatus::MissingCoverage; + missing.points.clear(); + missing.gaps.push(SketchGap { + source_region_id: RegionId::new(1, 1), + file_id: FileId::random(), + index_version: 2, + reason: SketchGapReason::ScopeMismatch, + }); + assert_eq!( + SketchSplitResponse::try_from( + pb::SketchSplitResponse::try_from(missing.clone()).unwrap() + ) + .unwrap(), + missing + ); + } + #[test] fn timestamp_precision_and_invalid_units() { let range = SketchTimeRange {