fix: backport expression depth guards and write retries to v1.1.1

Backport GreptimeDB #9564, the retry-hint prerequisite #8301, write retries from #9569, and routing follow-up #9584 onto 88fa784810. Adapt the fixes to the v1.1.1 APIs while retaining the existing protobuf revision and heartbeat format.

Validated with the enterprise all-targets/all-features workspace check, 69 focused tests, the PostgreSQL expression-depth regression, and two focused sqlness cases. Rust and TOML formatting checks pass.

Signed-off-by: evenyag <realevenyag@gmail.com>
This commit is contained in:
evenyag
2026-10-20 19:07:48 +08:00
parent 88fa784810
commit 3b96d50767
95 changed files with 7283 additions and 1141 deletions
Generated
+8
View File
@@ -2040,6 +2040,7 @@ dependencies = [
"tokio",
"tokio-stream",
"tonic 0.14.2",
"tonic-prost",
"tracing",
]
@@ -5526,6 +5527,7 @@ dependencies = [
"store-api",
"strfmt",
"table",
"temp-env",
"tokio",
"tokio-util",
"toml 0.8.23",
@@ -9785,7 +9787,9 @@ dependencies = [
"arrow-ipc 58.3.0",
"async-stream",
"async-trait",
"backon",
"bytes",
"cache",
"catalog",
"chrono",
"client",
@@ -9815,12 +9819,14 @@ dependencies = [
"futures",
"futures-util",
"humantime",
"humantime-serde",
"itertools 0.14.0",
"jsonb",
"lazy_static",
"meta-client",
"meter-core",
"meter-macros",
"mito-codec",
"moka",
"object-store",
"partition",
@@ -9830,6 +9836,7 @@ dependencies = [
"prost-types 0.14.1",
"query",
"regex",
"serde",
"serde_json",
"session",
"snafu 0.8.6",
@@ -9839,6 +9846,7 @@ dependencies = [
"substrait 1.1.1",
"table",
"tokio",
"tokio-stream",
"tokio-util",
"tonic 0.14.2",
"tracing",
+1
View File
@@ -254,6 +254,7 @@ toml = "0.8.8"
# Pin below 0.14.5 to avoid the `connection_timeout_future` "async fn resumed after
# completion" panic (greptimedb#8265 / grpc-rust#2522). Remove once tonic ships a fix.
tonic = { version = "0.14, <0.14.5", features = ["tls-aws-lc", "gzip", "zstd"] }
tonic-prost = "0.14"
tower = "0.5"
tower-http = "0.6"
tracing = "0.1"
+5
View File
@@ -316,6 +316,11 @@
| `query.parallelism` | Integer | `0` | Parallelism of the query engine.<br/>Default to 0, which means the number of CPU cores. |
| `query.allow_query_fallback` | Bool | `false` | Whether to allow query fallback when push down optimize fails.<br/>Default to false, meaning when push down optimize failed, return error msg |
| `query.memory_pool_size` | String | `50%` | Memory pool size for query execution operators (aggregation, sorting, join).<br/>Supports absolute size (e.g., "4GB", "8GB") or percentage of system memory (e.g., "30%").<br/>Setting it to 0 disables the limit (unbounded, default behavior).<br/>When this limit is reached, queries will fail with ResourceExhausted error.<br/>NOTE: This does NOT limit memory used by table scans (only applies to datanodes). |
| `write_retry` | -- | -- | Retry retryable distributed write failures.<br/>Backoff grows exponentially, with jitter to spread concurrent retries. |
| `write_retry.max_retries` | Integer | `3` | Maximum retries after the initial write attempt. Set to 0 to disable retries. |
| `write_retry.initial_backoff` | String | `1500ms` | Initial backoff before jitter is applied. Must be positive. |
| `write_retry.max_backoff` | String | `10s` | Maximum backoff before jitter is applied. Must be at least initial_backoff. |
| `write_retry.backoff_multiplier` | Float | `2.0` | Backoff multiplier. Must be finite and at least 1. |
| `datanode` | -- | -- | Datanode options. |
| `datanode.client` | -- | -- | Datanode client options. |
| `datanode.client.connect_timeout` | String | `10s` | -- |
+12
View File
@@ -275,6 +275,18 @@ allow_query_fallback = false
## NOTE: This does NOT limit memory used by table scans (only applies to datanodes).
memory_pool_size = "50%"
## Retry retryable distributed write failures.
## Backoff grows exponentially, with jitter to spread concurrent retries.
[write_retry]
## Maximum retries after the initial write attempt. Set to 0 to disable retries.
max_retries = 3
## Initial backoff before jitter is applied. Must be positive.
initial_backoff = "1500ms"
## Maximum backoff before jitter is applied. Must be at least initial_backoff.
max_backoff = "10s"
## Backoff multiplier. Must be finite and at least 1.
backoff_multiplier = 2.0
## Datanode options.
[datanode]
## Datanode client options.
+9 -1
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint, retry_hint_from_io_error};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use snafu::{Location, Snafu};
@@ -111,6 +111,14 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::Io { error, .. } => retry_hint_from_io_error(error),
Error::AuthBackend { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
+12 -1
View File
@@ -14,9 +14,10 @@
use std::any::Any;
use common_error::ext::ErrorExt;
use common_error::ext::{ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use object_store::error::retry_hint_from_opendal_error;
use snafu::{Location, Snafu};
#[derive(Snafu)]
@@ -243,4 +244,14 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::StorageOperation { error, .. } | Error::BuildObjectStore { error, .. } => {
retry_hint_from_opendal_error(error)
}
Error::Database { error, .. } => error.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
+20 -1
View File
@@ -14,7 +14,7 @@
use std::any::Any;
use common_error::ext::ErrorExt;
use common_error::ext::{ErrorExt, RetryHint, retry_hint_from_io_error};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use snafu::{Location, Snafu};
@@ -216,6 +216,25 @@ impl ErrorExt for Error {
}
}
fn retry_hint(&self) -> RetryHint {
match self {
#[cfg(test)]
Error::TestTaskFailed { retryable, .. } => {
if *retryable {
RetryHint::Retryable
} else {
RetryHint::NonRetryable
}
}
Error::Database { error, .. } => error.retry_hint(),
Error::SnapshotStorage { error, .. } | Error::ChunkImportFailed { error, .. } => {
error.retry_hint()
}
Error::ImportStateIo { error, .. } => retry_hint_from_io_error(error),
_ => RetryHint::NonRetryable,
}
}
fn as_any(&self) -> &dyn Any {
self
}
+1
View File
@@ -44,6 +44,7 @@ substrait.workspace = true
tokio.workspace = true
tokio-stream = { workspace = true, features = ["net"] }
tonic.workspace = true
tonic-prost.workspace = true
[dev-dependencies]
common-grpc-expr.workspace = true
+3 -3
View File
@@ -18,7 +18,6 @@ use api::v1::HealthCheckRequest;
use api::v1::flow::flow_client::FlowClient as PbFlowClient;
use api::v1::health_check_client::HealthCheckClient;
use api::v1::prometheus_gateway_client::PrometheusGatewayClient;
use api::v1::region::region_client::RegionClient as PbRegionClient;
use arrow_flight::flight_service_client::FlightServiceClient;
use common_grpc::channel_manager::{
ChannelConfig, ChannelManager, ClientTlsOption, load_client_tls_config,
@@ -186,9 +185,10 @@ impl Client {
Ok(FlightClient { addr, client })
}
pub(crate) fn raw_region_client(&self) -> Result<(String, PbRegionClient<Channel>)> {
/// Creates the region gRPC transport with the configured message limits.
pub(crate) fn raw_region_client(&self) -> Result<(String, tonic::client::Grpc<Channel>)> {
let (addr, channel) = self.find_channel()?;
let client = PbRegionClient::new(channel)
let client = tonic::client::Grpc::new(channel)
.max_decoding_message_size(self.max_grpc_recv_message_size())
.max_encoding_message_size(self.max_grpc_send_message_size());
Ok((addr, client))
+51
View File
@@ -868,13 +868,17 @@ mod tests {
use api::v1::auth_header::AuthScheme;
use api::v1::{AuthHeader, Basic};
use common_error::ext::{ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_error::{GREPTIME_DB_HEADER_ERROR_CODE, GREPTIME_DB_HEADER_ERROR_RETRY_HINT};
use common_query::OutputData;
use common_recordbatch::{OrderOption, RecordBatch, RecordBatchStream};
use datatypes::prelude::{ConcreteDataType, VectorRef};
use datatypes::schema::{ColumnSchema, Schema};
use datatypes::vectors::Int32Vector;
use futures_util::StreamExt;
use tonic::codegen::http::{HeaderMap, HeaderValue};
use tonic::metadata::MetadataMap;
use tonic::{Code, Status};
use super::*;
@@ -1008,6 +1012,7 @@ mod tests {
code: StatusCode::Internal,
msg: "blabla".to_string(),
tonic_code: Code::Internal,
retry_hint: RetryHint::NonRetryable,
}
.build();
@@ -1015,6 +1020,52 @@ mod tests {
let actual: Error = status.into();
assert_eq!(expected.to_string(), actual.to_string());
assert_eq!(expected.retry_hint(), actual.retry_hint());
assert_eq!(expected.should_retry(), actual.should_retry());
}
#[test]
fn test_from_tonic_status_with_retry_hint() {
let mut headers = HeaderMap::new();
headers.insert(
GREPTIME_DB_HEADER_ERROR_CODE,
HeaderValue::from(StatusCode::Internal as u32),
);
headers.insert(
GREPTIME_DB_HEADER_ERROR_RETRY_HINT,
HeaderValue::from_static(RetryHint::Retryable.as_str()),
);
let status =
Status::with_metadata(Code::Internal, "blabla", MetadataMap::from_headers(headers));
let actual: Error = status.into();
assert_eq!(actual.retry_hint(), RetryHint::Retryable);
assert!(actual.should_retry());
}
#[test]
fn test_from_tonic_status_fallback() {
let mut headers = HeaderMap::new();
headers.insert(
GREPTIME_DB_HEADER_ERROR_CODE,
HeaderValue::from(StatusCode::InvalidArguments as u32),
);
let status =
Status::with_metadata(Code::Internal, "blabla", MetadataMap::from_headers(headers));
let actual: Error = status.into();
assert_eq!(actual.retry_hint(), RetryHint::NonRetryable);
assert!(!actual.should_retry());
}
#[test]
fn test_should_retry_preserves_transport_retry() {
let status = Status::new(Code::Unavailable, "blabla");
let actual: Error = status.into();
assert!(actual.should_retry());
}
#[tokio::test]
+42 -3
View File
@@ -15,10 +15,10 @@
use std::any::Any;
use common_error::define_from_tonic_status;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use snafu::{Location, Snafu};
use snafu::{Location, Snafu, location};
use tonic::Code;
use tonic::metadata::errors::InvalidMetadataValue;
@@ -130,6 +130,7 @@ pub enum Error {
code: StatusCode,
msg: String,
tonic_code: Code,
retry_hint: RetryHint,
#[snafu(implicit)]
location: Location,
},
@@ -168,10 +169,47 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::Tonic { retry_hint, .. } => *retry_hint,
Error::FlightGet { source, .. }
| Error::FlowServer { source, .. }
| Error::External { source, .. } => source.retry_hint(),
Error::RegionServer { code, source, .. } => {
let hint = source.retry_hint();
// Preserve the transport retry policy previously applied by should_retry().
if !hint.is_retryable()
&& matches!(
code,
Code::Unavailable | Code::Cancelled | Code::DeadlineExceeded
)
{
RetryHint::Retryable
} else {
hint
}
}
Error::ConvertFlightData { source, .. }
| Error::CreateChannel { source, .. }
| Error::CreateTlsChannel { source, .. } => source.retry_hint(),
Error::ConvertSchema { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
define_from_tonic_status!(Error, Tonic);
impl From<Error> for common_meta::error::Error {
fn from(error: Error) -> Self {
Self::External {
source: BoxedError::new(error),
location: location!(),
}
}
}
impl Error {
/// Returns the gRPC status code if this error is caused by a gRPC request failure.
pub fn tonic_code(&self) -> Option<Code> {
@@ -194,7 +232,8 @@ impl Error {
}
pub fn should_retry(&self) -> bool {
self.is_connection_error()
self.retry_hint().is_retryable()
|| self.is_connection_error()
|| matches!(
self.tonic_code(),
Some(Code::Cancelled) | Some(Code::DeadlineExceeded)
+663 -56
View File
@@ -12,6 +12,9 @@
// See the License for the specific language governing permissions and
// limitations under the License.
mod codec;
use std::borrow::Borrow;
use std::sync::Arc;
use api::region::RegionResponse;
@@ -45,8 +48,10 @@ use crate::error::{
self, ConvertFlightDataSnafu, FlightGetSnafu, IllegalDatabaseResponseSnafu,
IllegalFlightMessagesSnafu, MissingFieldSnafu, Result, ServerSnafu,
};
use crate::region::codec::RegionCodec;
use crate::{Client, Error, metrics};
/// Sends region operations through a configured gRPC client.
#[derive(Debug)]
pub struct RegionRequester {
client: Client,
@@ -56,20 +61,8 @@ pub struct RegionRequester {
#[async_trait]
impl Datanode for RegionRequester {
async fn handle(&self, request: RegionRequest) -> MetaResult<RegionResponse> {
self.handle_inner(request).await.map_err(|err| {
if err.should_retry() {
meta_error::Error::RetryLater {
source: BoxedError::new(err),
clean_poisons: false,
}
} else {
meta_error::Error::External {
source: BoxedError::new(err),
location: location!(),
}
}
})
async fn handle_request(&self, request: Arc<RegionRequest>) -> MetaResult<RegionResponse> {
self.handle_inner(request).await.map_err(Into::into)
}
async fn handle_query(&self, request: QueryRequest) -> MetaResult<SendableRecordBatchStream> {
@@ -251,43 +244,15 @@ impl RegionRequester {
Ok(Box::pin(record_batch_stream))
}
async fn handle_inner(&self, request: RegionRequest) -> Result<RegionResponse> {
let request_type = request
.body
.as_ref()
.with_context(|| MissingFieldSnafu { field: "body" })?
.as_ref()
.to_string();
let _timer = metrics::METRIC_REGION_REQUEST_GRPC
.with_label_values(&[request_type.as_str()])
.start_timer();
let (addr, mut client) = self.client.raw_region_client()?;
let response = client
.handle(request)
.await
.map_err(|e| {
let code = e.code();
// Uses `Error::RegionServer` instead of `Error::Server`
error::Error::RegionServer {
addr,
code,
source: BoxedError::new(error::Error::from(e)),
location: location!(),
}
})?
.into_inner();
check_response_header(&response.header)?;
Ok(RegionResponse::from_region_response(response))
}
pub async fn handle(&self, request: RegionRequest) -> Result<RegionResponse> {
/// Sends an owned or shared request without deep-cloning its protobuf payload.
pub async fn handle<R>(&self, request: R) -> Result<RegionResponse>
where
R: Borrow<RegionRequest> + Send + Sync + 'static,
{
self.handle_inner(request).await
}
/// Sends a remote dynamic filter update to the region service.
pub async fn handle_remote_dyn_filter_update(
&self,
query_id: impl Into<String>,
@@ -297,6 +262,7 @@ impl RegionRequester {
.await
}
/// Unregisters a remote dynamic filter in the region service.
pub async fn handle_remote_dyn_filter_unregister(
&self,
query_id: impl Into<String>,
@@ -307,6 +273,72 @@ impl RegionRequester {
))
.await
}
async fn handle_inner<R>(&self, request: R) -> Result<RegionResponse>
where
R: Borrow<RegionRequest> + Send + Sync + 'static,
{
let request_body = request
.borrow()
.body
.as_ref()
.context(MissingFieldSnafu { field: "body" })?;
let is_insert = matches!(
request_body,
region_request::Body::Inserts(_) | region_request::Body::BulkInsert(_)
);
let request_type = request_body.as_ref().to_string();
let _timer = metrics::METRIC_REGION_REQUEST_GRPC
.with_label_values(&[request_type.as_str()])
.start_timer();
let (addr, mut client) = self.client.raw_region_client()?;
if is_insert {
if self.send_compression {
client = client.send_compressed(tonic::codec::CompressionEncoding::Zstd);
}
if self.accept_compression {
client = client.accept_compressed(tonic::codec::CompressionEncoding::Zstd);
}
}
let response = async {
client
.ready()
.await
.map_err(|e| tonic::Status::unknown(format!("Service was not ready: {e}")))?;
let mut request = tonic::Request::new(request);
request.extensions_mut().insert(tonic::GrpcMethod::new(
"greptime.v1.region.Region",
"Handle",
));
client
.unary(
request,
tonic::codegen::http::uri::PathAndQuery::from_static(
"/greptime.v1.region.Region/Handle",
),
RegionCodec::default(),
)
.await
}
.await
.map_err(|status| map_region_error(status, addr))?
.into_inner();
check_response_header(&response.header)?;
Ok(RegionResponse::from_region_response(response))
}
}
fn map_region_error(status: tonic::Status, addr: String) -> error::Error {
error::Error::RegionServer {
addr,
code: status.code(),
source: BoxedError::new(error::Error::from(status)),
location: location!(),
}
}
pub fn build_remote_dyn_filter_update_request(
@@ -371,27 +403,602 @@ pub fn check_response_header(header: &Option<ResponseHeader>) -> Result<()> {
}
#[cfg(test)]
mod test {
use api::v1::Status as PbStatus;
#[allow(deprecated)]
mod tests {
use std::collections::VecDeque;
use std::sync::Mutex;
use api::v1::region::region_server::{Region, RegionServer};
use api::v1::region::{
RemoteDynFilterUnregister, RemoteDynFilterUpdate, region_request, remote_dyn_filter_request,
BulkInsertRequest, InsertRequest, InsertRequests, RegionResponse as PbRegionResponse,
RemoteDynFilterUnregister, RemoteDynFilterUpdate, region_request,
remote_dyn_filter_request,
};
use api::v1::value::ValueData;
use api::v1::{
ColumnDataType, ColumnSchema as PbColumnSchema, Row, Rows, Status as PbStatus, Value,
};
use common_error::ext::{ErrorExt, RetryHint};
use common_grpc::channel_manager::{ChannelConfig, ChannelManager};
use tokio::net::TcpListener;
use tokio::task::JoinHandle;
use tokio_stream::wrappers::TcpListenerStream;
use tonic::codec::CompressionEncoding;
use tonic::{Request, Response, Status};
use super::*;
use crate::Error::{IllegalDatabaseResponse, Server};
use crate::Error;
#[derive(Clone, Default)]
struct RecordingRegionService {
requests: Arc<Mutex<Vec<(RegionRequest, bool, bool)>>>,
responses: Arc<Mutex<VecDeque<std::result::Result<PbRegionResponse, Status>>>>,
}
#[tonic::async_trait]
impl Region for RecordingRegionService {
async fn handle(
&self,
request: Request<RegionRequest>,
) -> std::result::Result<Response<PbRegionResponse>, Status> {
let metadata = request.metadata();
let sends_zstd = metadata.get("grpc-encoding").is_some_and(|v| v == "zstd");
let accepts_zstd = metadata
.get("grpc-accept-encoding")
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.split(',').any(|encoding| encoding == "zstd"));
self.requests
.lock()
.unwrap()
.push((request.into_inner(), sends_zstd, accepts_zstd));
self.responses
.lock()
.unwrap()
.pop_front()
.unwrap_or_else(|| Ok(build_response(StatusCode::Success)))
.map(Response::new)
}
}
struct RegionTestServer {
addr: String,
service: RecordingRegionService,
task: JoinHandle<()>,
}
impl RegionTestServer {
async fn start() -> Self {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap().to_string();
let service = RecordingRegionService::default();
let server_service = service.clone();
let task = tokio::spawn(async move {
tonic::transport::Server::builder()
.add_service(
RegionServer::new(server_service)
.accept_compressed(CompressionEncoding::Zstd)
.send_compressed(CompressionEncoding::Zstd),
)
.serve_with_incoming(TcpListenerStream::new(listener))
.await
.unwrap();
});
Self {
addr,
service,
task,
}
}
fn create_requester(
&self,
config: ChannelConfig,
send: bool,
accept: bool,
) -> RegionRequester {
RegionRequester::new(
Client::with_manager_and_urls(
ChannelManager::with_config(config, None),
[self.addr.clone()],
),
send,
accept,
)
}
}
impl Drop for RegionTestServer {
fn drop(&mut self) {
self.task.abort();
}
}
fn build_response(code: StatusCode) -> PbRegionResponse {
PbRegionResponse {
header: Some(ResponseHeader {
status: Some(PbStatus {
status_code: code as u32,
..Default::default()
}),
}),
affected_rows: 1,
..Default::default()
}
}
fn build_insert_request() -> RegionRequest {
RegionRequest {
header: Some(RegionRequestHeader {
dbname: "shared-request-test".to_string(),
..Default::default()
}),
body: Some(region_request::Body::Inserts(InsertRequests {
requests: vec![InsertRequest {
region_id: 42,
rows: Some(Rows {
schema: vec![
PbColumnSchema {
column_name: "message".to_string(),
datatype: ColumnDataType::String as i32,
..Default::default()
},
PbColumnSchema {
column_name: "payload".to_string(),
datatype: ColumnDataType::Binary as i32,
..Default::default()
},
],
rows: vec![Row {
values: vec![
Value {
value_data: Some(ValueData::StringValue(
"hello 世界".to_string(),
)),
},
Value {
value_data: Some(ValueData::BinaryValue(vec![0, 1, 127, 255])),
},
],
}],
}),
..Default::default()
}],
})),
}
}
#[tokio::test]
async fn test_owned_and_shared_requests_preserve_payload_and_compression() {
let server = RegionTestServer::start().await;
let shared = Arc::new(build_insert_request());
for (send, accept) in [(false, false), (true, false), (false, true), (true, true)] {
let requester = server.create_requester(ChannelConfig::default(), send, accept);
let channel =
tonic::transport::Endpoint::from_shared(format!("http://{}", server.addr))
.unwrap()
.connect()
.await
.unwrap();
let mut baseline = api::v1::region::region_client::RegionClient::new(channel);
if send {
baseline = baseline.send_compressed(CompressionEncoding::Zstd);
}
if accept {
baseline = baseline.accept_compressed(CompressionEncoding::Zstd);
}
assert_eq!(
baseline
.handle(build_insert_request())
.await
.unwrap()
.into_inner()
.affected_rows,
1
);
assert_eq!(
requester
.handle(build_insert_request())
.await
.unwrap()
.affected_rows,
1
);
assert_eq!(
requester
.handle(Arc::clone(&shared))
.await
.unwrap()
.affected_rows,
1
);
}
let requests = server.service.requests.lock().unwrap();
assert_eq!(requests.len(), 12);
for ((request, sends, accepts), (send, accept)) in requests.iter().zip(
[(false, false), (true, false), (false, true), (true, true)]
.into_iter()
.flat_map(|settings| [settings, settings, settings]),
) {
assert_eq!(request, shared.as_ref());
assert_eq!((*sends, *accepts), (send, accept));
}
}
#[tokio::test]
async fn test_shared_request_can_be_resent_after_transport_error() {
let server = RegionTestServer::start().await;
let mut status = Status::unavailable("migrating");
status.metadata_mut().insert(
common_error::GREPTIME_DB_HEADER_ERROR_RETRY_HINT,
RetryHint::Retryable.as_str().parse().unwrap(),
);
server
.service
.responses
.lock()
.unwrap()
.push_back(Err(status));
let requester = server.create_requester(ChannelConfig::default(), false, false);
let shared = Arc::new(build_insert_request());
let error = requester.handle(Arc::clone(&shared)).await.unwrap_err();
assert_eq!(error.retry_hint(), RetryHint::Retryable);
assert!(
matches!(error, Error::RegionServer { addr, code: tonic::Code::Unavailable, .. } if addr == server.addr)
);
requester.handle(Arc::clone(&shared)).await.unwrap();
let requests = server.service.requests.lock().unwrap();
assert_eq!(requests.len(), 2);
assert_eq!(&requests[0].0, shared.as_ref());
assert_eq!(&requests[1].0, shared.as_ref());
}
#[test]
fn test_retry_hint_wire_compatibility() {
for (name, wire_hint, expected_hint) in [
("legacy_missing", None, RetryHint::NonRetryable),
("legacy_retryable", Some("retryable"), RetryHint::Retryable),
(
"legacy_non_retryable",
Some("non_retryable"),
RetryHint::NonRetryable,
),
(
"route_refresh",
Some("retry_after_route_refresh"),
RetryHint::RetryAfterRouteRefresh,
),
(
"unknown_future_hint",
Some("future_retry_hint"),
RetryHint::NonRetryable,
),
] {
let mut status = Status::failed_precondition("region unavailable");
status.metadata_mut().insert(
common_error::GREPTIME_DB_HEADER_ERROR_CODE,
(StatusCode::RegionNotReady as u32)
.to_string()
.parse()
.unwrap(),
);
if let Some(hint) = wire_hint {
status.metadata_mut().insert(
common_error::GREPTIME_DB_HEADER_ERROR_RETRY_HINT,
hint.parse().unwrap(),
);
}
let error: Error = status.into();
assert_eq!(error.retry_hint(), expected_hint, "{name}");
assert_eq!(error.status_code(), StatusCode::RegionNotReady, "{name}");
assert_eq!(
error.tonic_code(),
Some(tonic::Code::FailedPrecondition),
"{name}"
);
}
}
#[tokio::test]
async fn test_transport_error_parity_and_datanode_mapping() {
let server = RegionTestServer::start().await;
let requester = server.create_requester(ChannelConfig::default(), false, false);
for hint in [
RetryHint::Retryable,
RetryHint::RetryAfterRouteRefresh,
RetryHint::NonRetryable,
] {
let mut status = Status::failed_precondition("region unavailable");
status.metadata_mut().insert(
common_error::GREPTIME_DB_HEADER_ERROR_RETRY_HINT,
hint.as_str().parse().unwrap(),
);
status.metadata_mut().insert(
common_error::GREPTIME_DB_HEADER_ERROR_CODE,
(StatusCode::RegionNotFound as u32)
.to_string()
.parse()
.unwrap(),
);
server
.service
.responses
.lock()
.unwrap()
.extend((0..4).map(|_| Err(status.clone())));
let mut baseline = api::v1::region::region_client::RegionClient::connect(format!(
"http://{}",
server.addr
))
.await
.unwrap();
let baseline: Error = baseline
.handle(build_insert_request())
.await
.unwrap_err()
.into();
assert_eq!(baseline.status_code(), StatusCode::RegionNotFound);
assert_eq!(baseline.retry_hint(), hint);
assert_eq!(baseline.tonic_code(), Some(tonic::Code::FailedPrecondition));
let owned = requester.handle(build_insert_request()).await.unwrap_err();
let shared = requester
.handle(Arc::new(build_insert_request()))
.await
.unwrap_err();
for error in [owned, shared] {
assert_eq!(error.status_code(), baseline.status_code());
assert_eq!(error.retry_hint(), baseline.retry_hint());
assert_eq!(error.tonic_code(), baseline.tonic_code());
}
let datanode: &dyn Datanode = &requester;
let error = datanode.handle(build_insert_request()).await.unwrap_err();
assert_eq!(error.status_code(), StatusCode::RegionNotFound);
assert_eq!(error.retry_hint(), hint);
assert!(matches!(error, meta_error::Error::External { .. }));
}
}
#[tokio::test]
async fn test_datanode_transport_retry_hints() {
let server = RegionTestServer::start().await;
let requester = server.create_requester(ChannelConfig::default(), false, false);
let datanode: &dyn Datanode = &requester;
let statuses = [
tonic::Code::Unavailable,
tonic::Code::Cancelled,
tonic::Code::DeadlineExceeded,
tonic::Code::FailedPrecondition,
]
.into_iter()
.flat_map(|code| {
[
None,
Some(RetryHint::NonRetryable),
Some(RetryHint::Retryable),
Some(RetryHint::RetryAfterRouteRefresh),
]
.into_iter()
.map(move |hint| (code, hint))
});
for (code, hint) in statuses {
for body in [
region_request::Body::Inserts(Default::default()),
region_request::Body::Deletes(Default::default()),
region_request::Body::BulkInsert(Default::default()),
region_request::Body::Create(Default::default()),
region_request::Body::RemoteDynFilter(Default::default()),
] {
let request_type = body.as_ref().to_string();
let mut status = Status::new(code, "request failed");
// Metadata status is deliberately different from the transport status.
status.metadata_mut().insert(
common_error::GREPTIME_DB_HEADER_ERROR_CODE,
(StatusCode::RegionNotReady as u32)
.to_string()
.parse()
.unwrap(),
);
if let Some(hint) = hint {
status.metadata_mut().insert(
common_error::GREPTIME_DB_HEADER_ERROR_RETRY_HINT,
hint.as_str().parse().unwrap(),
);
}
let original = Error::from(status.clone());
let expected = if original.should_retry() && !original.retry_hint().is_retryable() {
RetryHint::Retryable
} else {
original.retry_hint()
};
server
.service
.responses
.lock()
.unwrap()
.extend([Err(status.clone()), Err(status)]);
let request = RegionRequest {
header: None,
body: Some(body),
};
let shared = Arc::new(request);
let shared_error = datanode.handle(Arc::clone(&shared)).await.unwrap_err();
assert_eq!(Arc::strong_count(&shared), 1);
let request = Arc::try_unwrap(shared).unwrap();
let owned_error = datanode.handle(request).await.unwrap_err();
for error in [owned_error, shared_error] {
assert_eq!(
error.retry_hint(),
expected,
"{code:?}, {hint:?}, {request_type}"
);
assert_eq!(error.retry_hint().is_retryable(), original.should_retry());
assert_eq!(error.status_code(), StatusCode::RegionNotReady);
let meta_error::Error::External { source, .. } = error else {
panic!("expected an external error");
};
assert_eq!(source.retry_hint(), expected);
let Error::RegionServer {
source,
code: actual_code,
..
} = source.as_any().downcast_ref::<Error>().unwrap()
else {
panic!("expected a region server error");
};
assert_eq!(*actual_code, code);
assert_eq!(source.retry_hint(), original.retry_hint());
assert_eq!(source.to_string(), original.to_string());
}
}
}
}
#[tokio::test]
async fn test_shared_request_preserves_response_header_errors() {
let server = RegionTestServer::start().await;
server.service.responses.lock().unwrap().extend([
Ok(PbRegionResponse::default()),
Ok(build_response(StatusCode::RegionNotFound)),
]);
let requester = server.create_requester(ChannelConfig::default(), false, false);
let shared = Arc::new(build_insert_request());
assert!(matches!(
requester.handle(Arc::clone(&shared)).await.unwrap_err(),
Error::IllegalDatabaseResponse { .. }
));
assert!(matches!(
requester.handle(shared).await.unwrap_err(),
Error::Server {
code: StatusCode::RegionNotFound,
..
}
));
}
#[tokio::test]
async fn test_shared_request_respects_configured_message_limits() {
let server = RegionTestServer::start().await;
let shared = Arc::new(build_insert_request());
for send_limit in [true, false] {
let mut config = ChannelConfig::default();
if send_limit {
config.max_send_message_size = "1B".parse().unwrap();
} else {
config.max_recv_message_size = "1B".parse().unwrap();
}
let mut baseline = api::v1::region::region_client::RegionClient::connect(format!(
"http://{}",
server.addr
))
.await
.unwrap()
.max_encoding_message_size(config.max_send_message_size.as_bytes() as usize)
.max_decoding_message_size(config.max_recv_message_size.as_bytes() as usize);
let baseline: Error = baseline
.handle(build_insert_request())
.await
.unwrap_err()
.into();
if !send_limit {
assert_eq!(
baseline.tonic_code(),
Some(tonic::Code::OutOfRange),
"{baseline:?}"
);
}
let requester = server.create_requester(config, false, false);
let error = requester.handle(Arc::clone(&shared)).await.unwrap_err();
assert_eq!(
error.tonic_code(),
baseline.tonic_code(),
"shared: {error:?}; generated: {baseline:?}"
);
assert_eq!(
error.status_code(),
baseline.status_code(),
"shared: {error:?}; generated: {baseline:?}"
);
let Error::RegionServer { source, .. } = &error else {
panic!("expected a region server error: {error:?}");
};
assert_eq!(
source.retry_hint(),
baseline.retry_hint(),
"shared: {error:?}; generated: {baseline:?}"
);
assert_eq!(
server.service.requests.lock().unwrap().len(),
if send_limit { 0 } else { 2 }
);
}
let requester = server.create_requester(ChannelConfig::default(), false, false);
requester.handle(shared).await.unwrap();
}
#[tokio::test]
async fn test_inserts_and_bulk_insert_use_transport_compression() {
let server = RegionTestServer::start().await;
let requester = server.create_requester(ChannelConfig::default(), true, true);
let send_only_requester = server.create_requester(ChannelConfig::default(), true, false);
let accept_only_requester = server.create_requester(ChannelConfig::default(), false, true);
let disabled_requester = server.create_requester(ChannelConfig::default(), false, false);
let inserts = || RegionRequest {
body: Some(region_request::Body::Inserts(Default::default())),
..Default::default()
};
let bulk_insert = || RegionRequest {
body: Some(region_request::Body::BulkInsert(
BulkInsertRequest::default(),
)),
..Default::default()
};
requester.handle(inserts()).await.unwrap();
send_only_requester.handle(inserts()).await.unwrap();
accept_only_requester.handle(inserts()).await.unwrap();
requester.handle(bulk_insert()).await.unwrap();
disabled_requester.handle(bulk_insert()).await.unwrap();
requester
.handle(build_remote_dyn_filter_unregister_request(
"query-1",
RemoteDynFilterUnregister {
filter_id: "filter-1".to_string(),
},
))
.await
.unwrap();
assert_eq!(
vec![
(true, true),
(true, false),
(false, true),
(true, true),
(false, false),
(false, false)
],
server
.service
.requests
.lock()
.unwrap()
.iter()
.map(|(_, send, accept)| (*send, *accept))
.collect::<Vec<_>>()
);
}
#[test]
fn test_check_response_header() {
let result = check_response_header(&None);
assert!(matches!(
result.unwrap_err(),
IllegalDatabaseResponse { .. }
Error::IllegalDatabaseResponse { .. }
));
let result = check_response_header(&Some(ResponseHeader { status: None }));
assert!(matches!(
result.unwrap_err(),
IllegalDatabaseResponse { .. }
Error::IllegalDatabaseResponse { .. }
));
let result = check_response_header(&Some(ResponseHeader {
@@ -410,7 +1017,7 @@ mod test {
}));
assert!(matches!(
result.unwrap_err(),
IllegalDatabaseResponse { .. }
Error::IllegalDatabaseResponse { .. }
));
let result = check_response_header(&Some(ResponseHeader {
@@ -419,7 +1026,7 @@ mod test {
err_msg: "blabla".to_string(),
}),
}));
let Server { code, msg, .. } = result.unwrap_err() else {
let Error::Server { code, msg, .. } = result.unwrap_err() else {
unreachable!()
};
assert_eq!(code, StatusCode::Internal);
+63
View File
@@ -0,0 +1,63 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::borrow::Borrow;
use std::marker::PhantomData;
use api::v1::region::{RegionRequest, RegionResponse};
use prost::Message;
use tonic::Status;
use tonic::codec::{Codec, EncodeBuf, Encoder};
use tonic_prost::ProstDecoder;
/// Encodes owned or shared region requests using the existing protobuf wire format.
pub(crate) struct RegionCodec<R>(PhantomData<R>);
impl<R> Default for RegionCodec<R> {
fn default() -> Self {
Self(PhantomData)
}
}
impl<R> Codec for RegionCodec<R>
where
R: Borrow<RegionRequest> + Send + 'static,
{
type Encode = R;
type Decode = RegionResponse;
type Encoder = RegionEncoder<R>;
type Decoder = ProstDecoder<RegionResponse>;
fn encoder(&mut self) -> Self::Encoder {
RegionEncoder(PhantomData)
}
fn decoder(&mut self) -> Self::Decoder {
ProstDecoder::default()
}
}
/// Borrows the protobuf payload while consuming its owned or shared container.
pub(crate) struct RegionEncoder<R>(PhantomData<R>);
impl<R: Borrow<RegionRequest>> Encoder for RegionEncoder<R> {
type Item = R;
type Error = Status;
fn encode(&mut self, item: R, buf: &mut EncodeBuf<'_>) -> Result<(), Status> {
item.borrow()
.encode(buf)
.map_err(|error| Status::internal(error.to_string()))
}
}
+16 -1
View File
@@ -15,10 +15,11 @@
use std::any::Any;
use arrow_schema::ArrowError;
use common_error::ext::ErrorExt;
use common_error::ext::{ErrorExt, RetryHint, retry_hint_from_io_error};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use datafusion::parquet::errors::ParquetError;
use object_store::error::retry_hint_from_opendal_error;
use snafu::{Location, Snafu};
use url::ParseError;
@@ -250,4 +251,18 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
use Error::*;
match self {
BuildBackend { error, .. }
| ListObjects { error, .. }
| ReadObject { error, .. }
| WriteObject { error, .. } => retry_hint_from_opendal_error(error),
AsyncWrite { error, .. } => retry_hint_from_io_error(error),
WriteParquet { .. } => RetryHint::Retryable,
_ => RetryHint::NonRetryable,
}
}
}
+106
View File
@@ -14,12 +14,95 @@
use std::any::Any;
use std::fmt::{Debug, Formatter};
use std::io::ErrorKind;
use std::str::FromStr;
use std::sync::Arc;
use snafu::{FromString, Snafu};
use crate::status_code::StatusCode;
/// Describes whether an error instance is safe and useful to retry.
///
/// This is intentionally separate from [`StatusCode`]: status code describes the
/// error category exposed to users, while retry hint describes retry policy for
/// this specific error instance.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RetryHint {
/// The operation may succeed if retried later.
Retryable,
/// The operation may succeed after refreshing routing and partition information.
/// The request may need rebuilding when its partition assignment changes.
/// This hint does not imply that a failed operation had no side effects.
RetryAfterRouteRefresh,
/// Retrying the same operation is not expected to help.
///
/// This is the default for errors that do not explicitly opt in to retry.
NonRetryable,
}
const RETRY_HINT_RETRYABLE: &str = "retryable";
const RETRY_HINT_AFTER_ROUTE_REFRESH: &str = "retry_after_route_refresh";
const RETRY_HINT_NON_RETRYABLE: &str = "non_retryable";
impl RetryHint {
/// Returns whether another attempt may succeed, possibly after refreshing routes.
pub fn is_retryable(self) -> bool {
matches!(
self,
RetryHint::Retryable | RetryHint::RetryAfterRouteRefresh
)
}
/// Returns the retry hint encoded in gRPC error metadata.
pub fn as_str(self) -> &'static str {
match self {
RetryHint::Retryable => RETRY_HINT_RETRYABLE,
RetryHint::RetryAfterRouteRefresh => RETRY_HINT_AFTER_ROUTE_REFRESH,
RetryHint::NonRetryable => RETRY_HINT_NON_RETRYABLE,
}
}
}
impl FromStr for RetryHint {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
RETRY_HINT_RETRYABLE => Ok(RetryHint::Retryable),
RETRY_HINT_AFTER_ROUTE_REFRESH => Ok(RetryHint::RetryAfterRouteRefresh),
RETRY_HINT_NON_RETRYABLE => Ok(RetryHint::NonRetryable),
_ => Err(()),
}
}
}
/// Converts a [`std::io::Error`] into a conservative [`RetryHint`].
///
/// This helper classifies known transient I/O conditions as retryable and treats
/// request, permission, filesystem-capacity, and data-shape errors as
/// non-retryable. `std::io::ErrorKind` is non-exhaustive, so future or
/// unclassified kinds are considered non-retryable until reviewed explicitly.
pub fn retry_hint_from_io_error(error: &std::io::Error) -> RetryHint {
match error.kind() {
ErrorKind::ConnectionRefused
| ErrorKind::ConnectionReset
| ErrorKind::HostUnreachable
| ErrorKind::NetworkUnreachable
| ErrorKind::ConnectionAborted
| ErrorKind::NotConnected
| ErrorKind::NetworkDown
| ErrorKind::BrokenPipe
| ErrorKind::WouldBlock
| ErrorKind::StaleNetworkFileHandle
| ErrorKind::TimedOut
| ErrorKind::ResourceBusy
| ErrorKind::Interrupted => RetryHint::Retryable,
_ => RetryHint::NonRetryable,
}
}
/// Extension to [`Error`](std::error::Error) in std.
pub trait ErrorExt: StackError {
/// Map this error to [StatusCode].
@@ -27,6 +110,25 @@ pub trait ErrorExt: StackError {
StatusCode::Unknown
}
/// Returns the retry hint for this error instance.
///
/// Implementations should return [`RetryHint::Retryable`] only when retrying the
/// same operation may succeed without changing the request. The default is
/// [`RetryHint::NonRetryable`] to avoid accidental retry loops. Use
/// [`RetryHint::RetryAfterRouteRefresh`] when routing or partition information
/// must be refreshed before another attempt.
fn retry_hint(&self) -> RetryHint {
RetryHint::NonRetryable
}
/// Returns whether this error instance is marked retryable.
///
/// This is derived from [`Self::retry_hint`]. Transport-level retries, such as a
/// gRPC `Unavailable`, may still be handled separately by client code.
fn is_retryable(&self) -> bool {
self.retry_hint().is_retryable()
}
/// Returns the error as [Any](std::any::Any) so that it can be
/// downcast to a specific implementation.
fn as_any(&self) -> &dyn Any;
@@ -194,6 +296,10 @@ impl crate::ext::ErrorExt for BoxedError {
self.inner.status_code()
}
fn retry_hint(&self) -> RetryHint {
self.inner.retry_hint()
}
fn as_any(&self) -> &dyn std::any::Any {
self.inner.as_any()
}
+1
View File
@@ -27,6 +27,7 @@ use crate::status_code::StatusCode;
// please define in `src/servers/src/http/header.rs`.
pub const GREPTIME_DB_HEADER_ERROR_CODE: &str = "x-greptime-err-code";
pub const GREPTIME_DB_HEADER_ERROR_MSG: &str = "x-greptime-err-msg";
pub const GREPTIME_DB_HEADER_ERROR_RETRY_HINT: &str = "x-greptime-err-retry-hint";
/// Create a http header map from error code and message.
/// using `GREPTIME_DB_HEADER_ERROR_CODE` and `GREPTIME_DB_HEADER_ERROR_MSG` as keys.
+12 -50
View File
@@ -134,54 +134,6 @@ impl StatusCode {
Self::Success as u32 == code
}
/// Returns `true` if the error with this code is retryable.
pub fn is_retryable(&self) -> bool {
match self {
StatusCode::StorageUnavailable
| StatusCode::RuntimeResourcesExhausted
| StatusCode::Internal
| StatusCode::RegionNotReady
| StatusCode::TableUnavailable
| StatusCode::RegionBusy => true,
StatusCode::Success
| StatusCode::Unknown
| StatusCode::Unsupported
| StatusCode::IllegalState
| StatusCode::Unexpected
| StatusCode::InvalidArguments
| StatusCode::Cancelled
| StatusCode::DeadlineExceeded
| StatusCode::InvalidSyntax
| StatusCode::DatabaseAlreadyExists
| StatusCode::PlanQuery
| StatusCode::EngineExecuteQuery
| StatusCode::TableAlreadyExists
| StatusCode::TableNotFound
| StatusCode::RegionAlreadyExists
| StatusCode::RegionNotFound
| StatusCode::FlowAlreadyExists
| StatusCode::FlowNotFound
| StatusCode::TriggerAlreadyExists
| StatusCode::TriggerNotFound
| StatusCode::RegionReadonly
| StatusCode::TableColumnNotFound
| StatusCode::TableColumnExists
| StatusCode::DatabaseNotFound
| StatusCode::RateLimited
| StatusCode::UserNotFound
| StatusCode::UnsupportedPasswordType
| StatusCode::UserPasswordMismatch
| StatusCode::AuthHeaderNotFound
| StatusCode::InvalidAuthHeader
| StatusCode::AccessDenied
| StatusCode::PermissionDenied
| StatusCode::RequestOutdated
| StatusCode::External
| StatusCode::Suspended => false,
}
}
/// Returns `true` if we should print an error log for an error with
/// this status code.
pub fn should_log_error(&self) -> bool {
@@ -271,12 +223,16 @@ macro_rules! define_from_tonic_status {
let msg = metadata_value(&e, $crate::GREPTIME_DB_HEADER_ERROR_MSG)
.unwrap_or_else(|| e.message().to_string());
let retry_hint = metadata_value(&e, $crate::GREPTIME_DB_HEADER_ERROR_RETRY_HINT)
.and_then(|s| s.parse().ok())
.unwrap_or($crate::ext::RetryHint::NonRetryable);
// TODO(LFC): Make the error variant defined automatically.
Self::$Variant {
code,
msg,
tonic_code: e.code(),
retry_hint,
location: location!(),
}
}
@@ -291,11 +247,13 @@ macro_rules! define_into_tonic_status {
fn from(err: $Error) -> Self {
use tonic::codegen::http::{HeaderMap, HeaderValue};
use tonic::metadata::MetadataMap;
use $crate::GREPTIME_DB_HEADER_ERROR_CODE;
use $crate::{
GREPTIME_DB_HEADER_ERROR_CODE, GREPTIME_DB_HEADER_ERROR_RETRY_HINT,
};
common_telemetry::error!(err; "Failed to handle request");
let mut headers = HeaderMap::<HeaderValue>::with_capacity(2);
let mut headers = HeaderMap::<HeaderValue>::with_capacity(3);
// If either of the status_code or error msg cannot convert to valid HTTP header value
// (which is a very rare case), just ignore. Client will use Tonic status code and message.
@@ -304,6 +262,10 @@ macro_rules! define_into_tonic_status {
GREPTIME_DB_HEADER_ERROR_CODE,
HeaderValue::from(status_code as u32),
);
headers.insert(
GREPTIME_DB_HEADER_ERROR_RETRY_HINT,
HeaderValue::from_static(err.retry_hint().as_str()),
);
let root_error = err.output_msg();
let metadata = MetadataMap::from_headers(headers);
+155 -5
View File
@@ -13,8 +13,14 @@
// limitations under the License.
use std::any::Any;
use std::fmt::{Display, Formatter};
use std::io::{Error as IoError, ErrorKind};
use std::str::FromStr;
use common_error::ext::{ErrorExt, PlainError, StackError, WhateverResult};
use common_error::ext::{
BoxedError, ErrorExt, PlainError, RetryHint, StackError, WhateverResult,
retry_hint_from_io_error,
};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use snafu::{Location, ResultExt, Snafu};
@@ -70,8 +76,9 @@ fn test_into_whatever_error() {
let whatever = f(normal_error).unwrap_err();
assert_eq!(
normalize_path(&whatever.to_string()),
// The location points to the `NormalSnafu` context in `normal_error()`.
format!(
r#"0: A normal error with "display" attribute, message "blabla", at {}:55:22
r#"0: A normal error with "display" attribute, message "blabla", at {}:61:22
1: PlainError {{ msg: "<root cause>", status_code: Unexpected }}"#,
normalize_path(file!())
)
@@ -80,8 +87,9 @@ fn test_into_whatever_error() {
let whatever = f(transparent_error).unwrap_err();
assert_eq!(
normalize_path(&whatever.to_string()),
// The location points to the transparent `?` return in `transparent_error()`.
format!(
r#"0: <transparent>, at {}:60:5
r#"0: <transparent>, at {}:66:5
1: PlainError {{ msg: "<root cause>", status_code: Unexpected }}"#,
normalize_path(file!())
)
@@ -123,8 +131,9 @@ fn test_debug_format() {
assert_eq!(
normalize_path(&debug_output),
// The location points to the `NormalSnafu` context in `normal_error()`.
format!(
r#"0: A normal error with "display" attribute, message "blabla", at {}:55:22
r#"0: A normal error with "display" attribute, message "blabla", at {}:61:22
1: PlainError {{ msg: "<root cause>", status_code: Unexpected }}"#,
normalize_path(file!())
)
@@ -134,8 +143,9 @@ fn test_debug_format() {
let debug_output = format!("{:?}", result.unwrap_err());
assert_eq!(
normalize_path(&debug_output),
// The location points to the transparent `?` return in `transparent_error()`.
format!(
r#"0: <transparent>, at {}:60:5
r#"0: <transparent>, at {}:66:5
1: PlainError {{ msg: "<root cause>", status_code: Unexpected }}"#,
normalize_path(file!())
)
@@ -150,3 +160,143 @@ fn test_transparent_flag() {
let result = transparent_error();
assert!(result.unwrap_err().transparent());
}
#[test]
fn test_retry_hint_helpers() {
assert!(RetryHint::Retryable.is_retryable());
assert!(RetryHint::RetryAfterRouteRefresh.is_retryable());
assert_eq!(
RetryHint::RetryAfterRouteRefresh.as_str(),
"retry_after_route_refresh"
);
assert_eq!(
RetryHint::from_str("retry_after_route_refresh").unwrap(),
RetryHint::RetryAfterRouteRefresh
);
assert!(!RetryHint::NonRetryable.is_retryable());
assert_eq!(RetryHint::Retryable.as_str(), "retryable");
assert_eq!(RetryHint::NonRetryable.as_str(), "non_retryable");
assert_eq!(
RetryHint::from_str("retryable").unwrap(),
RetryHint::Retryable
);
assert_eq!(
RetryHint::from_str("non_retryable").unwrap(),
RetryHint::NonRetryable
);
assert!(RetryHint::from_str("unknown").is_err());
}
#[test]
fn test_retry_hint_default() {
let err = normal_error().unwrap_err();
assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
assert!(!err.is_retryable());
}
#[test]
fn test_boxed_error_retry_hint() {
let err = BoxedError::new(RetryableError);
assert_eq!(err.retry_hint(), RetryHint::Retryable);
assert!(err.is_retryable());
}
#[test]
fn test_retry_hint_from_io_error() {
let retryable_kinds = [
ErrorKind::ConnectionRefused,
ErrorKind::ConnectionReset,
ErrorKind::HostUnreachable,
ErrorKind::NetworkUnreachable,
ErrorKind::ConnectionAborted,
ErrorKind::NotConnected,
ErrorKind::NetworkDown,
ErrorKind::BrokenPipe,
ErrorKind::WouldBlock,
ErrorKind::StaleNetworkFileHandle,
ErrorKind::TimedOut,
ErrorKind::ResourceBusy,
ErrorKind::Interrupted,
];
for kind in retryable_kinds {
let error = IoError::from(kind);
assert_eq!(
retry_hint_from_io_error(&error),
RetryHint::Retryable,
"{kind:?}"
);
}
let non_retryable_kinds = [
ErrorKind::NotFound,
ErrorKind::PermissionDenied,
ErrorKind::AddrInUse,
ErrorKind::AddrNotAvailable,
ErrorKind::AlreadyExists,
ErrorKind::NotADirectory,
ErrorKind::IsADirectory,
ErrorKind::DirectoryNotEmpty,
ErrorKind::ReadOnlyFilesystem,
ErrorKind::InvalidInput,
ErrorKind::InvalidData,
ErrorKind::WriteZero,
ErrorKind::StorageFull,
ErrorKind::NotSeekable,
ErrorKind::QuotaExceeded,
ErrorKind::FileTooLarge,
ErrorKind::ExecutableFileBusy,
ErrorKind::Deadlock,
ErrorKind::CrossesDevices,
ErrorKind::TooManyLinks,
ErrorKind::InvalidFilename,
ErrorKind::ArgumentListTooLong,
ErrorKind::Unsupported,
ErrorKind::UnexpectedEof,
ErrorKind::OutOfMemory,
ErrorKind::Other,
];
for kind in non_retryable_kinds {
let error = IoError::from(kind);
assert_eq!(
retry_hint_from_io_error(&error),
RetryHint::NonRetryable,
"{kind:?}"
);
}
}
#[derive(Debug)]
struct RetryableError;
impl Display for RetryableError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "retryable error")
}
}
impl std::error::Error for RetryableError {}
impl StackError for RetryableError {
fn debug_fmt(&self, layer: usize, buf: &mut Vec<String>) {
buf.push(format!("{}: retryable error", layer))
}
fn next(&self) -> Option<&dyn StackError> {
None
}
}
impl ErrorExt for RetryableError {
fn retry_hint(&self) -> RetryHint {
RetryHint::Retryable
}
fn as_any(&self) -> &dyn Any {
self
}
}
+12 -1
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use snafu::{Location, Snafu};
@@ -75,4 +75,15 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn retry_hint(&self) -> RetryHint {
use Error::*;
match self {
External { source, .. } => source.retry_hint(),
Meta { source, .. } => source.retry_hint(),
CreateChannel { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
+17 -1
View File
@@ -15,7 +15,7 @@
use std::any::Any;
use std::io;
use common_error::ext::ErrorExt;
use common_error::ext::{ErrorExt, RetryHint, retry_hint_from_io_error};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use datatypes::arrow::error::ArrowError;
@@ -133,4 +133,20 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::CreateChannel { .. } => RetryHint::Retryable,
Error::Arrow { error, .. } => retry_hint_from_arrow_error(error),
Error::FileWatch { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
fn retry_hint_from_arrow_error(error: &ArrowError) -> RetryHint {
match error {
ArrowError::IoError(_, error) => retry_hint_from_io_error(error),
_ => RetryHint::NonRetryable,
}
}
+29
View File
@@ -37,6 +37,35 @@ use vec1::{Vec1, vec1};
use crate::error;
use crate::error::{DecodeFlightDataSnafu, InvalidFlightDataSnafu, Result};
/// Encodes a batch into the schema, record-batch header and payload used by bulk inserts.
///
/// Uses the default Flight compression and rejects dictionary batches, whose
/// additional Flight messages cannot be represented by this three-part format.
pub fn record_batch_to_ipc(
record_batch: DfRecordBatch,
) -> Result<(ProstBytes, ProstBytes, ProstBytes)> {
let mut encoder = FlightEncoder::default();
let schema = encoder.encode_schema(record_batch.schema().as_ref());
let mut iter = encoder
.encode(FlightMessage::RecordBatch(record_batch))
.into_iter();
let flight_data = iter.next().context(InvalidFlightDataSnafu {
reason: "Failed to encode empty flight data",
})?;
if iter.next().is_some() {
return error::NotSupportedSnafu {
feat: "bulk insert RecordBatch with dictionary arrays",
}
.fail();
}
Ok((
schema.data_header,
flight_data.data_header,
flight_data.data_body,
))
}
/// Flight metadata key used to carry flow query extensions as JSON pairs.
pub const FLOW_EXTENSIONS_METADATA_KEY: &str = "x-greptime-flow-extensions";
/// Flight metadata key used to carry query snapshot read upper bounds as JSON.
+9 -1
View File
@@ -15,7 +15,7 @@
use std::any::Any;
use std::path::PathBuf;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint, retry_hint_from_io_error};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use snafu::{Location, Snafu};
@@ -101,6 +101,14 @@ impl ErrorExt for Error {
}
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::OpenTempFile { error, .. } => retry_hint_from_io_error(error),
Error::DumpProfileData { .. } => RetryHint::Retryable,
_ => RetryHint::NonRetryable,
}
}
fn as_any(&self) -> &dyn Any {
self
}
+10 -1
View File
@@ -15,7 +15,7 @@
use std::any::Any;
use std::time::Duration;
use common_error::ext::ErrorExt;
use common_error::ext::{ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use snafu::Snafu;
@@ -60,4 +60,13 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::MemoryLimitExceeded { .. } | Error::MemoryAcquireTimeout { .. } => {
RetryHint::Retryable
}
_ => RetryHint::NonRetryable,
}
}
}
+70 -4
View File
@@ -28,7 +28,7 @@ use api::v1::region::{
region_request,
};
use common_catalog::consts::{METRIC_ENGINE, MITO_ENGINE};
use common_error::ext::BoxedError;
use common_error::ext::{BoxedError, ErrorExt};
use common_procedure::error::Error as ProcedureError;
use common_telemetry::tracing_context::TracingContext;
use common_telemetry::{error, info, warn};
@@ -59,7 +59,7 @@ use crate::rpc::router::{RegionRoute, find_follower_regions, find_followers};
pub fn add_peer_context_if_needed(datanode: Peer) -> impl FnOnce(Error) -> Error {
move |err| {
error!(err; "Failed to operate datanode, peer: {}", datanode);
if !err.is_retry_later() {
if !err.retry_hint().is_retryable() {
return Err::<(), BoxedError>(BoxedError::new(err))
.context(OperateDatanodeSnafu { peer: datanode })
.unwrap_err();
@@ -73,7 +73,7 @@ pub fn add_peer_context_if_needed(datanode: Peer) -> impl FnOnce(Error) -> Error
/// This function determines whether the error should be retried and if poison cleanup is needed,
/// then maps it to the appropriate procedure error variant.
pub fn map_to_procedure_error(e: Error) -> ProcedureError {
match (e.is_retry_later(), e.need_clean_poisons()) {
match (e.retry_hint().is_retryable(), e.need_clean_poisons()) {
(true, true) => ProcedureError::retry_later_and_clean_poisons(e),
(true, false) => ProcedureError::retry_later(e),
(false, true) => ProcedureError::external_and_clean_poisons(e),
@@ -260,7 +260,7 @@ pub fn handle_multiple_results<T: Debug>(results: Vec<Result<T>>) -> MultipleRes
match result {
Ok(value) => ok_results.push(value),
Err(err) => {
if err.is_retry_later() {
if err.retry_hint().is_retryable() {
retryable_results.push(err);
} else {
non_retryable_results.push(err);
@@ -479,8 +479,74 @@ pub fn extract_column_metadatas(
#[cfg(test)]
mod tests {
use common_error::mock::MockError;
use common_error::status_code::StatusCode;
use super::*;
fn external_error(retryable: bool) -> Error {
let source = MockError::new(StatusCode::Internal);
let source = if retryable {
BoxedError::new(Error::retry_later(source))
} else {
BoxedError::new(source)
};
Err::<(), _>(source)
.context(error::ExternalSnafu)
.unwrap_err()
}
#[test]
fn test_map_to_procedure_error() {
for retryable in [false, true] {
for clean_poisons in [false, true] {
let err = if retryable {
Error::RetryLater {
source: BoxedError::new(external_error(false)),
clean_poisons,
}
} else {
Err::<(), _>(BoxedError::new(external_error(true)))
.context(error::AbortProcedureSnafu { clean_poisons })
.unwrap_err()
};
let err = map_to_procedure_error(err);
assert_eq!(err.is_retry_later(), retryable);
assert_eq!(err.need_clean_poisons(), clean_poisons);
}
let err = map_to_procedure_error(external_error(retryable));
assert_eq!(err.is_retry_later(), retryable);
assert!(!err.need_clean_poisons());
}
}
#[test]
fn test_handle_multiple_results_retry_hint() {
assert!(matches!(
handle_multiple_results(vec![Ok(()), Err(external_error(true))]),
MultipleResults::PartialRetryable(_)
));
assert!(matches!(
handle_multiple_results::<()>(vec![
Err(external_error(true)),
Err(external_error(true))
]),
MultipleResults::AllRetryable(_)
));
assert!(matches!(
handle_multiple_results(vec![
Ok(()),
Err(external_error(true)),
Err(external_error(false))
]),
MultipleResults::PartialNonRetryable(_)
));
assert!(matches!(
handle_multiple_results::<()>(vec![Err(external_error(false))]),
MultipleResults::AllNonRetryable(_)
));
}
#[test]
fn test_get_catalog_and_schema() {
let test_catalog = "my_catalog";
+125 -1
View File
@@ -15,11 +15,13 @@
use std::str::Utf8Error;
use std::sync::Arc;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use common_procedure::ProcedureId;
use common_wal::kafka::rskafka_client_error_to_retry_hint;
use common_wal::options::WalOptions;
use object_store::error::retry_hint_from_opendal_error;
use serde_json::error::Error as JsonError;
use snafu::{Location, Snafu};
use store_api::storage::RegionId;
@@ -1281,6 +1283,50 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn retry_hint(&self) -> RetryHint {
use Error::*;
match self {
RetryLater { source, .. } => match source.retry_hint() {
RetryHint::RetryAfterRouteRefresh => RetryHint::RetryAfterRouteRefresh,
RetryHint::Retryable | RetryHint::NonRetryable => RetryHint::Retryable,
},
GetLatestCacheRetryExceeded { .. }
| NoLeader { .. }
| ElectionNoLeader { .. }
| ElectionLeaderLeaseExpired { .. }
| ElectionLeaderLeaseChanged { .. } => RetryHint::Retryable,
WriteObject { error, .. } | ReadObject { error, .. } => {
retry_hint_from_opendal_error(error)
}
BuildKafkaClient { error, .. }
| BuildKafkaCtrlClient { error, .. }
| KafkaPartitionClient { error, .. }
| KafkaGetOffset { error, .. }
| ProduceRecord { error, .. }
| CreateKafkaWalTopic { error, .. } => rskafka_client_error_to_retry_hint(error),
SubmitProcedure { source, .. }
| QueryProcedure { source, .. }
| WaitProcedure { source, .. }
| StartProcedureManager { source, .. }
| StopProcedureManager { source, .. }
| RegisterProcedureLoader { source, .. }
| PutPoison { source, .. } => source.retry_hint(),
External { source, .. }
| ResponseExceededSizeLimit { source, .. }
| OperateDatanode { source, .. }
| RegisterRepartitionProcedureLoader { source, .. }
| CreateRepartitionProcedure { source, .. } => source.retry_hint(),
// These errors end an operation; their sources cannot make it retryable.
AbortProcedure { .. } | ProcedureStateReceiver { .. } => RetryHint::NonRetryable,
Table { source, .. } => source.retry_hint(),
ConvertAlterTableRequest { source, .. } => source.retry_hint(),
ConvertColumnDef { source, .. } => source.retry_hint(),
GetCache { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
impl Error {
@@ -1350,3 +1396,81 @@ impl Error {
}
}
}
#[cfg(test)]
mod retry_hint_tests {
use std::sync::Arc;
use common_error::mock::MockError;
use snafu::ResultExt;
use super::*;
#[test]
fn test_retry_later_hint_is_retryable() {
let err = Error::retry_later(MockError::new(StatusCode::Internal));
assert_eq!(err.retry_hint(), RetryHint::Retryable);
}
#[test]
fn test_latest_cache_retry_exceeded_hint_is_retryable() {
let err = GetLatestCacheRetryExceededSnafu { attempts: 3_usize }.build();
assert_eq!(err.retry_hint(), RetryHint::Retryable);
}
#[test]
fn test_leader_retry_hints() {
for (error, expected) in [
(
NoLeaderSnafu { table_id: 1_u32 }.build(),
RetryHint::Retryable,
),
(ElectionNoLeaderSnafu.build(), RetryHint::Retryable),
(
ElectionLeaderLeaseExpiredSnafu.build(),
RetryHint::Retryable,
),
(
ElectionLeaderLeaseChangedSnafu.build(),
RetryHint::Retryable,
),
] {
assert_eq!(error.retry_hint(), expected, "{error:?}");
}
}
#[test]
fn test_procedure_error_retry_hints() {
let source = common_procedure::Error::retry_later(MockError::new(StatusCode::Internal));
let err = Err::<(), _>(source).context(PutPoisonSnafu).unwrap_err();
assert_eq!(err.retry_hint(), RetryHint::Retryable);
let source = common_procedure::Error::retry_later(MockError::new(StatusCode::Internal));
let err = Err::<(), _>(source)
.context(ProcedureStateReceiverSnafu {
procedure_id: ProcedureId::random(),
})
.unwrap_err();
assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
}
#[test]
fn test_get_cache_forwards_retry_hint() {
let source = Arc::new(Error::retry_later(MockError::new(StatusCode::Internal)));
let err = Error::GetCache { source };
assert_eq!(err.retry_hint(), RetryHint::Retryable);
}
#[test]
fn test_default_hint_is_non_retryable() {
let err = UnexpectedSnafu {
err_msg: "mock error",
}
.build();
assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
}
}
+11 -1
View File
@@ -28,12 +28,22 @@ use crate::peer::Peer;
#[async_trait::async_trait]
pub trait Datanode: Send + Sync {
/// Handles DML, and DDL requests.
async fn handle(&self, request: RegionRequest) -> Result<RegionResponse>;
async fn handle_request(&self, request: Arc<RegionRequest>) -> Result<RegionResponse>;
/// Handles query requests
async fn handle_query(&self, request: QueryRequest) -> Result<SendableRecordBatchStream>;
}
impl dyn Datanode + '_ {
/// Handles an owned or shared request without cloning its payload.
pub async fn handle<R>(&self, request: R) -> Result<RegionResponse>
where
R: Into<Arc<RegionRequest>> + Send,
{
self.handle_request(request.into()).await
}
}
pub type DatanodeRef = Arc<dyn Datanode>;
/// The trait for handling requests to flownode
+3
View File
@@ -22,6 +22,9 @@ use crate::cluster::NodeInfo;
use crate::error::Error;
use crate::{DatanodeId, FlownodeId};
/// Shared reference to a [`Peer`].
pub type PeerRef = Arc<Peer>;
/// [`PeerResolver`] provides methods to look up peer information by node ID.
///
/// This trait allows resolving both datanode and flownode peers, regardless of their current activity status.
@@ -16,6 +16,7 @@ use std::any::Any;
use std::fmt::Debug;
use std::time::Instant;
use common_error::ext::ErrorExt;
use common_procedure::error::FromJsonSnafu;
use common_procedure::{
Context as ProcedureContext, Error as ProcedureError, LockKey, Procedure,
@@ -188,7 +189,7 @@ impl Procedure for ReconcileCatalogProcedure {
Ok(status)
}
Err(e) => {
if e.is_retry_later() {
if e.retry_hint().is_retryable() {
metrics::METRIC_META_RECONCILIATION_PROCEDURE_ERROR
.with_label_values(&[procedure_name, step, metrics::ERROR_TYPE_RETRYABLE])
.inc();
@@ -23,6 +23,7 @@ use std::fmt::Debug;
use std::time::Instant;
use async_trait::async_trait;
use common_error::ext::ErrorExt;
use common_procedure::error::{FromJsonSnafu, ToJsonSnafu};
use common_procedure::{
Context as ProcedureContext, Error as ProcedureError, LockKey, Procedure,
@@ -228,7 +229,7 @@ impl Procedure for ReconcileDatabaseProcedure {
Ok(status)
}
Err(e) => {
if e.is_retry_later() {
if e.retry_hint().is_retryable() {
metrics::METRIC_META_RECONCILIATION_PROCEDURE_ERROR
.with_label_values(&[procedure_name, step, metrics::ERROR_TYPE_RETRYABLE])
.inc();
@@ -22,6 +22,7 @@ use std::any::Any;
use std::fmt::Debug;
use async_trait::async_trait;
use common_error::ext::ErrorExt;
use common_procedure::error::{FromJsonSnafu, ToJsonSnafu};
use common_procedure::{
Context as ProcedureContext, Error as ProcedureError, LockKey, Procedure,
@@ -204,7 +205,7 @@ impl Procedure for ReconcileLogicalTablesProcedure {
Ok(status)
}
Err(e) => {
if e.is_retry_later() {
if e.retry_hint().is_retryable() {
metrics::METRIC_META_RECONCILIATION_PROCEDURE_ERROR
.with_label_values(&[procedure_name, step, metrics::ERROR_TYPE_RETRYABLE])
.inc();
@@ -21,6 +21,7 @@ pub(crate) mod update_table_info;
use std::any::Any;
use std::fmt::Debug;
use common_error::ext::ErrorExt;
use common_procedure::error::{FromJsonSnafu, ToJsonSnafu};
use common_procedure::{
Context as ProcedureContext, Error as ProcedureError, LockKey, Procedure,
@@ -216,7 +217,7 @@ impl Procedure for ReconcileTableProcedure {
Ok(status)
}
Err(e) => {
if e.is_retry_later() {
if e.retry_hint().is_retryable() {
metrics::METRIC_META_RECONCILIATION_PROCEDURE_ERROR
.with_label_values(&[procedure_name, step, metrics::ERROR_TYPE_RETRYABLE])
.inc();
+32 -1
View File
@@ -128,15 +128,25 @@ pub fn convert_to_region_leader_map(region_routes: &[RegionRoute]) -> HashMap<Re
.collect::<HashMap<_, _>>()
}
/// Returns the leader of the first route matching the region number.
pub fn find_region_leader(
region_routes: &[RegionRoute],
region_number: RegionNumber,
) -> Option<Peer> {
find_region_leader_ref(region_routes, region_number).cloned()
}
/// Borrows the leader of the first route matching the region number.
///
/// Returns `None` if no route matches or the first matching route has no leader.
pub fn find_region_leader_ref(
region_routes: &[RegionRoute],
region_number: RegionNumber,
) -> Option<&Peer> {
region_routes
.iter()
.find(|x| x.region.id.region_number() == region_number)
.and_then(|r| r.leader_peer.as_ref())
.cloned()
}
/// Returns the region numbers of the leader regions on the target datanode.
@@ -616,6 +626,27 @@ mod tests {
}
}
#[test]
fn test_find_region_leader() {
let mut routes = vec![
new_test_region_route(RegionId::new(1, 1)),
new_test_region_route(RegionId::new(1, 1)),
];
routes[1].leader_peer = Some(Peer::new(2, "a2"));
assert_eq!(
find_region_leader_ref(&routes, 1),
routes[0].leader_peer.as_ref()
);
assert_eq!(find_region_leader(&routes, 1), routes[0].leader_peer);
assert_eq!(find_region_leader_ref(&routes, 2), None);
assert_eq!(find_region_leader(&routes, 2), None);
routes[0].leader_peer = None;
assert_eq!(find_region_leader_ref(&routes, 1), None);
assert_eq!(find_region_leader(&routes, 1), None);
}
#[test]
fn test_leader_is_downgraded() {
let mut region_route = RegionRoute {
+2 -1
View File
@@ -111,7 +111,8 @@ struct MockNode<T> {
#[async_trait::async_trait]
impl<T: MockDatanodeHandler> Datanode for MockNode<T> {
async fn handle(&self, request: RegionRequest) -> Result<RegionResponse> {
async fn handle_request(&self, request: Arc<RegionRequest>) -> Result<RegionResponse> {
let request = Arc::try_unwrap(request).expect("mock request must be exclusively owned");
self.handler.handle(&self.peer, request).await
}
+102 -3
View File
@@ -15,9 +15,10 @@
use std::any::Any;
use std::sync::Arc;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use object_store::error::retry_hint_from_opendal_error;
use snafu::{Location, Snafu};
use crate::PoisonKey;
@@ -293,6 +294,29 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::RetryLater { .. } => RetryHint::Retryable,
Error::External { source, .. }
| Error::PutState { source, .. }
| Error::DeleteStates { source, .. }
| Error::ListState { source, .. }
| Error::PutPoison { source, .. }
| Error::DeletePoison { source, .. }
| Error::GetPoison { source, .. }
| Error::CheckStatus { source, .. } => source.retry_hint(),
// The watcher reports this only after the child has failed or been poisoned.
Error::ProcedureExec { .. } => RetryHint::NonRetryable,
Error::StartRemoveOutdatedMetaTask { source, .. }
| Error::StopRemoveOutdatedMetaTask { source, .. } => source.retry_hint(),
Error::DeleteState { error, .. } => retry_hint_from_opendal_error(error),
Error::RetryTimesExceeded { .. } | Error::RollbackTimesExceeded { .. } => {
RetryHint::NonRetryable
}
_ => RetryHint::NonRetryable,
}
}
}
impl Error {
@@ -339,13 +363,88 @@ impl Error {
|| matches!(self, Error::RetryLater { clean_poisons, .. } if *clean_poisons)
}
#[cfg(test)]
/// Creates a new [Error::RetryLater] or [Error::External] error from source `err` according
/// to its [StatusCode].
/// to its [RetryHint].
pub fn from_error_ext<E: ErrorExt + Send + Sync + 'static>(err: E) -> Self {
if err.status_code().is_retryable() {
if err.retry_hint().is_retryable() {
Error::retry_later(err)
} else {
Error::external(err)
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use common_error::mock::MockError;
use tokio::sync::watch;
use super::*;
use crate::procedure::ProcedureState;
use crate::watcher;
#[test]
fn test_retry_later_hint_is_retryable() {
let err = Error::retry_later(MockError::new(StatusCode::Internal));
assert_eq!(err.retry_hint(), RetryHint::Retryable);
}
#[test]
fn test_external_forwards_retry_hint() {
let source = Error::retry_later(MockError::new(StatusCode::Internal));
let err = Error::external(source);
assert_eq!(err.retry_hint(), RetryHint::Retryable);
}
#[tokio::test]
async fn test_finished_procedure_hint_is_non_retryable() {
let source = Arc::new(Error::retry_later(MockError::new(StatusCode::Internal)));
for state in [
ProcedureState::failed(source.clone()),
ProcedureState::poisoned(Default::default(), source),
] {
let (sender, mut receiver) = watch::channel(ProcedureState::Running);
sender.send(state).unwrap();
let err = watcher::wait(&mut receiver).await.unwrap_err();
assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
}
}
#[test]
fn test_retry_exceeded_hint_is_non_retryable() {
let source = Arc::new(Error::retry_later(MockError::new(StatusCode::Internal)));
let err = Error::RetryTimesExceeded {
source: source.clone(),
procedure_id: ProcedureId::random(),
};
assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
let err = Error::RollbackTimesExceeded {
source,
procedure_id: ProcedureId::random(),
};
assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
}
#[test]
fn test_from_error_ext_uses_retry_hint() {
let err = Error::from_error_ext(Error::retry_later(MockError::new(
StatusCode::InvalidArguments,
)));
assert!(err.is_retry_later());
let err = Error::from_error_ext(MockError::new(StatusCode::InvalidArguments));
assert!(!err.is_retry_later());
let err = Error::from_error_ext(MockError::new(StatusCode::Internal));
assert!(!err.is_retry_later());
}
}
+12 -1
View File
@@ -15,7 +15,7 @@
//! Error of record batch.
use std::any::Any;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use datafusion_common::ScalarValue;
@@ -230,4 +230,15 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::ExceedMemoryLimit { .. } => RetryHint::Retryable,
Error::External { source, .. } => source.retry_hint(),
Error::SchemaConversion { source, .. } | Error::CastVector { source, .. } => {
source.retry_hint()
}
_ => RetryHint::NonRetryable,
}
}
}
+96
View File
@@ -0,0 +1,96 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use common_error::ext::RetryHint;
/// Maps an rskafka client error to a conservative retry hint.
///
/// rskafka already retries most transient Kafka/network errors internally. This helper only
/// marks errors retryable when rskafka has exhausted its own retry loop or returns an explicit
/// client timeout.
pub fn rskafka_client_error_to_retry_hint(error: &rskafka::client::error::Error) -> RetryHint {
use rskafka::client::error::Error;
match error {
Error::RetryFailed(_)
| Error::Timeout
| Error::Connection(rskafka::ConnectionError::RetryFailed(_)) => RetryHint::Retryable,
_ => RetryHint::NonRetryable,
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use common_error::ext::RetryHint;
use rskafka::BackoffError;
use rskafka::client::error::{Error as KafkaClientError, ProtocolError, RequestContext};
use super::*;
fn retry_failed_error() -> KafkaClientError {
KafkaClientError::RetryFailed(BackoffError::DeadlineExceded {
deadline: Duration::from_secs(1),
source: Box::new(std::io::Error::other("retry failed")),
})
}
#[test]
fn test_retry_failed_hint_is_retryable() {
assert_eq!(
rskafka_client_error_to_retry_hint(&retry_failed_error()),
RetryHint::Retryable
);
}
#[test]
fn test_timeout_hint_is_retryable() {
assert_eq!(
rskafka_client_error_to_retry_hint(&KafkaClientError::Timeout),
RetryHint::Retryable
);
}
#[test]
fn test_connection_retry_failed_hint_is_retryable() {
let err = KafkaClientError::Connection(rskafka::ConnectionError::RetryFailed(
BackoffError::DeadlineExceded {
deadline: Duration::from_secs(1),
source: Box::new(std::io::Error::other("retry failed")),
},
));
assert_eq!(
rskafka_client_error_to_retry_hint(&err),
RetryHint::Retryable
);
}
#[test]
fn test_raw_protocol_error_hint_is_non_retryable() {
let err = KafkaClientError::ServerError {
protocol_error: ProtocolError::NetworkException,
error_message: None,
request: RequestContext::Topic("test_topic".to_string()),
response: None,
is_virtual: false,
};
assert_eq!(
rskafka_client_error_to_retry_hint(&err),
RetryHint::NonRetryable
);
}
}
+1
View File
@@ -21,6 +21,7 @@ use tokio::net;
pub mod config;
pub mod error;
pub mod kafka;
pub mod options;
#[cfg(any(test, feature = "testing"))]
pub mod test_util;
+78 -1
View File
@@ -16,7 +16,7 @@ use std::any::Any;
use std::sync::Arc;
use common_error::define_into_tonic_status;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use common_runtime::JoinError;
@@ -496,6 +496,83 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
use Error::*;
match self {
RegionNotReady { .. } | RegionNotFound { .. } => RetryHint::RetryAfterRouteRefresh,
RegionBusy { .. }
| ConcurrentQueryLimiterClosed { .. }
| ConcurrentQueryLimiterTimeout { .. } => RetryHint::Retryable,
NewPlanDecoder { source, .. } | ExecuteLogicalPlan { source, .. } => {
source.retry_hint()
}
HandleHeartbeatResponse { source, .. } | GetMetadata { source, .. } => {
source.retry_hint()
}
DecodeLogicalPlan { source, .. } => source.retry_hint(),
Delete { source, .. } => source.retry_hint(),
AsyncTaskExecute { source, .. } => source.retry_hint(),
StartServer { source, .. } | ShutdownServer { source, .. } => source.retry_hint(),
OpenLogStore { source, .. } => source.retry_hint(),
MetaClientInit { source, .. } => source.retry_hint(),
HandleRegionRequest { source, .. }
| GetRegionMetadata { source, .. }
| HandleBatchOpenRequest { source, .. }
| HandleBatchDdlRequest { source, .. }
| StopRegionEngine { source, .. } => source.retry_hint(),
FindLogicalRegions { source, .. } => source.retry_hint(),
BuildMitoEngine { source, .. } => source.retry_hint(),
GcMitoEngine { source, .. } => source.retry_hint(),
BuildMetricEngine { source, .. } => source.retry_hint(),
ListStorageSsts { source, .. } => source.retry_hint(),
ObjectStore { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
define_into_tonic_status!(Error);
#[cfg(test)]
mod tests {
use common_error::ext::RetryHint;
use super::*;
#[test]
fn test_region_state_retry_hints() {
let region_id = RegionId::new(1024, 1);
for (error, status, hint) in [
(
RegionBusySnafu { region_id }.build(),
StatusCode::RegionBusy,
RetryHint::Retryable,
),
(
RegionNotReadySnafu { region_id }.build(),
StatusCode::RegionNotReady,
RetryHint::RetryAfterRouteRefresh,
),
(
RegionNotFoundSnafu { region_id }.build(),
StatusCode::RegionNotFound,
RetryHint::RetryAfterRouteRefresh,
),
] {
assert_eq!(error.status_code(), status);
assert_eq!(error.retry_hint(), hint);
}
}
#[test]
fn test_default_hint_is_non_retryable() {
let err = UnexpectedSnafu {
violated: "mock error",
}
.build();
assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
}
}
+4 -2
View File
@@ -1926,7 +1926,7 @@ mod tests {
use std::sync::Arc;
use api::v1::{Rows, SemanticType};
use common_error::ext::ErrorExt;
use common_error::ext::{ErrorExt, RetryHint};
use common_recordbatch::RecordBatches;
use common_recordbatch::adapter::{RecordBatchMetrics, RegionWatermarkEntry};
use datatypes::prelude::{ConcreteDataType, VectorRef};
@@ -2387,7 +2387,9 @@ mod tests {
)
.await
.unwrap_err();
assert_eq!(err.status_code(), StatusCode::Unexpected);
assert_matches!(&err, error::Error::HandleBatchOpenRequest { .. });
assert_eq!(err.status_code(), StatusCode::RegionNotFound);
assert_eq!(err.retry_hint(), RetryHint::RetryAfterRouteRefresh);
}
struct CurrentEngineTest {
+13 -5
View File
@@ -14,11 +14,12 @@
use std::any::Any;
use common_error::ext::ErrorExt;
use common_error::ext::{ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use datafusion::arrow::error::ArrowError;
use datafusion::error::DataFusionError;
use object_store::error::retry_hint_from_opendal_error;
use serde_json::error::Error as JsonError;
use snafu::{Location, Snafu};
use store_api::storage::RegionId;
@@ -234,10 +235,17 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
}
impl From<Error> for common_procedure::Error {
fn from(e: Error) -> common_procedure::Error {
common_procedure::Error::from_error_ext(e)
fn retry_hint(&self) -> RetryHint {
use Error::*;
match self {
BuildBackend { source, .. } | ParseFileFormat { source, .. } => source.retry_hint(),
CheckObject { error, .. }
| StoreRegionManifest { error, .. }
| LoadRegionManifest { error, .. }
| DeleteRegionManifest { error, .. } => retry_hint_from_opendal_error(error),
_ => RetryHint::NonRetryable,
}
}
}
+39 -3
View File
@@ -18,12 +18,15 @@ use std::any::Any;
use api::v1::CreateTableExpr;
use arrow_schema::ArrowError;
use common_error::ext::BoxedError;
use common_error::{define_into_tonic_status, from_err_code_msg_to_header};
use common_error::ext::{BoxedError, RetryHint};
use common_error::{
GREPTIME_DB_HEADER_ERROR_RETRY_HINT, define_into_tonic_status, from_err_code_msg_to_header,
};
use common_macro::stack_trace_debug;
use common_telemetry::common_error::ext::ErrorExt;
use common_telemetry::common_error::status_code::StatusCode;
use snafu::{Location, ResultExt, Snafu};
use tonic::codegen::http::HeaderValue;
use tonic::metadata::MetadataMap;
use crate::FlowId;
@@ -308,7 +311,11 @@ pub fn to_status_with_last_err(err: impl ErrorExt) -> tonic::Status {
let msg = err.to_string();
let last_err_msg = common_error::ext::StackError::last(&err).to_string();
let code = err.status_code() as u32;
let header = from_err_code_msg_to_header(code, &last_err_msg);
let mut header = from_err_code_msg_to_header(code, &last_err_msg);
header.insert(
GREPTIME_DB_HEADER_ERROR_RETRY_HINT,
HeaderValue::from_static(err.retry_hint().as_str()),
);
tonic::Status::with_metadata(
tonic::Code::InvalidArgument,
@@ -366,6 +373,35 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
match self {
Self::FlowNotRecovered { .. } | Self::NoAvailableFrontend { .. } => {
RetryHint::Retryable
}
Self::InsertIntoFlow { source, .. }
| Self::CreateFlow { source, .. }
| Self::CreateSinkTable { source, .. }
| Self::External { source, .. } => source.retry_hint(),
Self::Time { source, .. } => source.retry_hint(),
Self::TableNotFoundMeta { source, .. } | Self::ListFlows { source, .. } => {
source.retry_hint()
}
Self::Datatypes { source, .. } => source.retry_hint(),
Self::StartServer { source, .. } | Self::ShutdownServer { source, .. } => {
source.retry_hint()
}
Self::MetaClientInit { source, .. } => source.retry_hint(),
Self::InvalidRequest { source, .. } => source.retry_hint(),
Self::SubstraitEncodeLogicalPlan { source, .. } => source.retry_hint(),
Self::ConvertColumnSchema { source, .. } => source.retry_hint(),
Self::InvalidClientConfig { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
define_into_tonic_status!(Error);
+1
View File
@@ -94,5 +94,6 @@ meta-srv.workspace = true
reqwest.workspace = true
serde_json.workspace = true
strfmt = "0.2"
temp-env = "0.3"
tower.workspace = true
uuid.workspace = true
+50 -2
View File
@@ -16,7 +16,7 @@ use std::any::Any;
use common_datasource::file_format::Format;
use common_error::define_into_tonic_status;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use common_query::error::datafusion_status_code;
@@ -314,6 +314,13 @@ pub enum Error {
name: String,
},
#[snafu(display("Invalid write retry config: {}", reason))]
InvalidWriteRetryConfig {
reason: &'static str,
#[snafu(implicit)]
location: Location,
},
#[snafu(display("Invalid tls config"))]
InvalidTlsConfig {
#[snafu(source)]
@@ -381,7 +388,8 @@ impl ErrorExt for Error {
| Error::IllegalAuthConfig { .. }
| Error::ColumnNoneDefaultValue { .. }
| Error::IncompleteGrpcRequest { .. }
| Error::InvalidTlsConfig { .. } => StatusCode::InvalidArguments,
| Error::InvalidTlsConfig { .. }
| Error::InvalidWriteRetryConfig { .. } => StatusCode::InvalidArguments,
Error::NotSupported { .. } => StatusCode::Unsupported,
@@ -448,6 +456,46 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::InvalidateTableCache { source, .. }
| Error::HandleHeartbeatResponse { source, .. }
| Error::RequestQuery { source, .. } => source.retry_hint(),
Error::External { source, .. }
| Error::SqlExecIntercepted { source, .. }
| Error::InitPlugin { source, .. } => source.retry_hint(),
Error::StartServer { source, .. }
| Error::ShutdownServer { source, .. }
| Error::InvokeRegionServer { source, .. }
| Error::ExecutePromql { source, .. }
| Error::PromStoreRemoteQueryPlan { source, .. }
| Error::PrometheusMetricNamesQueryPlan { source, .. } => source.retry_hint(),
Error::ParseSql { source, .. } => source.retry_hint(),
Error::Catalog { source, .. } => source.retry_hint(),
Error::CreateMetaHeartbeatStream { source, .. } => source.retry_hint(),
Error::FindRegionPeer { source, .. } => source.retry_hint(),
Error::Table { source, .. } => source.retry_hint(),
Error::CollectRecordbatch { source, .. } => source.retry_hint(),
Error::PlanStatement { source, .. }
| Error::ReadTable { source, .. }
| Error::ExecLogicalPlan { source, .. }
| Error::DescribeStatement { source, .. } => source.retry_hint(),
Error::PrometheusLabelValuesQueryPlan { source, .. } => source.retry_hint(),
Error::Insert { source, .. } => source.retry_hint(),
Error::Permission { source, .. } => source.retry_hint(),
Error::TableOperation { source, .. } => source.retry_hint(),
Error::IllegalAuthConfig { source, .. } => source.retry_hint(),
Error::TomlFormat { source, .. } => source.retry_hint(),
Error::InvalidTlsConfig { error, .. } => error.retry_hint(),
Error::SubstraitDecodeLogicalPlan { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
define_into_tonic_status!(Error);
+71 -1
View File
@@ -35,9 +35,10 @@ use crate::heartbeat::HeartbeatTask;
use crate::instance::Instance;
use crate::service_config::{
InfluxdbOptions, JaegerOptions, MysqlOptions, OpentsdbOptions, OtlpOptions, PostgresOptions,
PromStoreOptions,
PromStoreOptions, WriteRetryOptions,
};
/// Configures frontend protocols, query execution, and distributed write retries.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct FrontendOptions {
@@ -70,6 +71,8 @@ pub struct FrontendOptions {
pub meta_client: Option<MetaClientOptions>,
pub logging: LoggingOptions,
pub datanode: DatanodeClientOptions,
/// Retry policy for retryable distributed write failures.
pub write_retry: WriteRetryOptions,
pub user_provider: Option<String>,
pub tracing: TracingOptions,
pub query: QueryOptions,
@@ -103,6 +106,7 @@ impl Default for FrontendOptions {
meta_client: None,
logging: LoggingOptions::default(),
datanode: DatanodeClientOptions::default(),
write_retry: WriteRetryOptions::default(),
user_provider: None,
tracing: TracingOptions::default(),
query: QueryOptions::default(),
@@ -191,6 +195,72 @@ mod tests {
use crate::instance::builder::FrontendBuilder;
use crate::server::Services;
#[test]
fn test_write_retry_config() {
let defaults: FrontendOptions = toml::from_str("").unwrap();
assert_eq!(defaults.write_retry, WriteRetryOptions::default());
let options: FrontendOptions = toml::from_str(
r#"
[write_retry]
max_retries = 5
initial_backoff = "250ms"
max_backoff = "5s"
backoff_multiplier = 3.0
"#,
)
.unwrap();
assert_eq!(
options.write_retry,
WriteRetryOptions {
max_retries: 5,
initial_backoff: Duration::from_millis(250),
max_backoff: Duration::from_secs(5),
backoff_multiplier: 3.0,
}
);
options.write_retry.validate().unwrap();
let serialized = toml::to_string(&options).unwrap();
let parsed: FrontendOptions = toml::from_str(&serialized).unwrap();
assert_eq!(options.write_retry, parsed.write_retry);
let disabled: FrontendOptions = toml::from_str("[write_retry]\nmax_retries = 0").unwrap();
assert_eq!(disabled.write_retry.max_retries, 0);
assert_eq!(
disabled.write_retry.initial_backoff,
defaults.write_retry.initial_backoff
);
}
#[test]
fn test_write_retry_config_from_env() {
temp_env::with_vars(
[
("FRONTEND_RETRY_TEST__WRITE_RETRY__MAX_RETRIES", Some("4")),
(
"FRONTEND_RETRY_TEST__WRITE_RETRY__INITIAL_BACKOFF",
Some("500ms"),
),
("FRONTEND_RETRY_TEST__WRITE_RETRY__MAX_BACKOFF", Some("8s")),
(
"FRONTEND_RETRY_TEST__WRITE_RETRY__BACKOFF_MULTIPLIER",
Some("1.5"),
),
],
|| {
let options =
FrontendOptions::load_layered_options(None, "FRONTEND_RETRY_TEST").unwrap();
assert_eq!(
options.write_retry,
WriteRetryOptions {
max_retries: 4,
initial_backoff: Duration::from_millis(500),
max_backoff: Duration::from_secs(8),
backoff_multiplier: 1.5,
}
);
},
);
}
#[test]
fn test_toml() {
let opts = FrontendOptions::default();
+116 -19
View File
@@ -21,7 +21,7 @@ use catalog::process_manager::ProcessManagerRef;
use common_base::Plugins;
use common_event_recorder::EventRecorderImpl;
use common_meta::cache::{LayeredCacheRegistryRef, TableRouteCacheRef};
use common_meta::cache_invalidator::{CacheInvalidatorRef, DummyCacheInvalidator};
use common_meta::cache_invalidator::CacheInvalidatorRef;
use common_meta::key::TableMetadataManager;
use common_meta::key::flow::FlowMetadataManager;
use common_meta::kv_backend::KvBackendRef;
@@ -38,6 +38,7 @@ use operator::statement::{
StatementExecutorRef,
};
use operator::table::TableMutationOperator;
use operator::write_dispatcher::WriteDispatcher;
use partition::cache::PartitionInfoCacheRef;
use partition::manager::PartitionRuleManager;
use pipeline::pipeline_operator::PipelineOperator;
@@ -57,7 +58,7 @@ pub struct FrontendBuilder {
options: FrontendOptions,
kv_backend: KvBackendRef,
layered_cache_registry: LayeredCacheRegistryRef,
local_cache_invalidator: Option<CacheInvalidatorRef>,
local_cache_invalidator: CacheInvalidatorRef,
catalog_manager: CatalogManagerRef,
node_manager: NodeManagerRef,
plugins: Option<Plugins>,
@@ -66,6 +67,9 @@ pub struct FrontendBuilder {
}
impl FrontendBuilder {
/// Creates a frontend builder from its configuration and shared services.
///
/// Uses the layered cache registry for local invalidation unless overridden.
#[allow(clippy::too_many_arguments)]
pub fn new(
options: FrontendOptions,
@@ -79,8 +83,8 @@ impl FrontendBuilder {
Self {
options,
kv_backend,
local_cache_invalidator: layered_cache_registry.clone(),
layered_cache_registry,
local_cache_invalidator: None,
catalog_manager,
node_manager,
plugins: None,
@@ -125,9 +129,10 @@ impl FrontendBuilder {
)
}
/// Overrides the default local cache invalidator.
pub fn with_local_cache_invalidator(self, cache_invalidator: CacheInvalidatorRef) -> Self {
Self {
local_cache_invalidator: Some(cache_invalidator),
local_cache_invalidator: cache_invalidator,
..self
}
}
@@ -167,7 +172,11 @@ impl FrontendBuilder {
}
}
/// Validates configuration and assembles the frontend [`Instance`].
pub async fn try_build(self) -> Result<Instance> {
if let Err(reason) = self.options.write_retry.validate() {
return error::InvalidWriteRetryConfigSnafu { reason }.fail();
}
let kv_backend = self.kv_backend;
let node_manager = self.node_manager;
let plugins = self.plugins.unwrap_or_default();
@@ -190,9 +199,18 @@ impl FrontendBuilder {
partition_info_cache.clone(),
));
let local_cache_invalidator = self
.local_cache_invalidator
.unwrap_or_else(|| Arc::new(DummyCacheInvalidator));
let local_cache_invalidator = self.local_cache_invalidator;
let mut write_dispatcher =
WriteDispatcher::new(node_manager.clone(), partition_manager.clone());
if self.options.write_retry.max_retries > 0 {
write_dispatcher = write_dispatcher.with_retry(
self.options.write_retry.clone(),
self.catalog_manager.clone(),
local_cache_invalidator.clone(),
);
}
let write_dispatcher = Arc::new(write_dispatcher);
let region_query_handler =
if let Some(factory) = plugins.get::<RegionQueryHandlerFactoryRef>() {
@@ -208,18 +226,24 @@ impl FrontendBuilder {
name: TABLE_FLOWNODE_SET_CACHE_NAME,
})?;
let inserter = Arc::new(Inserter::new(
self.catalog_manager.clone(),
partition_manager.clone(),
node_manager.clone(),
table_flownode_cache,
self.options.auto_create_table,
));
let deleter = Arc::new(Deleter::new(
self.catalog_manager.clone(),
partition_manager.clone(),
node_manager.clone(),
));
let inserter = Arc::new(
Inserter::new(
self.catalog_manager.clone(),
partition_manager.clone(),
node_manager.clone(),
table_flownode_cache,
self.options.auto_create_table,
)
.with_write_dispatcher(write_dispatcher.clone()),
);
let deleter = Arc::new(
Deleter::new(
self.catalog_manager.clone(),
partition_manager.clone(),
node_manager.clone(),
)
.with_write_dispatcher(write_dispatcher),
);
let requester = Arc::new(Requester::new(
self.catalog_manager.clone(),
partition_manager.clone(),
@@ -315,3 +339,76 @@ impl FrontendBuilder {
})
}
}
#[cfg(test)]
mod tests {
use api::v1::meta::Role;
use common_meta::cache_invalidator::{Context, DummyCacheInvalidator};
use common_meta::instruction::CacheIdent;
use common_meta::key::table_route::{TableRouteKey, TableRouteValue};
use common_meta::key::{MetadataKey, MetadataValue};
use common_meta::rpc::router::{Region, RegionRoute};
use common_meta::rpc::store::PutRequest;
use meta_client::client::MetaClientBuilder;
use store_api::storage::RegionId;
use super::*;
#[tokio::test]
async fn test_local_cache_invalidator() {
for custom_invalidator in [false, true] {
let mut builder = FrontendBuilder::new_test(
&FrontendOptions::default(),
Arc::new(MetaClientBuilder::new(0, Role::Frontend).build()),
);
if custom_invalidator {
builder = builder.with_local_cache_invalidator(Arc::new(DummyCacheInvalidator));
}
let backend = builder.kv_backend.clone();
let routes: TableRouteCacheRef = builder.layered_cache_registry.get().unwrap();
let partitions: PartitionInfoCacheRef = builder.layered_cache_registry.get().unwrap();
let instance = builder.try_build().await.unwrap();
let table_id = 1024;
for region_number in [1, 2] {
let route = TableRouteValue::physical(vec![RegionRoute {
region: Region {
id: RegionId::new(table_id, region_number),
..Default::default()
},
..Default::default()
}]);
backend
.put(
PutRequest::new()
.with_key(TableRouteKey::new(table_id).to_bytes())
.with_value(route.try_as_raw_value().unwrap()),
)
.await
.unwrap();
if region_number == 1 {
routes.get(table_id).await.unwrap().unwrap();
partitions.get(table_id).await.unwrap().unwrap();
}
}
assert!(routes.contains_key(&table_id));
assert!(partitions.contains_key(&table_id));
instance
.cache_invalidator()
.invalidate(&Context::default(), &[CacheIdent::TableId(table_id)])
.await
.unwrap();
assert_eq!(custom_invalidator, routes.contains_key(&table_id));
assert_eq!(custom_invalidator, partitions.contains_key(&table_id));
let route = routes.get(table_id).await.unwrap().unwrap();
let region = route.as_physical_table_route_ref().unwrap().region_routes[0]
.region
.id;
assert_eq!(
if custom_invalidator { 1 } else { 2 },
region.region_number()
);
}
}
}
+6 -1
View File
@@ -543,7 +543,12 @@ impl Instance {
| StatusCode::TableColumnNotFound => ChunkFailureReaction::RetryPerSpan,
StatusCode::DatabaseNotFound => ChunkFailureReaction::DiscardChunk,
StatusCode::Cancelled | StatusCode::DeadlineExceeded => ChunkFailureReaction::Propagate,
_ if status.is_retryable() => ChunkFailureReaction::Propagate,
StatusCode::StorageUnavailable
| StatusCode::RuntimeResourcesExhausted
| StatusCode::Internal
| StatusCode::RegionNotReady
| StatusCode::TableUnavailable
| StatusCode::RegionBusy => ChunkFailureReaction::Propagate,
_ => ChunkFailureReaction::DiscardChunk,
}
}
+11 -1
View File
@@ -77,7 +77,17 @@ impl RegionInvoker {
#[async_trait]
impl Datanode for RegionInvoker {
async fn handle(&self, request: RegionRequest) -> MetaResult<RegionResponse> {
async fn handle_request(&self, request: Arc<RegionRequest>) -> MetaResult<RegionResponse> {
// Local execution consumes the request; standalone does not retain it for retries.
let request = Arc::try_unwrap(request)
.map_err(|_| {
InvalidRegionRequestSnafu {
reason: "local region request has multiple owners",
}
.build()
})
.map_err(BoxedError::new)
.context(meta_error::ExternalSnafu)?;
let span = request
.header
.as_ref()
+1
View File
@@ -129,6 +129,7 @@ where
PendingRowsBatcher::try_new(
self.instance.partition_manager().clone(),
self.instance.node_manager().clone(),
self.instance.inserter().write_dispatcher().clone(),
self.instance.catalog_manager().clone(),
opts.prom_store.with_metric_engine,
self.instance.clone(),
+1
View File
@@ -24,6 +24,7 @@ pub use influxdb::{InfluxdbMergeMode, InfluxdbOptions};
pub use jaeger::JaegerOptions;
pub use mysql::MysqlOptions;
pub use opentsdb::OpentsdbOptions;
pub use operator::write_dispatcher::WriteRetryOptions;
pub use otlp::OtlpOptions;
pub use postgres::PostgresOptions;
pub use prom_store::PromStoreOptions;
+29 -1
View File
@@ -14,10 +14,12 @@
use std::any::Any;
use common_error::ext::ErrorExt;
use common_error::ext::{ErrorExt, RetryHint, retry_hint_from_io_error};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use common_runtime::error::Error as RuntimeError;
use common_wal::kafka::rskafka_client_error_to_retry_hint;
use object_store::error::retry_hint_from_opendal_error;
use serde_json::error::Error as JsonError;
use snafu::{Location, Snafu};
use store_api::storage::RegionId;
@@ -375,4 +377,30 @@ impl ErrorExt for Error {
| ConsumeRecord { error, .. } => rskafka_client_error_to_status_code(error),
}
}
fn retry_hint(&self) -> RetryHint {
use Error::*;
match self {
CreateWriter { error, .. } | WriteIndex { error, .. } | ReadIndex { error, .. } => {
retry_hint_from_opendal_error(error)
}
Io { error, .. } => retry_hint_from_io_error(error),
FetchEntry { .. } | RaftEngine { .. } | AddEntryLogBatch { .. } => RetryHint::Retryable,
ProduceRecord { error, .. } => match error {
rskafka::client::producer::Error::Client(error) => {
rskafka_client_error_to_retry_hint(error)
}
rskafka::client::producer::Error::Aggregator(_)
| rskafka::client::producer::Error::FlushError(_)
| rskafka::client::producer::Error::TooLarge => RetryHint::NonRetryable,
},
BuildClient { error, .. }
| BuildPartitionClient { error, .. }
| BatchProduce { error, .. }
| GetOffset { error, .. }
| ConsumeRecord { error, .. } => rskafka_client_error_to_retry_hint(error),
_ => RetryHint::NonRetryable,
}
}
}
+73 -1
View File
@@ -13,7 +13,7 @@
// limitations under the License.
use common_error::define_from_tonic_status;
use common_error::ext::ErrorExt;
use common_error::ext::{ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use snafu::{Location, Snafu};
@@ -34,6 +34,7 @@ pub enum Error {
code: StatusCode,
msg: String,
tonic_code: tonic::Code,
retry_hint: RetryHint,
#[snafu(implicit)]
location: Location,
},
@@ -156,6 +157,18 @@ impl ErrorExt for Error {
| Error::GetFlowStat { source, .. } => source.status_code(),
}
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::MetaServer { retry_hint, .. } => *retry_hint,
Error::InvalidResponseHeader { source, .. }
| Error::ConvertMetaRequest { source, .. }
| Error::ConvertMetaResponse { source, .. }
| Error::GetFlowStat { source, .. } => source.retry_hint(),
Error::CreateChannel { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
impl Error {
@@ -171,3 +184,62 @@ impl Error {
}
define_from_tonic_status!(Error, MetaServer);
#[cfg(test)]
mod tests {
use common_error::ext::{ErrorExt, RetryHint};
use common_error::{GREPTIME_DB_HEADER_ERROR_CODE, GREPTIME_DB_HEADER_ERROR_RETRY_HINT};
use tonic::codegen::http::{HeaderMap, HeaderValue};
use tonic::metadata::MetadataMap;
use super::*;
#[test]
fn test_from_tonic_status_fallbacks_to_status_code() {
let status = tonic::Status::new(tonic::Code::Internal, "blabla");
let err: Error = status.into();
assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
}
#[test]
fn test_from_tonic_status_fallback_can_be_non_retryable() {
let mut headers = HeaderMap::new();
headers.insert(
GREPTIME_DB_HEADER_ERROR_CODE,
HeaderValue::from(StatusCode::InvalidArguments as u32),
);
let status = tonic::Status::with_metadata(
tonic::Code::Internal,
"blabla",
MetadataMap::from_headers(headers),
);
let err: Error = status.into();
assert_eq!(err.retry_hint(), RetryHint::NonRetryable);
}
#[test]
fn test_from_tonic_status_with_retry_hint() {
let mut headers = HeaderMap::new();
headers.insert(
GREPTIME_DB_HEADER_ERROR_CODE,
HeaderValue::from(StatusCode::Internal as u32),
);
headers.insert(
GREPTIME_DB_HEADER_ERROR_RETRY_HINT,
HeaderValue::from_static(RetryHint::Retryable.as_str()),
);
let status = tonic::Status::with_metadata(
tonic::Code::Internal,
"blabla",
MetadataMap::from_headers(headers),
);
let err: Error = status.into();
assert_eq!(err.retry_hint(), RetryHint::Retryable);
}
}
+50 -32
View File
@@ -13,12 +13,13 @@
// limitations under the License.
use common_error::define_into_tonic_status;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use common_meta::DatanodeId;
use common_procedure::ProcedureId;
use common_runtime::JoinError;
use common_wal::kafka::rskafka_client_error_to_retry_hint;
use snafu::{Location, Snafu};
use store_api::storage::RegionId;
use table::metadata::TableId;
@@ -1131,29 +1132,7 @@ pub enum Error {
impl Error {
/// Returns `true` if the error is retryable.
pub fn is_retryable(&self) -> bool {
matches!(
self,
Error::RetryLater { .. }
| Error::RetryLaterWithSource { .. }
| Error::MailboxTimeout { .. }
) || matches!(
self,
Error::AllocateRegions { source, .. } if source.is_retry_later()
) || matches!(
self,
Error::DeallocateRegions { source, .. } if source.is_retry_later()
) || matches!(
self,
Error::DeleteRecords { error, .. }
| Error::BuildPartitionClient { error, .. }
| Error::GetOffset { error, .. }
if Self::is_retryable_kafka_client_error(error)
)
}
/// Returns `true` if the Kafka client has exhausted its internal retry.
fn is_retryable_kafka_client_error(err: &rskafka::client::error::Error) -> bool {
matches!(err, rskafka::client::error::Error::RetryFailed(_))
self.retry_hint().is_retryable()
}
}
@@ -1319,6 +1298,35 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::RetryLater { .. }
| Error::RetryLaterWithSource { .. }
| Error::MailboxTimeout { .. }
| Error::NoEnoughAvailableNode { .. }
| Error::NoLeader { .. }
| Error::LeaderLeaseExpired { .. }
| Error::LeaderLeaseChanged { .. }
| Error::PeerUnavailable { .. } => RetryHint::Retryable,
Error::AllocateRegions { source, .. } | Error::DeallocateRegions { source, .. }
if source.retry_hint().is_retryable() =>
{
RetryHint::Retryable
}
Error::DeleteRecords { error, .. }
| Error::BuildPartitionClient { error, .. }
| Error::GetOffset { error, .. } => rskafka_client_error_to_retry_hint(error),
Error::PusherNotFound { .. }
| Error::PushMessage { .. }
| Error::ExceededDeadline { .. } => RetryHint::NonRetryable,
_ => RetryHint::NonRetryable,
}
}
}
// for form tonic
@@ -1346,6 +1354,7 @@ pub(crate) fn match_for_io_error(err_status: &tonic::Status) -> Option<&std::io:
mod tests {
use std::time::Duration;
use common_error::ext::ErrorExt;
use common_error::mock::MockError;
use common_error::status_code::StatusCode;
use rskafka::BackoffError;
@@ -1371,6 +1380,7 @@ mod tests {
.unwrap_err();
assert!(err.is_retryable());
assert!(err.retry_hint().is_retryable());
}
#[test]
@@ -1384,6 +1394,7 @@ mod tests {
.unwrap_err();
assert!(!err.is_retryable());
assert!(!err.retry_hint().is_retryable());
}
#[test]
@@ -1410,24 +1421,28 @@ mod tests {
assert!(delete_records_err.is_retryable());
assert!(build_partition_client_err.is_retryable());
assert!(get_offset_err.is_retryable());
assert!(delete_records_err.retry_hint().is_retryable());
assert!(build_partition_client_err.retry_hint().is_retryable());
assert!(get_offset_err.retry_hint().is_retryable());
}
#[test]
fn test_kafka_non_retry_failed_errors_are_not_retryable() {
let delete_records_err = Err::<(), _>(KafkaClientError::Timeout)
let delete_records_err = Err::<(), _>(KafkaClientError::InvalidResponse("invalid".into()))
.context(DeleteRecordsSnafu {
topic: "test_topic",
partition: 0,
offset: 1024u64,
})
.unwrap_err();
let build_partition_client_err = Err::<(), _>(KafkaClientError::Timeout)
.context(BuildPartitionClientSnafu {
topic: "test_topic",
partition: 0,
})
.unwrap_err();
let get_offset_err = Err::<(), _>(KafkaClientError::Timeout)
let build_partition_client_err =
Err::<(), _>(KafkaClientError::InvalidResponse("invalid".into()))
.context(BuildPartitionClientSnafu {
topic: "test_topic",
partition: 0,
})
.unwrap_err();
let get_offset_err = Err::<(), _>(KafkaClientError::InvalidResponse("invalid".into()))
.context(GetOffsetSnafu {
topic: "test_topic",
})
@@ -1436,5 +1451,8 @@ mod tests {
assert!(!delete_records_err.is_retryable());
assert!(!build_partition_client_err.is_retryable());
assert!(!get_offset_err.is_retryable());
assert!(!delete_records_err.retry_hint().is_retryable());
assert!(!build_partition_client_err.retry_hint().is_retryable());
assert!(!get_offset_err.retry_hint().is_retryable());
}
}
+23 -1
View File
@@ -348,6 +348,19 @@ mod tests {
#[tokio::test]
async fn test_bulk_insert_physical_region_passthrough() {
check_bulk_insert_physical_region_passthrough(false).await;
}
#[tokio::test]
async fn test_physical_bulk_partition_columns_preserve_stored_rows() {
let stripped = check_bulk_insert_physical_region_passthrough(false).await;
let retained = check_bulk_insert_physical_region_passthrough(true).await;
assert_eq!(retained, stripped);
}
async fn check_bulk_insert_physical_region_passthrough(
retain_partition_columns: bool,
) -> String {
// Use flat format so that BulkMemtable is used (supports write_bulk).
let mito_config = MitoConfig {
default_flat_format: true,
@@ -376,7 +389,11 @@ mod tests {
index: 2,
column_id: 2, // column_id for "job" in the physical table
}];
let non_tag_indices = vec![0, 1]; // timestamp, value
let non_tag_indices = if retain_partition_columns {
vec![0, 1, 2] // timestamp, value, and the job partition column
} else {
vec![0, 1] // timestamp, value
};
let second_batch = build_logical_batch(3, 3);
let physical_batch = modify_batch_sparse(
second_batch,
@@ -385,6 +402,10 @@ mod tests {
&non_tag_indices,
)
.unwrap();
assert_eq!(
physical_batch.column_by_name("job").is_some(),
retain_partition_columns
);
let request = build_bulk_request(physical_region_id, physical_batch);
let response = env
.metric()
@@ -401,6 +422,7 @@ mod tests {
.unwrap();
let batches = RecordBatches::try_collect(stream).await.unwrap();
assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 6);
batches.pretty_print().unwrap()
}
#[tokio::test]
+47 -1
View File
@@ -15,7 +15,7 @@
use std::any::Any;
use std::sync::Arc;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use datatypes::prelude::ConcreteDataType;
@@ -464,4 +464,50 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
use Error::*;
match self {
PhysicalRegionNotFound { .. } | LogicalRegionNotFound { .. } => {
RetryHint::RetryAfterRouteRefresh
}
CreateMitoRegion { source, .. }
| OpenMitoRegion { source, .. }
| BatchOpenMitoRegion { source, .. }
| BatchCatchupMitoRegion { source, .. }
| CloseMitoRegion { source, .. }
| MitoReadOperation { source, .. }
| MitoWriteOperation { source, .. }
| MitoFlushOperation { source, .. }
| MitoSyncOperation { source, .. }
| MitoEnterStagingOperation { source, .. }
| MitoCopyRegionFromOperation { source, .. }
| MitoEditRegion { source, .. } => source.retry_hint(),
EncodePrimaryKey { source, .. } => source.retry_hint(),
CollectRecordBatchStream { source, .. } => source.retry_hint(),
StartRepeatedTask { source, .. } => source.retry_hint(),
CacheGet { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_missing_region_retry_hints() {
let region_id = RegionId::new(1024, 1);
for error in [
PhysicalRegionNotFoundSnafu { region_id }.build(),
LogicalRegionNotFoundSnafu { region_id }.build(),
] {
assert_eq!(error.status_code(), StatusCode::RegionNotFound);
assert_eq!(error.retry_hint(), RetryHint::RetryAfterRouteRefresh);
}
}
}
+8
View File
@@ -67,6 +67,13 @@ pub enum Error {
location: Location,
},
#[snafu(display("Invalid sparse primary key: {}", reason))]
InvalidSparsePrimaryKey {
reason: String,
#[snafu(implicit)]
location: Location,
},
#[snafu(display("Encode null value"))]
IndexEncodeNull {
#[snafu(implicit)]
@@ -94,6 +101,7 @@ impl ErrorExt for Error {
StatusCode::InvalidArguments
}
NotSupportedField { .. } | UnsupportedOperation { .. } => StatusCode::Unsupported,
InvalidSparsePrimaryKey { .. } => StatusCode::InvalidArguments,
EvaluateFilter { source, .. } => source.status_code(),
}
}
+71 -2
View File
@@ -21,13 +21,16 @@ use datatypes::prelude::ConcreteDataType;
use datatypes::value::{Value, ValueRef};
use memcomparable::{Deserializer, Serializer};
use serde::{Deserialize, Serialize};
use snafu::ResultExt;
use snafu::{ResultExt, ensure};
use store_api::codec::PrimaryKeyEncoding;
use store_api::metadata::RegionMetadataRef;
use store_api::storage::ColumnId;
use store_api::storage::consts::ReservedColumnId;
use crate::error::{DeserializeFieldSnafu, Result, SerializeFieldSnafu, UnsupportedOperationSnafu};
use crate::error::{
DeserializeFieldSnafu, InvalidSparsePrimaryKeySnafu, Result, SerializeFieldSnafu,
UnsupportedOperationSnafu,
};
use crate::key_values::KeyValue;
use crate::primary_key_filter::SparsePrimaryKeyFilter;
use crate::row_converter::dense::SortField;
@@ -346,6 +349,57 @@ impl SparsePrimaryKeyCodec {
Ok(())
}
/// Decodes the reserved `(table_id, tsid)` prefix from a sparse primary key.
pub fn decode_ids(&self, bytes: &[u8]) -> Result<(u32, u64)> {
// Two column IDs, two non-null markers, a u32 table ID, and a u64 TSID.
const INTERNAL_PREFIX_LEN: usize = 4 + 1 + 4 + 4 + 1 + 8;
ensure!(
bytes.len() >= INTERNAL_PREFIX_LEN,
InvalidSparsePrimaryKeySnafu {
reason: format!(
"internal prefix requires at least {INTERNAL_PREFIX_LEN} bytes, got {}",
bytes.len()
),
}
);
let mut deserializer = Deserializer::new(bytes);
let table_id_column = u32::deserialize(&mut deserializer).context(DeserializeFieldSnafu)?;
ensure!(
table_id_column == RESERVED_COLUMN_ID_TABLE_ID,
InvalidSparsePrimaryKeySnafu {
reason: format!(
"expected table id column {}, got {}",
RESERVED_COLUMN_ID_TABLE_ID, table_id_column
),
}
);
let table_id = self.inner.table_id_field.deserialize(&mut deserializer)?;
let tsid_column = u32::deserialize(&mut deserializer).context(DeserializeFieldSnafu)?;
ensure!(
tsid_column == RESERVED_COLUMN_ID_TSID,
InvalidSparsePrimaryKeySnafu {
reason: format!(
"expected tsid column {}, got {}",
RESERVED_COLUMN_ID_TSID, tsid_column
),
}
);
let tsid = self.inner.tsid_field.deserialize(&mut deserializer)?;
match (table_id, tsid) {
(Value::UInt32(table_id), Value::UInt64(tsid)) => Ok((table_id, tsid)),
(table_id, tsid) => InvalidSparsePrimaryKeySnafu {
reason: format!(
"expected UInt32 table id and UInt64 tsid, got {table_id:?} and {tsid:?}"
),
}
.fail(),
}
}
/// Decodes the given bytes into a [`SparseValues`].
fn decode_sparse(&self, bytes: &[u8]) -> Result<SparseValues> {
let mut deserializer = Deserializer::new(bytes);
@@ -805,6 +859,21 @@ mod tests {
assert_eq!(result, Value::UInt32(42));
}
#[test]
fn test_decode_ids() {
let region_metadata = test_region_metadata();
let codec = SparsePrimaryKeyCodec::new(&region_metadata);
let mut buffer = Vec::new();
codec.encode_internal(42, 100, &mut buffer).unwrap();
assert_eq!((42, 100), codec.decode_ids(&buffer).unwrap());
let mut invalid = buffer.clone();
invalid[0..4].copy_from_slice(&1_u32.to_be_bytes());
assert!(codec.decode_ids(&invalid).is_err());
assert!(codec.decode_ids(&buffer[..buffer.len() - 1]).is_err());
}
#[test]
fn test_has_column() {
let region_metadata = test_region_metadata();
+50 -20
View File
@@ -18,11 +18,14 @@ use std::sync::Arc;
use std::time::Duration;
use std::{assert_matches, fs};
use api::v1::Rows;
use common_error::ext::ErrorExt;
use api::v1::{ArrowIpc, Rows};
use common_error::ext::{ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_function::utils::partition_expr_version;
use common_grpc::flight;
use common_recordbatch::RecordBatches;
use datatypes::arrow::array::{ArrayRef, Float64Array, StringArray, TimestampMillisecondArray};
use datatypes::arrow::record_batch::RecordBatch;
use datatypes::value::Value;
use object_store::Buffer;
use object_store::layers::mock::{
@@ -34,8 +37,9 @@ use store_api::region_engine::{
RegionEngine, RemapManifestsRequest, SetRegionRoleStateResponse, SettableRegionRoleState,
};
use store_api::region_request::{
ApplyStagingManifestRequest, EnterStagingRequest, RegionAlterRequest, RegionFlushRequest,
RegionPutRequest, RegionRequest, RegionTruncateRequest, StagingPartitionDirective,
ApplyStagingManifestRequest, EnterStagingRequest, RegionAlterRequest, RegionBulkInsertsRequest,
RegionFlushRequest, RegionPutRequest, RegionRequest, RegionTruncateRequest,
StagingPartitionDirective,
};
use store_api::storage::{RegionId, ScanRequest};
@@ -252,7 +256,7 @@ fn default_partition_expr() -> String {
}
#[tokio::test]
async fn test_staging_reject_all_writes_rejects_put() {
async fn test_staging_reject_all_writes_rejects_put_and_bulk() {
let mut env = TestEnv::new().await;
let engine = env.create_engine(MitoConfig::default()).await;
@@ -279,22 +283,48 @@ async fn test_staging_reject_all_writes_rejects_put() {
schema: column_schemas,
rows: build_rows(0, 2),
};
let err = engine
.handle_request(
let payload = RecordBatch::try_from_iter([
(
"tag_0",
Arc::new(StringArray::from(vec!["0", "1"])) as ArrayRef,
),
(
"field_0",
Arc::new(Float64Array::from(vec![0.0, 1.0])) as ArrayRef,
),
(
"ts",
Arc::new(TimestampMillisecondArray::from(vec![0, 1000])) as ArrayRef,
),
])
.unwrap();
let (schema, data_header, data) = flight::record_batch_to_ipc(payload.clone()).unwrap();
for request in [
RegionRequest::Put(RegionPutRequest {
rows,
hint: None,
partition_expr_version: None,
}),
RegionRequest::BulkInserts(RegionBulkInsertsRequest {
region_id,
RegionRequest::Put(RegionPutRequest {
rows,
hint: None,
partition_expr_version: None,
}),
)
.await
.unwrap_err();
assert_eq!(err.status_code(), StatusCode::StorageUnavailable);
assert_matches!(
err.into_inner().as_any().downcast_ref::<Error>().unwrap(),
Error::RejectWrite { .. }
);
payload,
raw_data: ArrowIpc {
schema,
data_header,
payload: data,
},
partition_expr_version: None,
aligned_schema_version: None,
}),
] {
let err = engine.handle_request(region_id, request).await.unwrap_err();
assert_eq!(err.status_code(), StatusCode::StorageUnavailable);
assert_eq!(err.retry_hint(), RetryHint::RetryAfterRouteRefresh);
assert_matches!(
err.into_inner().as_any().downcast_ref::<Error>().unwrap(),
Error::RejectWriteInStaging { .. }
);
}
}
#[tokio::test]
+155 -2
View File
@@ -16,7 +16,7 @@ use std::any::Any;
use std::sync::Arc;
use common_datasource::compression::CompressionType;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use common_memory_manager;
@@ -26,6 +26,7 @@ use common_time::timestamp::TimeUnit;
use datatypes::arrow::error::ArrowError;
use datatypes::prelude::ConcreteDataType;
use object_store::ErrorKind;
use object_store::error::retry_hint_from_opendal_error;
use partition::error::Error as PartitionError;
use prost::DecodeError;
use snafu::{Location, Snafu};
@@ -548,6 +549,13 @@ pub enum Error {
location: Location,
},
#[snafu(display("Region {} rejects writes while in staging", region_id))]
RejectWriteInStaging {
region_id: RegionId,
#[snafu(implicit)]
location: Location,
},
#[snafu(display("Failed to compact region {}", region_id))]
CompactRegion {
region_id: RegionId,
@@ -1412,7 +1420,7 @@ impl ErrorExt for Error {
RegionDropped { .. } => StatusCode::Cancelled,
RegionClosed { .. } => StatusCode::Cancelled,
RegionTruncated { .. } => StatusCode::Cancelled,
RejectWrite { .. } => StatusCode::StorageUnavailable,
RejectWrite { .. } | RejectWriteInStaging { .. } => StatusCode::StorageUnavailable,
CompactRegion { source, .. } => source.status_code(),
EditRegion { source, .. } => source.status_code(),
CompatReader { .. } => StatusCode::Unexpected,
@@ -1498,4 +1506,149 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
use Error::*;
match self {
PartitionExprVersionMismatch { .. }
| RegionNotFound { .. }
| RejectWriteInStaging { .. }
| RegionState {
state: RegionRoleState::Follower,
..
} => RetryHint::RetryAfterRouteRefresh,
ReadParquet { .. }
| WriteParquet { .. }
| RejectWrite { .. }
| Download { .. }
| Upload { .. }
| RegionState { .. }
| UpdateManifest { .. }
| RegionStopped { .. }
| RegionBusy { .. }
| FlushableRegionState { .. } => RetryHint::Retryable,
OpenDal { error, .. }
| DeleteSsts { error, .. }
| DeleteIndex { error, .. }
| DeleteIndexes { error, .. } => retry_hint_from_opendal_error(error),
WriteWal { source, .. }
| ReadWal { source, .. }
| DeleteWal { source, .. }
| FetchManifests { source, .. }
| External { source, .. } => source.retry_hint(),
OpenRegion { source, .. }
| WriteGroup { source, .. }
| FlushRegion { source, .. }
| BuildIndexAsync { source, .. }
| CompactRegion { source, .. }
| EditRegion { source, .. }
| ScanSeries { source, .. }
| PruneFile { source, .. } => source.retry_hint(),
DataTypeMismatch { source, .. }
| ConvertVector { source, .. }
| ConvertValue { source, .. }
| IndexOptions { source, .. }
| CastVector { source, .. } => source.retry_hint(),
BuildIndexApplier { source, .. }
| PushIndexValue { source, .. }
| ApplyInvertedIndex { source, .. }
| IndexFinish { source, .. } => source.retry_hint(),
ApplyBloomFilterIndex { source, .. }
| PushBloomFilterValue { source, .. }
| BloomFilterFinish { source, .. } => source.retry_hint(),
PuffinReadBlob { source, .. }
| PuffinAddBlob { source, .. }
| PuffinInitStager { source, .. }
| PuffinBuildReader { source, .. }
| PuffinPurgeStager { source, .. } => source.retry_hint(),
CreateFulltextCreator { source, .. }
| FulltextPushText { source, .. }
| FulltextFinish { source, .. }
| ApplyFulltextIndex { source, .. } => source.retry_hint(),
InvalidRegionRequest { source, .. } => source.retry_hint(),
InvalidPartitionExpr { source, .. } => source.retry_hint(),
RecordBatch { source, .. } => source.retry_hint(),
GetSchemaMetadata { source, .. } => source.retry_hint(),
CompactionMemoryExhausted { source, .. } => source.retry_hint(),
ConvertBulkWalEntry { source, .. } => source.retry_hint(),
Encode { source, .. } | Decode { source, .. } => source.retry_hint(),
#[cfg(feature = "enterprise")]
ScanExternalRange { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::region::RegionLeaderState;
#[test]
fn test_partition_version_mismatch_retry_hint() {
let error = PartitionExprVersionMismatchSnafu {
region_id: RegionId::new(1, 1),
request_version: 1u64,
expected_version: 2u64,
}
.build();
assert_eq!(error.status_code(), StatusCode::InvalidArguments);
assert_eq!(error.retry_hint(), RetryHint::RetryAfterRouteRefresh);
}
#[test]
fn test_region_state_retry_hint() {
let region_id = RegionId::new(1, 1);
let writable = RegionRoleState::Leader(RegionLeaderState::Writable);
let follower_error = RegionStateSnafu {
region_id,
state: RegionRoleState::Follower,
expect: writable,
}
.build();
assert_eq!(
follower_error.retry_hint(),
RetryHint::RetryAfterRouteRefresh
);
assert_eq!(follower_error.status_code(), StatusCode::RegionNotReady);
let leader_error = RegionStateSnafu {
region_id,
state: writable,
expect: RegionRoleState::Follower,
}
.build();
assert_eq!(leader_error.retry_hint(), RetryHint::Retryable);
for (error, status, hint) in [
(
RejectWriteSnafu { region_id }.build(),
StatusCode::StorageUnavailable,
RetryHint::Retryable,
),
(
RejectWriteInStagingSnafu { region_id }.build(),
StatusCode::StorageUnavailable,
RetryHint::RetryAfterRouteRefresh,
),
(
RegionNotFoundSnafu { region_id }.build(),
StatusCode::RegionNotFound,
RetryHint::RetryAfterRouteRefresh,
),
] {
assert_eq!(error.status_code(), status);
assert_eq!(error.retry_hint(), hint);
}
}
}
+9 -5
View File
@@ -27,7 +27,7 @@ use store_api::storage::RegionId;
use crate::error::{
InvalidRequestSnafu, PartitionExprVersionMismatchSnafu, RegionNotFoundSnafu, RegionStateSnafu,
RejectWriteSnafu, Result,
RejectWriteInStagingSnafu, RejectWriteSnafu, Result,
};
use crate::metrics;
use crate::metrics::{
@@ -320,7 +320,7 @@ impl<S> RegionWorkerLoop<S> {
if region.reject_all_writes_in_staging() {
sender_req
.sender
.send(RejectWriteSnafu { region_id }.fail());
.send(RejectWriteInStagingSnafu { region_id }.fail());
continue;
}
@@ -383,7 +383,7 @@ impl<S> RegionWorkerLoop<S> {
if region.reject_all_writes_in_staging() {
sender_req
.sender
.send(RejectWriteSnafu { region_id }.fail());
.send(RejectWriteInStagingSnafu { region_id }.fail());
continue;
}
let expected_version = region.expected_partition_expr_version();
@@ -464,7 +464,9 @@ impl<S> RegionWorkerLoop<S> {
RegionRoleState::Leader(RegionLeaderState::Writable)
| RegionRoleState::Leader(RegionLeaderState::Staging) => {
if region.reject_all_writes_in_staging() {
bulk_req.sender.send(RejectWriteSnafu { region_id }.fail());
bulk_req
.sender
.send(RejectWriteInStagingSnafu { region_id }.fail());
continue;
}
let region_ctx = RegionWriteCtx::new(
@@ -511,7 +513,9 @@ impl<S> RegionWorkerLoop<S> {
continue;
};
if region.reject_all_writes_in_staging() {
bulk_req.sender.send(RejectWriteSnafu { region_id }.fail());
bulk_req
.sender
.send(RejectWriteInStagingSnafu { region_id }.fail());
continue;
}
let expected_version = region.expected_partition_expr_version();
+17 -1
View File
@@ -15,7 +15,7 @@
use std::any::Any;
use common_macro::stack_trace_debug;
use common_telemetry::common_error::ext::ErrorExt;
use common_telemetry::common_error::ext::{ErrorExt, RetryHint};
use common_telemetry::common_error::status_code::StatusCode;
use snafu::{Location, Snafu};
@@ -56,6 +56,15 @@ pub enum Error {
pub type Result<T> = std::result::Result<T, Error>;
/// Converts an `opendal::Error` into a `RetryHint`.
pub fn retry_hint_from_opendal_error(error: &opendal::Error) -> RetryHint {
if error.is_temporary() {
RetryHint::Retryable
} else {
RetryHint::NonRetryable
}
}
impl ErrorExt for Error {
fn status_code(&self) -> StatusCode {
use Error::*;
@@ -69,4 +78,11 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::InitBackend { error, .. } => retry_hint_from_opendal_error(error),
_ => RetryHint::NonRetryable,
}
}
}
+6
View File
@@ -18,6 +18,7 @@ arrow.workspace = true
arrow-ipc.workspace = true
async-stream.workspace = true
async-trait.workspace = true
backon.workspace = true
bytes.workspace = true
catalog.workspace = true
chrono.workspace = true
@@ -47,12 +48,14 @@ file-engine.workspace = true
futures.workspace = true
futures-util.workspace = true
humantime.workspace = true
humantime-serde.workspace = true
itertools.workspace = true
jsonb.workspace = true
lazy_static.workspace = true
meta-client.workspace = true
meter-core.workspace = true
meter-macros.workspace = true
mito-codec.workspace = true
moka = { workspace = true, features = ["future"] }
object-store.workspace = true
partition.workspace = true
@@ -61,6 +64,7 @@ prost.workspace = true
prost-types = { workspace = true, optional = true }
query.workspace = true
regex.workspace = true
serde.workspace = true
serde_json.workspace = true
session.workspace = true
snafu.workspace = true
@@ -75,7 +79,9 @@ tonic.workspace = true
tracing.workspace = true
[dev-dependencies]
cache.workspace = true
catalog = { workspace = true, features = ["testing"] }
common-meta = { workspace = true, features = ["testing"] }
common-test-util.workspace = true
path-slash = "0.2"
tokio-stream = { workspace = true, features = ["net"] }
+141 -119
View File
@@ -14,13 +14,13 @@
use std::collections::HashSet;
use ahash::{HashMap, HashMapExt};
use api::v1::flow::{DirtyWindowRequest, DirtyWindowRequests};
use api::v1::region::{
BulkInsertRequest, RegionRequest, RegionRequestHeader, bulk_insert_request, region_request,
};
use api::v1::{ArrowIpc, PartitionExprVersion};
use arrow::array::Array;
use arrow::compute;
use arrow::record_batch::RecordBatch;
use bytes::Bytes;
use common_base::AffectedRows;
@@ -28,12 +28,16 @@ use common_grpc::FlightData;
use common_grpc::flight::{FlightEncoder, FlightMessage};
use common_telemetry::error;
use common_telemetry::tracing_context::TracingContext;
use futures::future;
use snafu::{OptionExt, ResultExt, ensure};
use store_api::storage::RegionId;
use table::TableRef;
use table::metadata::TableInfoRef;
use tokio_util::sync::CancellationToken;
use crate::error::Result;
use crate::insert::Inserter;
use crate::write_dispatcher::WriteAttempt;
use crate::{error, metrics};
impl Inserter {
@@ -91,12 +95,6 @@ impl Inserter {
.get(&region_number)
.copied()
.unwrap_or_default();
let datanode = self
.partition_manager
.find_region_leader(region_id)
.await
.context(error::FindRegionLeaderSnafu)?;
let request = RegionRequest {
header: Some(RegionRequestHeader {
tracing_context: TracingContext::from_current_span().to_w3c(),
@@ -115,12 +113,16 @@ impl Inserter {
})),
};
let _datanode_handle_timer = metrics::HANDLE_BULK_INSERT_ELAPSED
.with_label_values(&["datanode_handle"])
.start_timer();
let datanode = self.node_manager.datanode(&datanode).await;
let result = datanode
.handle(request)
let writes = self.write_dispatcher.prepare(vec![request]).await?;
let result = self
.write_dispatcher
.execute(
writes,
Some(
metrics::HANDLE_BULK_INSERT_ELAPSED.with_label_values(&["datanode_handle"]),
),
None,
)
.await
.context(error::RequestRegionSnafu)
.map(|r| r.affected_rows);
@@ -132,122 +134,142 @@ impl Inserter {
return result;
}
let mut mask_per_datanode = HashMap::with_capacity(region_masks.len());
for (region_number, mask) in region_masks {
let region_id = RegionId::new(table_id, region_number);
let datanode = self
.partition_manager
.find_region_leader(region_id)
.await
.context(error::FindRegionLeaderSnafu)?;
mask_per_datanode
.entry(datanode)
.or_insert_with(Vec::new)
.push((region_id, mask));
}
let regions = region_masks
.keys()
.map(|region| RegionId::new(table_id, *region))
.collect::<Vec<_>>();
let mut peers = self
.write_dispatcher
.resolve_peers(&regions)
.await
.context(error::FindRegionLeaderSnafu)?;
let wait_all_datanode_timer = metrics::HANDLE_BULK_INSERT_ELAPSED
.with_label_values(&["wait_all_datanode"])
.start_timer();
let mut handles = Vec::with_capacity(mask_per_datanode.len());
// Dropping the caller stops retries without abandoning in-flight writes.
let cancellation = CancellationToken::new();
let _guard = cancellation.clone().drop_guard();
let mut handles = Vec::with_capacity(region_masks.len());
for (peer, masks) in mask_per_datanode {
for (region_id, mask) in masks {
if mask.select_none() {
continue;
}
let partition_expr_version = partition_versions
.get(&region_id.region_number())
.copied()
.unwrap_or_default();
let rb = record_batch.clone();
let schema_bytes = schema_bytes.clone();
let node_manager = self.node_manager.clone();
let peer = peer.clone();
let raw_header_and_data = if mask.select_all() {
Some((
raw_flight_data.data_header.clone(),
raw_flight_data.data_body.clone(),
))
} else {
None
};
let handle: common_runtime::JoinHandle<error::Result<api::region::RegionResponse>> =
common_runtime::spawn_global(async move {
let (header, payload) = if mask.select_all() {
// SAFETY: raw data must be present, we can avoid re-encoding.
raw_header_and_data.unwrap()
} else {
let filter_timer = metrics::HANDLE_BULK_INSERT_ELAPSED
.with_label_values(&["filter"])
.start_timer();
let batch = arrow::compute::filter_record_batch(&rb, mask.array())
.context(error::ComputeArrowSnafu)?;
filter_timer.observe_duration();
metrics::BULK_REQUEST_ROWS
.with_label_values(&["rows_per_region"])
.observe(batch.num_rows() as f64);
let encode_timer = metrics::HANDLE_BULK_INSERT_ELAPSED
.with_label_values(&["encode"])
.start_timer();
let mut iter = FlightEncoder::default()
.encode(FlightMessage::RecordBatch(batch))
.into_iter();
let Some(flight_data) = iter.next() else {
// Safety: `iter` on a type of `Vec1`, which is guaranteed to have
// at least one element.
unreachable!()
};
ensure!(
iter.next().is_none(),
error::NotSupportedSnafu {
feat: "bulk insert RecordBatch with dictionary arrays",
}
);
encode_timer.observe_duration();
(flight_data.data_header, flight_data.data_body)
};
let _datanode_handle_timer = metrics::HANDLE_BULK_INSERT_ELAPSED
.with_label_values(&["datanode_handle"])
.start_timer();
let request = RegionRequest {
header: Some(RegionRequestHeader {
tracing_context: TracingContext::from_current_span().to_w3c(),
..Default::default()
}),
body: Some(region_request::Body::BulkInsert(BulkInsertRequest {
region_id: region_id.as_u64(),
partition_expr_version: partition_expr_version
.map(|value| PartitionExprVersion { value }),
aligned_schema_version: None,
body: Some(bulk_insert_request::Body::ArrowIpc(ArrowIpc {
schema: schema_bytes,
data_header: header,
payload,
})),
})),
};
let datanode = node_manager.datanode(&peer).await;
datanode
.handle(request)
.await
.context(error::RequestRegionSnafu)
});
handles.push(handle);
for (region_number, mask) in region_masks {
let region_id = RegionId::new(table_id, region_number);
if mask.select_none() {
continue;
}
let partition_expr_version = partition_versions
.get(&region_id.region_number())
.copied()
.unwrap_or_default();
let peer = peers
.remove(&region_id)
.context(partition::error::FindLeaderSnafu {
region_id,
table_id,
})
.context(error::FindRegionLeaderSnafu)?;
let dispatcher = self.write_dispatcher.clone();
let rb = record_batch.clone();
let schema_bytes = schema_bytes.clone();
let raw_header_and_data = if mask.select_all() {
Some((
raw_flight_data.data_header.clone(),
raw_flight_data.data_body.clone(),
))
} else {
None
};
let handle: common_runtime::JoinHandle<Result<WriteAttempt>> =
common_runtime::spawn_global(async move {
let (header, payload) = if mask.select_all() {
// SAFETY: raw data must be present, we can avoid re-encoding.
raw_header_and_data.unwrap()
} else {
let filter_timer = metrics::HANDLE_BULK_INSERT_ELAPSED
.with_label_values(&["filter"])
.start_timer();
let batch = compute::filter_record_batch(&rb, mask.array())
.context(error::ComputeArrowSnafu)?;
filter_timer.observe_duration();
metrics::BULK_REQUEST_ROWS
.with_label_values(&["rows_per_region"])
.observe(batch.num_rows() as f64);
let encode_timer = metrics::HANDLE_BULK_INSERT_ELAPSED
.with_label_values(&["encode"])
.start_timer();
let mut iter = FlightEncoder::default()
.encode(FlightMessage::RecordBatch(batch))
.into_iter();
let Some(flight_data) = iter.next() else {
// Safety: `iter` on a type of `Vec1`, which is guaranteed to have
// at least one element.
unreachable!()
};
ensure!(
iter.next().is_none(),
error::NotSupportedSnafu {
feat: "bulk insert RecordBatch with dictionary arrays",
}
);
encode_timer.observe_duration();
(flight_data.data_header, flight_data.data_body)
};
let request = RegionRequest {
header: Some(RegionRequestHeader {
tracing_context: TracingContext::from_current_span().to_w3c(),
..Default::default()
}),
body: Some(region_request::Body::BulkInsert(BulkInsertRequest {
region_id: region_id.as_u64(),
partition_expr_version: partition_expr_version
.map(|value| PartitionExprVersion { value }),
aligned_schema_version: None,
body: Some(bulk_insert_request::Body::ArrowIpc(ArrowIpc {
schema: schema_bytes,
data_header: header,
payload,
})),
})),
};
Ok(dispatcher
.send(
peer,
request,
Some(
&metrics::HANDLE_BULK_INSERT_ELAPSED
.with_label_values(&["datanode_handle"]),
),
)
.await)
});
handles.push(handle);
}
let region_responses = futures::future::try_join_all(handles)
.await
.context(error::JoinTaskSnafu)?;
let dispatcher = self.write_dispatcher.clone();
let rows_inserted = common_runtime::spawn_global(async move {
let results = future::try_join_all(handles)
.await
.context(error::JoinTaskSnafu)?;
let attempts = results.into_iter().collect::<Result<Vec<_>>>()?;
dispatcher
.finish(
attempts,
Some(
&metrics::HANDLE_BULK_INSERT_ELAPSED
.with_label_values(&["datanode_handle"]),
),
Some(&cancellation),
)
.await
.context(error::RequestRegionSnafu)
.map(|response| response.affected_rows)
})
.await
.context(error::JoinTaskSnafu)??;
wait_all_datanode_timer.observe_duration();
let mut rows_inserted: usize = 0;
for res in region_responses {
rows_inserted += res?.affected_rows;
}
crate::metrics::DIST_INGEST_ROW_COUNT
.with_label_values(&[db_name.as_str()])
.inc_by(rows_inserted as u64);
+30 -47
View File
@@ -12,7 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::{HashMap, HashSet};
use std::collections::HashSet;
use std::sync::Arc;
use std::{iter, mem};
@@ -20,45 +20,55 @@ use api::v1::region::{DeleteRequests as RegionDeleteRequests, RegionRequestHeade
use api::v1::{DeleteRequests, RowDeleteRequests};
use catalog::CatalogManagerRef;
use common_meta::node_manager::{AffectedRows, NodeManagerRef};
use common_meta::peer::Peer;
use common_query::Output;
use common_telemetry::tracing_context::TracingContext;
use futures_util::future;
use partition::manager::PartitionRuleManagerRef;
use session::context::QueryContextRef;
use snafu::{OptionExt, ResultExt, ensure};
use table::TableRef;
use table::requests::DeleteRequest as TableDeleteRequest;
use tokio_util::sync::CancellationToken;
use crate::error::{
CatalogSnafu, FindRegionLeaderSnafu, InvalidDeleteRequestSnafu, JoinTaskSnafu,
MissingTimeIndexColumnSnafu, RequestDeletesSnafu, Result, TableNotFoundSnafu,
CatalogSnafu, InvalidDeleteRequestSnafu, JoinTaskSnafu, MissingTimeIndexColumnSnafu,
RequestDeletesSnafu, Result, TableNotFoundSnafu,
};
use crate::region_req_factory::RegionRequestFactory;
use crate::req_convert::common::preprocess_row_delete_requests;
use crate::req_convert::delete::{ColumnToRow, RowToRegion, TableToRegion};
use crate::write_dispatcher::{WriteDispatcher, WriteDispatcherRef};
pub struct Deleter {
catalog_manager: CatalogManagerRef,
partition_manager: PartitionRuleManagerRef,
node_manager: NodeManagerRef,
write_dispatcher: WriteDispatcherRef,
}
pub type DeleterRef = Arc<Deleter>;
impl Deleter {
/// Creates a row deleter with the default write dispatcher.
pub fn new(
catalog_manager: CatalogManagerRef,
partition_manager: PartitionRuleManagerRef,
node_manager: NodeManagerRef,
) -> Self {
Self {
write_dispatcher: Arc::new(WriteDispatcher::new(
node_manager,
partition_manager.clone(),
)),
catalog_manager,
partition_manager,
node_manager,
}
}
/// Installs the dispatcher shared with the other write paths.
pub fn with_write_dispatcher(mut self, dispatcher: WriteDispatcherRef) -> Self {
self.write_dispatcher = dispatcher;
self
}
pub async fn handle_column_deletes(
&self,
requests: DeleteRequests,
@@ -129,52 +139,25 @@ impl Deleter {
..Default::default()
});
let tasks = self
.group_requests_by_peer(requests)
.await?
.into_iter()
.map(|(peer, deletes)| {
let request = request_factory.build_delete(deletes);
let node_manager = self.node_manager.clone();
common_runtime::spawn_global(async move {
node_manager
.datanode(&peer)
.await
.handle(request)
.await
.context(RequestDeletesSnafu)
})
});
let results = future::try_join_all(tasks).await.context(JoinTaskSnafu)?;
let affected_rows = results
.into_iter()
.map(|resp| resp.map(|r| r.affected_rows))
.sum::<Result<AffectedRows>>()?;
let dispatcher = self.write_dispatcher.clone();
let request = request_factory.build_delete(requests);
let writes = dispatcher.prepare(vec![request]).await?;
// Dropping the caller stops retries without abandoning in-flight writes.
let cancellation = CancellationToken::new();
let _guard = cancellation.clone().drop_guard();
let affected_rows = common_runtime::spawn_global(async move {
dispatcher.execute(writes, None, Some(&cancellation)).await
})
.await
.context(JoinTaskSnafu)?
.context(RequestDeletesSnafu)?
.affected_rows;
crate::metrics::DIST_DELETE_ROW_COUNT
.with_label_values(&[ctx.get_db_string().as_str()])
.inc_by(affected_rows as u64);
Ok(affected_rows)
}
async fn group_requests_by_peer(
&self,
requests: RegionDeleteRequests,
) -> Result<HashMap<Peer, RegionDeleteRequests>> {
let mut deletes: HashMap<Peer, RegionDeleteRequests> = HashMap::new();
for req in requests.requests {
let peer = self
.partition_manager
.find_region_leader(req.region_id.into())
.await
.context(FindRegionLeaderSnafu)?;
deletes.entry(peer).or_default().requests.push(req);
}
Ok(deletes)
}
async fn trim_columns(
&self,
mut requests: RowDeleteRequests,
+68 -1
View File
@@ -16,13 +16,14 @@ use std::any::Any;
use common_datasource::file_format::Format;
use common_error::define_into_tonic_status;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use common_query::error::Error as QueryResult;
use datafusion::parquet;
use datafusion_common::DataFusionError;
use datatypes::arrow::error::ArrowError;
use object_store::error::retry_hint_from_opendal_error;
use snafu::{Location, Snafu};
use table::metadata::TableType;
@@ -1062,6 +1063,72 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::ReadObject { error, .. } => retry_hint_from_opendal_error(error),
Error::ReadParquetMetadata { .. } => RetryHint::Retryable,
Error::InvalidateTableCache { source, .. }
| Error::ExecuteDdl { source, .. }
| Error::RequestInserts { source, .. }
| Error::RequestDeletes { source, .. }
| Error::RequestRegion { source, .. }
| Error::FindViewInfo { source, .. }
| Error::TableMetadataManager { source, .. } => source.retry_hint(),
Error::ParseFileFormat { source, .. }
| Error::InferSchema { source, .. }
| Error::ListObjects { source, .. }
| Error::ParseUrl { source, .. }
| Error::BuildBackend { source, .. }
| Error::ReadOrc { source, .. } => source.retry_hint(),
Error::ExtractTableNames { source, .. }
| Error::ExecuteStatement { source, .. }
| Error::PlanStatement { source, .. }
| Error::ParseQuery { source, .. }
| Error::ExecLogicalPlan { source, .. }
| Error::DescribeStatement { source, .. } => source.retry_hint(),
Error::FindTablePartitionRule { source, .. }
| Error::SplitInsert { source, .. }
| Error::SplitDelete { source, .. }
| Error::FindRegionLeader { source, .. } => source.retry_hint(),
Error::BuildCreateExprOnInsertion { source, .. }
| Error::FindNewColumnsOnInsertion { source, .. }
| Error::AlterExprToRequest { source, .. } => source.retry_hint(),
Error::ConvertColumnDefaultConstraint { source, .. }
| Error::IntoVectors { source, .. }
| Error::ColumnDefaultValue { source, .. } => source.retry_hint(),
Error::ColumnDataType { source, .. }
| Error::InvalidColumnDef { source, .. }
| Error::ColumnOptions { source, .. } => source.retry_hint(),
Error::Table { source, .. }
| Error::Insert { source, .. }
| Error::MissingTimeIndexColumn { source, .. } => source.retry_hint(),
Error::Cast { source, .. } => source.retry_hint(),
Error::ParseSql { source, .. } => source.retry_hint(),
Error::Catalog { source, .. } => source.retry_hint(),
Error::SubstraitCodec { source, .. } => source.retry_hint(),
Error::External { source, .. } => source.retry_hint(),
Error::BuildRecordBatch { source, .. } => source.retry_hint(),
Error::DecodeFlightData { source, .. } => source.retry_hint(),
Error::SqlCommon { source, .. } => source.retry_hint(),
Error::ConvertSchema { source, .. } => source.retry_hint(),
Error::WriteStreamToFile { source, .. } => source.retry_hint(),
Error::PrepareFileTable { source, .. } | Error::InferFileTableSchema { source, .. } => {
source.retry_hint()
}
#[cfg(feature = "enterprise")]
Error::TriggerQuerier { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
define_into_tonic_status!(Error);
+35 -62
View File
@@ -34,14 +34,13 @@ use common_catalog::consts::{
};
use common_grpc_expr::util::ColumnExpr;
use common_meta::cache::TableFlownodeSetCacheRef;
use common_meta::node_manager::{AffectedRows, NodeManagerRef};
use common_meta::node_manager::NodeManagerRef;
use common_meta::peer::Peer;
use common_query::Output;
use common_query::prelude::{greptime_timestamp, greptime_value};
use common_telemetry::tracing_context::TracingContext;
use common_telemetry::{error, info, warn};
use datatypes::schema::SkippingIndexOptions;
use futures_util::future;
use meter_macros::write_meter;
use partition::manager::PartitionRuleManagerRef;
use session::context::QueryContextRef;
@@ -66,10 +65,11 @@ use table::requests::{
VALID_TABLE_OPTION_KEYS, is_semantic_option_key, validate_semantic_option,
};
use table::table_reference::TableReference;
use tokio_util::sync::CancellationToken;
use crate::error::{
CatalogSnafu, ColumnOptionsSnafu, CreatePartitionRulesSnafu, FindRegionLeaderSnafu,
InvalidInsertRequestSnafu, JoinTaskSnafu, RequestInsertsSnafu, Result, TableNotFoundSnafu,
CatalogSnafu, ColumnOptionsSnafu, CreatePartitionRulesSnafu, InvalidInsertRequestSnafu,
JoinTaskSnafu, RequestInsertsSnafu, Result, TableNotFoundSnafu,
};
use crate::expr_helper;
use crate::region_req_factory::RegionRequestFactory;
@@ -78,11 +78,13 @@ use crate::req_convert::insert::{
ColumnToRow, RowToRegion, StatementToRegion, TableToRegion, fill_reqs_with_impure_default,
};
use crate::statement::StatementExecutor;
use crate::write_dispatcher::{WriteDispatcher, WriteDispatcherRef};
pub struct Inserter {
catalog_manager: CatalogManagerRef,
pub(crate) partition_manager: PartitionRuleManagerRef,
pub(crate) node_manager: NodeManagerRef,
pub(crate) write_dispatcher: WriteDispatcherRef,
pub(crate) table_flownode_set_cache: TableFlownodeSetCacheRef,
/// Server-side upper bound for auto table creation on write.
/// When `false`, missing tables are never auto-created regardless of the
@@ -135,6 +137,7 @@ pub struct InstantAndNormalInsertRequests {
}
impl Inserter {
/// Creates a row inserter with the default write dispatcher.
pub fn new(
catalog_manager: CatalogManagerRef,
partition_manager: PartitionRuleManagerRef,
@@ -143,6 +146,10 @@ impl Inserter {
auto_create_table: bool,
) -> Self {
Self {
write_dispatcher: Arc::new(WriteDispatcher::new(
node_manager.clone(),
partition_manager.clone(),
)),
catalog_manager,
partition_manager,
node_manager,
@@ -151,6 +158,12 @@ impl Inserter {
}
}
/// Installs the shared dispatcher used by direct writes.
pub fn with_write_dispatcher(mut self, dispatcher: WriteDispatcherRef) -> Self {
self.write_dispatcher = dispatcher;
self
}
pub async fn handle_column_inserts(
&self,
requests: InsertRequests,
@@ -409,30 +422,19 @@ impl Inserter {
.await?;
flow_mirror_task.detach(self.node_manager.clone())?;
// Write requests to datanode and wait for response
let write_tasks = self
.group_requests_by_peer(normal_requests)
.await?
.into_iter()
.map(|(peer, inserts)| {
let node_manager = self.node_manager.clone();
let request = request_factory.build_insert(inserts);
common_runtime::spawn_global(async move {
node_manager
.datanode(&peer)
.await
.handle(request)
.await
.context(RequestInsertsSnafu)
})
});
let results = future::try_join_all(write_tasks)
.await
.context(JoinTaskSnafu)?;
let affected_rows = results
.into_iter()
.map(|resp| resp.map(|r| r.affected_rows))
.sum::<Result<AffectedRows>>()?;
let dispatcher = self.write_dispatcher.clone();
let request = request_factory.build_insert(normal_requests);
let writes = dispatcher.prepare(vec![request]).await?;
// Dropping the caller stops retries without abandoning in-flight writes.
let cancellation = CancellationToken::new();
let _guard = cancellation.clone().drop_guard();
let affected_rows = common_runtime::spawn_global(async move {
dispatcher.execute(writes, None, Some(&cancellation)).await
})
.await
.context(JoinTaskSnafu)?
.context(RequestInsertsSnafu)?
.affected_rows;
crate::metrics::DIST_INGEST_ROW_COUNT
.with_label_values(&[ctx.get_db_string().as_str()])
.inc_by(affected_rows as u64);
@@ -442,40 +444,6 @@ impl Inserter {
))
}
async fn group_requests_by_peer(
&self,
requests: RegionInsertRequests,
) -> Result<HashMap<Peer, RegionInsertRequests>> {
// group by region ids first to reduce repeatedly call `find_region_leader`
// TODO(discord9): determine if a addition clone is worth it
let mut requests_per_region: HashMap<RegionId, RegionInsertRequests> = HashMap::new();
for req in requests.requests {
let region_id = RegionId::from_u64(req.region_id);
requests_per_region
.entry(region_id)
.or_default()
.requests
.push(req);
}
let mut inserts: HashMap<Peer, RegionInsertRequests> = HashMap::new();
for (region_id, reqs) in requests_per_region {
let peer = self
.partition_manager
.find_region_leader(region_id)
.await
.context(FindRegionLeaderSnafu)?;
inserts
.entry(peer)
.or_default()
.requests
.extend(reqs.requests);
}
Ok(inserts)
}
/// Returns `None` if auto table creation is allowed, or `Some(reason)` if
/// disabled by either the global config or the request hint. The reason tells
/// which one, for a clearer error.
@@ -1049,6 +1017,11 @@ impl Inserter {
}
}
/// Returns the dispatcher shared with batching execution paths.
pub fn write_dispatcher(&self) -> &WriteDispatcherRef {
&self.write_dispatcher
}
pub fn node_manager(&self) -> &NodeManagerRef {
&self.node_manager
}
+1
View File
@@ -28,3 +28,4 @@ pub mod table;
#[cfg(test)]
pub(crate) mod tests;
pub mod utils;
pub mod write_dispatcher;
+2
View File
@@ -15,3 +15,5 @@
pub(crate) mod common;
pub mod delete;
pub mod insert;
pub(crate) use common::partitioner::TablePartitioner;
File diff suppressed because it is too large Load Diff
+4 -1
View File
@@ -16,4 +16,7 @@ mod kv_backend;
mod partition_manager;
pub(crate) use kv_backend::prepare_mocked_backend;
pub(crate) use partition_manager::{create_partition_rule_manager, new_test_table_info};
pub(crate) use partition_manager::{
create_partition_rule_manager, new_test_table_info, test_new_partition_info_cache,
test_new_table_route_cache,
};
+4 -2
View File
@@ -75,7 +75,7 @@ fn new_test_region_wal_options(regions: Vec<RegionNumber>) -> HashMap<RegionNumb
HashMap::default()
}
fn test_new_table_route_cache(kv_backend: KvBackendRef) -> TableRouteCacheRef {
pub(crate) fn test_new_table_route_cache(kv_backend: KvBackendRef) -> TableRouteCacheRef {
let cache = CacheBuilder::new(128).build();
Arc::new(new_table_route_cache(
"table_route_cache".to_string(),
@@ -84,7 +84,9 @@ fn test_new_table_route_cache(kv_backend: KvBackendRef) -> TableRouteCacheRef {
))
}
fn test_new_partition_info_cache(table_route_cache: TableRouteCacheRef) -> PartitionInfoCacheRef {
pub(crate) fn test_new_partition_info_cache(
table_route_cache: TableRouteCacheRef,
) -> PartitionInfoCacheRef {
let cache = CacheBuilder::new(128).build();
Arc::new(new_partition_info_cache(
"partition_info_cache".to_string(),
+664
View File
@@ -0,0 +1,664 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
mod options;
#[cfg(test)]
mod tests;
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use api::region::RegionResponse;
use api::v1::region::region_request::Body;
use api::v1::region::{DeleteRequests, InsertRequests, RegionRequest};
use backon::{BackoffBuilder, ExponentialBuilder};
use catalog::CatalogManagerRef;
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_meta::cache_invalidator::{CacheInvalidatorRef, Context};
use common_meta::error::{Error, ExternalSnafu, Result, TableInfoNotFoundSnafu, UnexpectedSnafu};
use common_meta::instruction::CacheIdent;
use common_meta::node_manager::NodeManagerRef;
use common_meta::peer::{Peer, PeerRef};
use common_meta::rpc::router;
use futures::future;
use partition::manager::{PartitionRuleManager, PartitionRuleManagerRef};
use prometheus::Histogram;
use snafu::{OptionExt, ResultExt, ensure};
use store_api::storage::RegionId;
use table::table_name::TableName;
use tokio_util::sync::CancellationToken;
pub use self::options::WriteRetryOptions;
use crate::error::{self, FindRegionLeaderSnafu, RequestRegionSnafu};
use crate::req_convert::TablePartitioner;
/// Dispatches already partitioned writes, retaining only failed payloads for retries.
pub struct WriteDispatcher {
node_manager: NodeManagerRef,
partition_manager: PartitionRuleManagerRef,
retry: Option<WriteRetry>,
}
/// Shared reference to a [`WriteDispatcher`].
pub type WriteDispatcherRef = Arc<WriteDispatcher>;
/// The result of one write RPC attempt.
pub(crate) enum WriteAttempt {
Success(RegionResponse),
Failed {
error: Error,
/// Retained when retries are enabled and the original client error allows retry.
/// The remaining retry budget is checked separately.
request: Option<RoutedWrite>,
},
}
impl WriteDispatcher {
/// Creates an owned-request dispatcher without retries, including for standalone.
pub fn new(node_manager: NodeManagerRef, partition_manager: PartitionRuleManagerRef) -> Self {
Self {
node_manager,
partition_manager,
retry: None,
}
}
/// Enables shared remote sends and retries using frontend configuration and caches.
pub fn with_retry(
mut self,
options: WriteRetryOptions,
catalog_manager: CatalogManagerRef,
cache_invalidator: CacheInvalidatorRef,
) -> Self {
if options.max_retries > 0 {
self.retry = Some(WriteRetry {
node_manager: self.node_manager.clone(),
partition_manager: self.partition_manager.clone(),
options,
catalog_manager,
cache_invalidator,
});
} else {
self.retry = None;
}
self
}
/// Writes planned requests without repeating admission, default values, or Flow side effects.
pub async fn dispatch(&self, requests: Vec<RegionRequest>) -> Result<RegionResponse> {
self.dispatch_inner(requests, None).await
}
/// Records each datanode send attempt, including retries, in the supplied histogram.
pub async fn dispatch_with_metrics(
&self,
requests: Vec<RegionRequest>,
histogram: Histogram,
) -> Result<RegionResponse> {
self.dispatch_inner(requests, Some(histogram)).await
}
/// Resolves routes before writes are detached from the caller.
pub(crate) async fn prepare(
&self,
requests: Vec<RegionRequest>,
) -> error::Result<Vec<(PeerRef, RegionRequest)>> {
let requests = requests
.into_iter()
.map(|mut request| {
let header = request.header.take();
(header, split_request(request))
})
.collect::<Vec<_>>();
let regions = requests
.iter()
.flat_map(|(_, requests)| requests)
.map(write_region_id)
.collect::<Result<Vec<_>>>()
.context(RequestRegionSnafu)?;
let peers = self
.resolve_peers(&regions)
.await
.context(FindRegionLeaderSnafu)?;
let mut writes = Vec::new();
// Preserve each original envelope and peer batching when retries are disabled.
for (header, requests) in requests {
let mut by_peer: HashMap<PeerRef, RegionRequest> = HashMap::new();
for request in requests {
let peer = get_peer(
&peers,
write_region_id(&request).context(RequestRegionSnafu)?,
)
.context(RequestRegionSnafu)?;
match by_peer.entry(peer) {
Entry::Vacant(entry) => {
entry.insert(request);
}
Entry::Occupied(mut entry) => match (&mut entry.get_mut().body, request.body) {
(Some(Body::Inserts(existing)), Some(Body::Inserts(next))) => {
existing.requests.extend(next.requests)
}
(Some(Body::Deletes(existing)), Some(Body::Deletes(next))) => {
existing.requests.extend(next.requests)
}
_ => {
return UnexpectedSnafu {
err_msg: "Cannot combine different write kinds",
}
.fail()
.context(RequestRegionSnafu);
}
},
}
}
for (peer, mut request) in by_peer {
request.header = header.clone();
writes.push((peer, request));
}
}
Ok(writes)
}
/// Sends requests using routes already resolved by the caller.
/// Cancellation stops future retries while allowing in-flight requests to complete.
pub(crate) async fn execute(
&self,
writes: Vec<(PeerRef, RegionRequest)>,
histogram: Option<Histogram>,
cancellation: Option<&CancellationToken>,
) -> Result<RegionResponse> {
let histogram = histogram.as_ref();
let writes = if self.retry.is_some() {
writes
.into_iter()
.flat_map(|(peer, request)| {
split_request(request)
.into_iter()
.map(move |request| (Arc::clone(&peer), request))
})
.collect()
} else {
writes
};
let attempts = future::join_all(
writes
.into_iter()
.map(|(peer, request)| self.send(peer, request, histogram)),
)
.await;
self.finish(attempts, histogram, cancellation).await
}
/// Sends the first attempt immediately so bulk encoding can overlap other sends.
pub(crate) async fn send(
&self,
peer: PeerRef,
request: RegionRequest,
histogram: Option<&Histogram>,
) -> WriteAttempt {
if let Some(retry) = &self.retry {
return retry
.send(
RoutedWrite {
peer,
request: Arc::new(request),
},
histogram,
)
.await;
}
let _timer = histogram.map(Histogram::start_timer);
let datanode = self.node_manager.datanode(&peer).await;
match datanode.handle(request).await {
Ok(response) => WriteAttempt::Success(response),
Err(error) => WriteAttempt::Failed {
error,
request: None,
},
}
}
/// Collects first attempts and retries their failures together, refreshing routes once per round.
pub(crate) async fn finish(
&self,
attempts: Vec<WriteAttempt>,
histogram: Option<&Histogram>,
cancellation: Option<&CancellationToken>,
) -> Result<RegionResponse> {
if let Some(retry) = &self.retry {
if retry.should_retry(&attempts, 0) {
return retry.retry(attempts, histogram, cancellation).await;
}
let mut response = RegionResponse::new(0);
let failures = merge_attempts(attempts, &mut response)?;
return match failures.into_iter().next() {
Some((_, error)) => Err(error),
None => Ok(response),
};
}
let mut response = RegionResponse::new(0);
for attempt in attempts {
match attempt {
WriteAttempt::Success(result) => merge_response(&mut response, result),
WriteAttempt::Failed { error, .. } => return Err(error),
}
}
Ok(response)
}
/// Resolves only the requested peers, loading each table route once.
pub(crate) async fn resolve_peers(
&self,
regions: &[RegionId],
) -> partition::error::Result<HashMap<RegionId, PeerRef>> {
resolve_peers(&self.partition_manager, regions).await
}
async fn dispatch_inner(
&self,
requests: Vec<RegionRequest>,
histogram: Option<Histogram>,
) -> Result<RegionResponse> {
let writes = self
.prepare(requests)
.await
.map_err(BoxedError::new)
.context(ExternalSnafu)?;
self.execute(writes, histogram, None).await
}
}
/// Sends shared requests and coordinates retries with refreshed routes.
struct WriteRetry {
node_manager: NodeManagerRef,
partition_manager: PartitionRuleManagerRef,
options: WriteRetryOptions,
catalog_manager: CatalogManagerRef,
cache_invalidator: CacheInvalidatorRef,
}
/// A single-region write request paired with its destination peer.
pub(crate) struct RoutedWrite {
peer: PeerRef,
request: Arc<RegionRequest>,
}
impl WriteRetry {
async fn send(&self, write: RoutedWrite, histogram: Option<&Histogram>) -> WriteAttempt {
let _timer = histogram.map(Histogram::start_timer);
let requester = self.node_manager.datanode(&write.peer).await;
match requester.handle(Arc::clone(&write.request)).await {
Ok(response) => WriteAttempt::Success(response),
Err(error) => {
let request = error.retry_hint().is_retryable().then_some(write);
WriteAttempt::Failed { error, request }
}
}
}
fn should_retry(&self, attempts: &[WriteAttempt], retries: usize) -> bool {
if retries >= self.options.max_retries {
return false;
}
let mut retryable = false;
for attempt in attempts {
match attempt {
WriteAttempt::Success(_) => {}
WriteAttempt::Failed {
request: Some(_), ..
} => retryable = true,
WriteAttempt::Failed { request: None, .. } => return false,
}
}
retryable
}
async fn retry(
&self,
mut attempts: Vec<WriteAttempt>,
histogram: Option<&Histogram>,
cancellation: Option<&CancellationToken>,
) -> Result<RegionResponse> {
let mut response = RegionResponse::new(0);
let mut backoff = ExponentialBuilder::default()
.with_min_delay(self.options.initial_backoff)
.with_max_delay(self.options.max_backoff)
.with_factor(self.options.backoff_multiplier)
.with_max_times(self.options.max_retries)
.with_jitter()
.build();
let mut retries = 0;
while self.should_retry(&attempts, retries) {
let Some(delay) = backoff.next() else {
break;
};
if let Some(cancellation) = cancellation {
tokio::select! {
biased;
_ = cancellation.cancelled() => break,
_ = tokio::time::sleep(delay) => {}
}
} else {
tokio::time::sleep(delay).await;
}
if cancellation.is_some_and(CancellationToken::is_cancelled) {
break;
}
let failures = merge_attempts(attempts, &mut response)?;
let mut first_error = None;
let mut refresh = Vec::new();
let mut pending = Vec::new();
for (write, error) in failures {
if error.retry_hint() == RetryHint::RetryAfterRouteRefresh {
refresh.push(write);
} else {
pending.push(write);
}
first_error.get_or_insert(error);
}
if !refresh.is_empty() {
pending.extend(self.reroute_failed_writes(refresh).await?);
}
if let Some(error) =
first_error.filter(|_| cancellation.is_some_and(CancellationToken::is_cancelled))
{
return Err(error);
}
attempts =
future::join_all(pending.into_iter().map(|write| self.send(write, histogram)))
.await;
retries += 1;
}
match merge_attempts(attempts, &mut response)?.into_iter().next() {
Some((_, error)) => Err(error),
None => Ok(response),
}
}
async fn reroute_failed_writes(&self, writes: Vec<RoutedWrite>) -> Result<Vec<RoutedWrite>> {
let regions = writes
.iter()
.map(|write| write_region_id(&write.request))
.collect::<Result<Vec<_>>>()?;
self.invalidate_routes(&regions).await?;
let mut table_names = HashMap::new();
for table_id in regions
.iter()
.map(|region| region.table_id())
.collect::<HashSet<_>>()
{
// Raw metadata is only used to recover the name of the failed request's table.
let table_info = self
.catalog_manager
.table_info_by_id(table_id)
.await
.map_err(BoxedError::new)
.context(ExternalSnafu)?
.with_context(|| TableInfoNotFoundSnafu {
table: table_id.to_string(),
})?;
table_names.insert(
table_id,
TableName::new(
&table_info.catalog_name,
&table_info.schema_name,
&table_info.name,
),
);
}
// TableId invalidation refreshes metadata and routes, but TableCache is keyed by name.
// Use the refreshed names in case a table was renamed while the write was pending.
let caches = table_names
.values()
.cloned()
.map(CacheIdent::TableName)
.collect::<Vec<_>>();
self.cache_invalidator
.invalidate(&Context::default(), &caches)
.await?;
let mut partitioners = HashMap::new();
for (table_id, name) in table_names {
let table = self
.catalog_manager
.table(
&name.catalog_name,
&name.schema_name,
&name.table_name,
None,
)
.await
.map_err(BoxedError::new)
.context(ExternalSnafu)?
.with_context(|| TableInfoNotFoundSnafu {
table: name.to_string(),
})?;
let table_info = table.table_info();
ensure!(
table_info.table_id() == table_id,
UnexpectedSnafu {
err_msg: format!(
"Table {name} changed ID from {table_id} to {} while retrying writes",
table_info.table_id()
),
}
);
let partitioner = TablePartitioner::try_new(&self.partition_manager, &table_info)
.await
.map_err(BoxedError::new)
.context(ExternalSnafu)?;
partitioners.insert(table_id, (table_info, partitioner));
}
let mut rebuilt_requests = Vec::new();
for write in writes {
let request = Arc::try_unwrap(write.request).map_err(|_| {
UnexpectedSnafu {
err_msg: "Write request is still shared after its RPC completed",
}
.build()
})?;
let table_id = write_region_id(&request)?.table_id();
let (table_info, partitioner) =
partitioners.get(&table_id).context(UnexpectedSnafu {
err_msg: "Refreshed write has no partition snapshot",
})?;
let requests = partitioner
.rebuild_write_requests(request, table_info)
.map_err(BoxedError::new)
.context(ExternalSnafu)?;
rebuilt_requests.extend(requests);
}
self.prepare(rebuilt_requests).await
}
async fn prepare(&self, requests: Vec<RegionRequest>) -> Result<Vec<RoutedWrite>> {
let regions = requests
.iter()
.map(write_region_id)
.collect::<Result<Vec<_>>>()?;
let peers = resolve_peers(&self.partition_manager, &regions)
.await
.map_err(BoxedError::new)
.context(ExternalSnafu)?;
requests
.into_iter()
.zip(regions)
.map(|(request, region)| {
Ok(RoutedWrite {
peer: get_peer(&peers, region)?,
request: Arc::new(request),
})
})
.collect()
}
async fn invalidate_routes(&self, regions: &[RegionId]) -> Result<()> {
let mut table_ids = regions
.iter()
.map(|region| region.table_id())
.collect::<HashSet<_>>();
let mut physical_ids = HashSet::new();
for table_id in &table_ids {
let (physical_id, _) = self
.partition_manager
.find_physical_table_route_with_id(*table_id)
.await
.map_err(BoxedError::new)
.context(ExternalSnafu)?;
physical_ids.insert(physical_id);
}
table_ids.extend(physical_ids);
let caches = table_ids
.into_iter()
.map(CacheIdent::TableId)
.collect::<Vec<_>>();
self.cache_invalidator
.invalidate(&Context::default(), &caches)
.await
}
}
async fn resolve_peers(
partition_manager: &PartitionRuleManager,
regions: &[RegionId],
) -> partition::error::Result<HashMap<RegionId, PeerRef>> {
let table_ids = regions
.iter()
.map(|region| region.table_id())
.collect::<HashSet<_>>();
let mut physical_tables = HashMap::new();
let mut routes = HashMap::new();
for table_id in table_ids {
let (physical_id, route) = partition_manager
.find_physical_table_route_with_id(table_id)
.await?;
physical_tables.insert(table_id, physical_id);
routes.entry(physical_id).or_insert(route);
}
let mut shared_peers: HashMap<&Peer, PeerRef> = HashMap::new();
let mut peers = HashMap::with_capacity(regions.len());
for region in regions {
if peers.contains_key(region) {
continue;
}
let peer = physical_tables
.get(&region.table_id())
.and_then(|physical_id| routes.get(physical_id))
.and_then(|route| {
router::find_region_leader_ref(&route.region_routes, region.region_number())
})
.context(partition::error::FindLeaderSnafu {
region_id: *region,
table_id: region.table_id(),
})?;
let peer = shared_peers
.entry(peer)
.or_insert_with(|| Arc::new(peer.clone()));
peers.insert(*region, Arc::clone(peer));
}
Ok(peers)
}
fn get_peer(peers: &HashMap<RegionId, PeerRef>, region: RegionId) -> Result<PeerRef> {
peers.get(&region).cloned().context(UnexpectedSnafu {
err_msg: "Planned write has no resolved peer",
})
}
fn merge_attempts(
attempts: Vec<WriteAttempt>,
response: &mut RegionResponse,
) -> Result<Vec<(RoutedWrite, Error)>> {
let mut failures = Vec::new();
let mut terminal_error = None;
for attempt in attempts {
match attempt {
WriteAttempt::Success(result) => merge_response(response, result),
WriteAttempt::Failed {
error,
request: Some(write),
} => failures.push((write, error)),
WriteAttempt::Failed {
error,
request: None,
} => {
terminal_error.get_or_insert(error);
}
}
}
// A terminal error takes precedence over retained retryable failures.
match terminal_error {
Some(error) => Err(error),
None => Ok(failures),
}
}
fn merge_response(response: &mut RegionResponse, result: RegionResponse) {
response.affected_rows += result.affected_rows;
response.extensions.extend(result.extensions);
response.metadata = result.metadata;
}
fn split_request(request: RegionRequest) -> Vec<RegionRequest> {
let RegionRequest { header, body } = request;
let bodies: Vec<Body> = match body {
Some(Body::Inserts(inserts)) => inserts
.requests
.into_iter()
.map(|request| {
Body::Inserts(InsertRequests {
requests: vec![request],
})
})
.collect(),
Some(Body::Deletes(deletes)) => deletes
.requests
.into_iter()
.map(|request| {
Body::Deletes(DeleteRequests {
requests: vec![request],
})
})
.collect(),
body => return vec![RegionRequest { header, body }],
};
bodies
.into_iter()
.map(|body| RegionRequest {
header: header.clone(),
body: Some(body),
})
.collect()
}
fn write_region_id(request: &RegionRequest) -> Result<RegionId> {
let region_id = match &request.body {
Some(Body::Inserts(inserts)) => match inserts.requests.as_slice() {
[request] => Some(request.region_id),
_ => None,
},
Some(Body::Deletes(deletes)) => match deletes.requests.as_slice() {
[request] => Some(request.region_id),
_ => None,
},
Some(Body::BulkInsert(bulk)) => Some(bulk.region_id),
_ => None,
};
region_id.map(RegionId::from_u64).ok_or_else(|| {
UnexpectedSnafu {
err_msg: "Expected a single-region write request",
}
.build()
})
}
@@ -0,0 +1,106 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::time::Duration;
use serde::{Deserialize, Serialize};
/// Exponential backoff for retryable distributed writes.
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct WriteRetryOptions {
/// Maximum additional attempts after the original write. Zero disables retries.
pub max_retries: usize,
/// Initial backoff before jitter is applied.
#[serde(with = "humantime_serde")]
pub initial_backoff: Duration,
/// Maximum backoff before jitter is applied.
#[serde(with = "humantime_serde")]
pub max_backoff: Duration,
/// Multiplier applied to the backoff after each retry.
pub backoff_multiplier: f32,
}
impl Default for WriteRetryOptions {
fn default() -> Self {
Self {
max_retries: 3,
initial_backoff: Duration::from_millis(1500),
max_backoff: Duration::from_secs(10),
backoff_multiplier: 2.0,
}
}
}
impl WriteRetryOptions {
/// Checks that the configured backoff is positive, bounded, and nondecreasing.
pub fn validate(&self) -> Result<(), &'static str> {
if self.initial_backoff.is_zero() {
return Err("write_retry.initial_backoff must be positive");
}
if self.max_backoff < self.initial_backoff {
return Err("write_retry.max_backoff must be at least initial_backoff");
}
if !self.backoff_multiplier.is_finite() || self.backoff_multiplier < 1.0 {
return Err("write_retry.backoff_multiplier must be finite and at least 1");
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_validate_write_retry_options() {
for options in [
WriteRetryOptions::default(),
WriteRetryOptions {
max_retries: 0,
..Default::default()
},
WriteRetryOptions {
backoff_multiplier: 1.0,
..Default::default()
},
] {
options.validate().unwrap();
}
for options in [
WriteRetryOptions {
initial_backoff: Duration::ZERO,
..Default::default()
},
WriteRetryOptions {
max_backoff: Duration::from_secs(1),
..Default::default()
},
WriteRetryOptions {
backoff_multiplier: 0.5,
..Default::default()
},
WriteRetryOptions {
backoff_multiplier: f32::NAN,
..Default::default()
},
WriteRetryOptions {
backoff_multiplier: f32::INFINITY,
..Default::default()
},
] {
assert!(options.validate().is_err(), "{options:?}");
}
}
}
File diff suppressed because it is too large Load Diff
+12 -1
View File
@@ -14,7 +14,7 @@
use std::any::Any;
use common_error::ext::ErrorExt;
use common_error::ext::{ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use datafusion_common::ScalarValue;
@@ -283,6 +283,17 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
match self {
Error::GetCache { .. } | Error::FindLeader { .. } => RetryHint::Retryable,
Error::TableRouteManager { source, .. }
| Error::GetPartitionInfo { source, .. }
| Error::UnexpectedLogicalRouteTable { source, .. } => source.retry_hint(),
Error::ConvertToVector { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
+16 -4
View File
@@ -74,6 +74,14 @@ impl PartitionRuleManager {
&self,
table_id: TableId,
) -> Result<Arc<PhysicalTableRouteValue>> {
Ok(self.find_physical_table_route_with_id(table_id).await?.1)
}
/// Returns the resolved physical table id and its route.
pub async fn find_physical_table_route_with_id(
&self,
table_id: TableId,
) -> Result<(TableId, Arc<PhysicalTableRouteValue>)> {
match self
.table_route_cache
.get(table_id)
@@ -82,7 +90,9 @@ impl PartitionRuleManager {
.context(error::TableRouteNotFoundSnafu { table_id })?
.as_ref()
{
TableRoute::Physical(physical_table_route) => Ok(physical_table_route.clone()),
TableRoute::Physical(physical_table_route) => {
Ok((table_id, physical_table_route.clone()))
}
TableRoute::Logical(logical_table_route) => {
let physical_table_id = logical_table_route.physical_table_id();
let physical_table_route = self
@@ -90,17 +100,19 @@ impl PartitionRuleManager {
.get(physical_table_id)
.await
.context(error::TableRouteManagerSnafu)?
.context(error::TableRouteNotFoundSnafu { table_id })?;
.context(error::TableRouteNotFoundSnafu {
table_id: physical_table_id,
})?;
let physical_table_route = physical_table_route
.as_physical_table_route_ref()
.context(error::UnexpectedSnafu{
err_msg: format!(
"Expected the physical table route, but got logical table route, table: {table_id}"
"Expected the physical table route, but got logical table route, table: {physical_table_id}"
),
})?;
Ok(physical_table_route.clone())
Ok((physical_table_id, physical_table_route.clone()))
}
}
}
@@ -107,6 +107,11 @@ impl EmptyMetric {
})
}
/// Returns the expression used to generate metric values.
pub fn expr(&self) -> Option<&Expr> {
self.expr.as_ref()
}
pub const fn name() -> &'static str {
"EmptyMetric"
}
+5
View File
@@ -66,6 +66,7 @@ use crate::metrics::{
OnDone, QUERY_STAGE_ELAPSED, maybe_attach_region_watermark_metrics,
should_collect_region_watermark_from_query_ctx,
};
use crate::optimizer::expr_depth;
use crate::options::ScheduledTimeExtension;
use crate::physical_wrapper::PhysicalPlanWrapperRef;
use crate::planner::{DfLogicalPlanner, LogicalPlanner};
@@ -314,6 +315,8 @@ impl DatafusionQueryEngine {
}
}
expr_depth::validate_plan(logical_plan)?;
let mut logger = PanicLogger {
input_logical_plan: logical_plan,
after_analyze: None,
@@ -341,6 +344,7 @@ impl DatafusionQueryEngine {
|_, _| {},
)?;
expr_depth::validate_plan(&analyzed_plan)?;
logger.after_analyze = Some(analyzed_plan.clone());
common_telemetry::debug!("Create physical plan, analyzed plan: {analyzed_plan}");
@@ -356,6 +360,7 @@ impl DatafusionQueryEngine {
.optimize(analyzed_plan, state, |_, _| {})?
};
expr_depth::validate_plan(&optimized_plan)?;
common_telemetry::debug!("Create physical plan, optimized plan: {optimized_plan}");
logger.after_optimize = Some(optimized_plan.clone());
+1
View File
@@ -27,6 +27,7 @@ mod remote_dyn_filter_registry;
pub use analyzer::{DistPlannerAnalyzer, DistPlannerOptions};
pub use filter_id::{FilterFingerprint, FilterId, ParseFilterIdError, RemoteDynFilterProducerId};
pub use merge_scan::{MergeScanExec, MergeScanLogicalPlan};
pub(crate) use merge_sort::MergeSortLogicalPlan;
pub use planner::{DistExtensionPlanner, MergeSortExtensionPlanner};
pub use predicate_extractor::PredicateExtractor;
pub use region_pruner::ConstraintPruner;
+3
View File
@@ -42,6 +42,7 @@ use crate::dist_plan::commutativity::{
use crate::dist_plan::merge_scan::MergeScanLogicalPlan;
use crate::dist_plan::merge_sort::MergeSortLogicalPlan;
use crate::metrics::PUSH_DOWN_FALLBACK_ERRORS_TOTAL;
use crate::optimizer::expr_depth;
use crate::options::ScheduledTimeExtension;
use crate::plan::ExtractExpr;
use crate::query_engine::DefaultSerializer;
@@ -107,6 +108,7 @@ impl AnalyzerRule for DistPlannerAnalyzer {
plan: LogicalPlan,
config: &ConfigOptions,
) -> datafusion_common::Result<LogicalPlan> {
expr_depth::validate_plan(&plan)?;
let mut config = config.clone();
// Aligned with the behavior in `datafusion_optimizer::OptimizerContext::new()`.
config.optimizer.filter_null_join_keys = true;
@@ -129,6 +131,7 @@ impl AnalyzerRule for DistPlannerAnalyzer {
let plan = plan
.rewrite_with_subqueries(&mut PlanTreeExpressionSimplifier::new(optimizer_context))?
.data;
expr_depth::validate_plan(&plan)?;
let opt = config.extensions.get::<DistPlannerOptions>();
let allow_fallback = opt.map(|o| o.allow_query_fallback).unwrap_or(false);
+2
View File
@@ -42,6 +42,7 @@ use crate::dist_plan::merge_scan::{MergeScanExec, MergeScanLogicalPlan};
use crate::dist_plan::merge_sort::MergeSortLogicalPlan;
use crate::dist_plan::region_pruner::ConstraintPruner;
use crate::error::{CatalogSnafu, PartitionRuleManagerSnafu, TableNotFoundSnafu};
use crate::optimizer::expr_depth;
use crate::region_query::RegionQueryHandlerRef;
/// Planner for convert merge sort logical plan to physical plan
@@ -326,6 +327,7 @@ impl DistExtensionPlanner {
session_state: &SessionState,
plan: &LogicalPlan,
) -> Result<LogicalPlan> {
expr_depth::validate_plan(plan)?;
let state = session_state.clone();
state.optimizer().optimize(plan.clone(), &state, |_, _| {})
}
+24 -1
View File
@@ -15,7 +15,7 @@
use std::any::Any;
use std::time::{Duration, TryFromFloatSecsError};
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use common_query::error::datafusion_status_code;
@@ -462,6 +462,29 @@ impl ErrorExt for Error {
fn as_any(&self) -> &dyn Any {
self
}
fn retry_hint(&self) -> RetryHint {
use Error::*;
match self {
BuildBackend { source, .. } | ListObjects { source, .. } => source.retry_hint(),
GetRegionMetadata { .. } => RetryHint::Retryable,
ParseFileFormat { source, .. } | InferSchema { source, .. } => source.retry_hint(),
Catalog { source, .. } => source.retry_hint(),
CreateRecordBatch { source, .. } => source.retry_hint(),
PartitionRuleManager { source, .. } => source.retry_hint(),
QueryExecution { source, .. } | QueryPlan { source, .. } => source.retry_hint(),
Sql { source, .. } => source.retry_hint(),
ConvertSqlType { source, .. } | ConvertSqlValue { source, .. } => source.retry_hint(),
RegionQuery { source, .. } => source.retry_hint(),
TableMutation { source, .. } => source.retry_hint(),
GetFulltextOptions { source, .. }
| GetSkippingIndexOptions { source, .. }
| GetVectorIndexOptions { source, .. }
| Datatypes { source, .. } => source.retry_hint(),
_ => RetryHint::NonRetryable,
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
+1
View File
@@ -16,6 +16,7 @@ pub mod const_normalization;
pub mod constant_term;
pub mod count_nest_aggr;
pub mod count_wildcard;
pub(crate) mod expr_depth;
pub(crate) mod json_type_concretize;
pub mod parallelize_scan;
pub mod pass_distribution;
+92 -89
View File
@@ -23,8 +23,6 @@ use datafusion_expr::{Between, BinaryExpr, Expr, ExprSchemable, LogicalPlan, Ope
use datafusion_expr_common::casts::try_cast_literal_to_type;
use datafusion_optimizer::analyzer::AnalyzerRule;
use crate::plan::ExtractExpr;
/// ConstNormalizationRule rewrites castable constants against their
/// non-constant comparison operand ahead of filter pushdown.
#[derive(Debug)]
@@ -52,26 +50,12 @@ impl AnalyzerRule for ConstNormalizationRule {
}
fn rewrite_plan_exprs(plan: LogicalPlan, schema: DFSchemaRef) -> Result<Transformed<LogicalPlan>> {
let mut rewriter = ConstNormalizationRewriter {
schema,
transformed: false,
};
let exprs = plan
.expressions_consider_join()
.into_iter()
.map(|expr| expr.rewrite(&mut rewriter).map(|rewritten| rewritten.data))
.collect::<Result<Vec<_>>>()?;
if !rewriter.transformed {
return Ok(Transformed::no(plan));
}
let inputs = plan.inputs().into_iter().cloned().collect::<Vec<_>>();
plan.with_new_exprs(exprs, inputs).map(Transformed::yes)
let mut rewriter = ConstNormalizationRewriter { schema };
plan.map_expressions(|expr| expr.rewrite(&mut rewriter))
}
struct ConstNormalizationRewriter {
schema: DFSchemaRef,
transformed: bool,
}
impl TreeNodeRewriter for ConstNormalizationRewriter {
@@ -91,44 +75,36 @@ impl TreeNodeRewriter for ConstNormalizationRewriter {
}
fn f_up(&mut self, expr: Expr) -> Result<Transformed<Expr>> {
let rewritten = rewrite_expr_node(expr, &self.schema)?;
self.transformed |= rewritten.transformed;
Ok(rewritten)
rewrite_expr_node(expr, &self.schema)
}
}
fn rewrite_expr_node(expr: Expr, schema: &DFSchemaRef) -> Result<Transformed<Expr>> {
match expr {
Expr::BinaryExpr(binary) => match rewrite_binary_expr(binary.clone(), schema)? {
Some(expr) => Ok(Transformed::yes(expr)),
None => Ok(Transformed::no(Expr::BinaryExpr(binary))),
},
Expr::Between(between) => match rewrite_between_expr(between.clone(), schema)? {
Some(expr) => Ok(Transformed::yes(expr)),
None => Ok(Transformed::no(Expr::Between(between))),
},
Expr::InList(in_list) => match rewrite_in_list_expr(in_list.clone(), schema)? {
Some(expr) => Ok(Transformed::yes(expr)),
None => Ok(Transformed::no(Expr::InList(in_list))),
},
Expr::Like(like) => rewrite_like_expr(like, PatternMatchKind::Like, schema),
Expr::SimilarTo(like) => rewrite_like_expr(like, PatternMatchKind::SimilarTo, schema),
expr => Ok(Transformed::no(expr)),
}
// Borrow while checking eligibility: cloning unchanged subtrees here can overflow
// the stack even though DataFusion protects the surrounding rewrite traversal.
let rewritten = match &expr {
Expr::BinaryExpr(binary) => rewrite_binary_expr(binary, schema)?,
Expr::Between(between) => rewrite_between_expr(between, schema)?,
Expr::InList(in_list) => rewrite_in_list_expr(in_list, schema)?,
Expr::Like(like) => rewrite_like_expr(like, PatternMatchKind::Like, schema)?,
Expr::SimilarTo(like) => rewrite_like_expr(like, PatternMatchKind::SimilarTo, schema)?,
_ => None,
};
Ok(match rewritten {
Some(rewritten) => Transformed::yes(rewritten),
None => Transformed::no(expr),
})
}
fn rewrite_between_expr(between: Between, schema: &DFSchemaRef) -> Result<Option<Expr>> {
fn rewrite_between_expr(between: &Between, schema: &DFSchemaRef) -> Result<Option<Expr>> {
let Between {
expr,
negated,
low,
high,
} = between;
let expr = *expr;
let low_expr = *low;
let high_expr = *high;
let Some((target, constants)) =
extract_rewrite_operands(&expr, &[low_expr.clone(), high_expr.clone()], schema)?
extract_rewrite_operands(expr, [low.as_ref(), high.as_ref()], schema)?
else {
return Ok(None);
};
@@ -142,7 +118,7 @@ fn rewrite_between_expr(between: Between, schema: &DFSchemaRef) -> Result<Option
.expect("between normalization expects low constant");
return Ok(Some(Expr::Between(Between {
expr: Box::new(target.expr.clone()),
negated,
negated: *negated,
low: Box::new(lit(low)),
high: Box::new(lit(high)),
})));
@@ -153,14 +129,13 @@ fn rewrite_between_expr(between: Between, schema: &DFSchemaRef) -> Result<Option
.flatten())
}
fn rewrite_in_list_expr(in_list: InList, schema: &DFSchemaRef) -> Result<Option<Expr>> {
fn rewrite_in_list_expr(in_list: &InList, schema: &DFSchemaRef) -> Result<Option<Expr>> {
let InList {
expr,
list,
negated,
} = in_list;
let expr = *expr;
let Some((target, constants)) = extract_rewrite_operands(&expr, &list, schema)? else {
let Some((target, constants)) = extract_rewrite_operands(expr, list, schema)? else {
return Ok(None);
};
@@ -168,19 +143,15 @@ fn rewrite_in_list_expr(in_list: InList, schema: &DFSchemaRef) -> Result<Option<
target
.expr
.clone()
.in_list(constants.into_iter().map(lit).collect(), negated)
.in_list(constants.into_iter().map(lit).collect(), *negated)
}))
}
fn rewrite_like_expr(
like: Like,
like: &Like,
kind: PatternMatchKind,
schema: &DFSchemaRef,
) -> Result<Transformed<Expr>> {
let original = match kind {
PatternMatchKind::Like => Expr::Like(like.clone()),
PatternMatchKind::SimilarTo => Expr::SimilarTo(like.clone()),
};
) -> Result<Option<Expr>> {
let Like {
negated,
expr,
@@ -188,43 +159,38 @@ fn rewrite_like_expr(
escape_char,
case_insensitive,
} = like;
let expr = *expr;
let pattern = *pattern;
let Some((target, constants)) =
extract_rewrite_operands(&expr, std::slice::from_ref(&pattern), schema)?
let Some((target, constants)) = extract_rewrite_operands(expr, [pattern.as_ref()], schema)?
else {
return Ok(Transformed::no(original));
return Ok(None);
};
let Some(mut constants) = target.normalize_constants(&constants) else {
return Ok(Transformed::no(original));
return Ok(None);
};
let pattern = lit(constants
.pop()
.expect("pattern normalization expects one constant"));
let like = Like::new(
negated,
*negated,
Box::new(target.expr.clone()),
Box::new(pattern),
escape_char,
case_insensitive,
*escape_char,
*case_insensitive,
);
let rewritten = match kind {
PatternMatchKind::Like => Expr::Like(like),
PatternMatchKind::SimilarTo => Expr::SimilarTo(like),
};
Ok(Transformed::yes(rewritten))
Ok(Some(rewritten))
}
fn rewrite_binary_expr(binary: BinaryExpr, schema: &DFSchemaRef) -> Result<Option<Expr>> {
fn rewrite_binary_expr(binary: &BinaryExpr, schema: &DFSchemaRef) -> Result<Option<Expr>> {
if !binary.op.supports_propagation() {
return Ok(None);
}
let BinaryExpr { left, op, right } = binary;
let left = *left;
let right = *right;
if let Some(expr) = rewrite_binary_side(left.clone(), op, right.clone(), schema)? {
if let Some(expr) = rewrite_binary_side(left, *op, right, schema)? {
return Ok(Some(expr));
}
@@ -236,13 +202,12 @@ fn rewrite_binary_expr(binary: BinaryExpr, schema: &DFSchemaRef) -> Result<Optio
}
fn rewrite_binary_side(
target_expr: Expr,
target_expr: &Expr,
op: Operator,
constant_expr: Expr,
constant_expr: &Expr,
schema: &DFSchemaRef,
) -> Result<Option<Expr>> {
let Some((target, constants)) =
extract_rewrite_operands(&target_expr, std::slice::from_ref(&constant_expr), schema)?
let Some((target, constants)) = extract_rewrite_operands(target_expr, [constant_expr], schema)?
else {
return Ok(None);
};
@@ -261,11 +226,11 @@ fn rewrite_binary_side(
Ok(target.normalize_timestamp_binary(op, &constants[0]))
}
fn extract_rewrite_operands(
target_expr: &Expr,
constant_exprs: &[Expr],
fn extract_rewrite_operands<'a, 'b>(
target_expr: &'a Expr,
constant_exprs: impl IntoIterator<Item = &'b Expr>,
schema: &DFSchemaRef,
) -> Result<Option<(NormalizationTarget, Vec<ScalarValue>)>> {
) -> Result<Option<(NormalizationTarget<'a>, Vec<ScalarValue>)>> {
let Some(target) = extract_normalization_target(target_expr, schema)? else {
return Ok(None);
};
@@ -275,8 +240,8 @@ fn extract_rewrite_operands(
}
#[derive(Clone)]
struct NormalizationTarget {
expr: Expr,
struct NormalizationTarget<'a> {
expr: &'a Expr,
data_type: DataType,
kind: NormalizationKind,
}
@@ -293,7 +258,7 @@ enum NormalizationKind {
},
}
impl NormalizationTarget {
impl NormalizationTarget<'_> {
/// Normalizes constants for rewrites that can preserve the original predicate with a direct
/// literal cast. Timestamp precision-changing casts are handled by timestamp-specific helpers.
fn normalize_constants(&self, constants: &[ScalarValue]) -> Option<Vec<ScalarValue>> {
@@ -394,17 +359,17 @@ impl NormalizationTarget {
///
/// Plain expressions normalize literals to their own type. Cast expressions only participate when
/// the cast is lossless or when timestamp downcasts can be rewritten as wider source-side bounds.
fn extract_normalization_target(
expr: &Expr,
fn extract_normalization_target<'a>(
expr: &'a Expr,
schema: &DFSchemaRef,
) -> Result<Option<NormalizationTarget>> {
) -> Result<Option<NormalizationTarget<'a>>> {
if extract_constant_scalar(expr)?.is_some() {
return Ok(None);
}
let Some((_, source_expr, target_type)) = extract_cast_input(expr) else {
return Ok(Some(NormalizationTarget {
expr: expr.clone(),
expr,
data_type: expr.get_type(schema)?,
kind: NormalizationKind::Lossless,
}));
@@ -416,7 +381,7 @@ fn extract_normalization_target(
};
Ok(Some(NormalizationTarget {
expr: source_expr.clone(),
expr: source_expr,
data_type,
kind,
}))
@@ -476,8 +441,11 @@ enum PatternMatchKind {
SimilarTo,
}
fn extract_constant_scalars(exprs: &[Expr]) -> Result<Option<Vec<ScalarValue>>> {
let mut values = Vec::with_capacity(exprs.len());
fn extract_constant_scalars<'a>(
exprs: impl IntoIterator<Item = &'a Expr>,
) -> Result<Option<Vec<ScalarValue>>> {
let exprs = exprs.into_iter();
let mut values = Vec::with_capacity(exprs.size_hint().0);
for expr in exprs {
let Some(value) = extract_constant_scalar(expr)? else {
return Ok(None);
@@ -606,11 +574,11 @@ mod tests {
use datafusion::physical_plan::ExecutionPlan;
use datafusion_common::arrow::datatypes::Field;
use datafusion_common::{DFSchema, ScalarValue, ToDFSchema};
use datafusion_expr::expr::{Between, Like};
use datafusion_expr::expr::{Between, BinaryExpr, Like};
use datafusion_expr::expr_fn::{cast, col, try_cast};
use datafusion_expr::{
Expr, LogicalPlan, LogicalPlanBuilder, TableProviderFilterPushDown, TableScan, TableSource,
TableType, lit,
Expr, LogicalPlan, LogicalPlanBuilder, Operator, TableProviderFilterPushDown, TableScan,
TableSource, TableType, lit,
};
use datafusion_optimizer::analyzer::AnalyzerRule;
use datafusion_optimizer::optimizer::{Optimizer, OptimizerContext};
@@ -621,6 +589,41 @@ mod tests {
ConstNormalizationRule, PatternMatchKind, lower_bound_for_ge, try_cast_literal_to_type,
};
#[test]
fn test_normalize_deep_predicate() {
std::thread::Builder::new()
.stack_size(2 * 1024 * 1024)
.spawn(|| {
let mut predicate = col("t.v").eq(lit(0_i64));
for value in 1..1024_i64 {
predicate = predicate.or(col("t.v").eq(lit(value)));
}
let schema = test_schema(vec![Field::new("v", DataType::Int32, false)]);
// Construct the filter directly to isolate this rule from other planner passes.
let plan = analyze_plan(LogicalPlan::Filter(
datafusion_expr::Filter::try_new(predicate, Arc::new(build_scan_plan(schema)))
.unwrap(),
));
let LogicalPlan::Filter(filter) = plan else {
panic!("expected filter");
};
// Inspect and consume the chain without recursive formatting or equality.
let mut predicate = filter.predicate;
for value in (1..1024_i32).rev() {
let Expr::BinaryExpr(BinaryExpr { left, op, right }) = predicate else {
panic!("expected binary predicate");
};
assert_eq!(op, Operator::Or);
assert_eq!(*right, col("t.v").eq(lit(value)));
predicate = *left;
}
assert_eq!(predicate, col("t.v").eq(lit(0_i32)));
})
.unwrap()
.join()
.unwrap();
}
#[test]
fn test_normalize_direct_integer_cast_comparison() {
assert_filter_plan(
+215
View File
@@ -0,0 +1,215 @@
// Copyright 2023 Greptime Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use datafusion_common::config::ConfigOptions;
use datafusion_common::tree_node::{TreeNode, TreeNodeRecursion};
use datafusion_common::{Result, plan_err};
use datafusion_expr::{Expr, LogicalPlan};
use datafusion_optimizer::analyzer::AnalyzerRule;
use promql::extension_plan::EmptyMetric;
use crate::dist_plan::{MergeScanLogicalPlan, MergeSortLogicalPlan};
use crate::range_select::plan::RangeSelect;
// A conservative optimizer input limit, not a guarantee for every recursive operation
// performed while parsing, planning, or dropping an arbitrarily deep query.
const MAX_EXPR_DEPTH: usize = 128;
/// Checks the analyzer output, including the SessionState EXPLAIN path.
#[derive(Debug)]
pub(crate) struct ExprDepthRule;
impl AnalyzerRule for ExprDepthRule {
fn name(&self) -> &str {
"expr_depth"
}
fn analyze(&self, plan: LogicalPlan, _: &ConfigOptions) -> Result<LogicalPlan> {
validate_plan(&plan)?;
Ok(plan)
}
}
/// Rejects deep expressions before recursive optimizer traversal, cloning, or display.
/// Both plan and expression traversal are iterative. Subquery Arcs are retained so
/// expressions supplied temporarily by extension nodes can also be inspected safely.
pub(crate) fn validate_plan(plan: &LogicalPlan) -> Result<()> {
let mut subqueries = Vec::new();
validate_plan_exprs(plan, &mut subqueries)?;
while let Some(plan) = subqueries.pop() {
validate_plan_exprs(&plan, &mut subqueries)?;
}
Ok(())
}
fn validate_plan_exprs(plan: &LogicalPlan, subqueries: &mut Vec<Arc<LogicalPlan>>) -> Result<()> {
let mut plans = vec![plan];
while let Some(plan) = plans.pop() {
let mut check = |expr: &Expr| {
validate_expr(expr, subqueries)?;
Ok(TreeNodeRecursion::Continue)
};
match plan {
// Extension expressions may clone deep trees; borrow known nodes instead.
LogicalPlan::Extension(extension) => {
let node = extension.node.as_any();
if let Some(range) = node.downcast_ref::<RangeSelect>() {
for expr in &range.range_expr {
check(&expr.expr)?;
}
check(&range.time_expr)?;
for expr in &range.by {
check(expr)?;
}
} else if let Some(sort) = node.downcast_ref::<MergeSortLogicalPlan>() {
for expr in &sort.expr {
check(&expr.expr)?;
}
} else if let Some(metric) = node.downcast_ref::<EmptyMetric>() {
if let Some(expr) = metric.expr() {
check(expr)?;
}
} else if let Some(scan) = node.downcast_ref::<MergeScanLogicalPlan>() {
// MergeScan deliberately hides this input from optimizer visitors.
plans.push(scan.input());
} else {
// The remaining built-in nodes only expose column expressions.
// External extensions own the safety of their expressions() implementation.
plan.apply_expressions(check)?;
}
}
LogicalPlan::Subquery(subquery) => {
for expr in &subquery.outer_ref_columns {
check(expr)?;
}
}
_ => {
plan.apply_expressions(check)?;
}
}
plans.extend(plan.inputs());
}
Ok(())
}
fn validate_expr(expr: &Expr, subqueries: &mut Vec<Arc<LogicalPlan>>) -> Result<()> {
let mut expressions = vec![(expr, 1)];
while let Some((expr, depth)) = expressions.pop() {
if depth > MAX_EXPR_DEPTH {
return plan_err!(
"Expression depth exceeds the maximum supported depth of {MAX_EXPR_DEPTH}"
);
}
let subquery = match expr {
Expr::Exists(exists) => Some(&exists.subquery),
Expr::ScalarSubquery(subquery) => Some(subquery),
Expr::InSubquery(in_subquery) => Some(&in_subquery.subquery),
Expr::SetComparison(comparison) => Some(&comparison.subquery),
_ => None,
};
if let Some(subquery) = subquery {
subqueries.push(Arc::clone(&subquery.subquery));
expressions.extend(subquery.outer_ref_columns.iter().map(|expr| (expr, 1)));
}
expr.apply_children(|child| {
expressions.push((child, depth + 1));
Ok(TreeNodeRecursion::Continue)
})?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use arrow_schema::{DataType, Field, Schema};
use datafusion_common::DFSchema;
use datafusion_expr::expr::{Exists, InSubquery, SetComparison, SetQuantifier};
use datafusion_expr::{EmptyRelation, Filter, Operator, Subquery, lit};
use super::*;
fn filter(predicate: Expr) -> LogicalPlan {
LogicalPlan::Filter(
Filter::try_new(
predicate,
Arc::new(LogicalPlan::EmptyRelation(EmptyRelation {
produce_one_row: true,
schema: Arc::new(
DFSchema::try_from(Schema::new(vec![Field::new(
"value",
DataType::Boolean,
false,
)]))
.unwrap(),
),
})),
)
.unwrap(),
)
}
#[test]
fn test_depth_in_subqueries_and_hidden_input() {
std::thread::Builder::new()
.stack_size(2 * 1024 * 1024)
.spawn(|| {
for depth in [MAX_EXPR_DEPTH, MAX_EXPR_DEPTH + 1, 512] {
let mut predicate = lit(true);
for _ in 1..depth {
predicate = predicate.or(lit(false));
}
// MergeScan hides its input, and apply_children on an Expr
// does not visit the plan embedded in its subquery.
let plan = MergeScanLogicalPlan::new(filter(predicate), false, Default::default())
.into_logical_plan();
let subquery = Subquery {
subquery: Arc::new(plan),
outer_ref_columns: vec![],
spans: Default::default(),
};
for expr in [
Expr::Exists(Exists::new(subquery.clone(), false)),
Expr::ScalarSubquery(subquery.clone()),
Expr::InSubquery(InSubquery::new(
Box::new(lit(true)),
subquery.clone(),
false,
)),
Expr::SetComparison(SetComparison::new(
Box::new(lit(true)),
subquery.clone(),
Operator::Eq,
SetQuantifier::Any,
)),
] {
let result = validate_plan(&filter(expr));
if depth <= MAX_EXPR_DEPTH {
result.unwrap();
} else {
assert!(matches!(
result,
Err(datafusion_common::DataFusionError::Plan(message))
if message == "Expression depth exceeds the maximum supported depth of 128"
));
}
}
}
})
.unwrap()
.join()
.unwrap();
}
}
+2
View File
@@ -51,6 +51,7 @@ use crate::error::{
UnimplementedSnafu,
};
use crate::log_query::planner::LogQueryPlanner;
use crate::optimizer::expr_depth;
use crate::parser::{DEFAULT_LOOKBACK_STRING, PromQuery, QueryLanguageParser, QueryStatement};
use crate::promql::planner::PromPlanner;
use crate::query_engine::{DefaultPlanDecoder, QueryEngineState};
@@ -251,6 +252,7 @@ impl DfLogicalPlanner {
.context(PlanSqlSnafu)?
};
expr_depth::validate_plan(&result)?;
common_telemetry::debug!("Logical planner, statement to plan result: {result}");
let plan = RangePlanRewriter::new(table_provider, query_ctx.clone())
.rewrite(result)
+8 -2
View File
@@ -61,7 +61,6 @@ use crate::dist_plan::{
RemoteDynFilterRegistryLease,
};
use crate::metrics::{QUERY_MEMORY_POOL_REJECTED_TOTAL, QUERY_MEMORY_POOL_USAGE_BYTES};
use crate::optimizer::ExtensionAnalyzerRule;
use crate::optimizer::const_normalization::ConstNormalizationRule;
use crate::optimizer::constant_term::MatchesConstantTermOptimizer;
use crate::optimizer::count_nest_aggr::CountNestAggrRule;
@@ -76,6 +75,7 @@ use crate::optimizer::string_normalization::StringNormalizationRule;
use crate::optimizer::transcribe_atat::TranscribeAtatRule;
use crate::optimizer::type_conversion::TypeConversionRule;
use crate::optimizer::windowed_sort::WindowedSortPhysicalRule;
use crate::optimizer::{ExtensionAnalyzerRule, expr_depth};
use crate::options::QueryOptions as QueryOptionsNew;
use crate::query_engine::DefaultSerializer;
use crate::query_engine::options::QueryOptions;
@@ -179,6 +179,7 @@ impl QueryEngineState {
analyzer.rules.push(Arc::new(DistPlannerAnalyzer));
}
analyzer.rules.push(Arc::new(FixStateUdafOrderingAnalyzer));
analyzer.rules.push(Arc::new(expr_depth::ExprDepthRule));
let mut optimizer = Optimizer::new();
optimizer.rules.push(Arc::new(ScanHintRule));
@@ -271,15 +272,20 @@ impl QueryEngineState {
plan: DfLogicalPlan,
context: &QueryEngineContext,
) -> DfResult<DfLogicalPlan> {
expr_depth::validate_plan(&plan)?;
self.extension_rules
.iter()
.try_fold(plan, |acc_plan, rule| {
rule.analyze(acc_plan, context, self.session_state().config_options())
let plan =
rule.analyze(acc_plan, context, self.session_state().config_options())?;
expr_depth::validate_plan(&plan)?;
Ok(plan)
})
}
/// Run the full logical plan optimize phase for the given plan.
pub fn optimize_logical_plan(&self, plan: DfLogicalPlan) -> DfResult<DfLogicalPlan> {
expr_depth::validate_plan(&plan)?;
self.session_state().optimize(&plan)
}
+11 -21
View File
@@ -15,8 +15,6 @@
use std::collections::HashMap;
use std::sync::Arc;
use api::region::RegionResponse;
use api::v1::meta::Peer;
use api::v1::region::RegionRequest;
use arrow::array::{Float64Array, StringArray, TimestampMillisecondArray};
use arrow::datatypes::{DataType as ArrowDataType, Field, Schema as ArrowSchema, TimeUnit};
@@ -28,12 +26,11 @@ use datatypes::prelude::ConcreteDataType;
use datatypes::schema::{ColumnSchema as DtColumnSchema, Schema as DtSchema};
use partition::error::Result as PartitionResult;
use partition::partition::{PartitionRule, PartitionRuleRef, RegionMask};
use servers::error::{self, Result};
use servers::error;
use servers::pending_rows_batcher::{
PhysicalFlushCatalogProvider, PhysicalFlushNodeRequester, PhysicalFlushPartitionProvider,
PhysicalFlushCatalogProvider, PhysicalFlushPartitionProvider, PhysicalFlushWriteDispatcher,
PhysicalTableMetadata, TableBatch, flush_batch_physical,
};
use store_api::storage::RegionId;
use table::test_util::table_info::test_table_info;
use tokio::runtime::Runtime;
@@ -95,24 +92,17 @@ impl PhysicalFlushPartitionProvider for BenchPartitionProvider {
async fn find_table_partition_rule(
&self,
_table_info: &table::metadata::TableInfo,
) -> PartitionResult<PartitionRuleRef> {
Ok(Arc::new(SingleRegionPartitionRule))
}
async fn find_region_leader(&self, _region_id: RegionId) -> Result<Peer> {
Ok(Peer {
id: 1,
addr: "bench-node".to_string(),
})
) -> PartitionResult<(PartitionRuleRef, HashMap<u32, Option<u64>>)> {
Ok((Arc::new(SingleRegionPartitionRule), HashMap::new()))
}
}
struct BenchNodeRequester;
struct BenchWriteDispatcher;
#[async_trait]
impl PhysicalFlushNodeRequester for BenchNodeRequester {
async fn handle(&self, _peer: &Peer, _request: RegionRequest) -> error::Result<RegionResponse> {
Ok(RegionResponse::new(0))
impl PhysicalFlushWriteDispatcher for BenchWriteDispatcher {
async fn dispatch(&self, _requests: Vec<RegionRequest>) -> error::Result<usize> {
Ok(0)
}
}
@@ -224,7 +214,7 @@ fn bench_flush_batch_physical(c: &mut Criterion) {
table: make_physical_table_metadata(num_tags),
};
let partition_provider = BenchPartitionProvider;
let node_requester = BenchNodeRequester;
let write_dispatcher = BenchWriteDispatcher;
let mut group = c.benchmark_group("flush_batch_physical");
@@ -244,7 +234,7 @@ fn bench_flush_batch_physical(c: &mut Criterion) {
"phy",
&ctx,
&partition_provider,
&node_requester,
&write_dispatcher,
&catalog_provider,
)
.await
@@ -271,7 +261,7 @@ fn bench_flush_batch_physical(c: &mut Criterion) {
"phy",
&ctx,
&partition_provider,
&node_requester,
&write_dispatcher,
&catalog_provider,
)
.await
+42 -1
View File
@@ -23,7 +23,7 @@ use axum::{Json, http};
use base64::DecodeError;
use common_base::readable_size::ReadableSize;
use common_error::define_into_tonic_status;
use common_error::ext::{BoxedError, ErrorExt};
use common_error::ext::{BoxedError, ErrorExt, RetryHint};
use common_error::status_code::StatusCode;
use common_macro::stack_trace_debug;
use common_telemetry::{error, warn};
@@ -853,6 +853,47 @@ impl ErrorExt for Error {
}
}
fn retry_hint(&self) -> RetryHint {
use Error::*;
match self {
ExecuteQuery { source, .. }
| ExecutePlan { source, .. }
| ExecuteGrpcQuery { source, .. }
| ExecuteGrpcRequest { source, .. }
| CheckDatabaseValidity { source, .. }
| DescribeStatement { source } => source.retry_hint(),
Pipeline { source, .. } => source.retry_hint(),
CommonMeta { source, .. } => source.retry_hint(),
Catalog { source, .. } => source.retry_hint(),
RowWriter { source, .. } => source.retry_hint(),
Auth { source, .. } => source.retry_hint(),
#[cfg(feature = "mem-prof")]
DumpProfileData { source, .. } => source.retry_hint(),
ParsePromQL { source, .. } => source.retry_hint(),
Other { source, .. } => source.retry_hint(),
#[cfg(feature = "pprof")]
DumpPprof { source, .. } => source.retry_hint(),
ConvertScalarValue { source, .. } => source.retry_hint(),
ConvertSqlValue { source, .. } => source.retry_hint(),
GreptimeProto { source, .. } => source.retry_hint(),
Partition { source, .. } => source.retry_hint(),
MetricEngine { source, .. } => source.retry_hint(),
SubmitBatch { source, .. } => source.retry_hint(),
MemoryLimitExceeded { source, .. } => source.retry_hint(),
CollectRecordbatch { source, .. } => source.retry_hint(),
TooManyConcurrentRequests { .. } => RetryHint::Retryable,
_ => RetryHint::NonRetryable,
}
}
fn as_any(&self) -> &dyn Any {
self
}
File diff suppressed because it is too large Load Diff
+23 -1
View File
@@ -24,7 +24,7 @@ use flow::FlowConfig;
use frontend::frontend::FrontendOptions;
use frontend::service_config::{
InfluxdbOptions, JaegerOptions, MysqlOptions, OpentsdbOptions, PostgresOptions,
PromStoreOptions,
PromStoreOptions, WriteRetryOptions,
};
use mito2::config::MitoConfig;
use query::options::QueryOptions;
@@ -147,6 +147,11 @@ impl StandaloneOptions {
jaeger: cloned_opts.jaeger,
prom_store: cloned_opts.prom_store,
meta_client: None,
// Local region calls consume requests directly and do not use remote write retries.
write_retry: WriteRetryOptions {
max_retries: 0,
..Default::default()
},
logging: cloned_opts.logging,
user_provider: cloned_opts.user_provider,
slow_query: cloned_opts.slow_query,
@@ -183,3 +188,20 @@ impl StandaloneOptions {
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_frontend_write_retries_disabled() {
assert!(FrontendOptions::default().write_retry.max_retries > 0);
assert_eq!(
StandaloneOptions::default()
.frontend_options()
.write_retry
.max_retries,
0
);
}
}
+1
View File
@@ -643,6 +643,7 @@ async fn setup_test_prom_app_with_frontend_inner(
PendingRowsBatcher::try_new(
frontend_ref.partition_manager().clone(),
frontend_ref.node_manager().clone(),
frontend_ref.inserter().write_dispatcher().clone(),
frontend_ref.catalog_manager().clone(),
true,
frontend_ref.clone(),
+51
View File
@@ -82,6 +82,7 @@ macro_rules! sql_tests {
test_postgres_datestyle,
test_postgres_intervalstyle,
test_postgres_parameter_inference,
test_postgres_expression_depth,
test_postgres_uint64_parameter,
test_postgres_explain_bind_parameter,
test_postgres_array_types,
@@ -1303,6 +1304,56 @@ pub async fn test_postgres_parameter_inference(store_type: StorageType) {
guard.remove_all().await;
}
// Regression for #9553: reject the predicate before DataFusion's simplifier
// overflows the worker stack, and keep the extended-query connection usable.
pub async fn test_postgres_expression_depth(store_type: StorageType) {
let (mut guard, server) = setup_pg_server(store_type, "test_postgres_expression_depth").await;
let addr = server.bind_addr().unwrap();
let (client, connection) = tokio_postgres::connect(&format!("postgres://{addr}/public"), NoTls)
.await
.unwrap();
let connection = tokio::spawn(connection);
client
.simple_query(
"CREATE TABLE depth_guard (ts TIMESTAMP TIME INDEX, v INT); \
INSERT INTO depth_guard VALUES (0, 42)",
)
.await
.unwrap();
let query = |terms: usize| {
let predicate = std::iter::once("CAST(v AS BIGINT) = $1".to_string())
.chain((1..terms).map(|i| format!("CAST(v AS BIGINT) = {i}")))
.collect::<Vec<_>>()
.join(" OR ");
format!("SELECT count(*) FROM depth_guard WHERE {predicate}")
};
let row = client.query_one(&query(64), &[&42_i64]).await.unwrap();
assert_eq!(row.get::<_, i64>(0), 1);
for prefix in ["", "EXPLAIN ", "EXPLAIN ANALYZE "] {
let error = client
.query(&format!("{prefix}{}", query(512)), &[&42_i64])
.await
.unwrap_err();
assert!(
error
.as_db_error()
.unwrap()
.message()
.contains("Expression depth exceeds the maximum supported depth of 128"),
"{error}"
);
let row = client.query_one("SELECT 42::BIGINT", &[]).await.unwrap();
assert_eq!(row.get::<_, i64>(0), 42);
}
drop(client);
connection.await.unwrap().unwrap();
server.shutdown().await.unwrap();
guard.remove_all().await;
}
pub async fn test_postgres_uint64_parameter(store_type: StorageType) {
let (mut guard, fe_pg_server) =
setup_pg_server(store_type, "test_postgres_uint64_parameter").await;
@@ -0,0 +1,24 @@
CREATE TABLE depth_guard (ts TIMESTAMP TIME INDEX, v INT);
Affected Rows: 0
INSERT INTO depth_guard VALUES (0, 42);
Affected Rows: 1
SELECT count(*) FROM depth_guard WHERE CAST(v AS BIGINT) = 0 OR CAST(v AS BIGINT) = 1 OR CAST(v AS BIGINT) = 2 OR CAST(v AS BIGINT) = 3 OR CAST(v AS BIGINT) = 4 OR CAST(v AS BIGINT) = 5 OR CAST(v AS BIGINT) = 6 OR CAST(v AS BIGINT) = 7 OR CAST(v AS BIGINT) = 8 OR CAST(v AS BIGINT) = 9 OR CAST(v AS BIGINT) = 10 OR CAST(v AS BIGINT) = 11 OR CAST(v AS BIGINT) = 12 OR CAST(v AS BIGINT) = 13 OR CAST(v AS BIGINT) = 14 OR CAST(v AS BIGINT) = 15 OR CAST(v AS BIGINT) = 16 OR CAST(v AS BIGINT) = 17 OR CAST(v AS BIGINT) = 18 OR CAST(v AS BIGINT) = 19 OR CAST(v AS BIGINT) = 20 OR CAST(v AS BIGINT) = 21 OR CAST(v AS BIGINT) = 22 OR CAST(v AS BIGINT) = 23 OR CAST(v AS BIGINT) = 24 OR CAST(v AS BIGINT) = 25 OR CAST(v AS BIGINT) = 26 OR CAST(v AS BIGINT) = 27 OR CAST(v AS BIGINT) = 28 OR CAST(v AS BIGINT) = 29 OR CAST(v AS BIGINT) = 30 OR CAST(v AS BIGINT) = 31 OR CAST(v AS BIGINT) = 32 OR CAST(v AS BIGINT) = 33 OR CAST(v AS BIGINT) = 34 OR CAST(v AS BIGINT) = 35 OR CAST(v AS BIGINT) = 36 OR CAST(v AS BIGINT) = 37 OR CAST(v AS BIGINT) = 38 OR CAST(v AS BIGINT) = 39 OR CAST(v AS BIGINT) = 40 OR CAST(v AS BIGINT) = 41 OR CAST(v AS BIGINT) = 42 OR CAST(v AS BIGINT) = 43 OR CAST(v AS BIGINT) = 44 OR CAST(v AS BIGINT) = 45 OR CAST(v AS BIGINT) = 46 OR CAST(v AS BIGINT) = 47 OR CAST(v AS BIGINT) = 48 OR CAST(v AS BIGINT) = 49 OR CAST(v AS BIGINT) = 50 OR CAST(v AS BIGINT) = 51 OR CAST(v AS BIGINT) = 52 OR CAST(v AS BIGINT) = 53 OR CAST(v AS BIGINT) = 54 OR CAST(v AS BIGINT) = 55 OR CAST(v AS BIGINT) = 56 OR CAST(v AS BIGINT) = 57 OR CAST(v AS BIGINT) = 58 OR CAST(v AS BIGINT) = 59 OR CAST(v AS BIGINT) = 60 OR CAST(v AS BIGINT) = 61 OR CAST(v AS BIGINT) = 62 OR CAST(v AS BIGINT) = 63 OR CAST(v AS BIGINT) = 64 OR CAST(v AS BIGINT) = 65 OR CAST(v AS BIGINT) = 66 OR CAST(v AS BIGINT) = 67 OR CAST(v AS BIGINT) = 68 OR CAST(v AS BIGINT) = 69 OR CAST(v AS BIGINT) = 70 OR CAST(v AS BIGINT) = 71 OR CAST(v AS BIGINT) = 72 OR CAST(v AS BIGINT) = 73 OR CAST(v AS BIGINT) = 74 OR CAST(v AS BIGINT) = 75 OR CAST(v AS BIGINT) = 76 OR CAST(v AS BIGINT) = 77 OR CAST(v AS BIGINT) = 78 OR CAST(v AS BIGINT) = 79 OR CAST(v AS BIGINT) = 80 OR CAST(v AS BIGINT) = 81 OR CAST(v AS BIGINT) = 82 OR CAST(v AS BIGINT) = 83 OR CAST(v AS BIGINT) = 84 OR CAST(v AS BIGINT) = 85 OR CAST(v AS BIGINT) = 86 OR CAST(v AS BIGINT) = 87 OR CAST(v AS BIGINT) = 88 OR CAST(v AS BIGINT) = 89 OR CAST(v AS BIGINT) = 90 OR CAST(v AS BIGINT) = 91 OR CAST(v AS BIGINT) = 92 OR CAST(v AS BIGINT) = 93 OR CAST(v AS BIGINT) = 94 OR CAST(v AS BIGINT) = 95 OR CAST(v AS BIGINT) = 96 OR CAST(v AS BIGINT) = 97 OR CAST(v AS BIGINT) = 98 OR CAST(v AS BIGINT) = 99 OR CAST(v AS BIGINT) = 100 OR CAST(v AS BIGINT) = 101 OR CAST(v AS BIGINT) = 102 OR CAST(v AS BIGINT) = 103 OR CAST(v AS BIGINT) = 104 OR CAST(v AS BIGINT) = 105 OR CAST(v AS BIGINT) = 106 OR CAST(v AS BIGINT) = 107 OR CAST(v AS BIGINT) = 108 OR CAST(v AS BIGINT) = 109 OR CAST(v AS BIGINT) = 110 OR CAST(v AS BIGINT) = 111 OR CAST(v AS BIGINT) = 112 OR CAST(v AS BIGINT) = 113 OR CAST(v AS BIGINT) = 114 OR CAST(v AS BIGINT) = 115 OR CAST(v AS BIGINT) = 116 OR CAST(v AS BIGINT) = 117 OR CAST(v AS BIGINT) = 118 OR CAST(v AS BIGINT) = 119 OR CAST(v AS BIGINT) = 120 OR CAST(v AS BIGINT) = 121 OR CAST(v AS BIGINT) = 122 OR CAST(v AS BIGINT) = 123 OR CAST(v AS BIGINT) = 124 OR CAST(v AS BIGINT) = 125 OR CAST(v AS BIGINT) = 126 OR CAST(v AS BIGINT) = 127 OR CAST(v AS BIGINT) = 128 OR CAST(v AS BIGINT) = 129;
Error: 3000(PlanQuery), Error during planning: Expression depth exceeds the maximum supported depth of 128
SELECT count(*) FROM depth_guard WHERE v = 42;
+----------+
| count(*) |
+----------+
| 1 |
+----------+
DROP TABLE depth_guard;
Affected Rows: 0
@@ -0,0 +1,9 @@
CREATE TABLE depth_guard (ts TIMESTAMP TIME INDEX, v INT);
INSERT INTO depth_guard VALUES (0, 42);
SELECT count(*) FROM depth_guard WHERE CAST(v AS BIGINT) = 0 OR CAST(v AS BIGINT) = 1 OR CAST(v AS BIGINT) = 2 OR CAST(v AS BIGINT) = 3 OR CAST(v AS BIGINT) = 4 OR CAST(v AS BIGINT) = 5 OR CAST(v AS BIGINT) = 6 OR CAST(v AS BIGINT) = 7 OR CAST(v AS BIGINT) = 8 OR CAST(v AS BIGINT) = 9 OR CAST(v AS BIGINT) = 10 OR CAST(v AS BIGINT) = 11 OR CAST(v AS BIGINT) = 12 OR CAST(v AS BIGINT) = 13 OR CAST(v AS BIGINT) = 14 OR CAST(v AS BIGINT) = 15 OR CAST(v AS BIGINT) = 16 OR CAST(v AS BIGINT) = 17 OR CAST(v AS BIGINT) = 18 OR CAST(v AS BIGINT) = 19 OR CAST(v AS BIGINT) = 20 OR CAST(v AS BIGINT) = 21 OR CAST(v AS BIGINT) = 22 OR CAST(v AS BIGINT) = 23 OR CAST(v AS BIGINT) = 24 OR CAST(v AS BIGINT) = 25 OR CAST(v AS BIGINT) = 26 OR CAST(v AS BIGINT) = 27 OR CAST(v AS BIGINT) = 28 OR CAST(v AS BIGINT) = 29 OR CAST(v AS BIGINT) = 30 OR CAST(v AS BIGINT) = 31 OR CAST(v AS BIGINT) = 32 OR CAST(v AS BIGINT) = 33 OR CAST(v AS BIGINT) = 34 OR CAST(v AS BIGINT) = 35 OR CAST(v AS BIGINT) = 36 OR CAST(v AS BIGINT) = 37 OR CAST(v AS BIGINT) = 38 OR CAST(v AS BIGINT) = 39 OR CAST(v AS BIGINT) = 40 OR CAST(v AS BIGINT) = 41 OR CAST(v AS BIGINT) = 42 OR CAST(v AS BIGINT) = 43 OR CAST(v AS BIGINT) = 44 OR CAST(v AS BIGINT) = 45 OR CAST(v AS BIGINT) = 46 OR CAST(v AS BIGINT) = 47 OR CAST(v AS BIGINT) = 48 OR CAST(v AS BIGINT) = 49 OR CAST(v AS BIGINT) = 50 OR CAST(v AS BIGINT) = 51 OR CAST(v AS BIGINT) = 52 OR CAST(v AS BIGINT) = 53 OR CAST(v AS BIGINT) = 54 OR CAST(v AS BIGINT) = 55 OR CAST(v AS BIGINT) = 56 OR CAST(v AS BIGINT) = 57 OR CAST(v AS BIGINT) = 58 OR CAST(v AS BIGINT) = 59 OR CAST(v AS BIGINT) = 60 OR CAST(v AS BIGINT) = 61 OR CAST(v AS BIGINT) = 62 OR CAST(v AS BIGINT) = 63 OR CAST(v AS BIGINT) = 64 OR CAST(v AS BIGINT) = 65 OR CAST(v AS BIGINT) = 66 OR CAST(v AS BIGINT) = 67 OR CAST(v AS BIGINT) = 68 OR CAST(v AS BIGINT) = 69 OR CAST(v AS BIGINT) = 70 OR CAST(v AS BIGINT) = 71 OR CAST(v AS BIGINT) = 72 OR CAST(v AS BIGINT) = 73 OR CAST(v AS BIGINT) = 74 OR CAST(v AS BIGINT) = 75 OR CAST(v AS BIGINT) = 76 OR CAST(v AS BIGINT) = 77 OR CAST(v AS BIGINT) = 78 OR CAST(v AS BIGINT) = 79 OR CAST(v AS BIGINT) = 80 OR CAST(v AS BIGINT) = 81 OR CAST(v AS BIGINT) = 82 OR CAST(v AS BIGINT) = 83 OR CAST(v AS BIGINT) = 84 OR CAST(v AS BIGINT) = 85 OR CAST(v AS BIGINT) = 86 OR CAST(v AS BIGINT) = 87 OR CAST(v AS BIGINT) = 88 OR CAST(v AS BIGINT) = 89 OR CAST(v AS BIGINT) = 90 OR CAST(v AS BIGINT) = 91 OR CAST(v AS BIGINT) = 92 OR CAST(v AS BIGINT) = 93 OR CAST(v AS BIGINT) = 94 OR CAST(v AS BIGINT) = 95 OR CAST(v AS BIGINT) = 96 OR CAST(v AS BIGINT) = 97 OR CAST(v AS BIGINT) = 98 OR CAST(v AS BIGINT) = 99 OR CAST(v AS BIGINT) = 100 OR CAST(v AS BIGINT) = 101 OR CAST(v AS BIGINT) = 102 OR CAST(v AS BIGINT) = 103 OR CAST(v AS BIGINT) = 104 OR CAST(v AS BIGINT) = 105 OR CAST(v AS BIGINT) = 106 OR CAST(v AS BIGINT) = 107 OR CAST(v AS BIGINT) = 108 OR CAST(v AS BIGINT) = 109 OR CAST(v AS BIGINT) = 110 OR CAST(v AS BIGINT) = 111 OR CAST(v AS BIGINT) = 112 OR CAST(v AS BIGINT) = 113 OR CAST(v AS BIGINT) = 114 OR CAST(v AS BIGINT) = 115 OR CAST(v AS BIGINT) = 116 OR CAST(v AS BIGINT) = 117 OR CAST(v AS BIGINT) = 118 OR CAST(v AS BIGINT) = 119 OR CAST(v AS BIGINT) = 120 OR CAST(v AS BIGINT) = 121 OR CAST(v AS BIGINT) = 122 OR CAST(v AS BIGINT) = 123 OR CAST(v AS BIGINT) = 124 OR CAST(v AS BIGINT) = 125 OR CAST(v AS BIGINT) = 126 OR CAST(v AS BIGINT) = 127 OR CAST(v AS BIGINT) = 128 OR CAST(v AS BIGINT) = 129;
SELECT count(*) FROM depth_guard WHERE v = 42;
DROP TABLE depth_guard;
@@ -101,6 +101,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test;
|_|_TableScan: test_|
|_| ]]_|
| logical_plan after FixStateUdafOrderingAnalyzer_| SAME TEXT AS ABOVE_|
| logical_plan after expr_depth_| SAME TEXT AS ABOVE_|
| analyzed_logical_plan_| SAME TEXT AS ABOVE_|
| logical_plan after rewrite_set_comparison_| SAME TEXT AS ABOVE_|
| logical_plan after optimize_unions_| SAME TEXT AS ABOVE_|
@@ -250,6 +251,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test AS series;
|_|_TableScan: test_|
|_| ]]_|
| logical_plan after FixStateUdafOrderingAnalyzer_| SAME TEXT AS ABOVE_|
| logical_plan after expr_depth_| SAME TEXT AS ABOVE_|
| analyzed_logical_plan_| SAME TEXT AS ABOVE_|
| logical_plan after rewrite_set_comparison_| SAME TEXT AS ABOVE_|
| logical_plan after optimize_unions_| SAME TEXT AS ABOVE_|
@@ -439,6 +441,7 @@ TQL EXPLAIN VERBOSE (0, 10, '5s') test_nano;
|_| TableScan: test_nano_|
|_| ]]_|
| logical_plan after FixStateUdafOrderingAnalyzer_| SAME TEXT AS ABOVE_|
| logical_plan after expr_depth_| SAME TEXT AS ABOVE_|
| analyzed_logical_plan_| SAME TEXT AS ABOVE_|
| logical_plan after rewrite_set_comparison_| SAME TEXT AS ABOVE_|
| logical_plan after optimize_unions_| SAME TEXT AS ABOVE_|