mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-28 05:34:02 +00:00
feat: add single-snapshot sketch split RPC
Add bounded progressive split requests and validated outcomes, with engine and metric-engine forwarding and a dedicated client RPC. Keep ordinary sketch queries unchanged and validate controls before acquiring region snapshots. Signed-off-by: WenyXu <wenymedia@gmail.com>
This commit is contained in:
Generated
+11
-11
@@ -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",
|
||||
]
|
||||
|
||||
@@ -6160,7 +6160,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",
|
||||
@@ -6772,7 +6772,7 @@ dependencies = [
|
||||
"libc",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2 0.5.10",
|
||||
"socket2 0.6.4",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
@@ -9348,7 +9348,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]]
|
||||
@@ -11624,7 +11624,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",
|
||||
@@ -11672,7 +11672,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",
|
||||
@@ -11685,7 +11685,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",
|
||||
@@ -13241,7 +13241,7 @@ dependencies = [
|
||||
"security-framework 3.7.0",
|
||||
"security-framework-sys",
|
||||
"webpki-root-certs",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -14163,7 +14163,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]]
|
||||
@@ -14734,7 +14734,7 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"psm",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -15359,7 +15359,7 @@ dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"once_cell",
|
||||
"rustix 1.0.7",
|
||||
"windows-sys 0.60.2",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
+1
-1
@@ -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"
|
||||
|
||||
@@ -37,6 +37,8 @@ pub struct RegionResponse {
|
||||
pub metadata: Vec<u8>,
|
||||
/// Structured response for persisted sketch operations.
|
||||
pub sketch: Option<greptime_proto::v1::region::SketchResponse>,
|
||||
/// Validated split points from one pinned statistics snapshot.
|
||||
pub sketch_split: Option<greptime_proto::v1::region::SketchSplitResponse>,
|
||||
}
|
||||
|
||||
/// 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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<api::v1::region::SketchSplitResponse> {
|
||||
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,
|
||||
@@ -764,6 +783,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 {
|
||||
|
||||
@@ -40,6 +40,7 @@ impl MockDatanodeHandler for () {
|
||||
extensions: Default::default(),
|
||||
metadata: Vec::new(),
|
||||
sketch: None,
|
||||
sketch_split: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -676,6 +676,7 @@ impl RegionServer {
|
||||
extensions,
|
||||
metadata: Vec::new(),
|
||||
sketch: None,
|
||||
sketch_split: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1143,6 +1144,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)
|
||||
@@ -1188,6 +1195,7 @@ impl RegionServer {
|
||||
extensions: response.extensions,
|
||||
metadata: response.metadata,
|
||||
sketch: None,
|
||||
sketch_split: None,
|
||||
failures: Vec::new(),
|
||||
})
|
||||
}
|
||||
@@ -1338,6 +1346,7 @@ fn encode_batch_write_response(result: BatchRegionResponse<error::Error>) -> Reg
|
||||
}),
|
||||
metadata: Vec::new(),
|
||||
sketch: None,
|
||||
sketch_split: None,
|
||||
affected_rows: result.affected_rows as _,
|
||||
extensions: result.extensions,
|
||||
failures: result
|
||||
@@ -1958,6 +1967,7 @@ impl RegionServerInner {
|
||||
extensions: result.extensions,
|
||||
metadata: Vec::new(),
|
||||
sketch: None,
|
||||
sketch_split: None,
|
||||
})
|
||||
}
|
||||
Err(err) => {
|
||||
@@ -2066,6 +2076,7 @@ impl RegionServerInner {
|
||||
extensions: result.extensions,
|
||||
metadata: Vec::new(),
|
||||
sketch: None,
|
||||
sketch_split: None,
|
||||
})
|
||||
}
|
||||
Err(err) => {
|
||||
|
||||
@@ -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<SketchSplitResponse, BoxedError> {
|
||||
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<api::v1::region::RegionResponse> {
|
||||
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,
|
||||
|
||||
@@ -363,6 +363,7 @@ pub mod mock {
|
||||
extensions: Default::default(),
|
||||
metadata: Vec::new(),
|
||||
sketch: None,
|
||||
sketch_split: None,
|
||||
failures: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -181,6 +181,7 @@ impl RegionEngine for MetricEngine {
|
||||
extensions: extension_return_value,
|
||||
metadata: Vec::new(),
|
||||
sketch: None,
|
||||
sketch_split: None,
|
||||
})
|
||||
}
|
||||
BatchRegionDdlRequest::Alter(requests) => {
|
||||
@@ -196,6 +197,7 @@ impl RegionEngine for MetricEngine {
|
||||
extensions: extension_return_value,
|
||||
metadata: Vec::new(),
|
||||
sketch: None,
|
||||
sketch_split: None,
|
||||
})
|
||||
}
|
||||
BatchRegionDdlRequest::Drop(requests) => {
|
||||
@@ -326,6 +328,7 @@ impl RegionEngine for MetricEngine {
|
||||
extensions: extension_return_value,
|
||||
metadata: Vec::new(),
|
||||
sketch: None,
|
||||
sketch_split: None,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -639,6 +642,7 @@ impl MetricEngine {
|
||||
extensions,
|
||||
metadata: Vec::new(),
|
||||
sketch: None,
|
||||
sketch_split: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,9 @@ use snafu::{OptionExt, ResultExt};
|
||||
use store_api::metadata::{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<SketchSplitResponse, BoxedError> {
|
||||
request.validate()?;
|
||||
self.physical_sketch_reader(region_id)?
|
||||
.split(utils::to_data_region_id(region_id), request)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
impl MetricEngine {
|
||||
@@ -394,6 +407,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<SketchResponse, BoxedError> {
|
||||
panic!("split must not issue a stat request")
|
||||
}
|
||||
|
||||
async fn query(
|
||||
&self,
|
||||
_: &SketchReadContext<'_>,
|
||||
_: &SketchRequest,
|
||||
) -> std::result::Result<SketchResponse, BoxedError> {
|
||||
panic!("split must not issue a generic query")
|
||||
}
|
||||
|
||||
async fn split(
|
||||
&self,
|
||||
context: &SketchReadContext<'_>,
|
||||
request: &SketchSplitRequest,
|
||||
) -> std::result::Result<SketchSplitResponse, BoxedError> {
|
||||
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::<SketchReadHandlerRef>(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<'_> {
|
||||
|
||||
+2
-1
@@ -73,7 +73,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.
|
||||
|
||||
|
||||
@@ -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<SketchResponse, BoxedError> {
|
||||
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<SketchResponse, BoxedError> {
|
||||
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<SketchSplitResponse, BoxedError> {
|
||||
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<PreparedSketchRead<'_>, 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;
|
||||
|
||||
@@ -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<SketchResponse, BoxedError>;
|
||||
|
||||
/// Proposes and validates split points using this call's pinned file snapshot.
|
||||
async fn split(
|
||||
&self,
|
||||
_context: &SketchReadContext<'_>,
|
||||
_request: &SketchSplitRequest,
|
||||
) -> Result<SketchSplitResponse, BoxedError> {
|
||||
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.
|
||||
|
||||
@@ -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,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1176,6 +1176,7 @@ pub trait RegionEngine: Send + Sync {
|
||||
extensions,
|
||||
metadata: Vec::new(),
|
||||
sketch: None,
|
||||
sketch_split: None,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -200,12 +200,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",
|
||||
}
|
||||
|
||||
@@ -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<f64>,
|
||||
}
|
||||
|
||||
/// 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<SketchSplitPoint>,
|
||||
/// 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<SketchGap>,
|
||||
}
|
||||
|
||||
/// 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<SketchResponse, BoxedError>;
|
||||
|
||||
/// Proposes and validates split points without changing snapshots between rounds.
|
||||
async fn split(
|
||||
&self,
|
||||
_region_id: RegionId,
|
||||
_request: SketchSplitRequest,
|
||||
) -> Result<SketchSplitResponse, BoxedError> {
|
||||
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)] {
|
||||
|
||||
@@ -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<SketchResponse> for pb::SketchResponse {
|
||||
})
|
||||
})
|
||||
.collect::<Result<_, BoxedError>>()?;
|
||||
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<pb::SketchResponse> 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::<Result<_, BoxedError>>()?;
|
||||
Ok(ColumnSketchResult {
|
||||
column_name: result.column_name,
|
||||
@@ -399,6 +352,225 @@ impl TryFrom<pb::SketchResponse> for SketchResponse {
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::SketchSplitRequest> for SketchSplitRequest {
|
||||
type Error = BoxedError;
|
||||
|
||||
fn try_from(request: pb::SketchSplitRequest) -> Result<Self, Self::Error> {
|
||||
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<pb::SketchSplitRequest, BoxedError> {
|
||||
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<SketchGap> 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<pb::SketchGap> for SketchGap {
|
||||
type Error = BoxedError;
|
||||
|
||||
fn try_from(gap: pb::SketchGap) -> Result<Self, Self::Error> {
|
||||
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<pb::SketchSplitResponse> for SketchSplitResponse {
|
||||
type Error = BoxedError;
|
||||
|
||||
fn try_from(response: pb::SketchSplitResponse) -> Result<Self, Self::Error> {
|
||||
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::<Result<_, BoxedError>>()?,
|
||||
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::<Result<_, _>>()?,
|
||||
};
|
||||
validate_split_response(&response)?;
|
||||
Ok(response)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<SketchSplitResponse> for pb::SketchSplitResponse {
|
||||
type Error = BoxedError;
|
||||
|
||||
fn try_from(response: SketchSplitResponse) -> Result<Self, Self::Error> {
|
||||
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<v1::Value>) -> Result<Value, BoxedError> {
|
||||
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 {
|
||||
|
||||
Reference in New Issue
Block a user