diff --git a/Cargo.lock b/Cargo.lock
index 6f9fcb4ae81..ee3747744d6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -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",
diff --git a/Cargo.toml b/Cargo.toml
index 60e29c40de8..cdfbde440d3 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -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"
diff --git a/config/config.md b/config/config.md
index 15d431e2af3..0c8e6f263e7 100644
--- a/config/config.md
+++ b/config/config.md
@@ -316,6 +316,11 @@
| `query.parallelism` | Integer | `0` | Parallelism of the query engine.
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.
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).
Supports absolute size (e.g., "4GB", "8GB") or percentage of system memory (e.g., "30%").
Setting it to 0 disables the limit (unbounded, default behavior).
When this limit is reached, queries will fail with ResourceExhausted error.
NOTE: This does NOT limit memory used by table scans (only applies to datanodes). |
+| `write_retry` | -- | -- | Retry retryable distributed write failures.
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` | -- |
diff --git a/config/frontend.example.toml b/config/frontend.example.toml
index 23de91fbb22..19da5e5cbc9 100644
--- a/config/frontend.example.toml
+++ b/config/frontend.example.toml
@@ -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.
diff --git a/src/auth/src/error.rs b/src/auth/src/error.rs
index a8dfe7f629e..2b339b86554 100644
--- a/src/auth/src/error.rs
+++ b/src/auth/src/error.rs
@@ -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 = std::result::Result;
diff --git a/src/cli/src/data/export_v2/error.rs b/src/cli/src/data/export_v2/error.rs
index e16e3a6176a..078f5bd2e1f 100644
--- a/src/cli/src/data/export_v2/error.rs
+++ b/src/cli/src/data/export_v2/error.rs
@@ -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,
+ }
+ }
}
diff --git a/src/cli/src/data/import_v2/error.rs b/src/cli/src/data/import_v2/error.rs
index 165f1c01188..967a62bd831 100644
--- a/src/cli/src/data/import_v2/error.rs
+++ b/src/cli/src/data/import_v2/error.rs
@@ -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
}
diff --git a/src/client/Cargo.toml b/src/client/Cargo.toml
index 963656e17b1..024994f67be 100644
--- a/src/client/Cargo.toml
+++ b/src/client/Cargo.toml
@@ -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
diff --git a/src/client/src/client.rs b/src/client/src/client.rs
index 39cb5c30aab..f03e664b2d0 100644
--- a/src/client/src/client.rs
+++ b/src/client/src/client.rs
@@ -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)> {
+ /// Creates the region gRPC transport with the configured message limits.
+ pub(crate) fn raw_region_client(&self) -> Result<(String, tonic::client::Grpc)> {
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))
diff --git a/src/client/src/database.rs b/src/client/src/database.rs
index 66169628388..384a6ad4c21 100644
--- a/src/client/src/database.rs
+++ b/src/client/src/database.rs
@@ -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]
diff --git a/src/client/src/error.rs b/src/client/src/error.rs
index aa6940dd8be..881d4f004ec 100644
--- a/src/client/src/error.rs
+++ b/src/client/src/error.rs
@@ -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 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 {
@@ -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)
diff --git a/src/client/src/region.rs b/src/client/src/region.rs
index 19c173bd05d..ca2672685a6 100644
--- a/src/client/src/region.rs
+++ b/src/client/src/region.rs
@@ -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 {
- 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) -> MetaResult {
+ self.handle_inner(request).await.map_err(Into::into)
}
async fn handle_query(&self, request: QueryRequest) -> MetaResult {
@@ -251,43 +244,15 @@ impl RegionRequester {
Ok(Box::pin(record_batch_stream))
}
- async fn handle_inner(&self, request: RegionRequest) -> Result {
- 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 {
+ /// Sends an owned or shared request without deep-cloning its protobuf payload.
+ pub async fn handle(&self, request: R) -> Result
+ where
+ R: Borrow + 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,
@@ -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,
@@ -307,6 +273,72 @@ impl RegionRequester {
))
.await
}
+
+ async fn handle_inner(&self, request: R) -> Result
+ where
+ R: Borrow + 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) -> 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>>,
+ responses: Arc>>>,
+ }
+
+ #[tonic::async_trait]
+ impl Region for RecordingRegionService {
+ async fn handle(
+ &self,
+ request: Request,
+ ) -> std::result::Result, 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::().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::>()
+ );
+ }
#[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);
diff --git a/src/client/src/region/codec.rs b/src/client/src/region/codec.rs
new file mode 100644
index 00000000000..9476385df36
--- /dev/null
+++ b/src/client/src/region/codec.rs
@@ -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(PhantomData);
+
+impl Default for RegionCodec {
+ fn default() -> Self {
+ Self(PhantomData)
+ }
+}
+
+impl Codec for RegionCodec
+where
+ R: Borrow + Send + 'static,
+{
+ type Encode = R;
+ type Decode = RegionResponse;
+ type Encoder = RegionEncoder;
+ type Decoder = ProstDecoder;
+
+ 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(PhantomData);
+
+impl> Encoder for RegionEncoder {
+ 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()))
+ }
+}
diff --git a/src/common/datasource/src/error.rs b/src/common/datasource/src/error.rs
index 4b514b5b200..3c68bbc1475 100644
--- a/src/common/datasource/src/error.rs
+++ b/src/common/datasource/src/error.rs
@@ -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,
+ }
+ }
}
diff --git a/src/common/error/src/ext.rs b/src/common/error/src/ext.rs
index edd49fed359..408453d6f35 100644
--- a/src/common/error/src/ext.rs
+++ b/src/common/error/src/ext.rs
@@ -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 {
+ 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()
}
diff --git a/src/common/error/src/lib.rs b/src/common/error/src/lib.rs
index 9b6facda2c3..eeedc637133 100644
--- a/src/common/error/src/lib.rs
+++ b/src/common/error/src/lib.rs
@@ -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.
diff --git a/src/common/error/src/status_code.rs b/src/common/error/src/status_code.rs
index 4dc5a0398e0..a299b18994c 100644
--- a/src/common/error/src/status_code.rs
+++ b/src/common/error/src/status_code.rs
@@ -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::::with_capacity(2);
+ let mut headers = HeaderMap::::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);
diff --git a/src/common/error/tests/ext.rs b/src/common/error/tests/ext.rs
index c9e6137729e..c34a47c400f 100644
--- a/src/common/error/tests/ext.rs
+++ b/src/common/error/tests/ext.rs
@@ -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: "", 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: , at {}:60:5
+ r#"0: , at {}:66:5
1: PlainError {{ msg: "", 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: "", 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: , at {}:60:5
+ r#"0: , at {}:66:5
1: PlainError {{ msg: "", 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) {
+ 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
+ }
+}
diff --git a/src/common/frontend/src/error.rs b/src/common/frontend/src/error.rs
index 19fb29aeb77..9961ed1879e 100644
--- a/src/common/frontend/src/error.rs
+++ b/src/common/frontend/src/error.rs
@@ -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,
+ }
+ }
}
diff --git a/src/common/grpc/src/error.rs b/src/common/grpc/src/error.rs
index 1d987514df5..26cef0902cf 100644
--- a/src/common/grpc/src/error.rs
+++ b/src/common/grpc/src/error.rs
@@ -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,
+ }
}
diff --git a/src/common/grpc/src/flight.rs b/src/common/grpc/src/flight.rs
index 235223559ae..88ffc9c30d5 100644
--- a/src/common/grpc/src/flight.rs
+++ b/src/common/grpc/src/flight.rs
@@ -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.
diff --git a/src/common/mem-prof/src/jemalloc/error.rs b/src/common/mem-prof/src/jemalloc/error.rs
index 79e4b8f9a6f..5e6442e0cf8 100644
--- a/src/common/mem-prof/src/jemalloc/error.rs
+++ b/src/common/mem-prof/src/jemalloc/error.rs
@@ -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
}
diff --git a/src/common/memory-manager/src/error.rs b/src/common/memory-manager/src/error.rs
index 455b3c6a6d9..f164c2fbf26 100644
--- a/src/common/memory-manager/src/error.rs
+++ b/src/common/memory-manager/src/error.rs
@@ -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,
+ }
+ }
}
diff --git a/src/common/meta/src/ddl/utils.rs b/src/common/meta/src/ddl/utils.rs
index d88e402adfb..6030889dcae 100644
--- a/src/common/meta/src/ddl/utils.rs
+++ b/src/common/meta/src/ddl/utils.rs
@@ -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(results: Vec>) -> 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";
diff --git a/src/common/meta/src/error.rs b/src/common/meta/src/error.rs
index 54a5c30fede..e7677606c64 100644
--- a/src/common/meta/src/error.rs
+++ b/src/common/meta/src/error.rs
@@ -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);
+ }
+}
diff --git a/src/common/meta/src/node_manager.rs b/src/common/meta/src/node_manager.rs
index 6cc6c3e1539..d18e2cc8471 100644
--- a/src/common/meta/src/node_manager.rs
+++ b/src/common/meta/src/node_manager.rs
@@ -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;
+ async fn handle_request(&self, request: Arc) -> Result;
/// Handles query requests
async fn handle_query(&self, request: QueryRequest) -> Result;
}
+impl dyn Datanode + '_ {
+ /// Handles an owned or shared request without cloning its payload.
+ pub async fn handle(&self, request: R) -> Result
+ where
+ R: Into> + Send,
+ {
+ self.handle_request(request.into()).await
+ }
+}
+
pub type DatanodeRef = Arc;
/// The trait for handling requests to flownode
diff --git a/src/common/meta/src/peer.rs b/src/common/meta/src/peer.rs
index 924c293bbe0..18ffd92f8bb 100644
--- a/src/common/meta/src/peer.rs
+++ b/src/common/meta/src/peer.rs
@@ -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;
+
/// [`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.
diff --git a/src/common/meta/src/reconciliation/reconcile_catalog.rs b/src/common/meta/src/reconciliation/reconcile_catalog.rs
index d3c2e526dd3..d154f5aa27f 100644
--- a/src/common/meta/src/reconciliation/reconcile_catalog.rs
+++ b/src/common/meta/src/reconciliation/reconcile_catalog.rs
@@ -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();
diff --git a/src/common/meta/src/reconciliation/reconcile_database.rs b/src/common/meta/src/reconciliation/reconcile_database.rs
index 7d4262877c1..c5c23c28023 100644
--- a/src/common/meta/src/reconciliation/reconcile_database.rs
+++ b/src/common/meta/src/reconciliation/reconcile_database.rs
@@ -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();
diff --git a/src/common/meta/src/reconciliation/reconcile_logical_tables.rs b/src/common/meta/src/reconciliation/reconcile_logical_tables.rs
index 19d9045d969..3e96f64e12a 100644
--- a/src/common/meta/src/reconciliation/reconcile_logical_tables.rs
+++ b/src/common/meta/src/reconciliation/reconcile_logical_tables.rs
@@ -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();
diff --git a/src/common/meta/src/reconciliation/reconcile_table.rs b/src/common/meta/src/reconciliation/reconcile_table.rs
index 004b93d38c5..df1b580c440 100644
--- a/src/common/meta/src/reconciliation/reconcile_table.rs
+++ b/src/common/meta/src/reconciliation/reconcile_table.rs
@@ -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();
diff --git a/src/common/meta/src/rpc/router.rs b/src/common/meta/src/rpc/router.rs
index 519b12e081f..b43b9cc0b4a 100644
--- a/src/common/meta/src/rpc/router.rs
+++ b/src/common/meta/src/rpc/router.rs
@@ -128,15 +128,25 @@ pub fn convert_to_region_leader_map(region_routes: &[RegionRoute]) -> HashMap>()
}
+/// Returns the leader of the first route matching the region number.
pub fn find_region_leader(
region_routes: &[RegionRoute],
region_number: RegionNumber,
) -> Option {
+ 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 {
diff --git a/src/common/meta/src/test_util.rs b/src/common/meta/src/test_util.rs
index 3396870ab66..6fbb7e549b0 100644
--- a/src/common/meta/src/test_util.rs
+++ b/src/common/meta/src/test_util.rs
@@ -111,7 +111,8 @@ struct MockNode {
#[async_trait::async_trait]
impl Datanode for MockNode {
- async fn handle(&self, request: RegionRequest) -> Result {
+ async fn handle_request(&self, request: Arc) -> Result {
+ let request = Arc::try_unwrap(request).expect("mock request must be exclusively owned");
self.handler.handle(&self.peer, request).await
}
diff --git a/src/common/procedure/src/error.rs b/src/common/procedure/src/error.rs
index c8081a67fc9..b3f4a83d5f4 100644
--- a/src/common/procedure/src/error.rs
+++ b/src/common/procedure/src/error.rs
@@ -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(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());
+ }
+}
diff --git a/src/common/recordbatch/src/error.rs b/src/common/recordbatch/src/error.rs
index 00d4291ead2..469320c19cf 100644
--- a/src/common/recordbatch/src/error.rs
+++ b/src/common/recordbatch/src/error.rs
@@ -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,
+ }
+ }
}
diff --git a/src/common/wal/src/kafka.rs b/src/common/wal/src/kafka.rs
new file mode 100644
index 00000000000..2586f0a007c
--- /dev/null
+++ b/src/common/wal/src/kafka.rs
@@ -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
+ );
+ }
+}
diff --git a/src/common/wal/src/lib.rs b/src/common/wal/src/lib.rs
index a0b1dc99f9e..cbf48a3e780 100644
--- a/src/common/wal/src/lib.rs
+++ b/src/common/wal/src/lib.rs
@@ -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;
diff --git a/src/datanode/src/error.rs b/src/datanode/src/error.rs
index 9b47644b45a..751604ba8d9 100644
--- a/src/datanode/src/error.rs
+++ b/src/datanode/src/error.rs
@@ -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);
+ }
+}
diff --git a/src/datanode/src/region_server.rs b/src/datanode/src/region_server.rs
index 615b3f996bd..0ca1c9873cb 100644
--- a/src/datanode/src/region_server.rs
+++ b/src/datanode/src/region_server.rs
@@ -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 {
diff --git a/src/file-engine/src/error.rs b/src/file-engine/src/error.rs
index 877b493cc63..f40adfe65f4 100644
--- a/src/file-engine/src/error.rs
+++ b/src/file-engine/src/error.rs
@@ -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 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,
+ }
}
}
diff --git a/src/flow/src/error.rs b/src/flow/src/error.rs
index 825c1dc5ac4..2dcefd95c86 100644
--- a/src/flow/src/error.rs
+++ b/src/flow/src/error.rs
@@ -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);
diff --git a/src/frontend/Cargo.toml b/src/frontend/Cargo.toml
index aa9276a0cba..13cd616b87e 100644
--- a/src/frontend/Cargo.toml
+++ b/src/frontend/Cargo.toml
@@ -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
diff --git a/src/frontend/src/error.rs b/src/frontend/src/error.rs
index 6f78d23e14e..357512932cf 100644
--- a/src/frontend/src/error.rs
+++ b/src/frontend/src/error.rs
@@ -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);
diff --git a/src/frontend/src/frontend.rs b/src/frontend/src/frontend.rs
index 918185cb8f6..f34af36ff2c 100644
--- a/src/frontend/src/frontend.rs
+++ b/src/frontend/src/frontend.rs
@@ -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,
pub logging: LoggingOptions,
pub datanode: DatanodeClientOptions,
+ /// Retry policy for retryable distributed write failures.
+ pub write_retry: WriteRetryOptions,
pub user_provider: Option,
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();
diff --git a/src/frontend/src/instance/builder.rs b/src/frontend/src/instance/builder.rs
index 238de303d5f..618a65e992a 100644
--- a/src/frontend/src/instance/builder.rs
+++ b/src/frontend/src/instance/builder.rs
@@ -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,
+ local_cache_invalidator: CacheInvalidatorRef,
catalog_manager: CatalogManagerRef,
node_manager: NodeManagerRef,
plugins: Option,
@@ -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 {
+ 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::() {
@@ -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()
+ );
+ }
+ }
+}
diff --git a/src/frontend/src/instance/otlp.rs b/src/frontend/src/instance/otlp.rs
index 4b4b1b6cfd5..9672b05301b 100644
--- a/src/frontend/src/instance/otlp.rs
+++ b/src/frontend/src/instance/otlp.rs
@@ -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,
}
}
diff --git a/src/frontend/src/instance/standalone.rs b/src/frontend/src/instance/standalone.rs
index d34922956b3..c6981f1d318 100644
--- a/src/frontend/src/instance/standalone.rs
+++ b/src/frontend/src/instance/standalone.rs
@@ -77,7 +77,17 @@ impl RegionInvoker {
#[async_trait]
impl Datanode for RegionInvoker {
- async fn handle(&self, request: RegionRequest) -> MetaResult {
+ async fn handle_request(&self, request: Arc) -> MetaResult {
+ // 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()
diff --git a/src/frontend/src/server.rs b/src/frontend/src/server.rs
index 6b120ccba5b..87cf0e5072f 100644
--- a/src/frontend/src/server.rs
+++ b/src/frontend/src/server.rs
@@ -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(),
diff --git a/src/frontend/src/service_config.rs b/src/frontend/src/service_config.rs
index 03ec12e2c9f..4dc152d0df9 100644
--- a/src/frontend/src/service_config.rs
+++ b/src/frontend/src/service_config.rs
@@ -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;
diff --git a/src/log-store/src/error.rs b/src/log-store/src/error.rs
index b56334a01aa..a83944d5174 100644
--- a/src/log-store/src/error.rs
+++ b/src/log-store/src/error.rs
@@ -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,
+ }
+ }
}
diff --git a/src/meta-client/src/error.rs b/src/meta-client/src/error.rs
index 19577f672cc..917559fffb8 100644
--- a/src/meta-client/src/error.rs
+++ b/src/meta-client/src/error.rs
@@ -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);
+ }
+}
diff --git a/src/meta-srv/src/error.rs b/src/meta-srv/src/error.rs
index ba45b45b49a..86edad8f08e 100644
--- a/src/meta-srv/src/error.rs
+++ b/src/meta-srv/src/error.rs
@@ -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());
}
}
diff --git a/src/metric-engine/src/engine/bulk_insert.rs b/src/metric-engine/src/engine/bulk_insert.rs
index d700d858acf..babde5a1262 100644
--- a/src/metric-engine/src/engine/bulk_insert.rs
+++ b/src/metric-engine/src/engine/bulk_insert.rs
@@ -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::(), 6);
+ batches.pretty_print().unwrap()
}
#[tokio::test]
diff --git a/src/metric-engine/src/error.rs b/src/metric-engine/src/error.rs
index f01737e7647..00baf102002 100644
--- a/src/metric-engine/src/error.rs
+++ b/src/metric-engine/src/error.rs
@@ -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);
+ }
+ }
}
diff --git a/src/mito-codec/src/error.rs b/src/mito-codec/src/error.rs
index 78a656415a1..3d3b0efcc07 100644
--- a/src/mito-codec/src/error.rs
+++ b/src/mito-codec/src/error.rs
@@ -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(),
}
}
diff --git a/src/mito-codec/src/row_converter/sparse.rs b/src/mito-codec/src/row_converter/sparse.rs
index 37e18134702..c70293886f8 100644
--- a/src/mito-codec/src/row_converter/sparse.rs
+++ b/src/mito-codec/src/row_converter/sparse.rs
@@ -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 {
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(®ion_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();
diff --git a/src/mito2/src/engine/staging_test.rs b/src/mito2/src/engine/staging_test.rs
index 71abd67eb22..ac5c0f5ecec 100644
--- a/src/mito2/src/engine/staging_test.rs
+++ b/src/mito2/src/engine/staging_test.rs
@@ -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::().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::().unwrap(),
+ Error::RejectWriteInStaging { .. }
+ );
+ }
}
#[tokio::test]
diff --git a/src/mito2/src/error.rs b/src/mito2/src/error.rs
index 2cbe54c6f4f..502031d9ba6 100644
--- a/src/mito2/src/error.rs
+++ b/src/mito2/src/error.rs
@@ -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);
+ }
+ }
}
diff --git a/src/mito2/src/worker/handle_write.rs b/src/mito2/src/worker/handle_write.rs
index 64fdd33edc8..6f0e430a637 100644
--- a/src/mito2/src/worker/handle_write.rs
+++ b/src/mito2/src/worker/handle_write.rs
@@ -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 RegionWorkerLoop {
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 RegionWorkerLoop {
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 RegionWorkerLoop {
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 RegionWorkerLoop {
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();
diff --git a/src/object-store/src/error.rs b/src/object-store/src/error.rs
index cb259ef5c81..14661e261cd 100644
--- a/src/object-store/src/error.rs
+++ b/src/object-store/src/error.rs
@@ -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 = std::result::Result;
+/// 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,
+ }
+ }
}
diff --git a/src/operator/Cargo.toml b/src/operator/Cargo.toml
index ea353f4ced8..6e7a23c167c 100644
--- a/src/operator/Cargo.toml
+++ b/src/operator/Cargo.toml
@@ -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"] }
diff --git a/src/operator/src/bulk_insert.rs b/src/operator/src/bulk_insert.rs
index 2dbec530eb4..c765672d050 100644
--- a/src/operator/src/bulk_insert.rs
+++ b/src/operator/src/bulk_insert.rs
@@ -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(®ion_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::>();
+ let mut peers = self
+ .write_dispatcher
+ .resolve_peers(®ions)
+ .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(®ion_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> =
- 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(®ion_id.region_number())
+ .copied()
+ .unwrap_or_default();
+ let peer = peers
+ .remove(®ion_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> =
+ 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::>>()?;
+ 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);
diff --git a/src/operator/src/delete.rs b/src/operator/src/delete.rs
index 9641e0e27d4..9bf14471696 100644
--- a/src/operator/src/delete.rs
+++ b/src/operator/src/delete.rs
@@ -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;
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::>()?;
+ 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> {
- let mut deletes: HashMap = 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,
diff --git a/src/operator/src/error.rs b/src/operator/src/error.rs
index da65cc8c2f9..13b86140aa1 100644
--- a/src/operator/src/error.rs
+++ b/src/operator/src/error.rs
@@ -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);
diff --git a/src/operator/src/insert.rs b/src/operator/src/insert.rs
index 0c627af08f8..aaa78eb65f5 100644
--- a/src/operator/src/insert.rs
+++ b/src/operator/src/insert.rs
@@ -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::>()?;
+ 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> {
- // 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 = 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 = 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
}
diff --git a/src/operator/src/lib.rs b/src/operator/src/lib.rs
index 5e723faeb5c..80b820ff2aa 100644
--- a/src/operator/src/lib.rs
+++ b/src/operator/src/lib.rs
@@ -28,3 +28,4 @@ pub mod table;
#[cfg(test)]
pub(crate) mod tests;
pub mod utils;
+pub mod write_dispatcher;
diff --git a/src/operator/src/req_convert.rs b/src/operator/src/req_convert.rs
index 456ff0b328d..82681e09968 100644
--- a/src/operator/src/req_convert.rs
+++ b/src/operator/src/req_convert.rs
@@ -15,3 +15,5 @@
pub(crate) mod common;
pub mod delete;
pub mod insert;
+
+pub(crate) use common::partitioner::TablePartitioner;
diff --git a/src/operator/src/req_convert/common/partitioner.rs b/src/operator/src/req_convert/common/partitioner.rs
index b52a6f6be6c..94fb09e3eb3 100644
--- a/src/operator/src/req_convert/common/partitioner.rs
+++ b/src/operator/src/req_convert/common/partitioner.rs
@@ -12,70 +12,1075 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-use api::v1::region::{DeleteRequest, InsertRequest};
-use api::v1::{PartitionExprVersion, Rows};
+use std::collections::HashMap;
+use std::sync::Arc;
+
+use api::v1::region::region_request::Body;
+use api::v1::region::{
+ BulkInsertRequest, DeleteRequest, DeleteRequests, InsertRequest, InsertRequests, RegionRequest,
+ bulk_insert_request,
+};
+use api::v1::{ArrowIpc, PartitionExprVersion, Rows};
+use common_error::ext::BoxedError;
+use common_grpc::flight::{self, FlightDecoder};
+use datatypes::arrow::array::{Array, BinaryArray, StringBuilder};
+use datatypes::arrow::compute;
+use datatypes::arrow::datatypes::{DataType, Field, Schema};
+use datatypes::arrow::record_batch::RecordBatch;
+use datatypes::value::Value;
+use mito_codec::row_converter::{CompositeValues, PrimaryKeyCodec, SparsePrimaryKeyCodec};
+use partition::PartitionRuleRef;
use partition::manager::PartitionRuleManager;
-use snafu::ResultExt;
-use store_api::storage::RegionId;
+use partition::partition::RegionMask;
+use partition::splitter::RowSplitter;
+use snafu::{OptionExt, ResultExt, ensure};
+use store_api::storage::{RegionId, RegionNumber, TableId, consts};
use table::metadata::TableInfo;
-use crate::error::{Result, SplitDeleteSnafu, SplitInsertSnafu};
+use crate::error::{self, Result, SplitDeleteSnafu, SplitInsertSnafu};
+/// Loads table routing rules and converts rows to region write requests.
pub struct Partitioner<'a> {
partition_manager: &'a PartitionRuleManager,
}
+/// A single snapshot of a table's partition rule and expression versions.
+pub(crate) struct TablePartitioner {
+ table_id: TableId,
+ rule: PartitionRuleRef,
+ versions: HashMap>,
+}
+
impl<'a> Partitioner<'a> {
+ /// Creates a partitioner backed by the shared routing caches.
pub fn new(partition_manager: &'a PartitionRuleManager) -> Self {
Self { partition_manager }
}
+ /// Routes insert rows using the current table partitions.
pub async fn partition_insert_requests(
&self,
table_info: &TableInfo,
rows: Rows,
) -> Result> {
- let table_id = table_info.table_id();
- let requests = self
- .partition_manager
- .split_rows(table_info, rows)
+ TablePartitioner::try_new(self.partition_manager, table_info)
.await
.context(SplitInsertSnafu)?
- .into_iter()
- .map(
- |(region_number, (rows, partition_expr_version))| InsertRequest {
- region_id: RegionId::new(table_id, region_number).into(),
- rows: Some(rows),
- partition_expr_version: partition_expr_version
- .map(|value| PartitionExprVersion { value }),
- },
- )
- .collect();
- Ok(requests)
+ .partition_insert_requests(rows)
}
+ /// Routes delete rows using the current table partitions.
pub async fn partition_delete_requests(
&self,
table_info: &TableInfo,
rows: Rows,
) -> Result> {
- let table_id = table_info.table_id();
-
- let requests = self
- .partition_manager
- .split_rows(table_info, rows)
+ TablePartitioner::try_new(self.partition_manager, table_info)
.await
.context(SplitDeleteSnafu)?
+ .partition_delete_requests(rows)
+ }
+}
+
+impl TablePartitioner {
+ /// Reads a table's partition rule and expression versions into one routing snapshot.
+ pub async fn try_new(
+ partition_manager: &PartitionRuleManager,
+ table_info: &TableInfo,
+ ) -> partition::error::Result {
+ let (rule, versions) = partition_manager
+ .find_table_partition_rule(table_info)
+ .await?;
+ Ok(Self {
+ table_id: table_info.table_id(),
+ rule,
+ versions: versions
+ .into_iter()
+ .map(|(region, version)| {
+ (region, version.map(|value| PartitionExprVersion { value }))
+ })
+ .collect(),
+ })
+ }
+
+ /// Rebuilds write requests using this partition snapshot after a route refresh.
+ ///
+ /// Takes ownership so row payloads can move into their new regions. Requests whose
+ /// region and partition version still match retain their original payloads.
+ /// The table metadata comes from the same refresh that created this partitioner.
+ pub(crate) fn rebuild_write_requests(
+ &self,
+ request: RegionRequest,
+ table_info: &TableInfo,
+ ) -> Result> {
+ let RegionRequest { header, body } = request;
+ let bodies = match body.context(error::UnexpectedSnafu {
+ violated: "Cannot rebuild a request without a body",
+ })? {
+ Body::Inserts(inserts) => self.rebuild_insert_requests(inserts)?,
+ Body::Deletes(deletes) => self.rebuild_delete_requests(deletes)?,
+ Body::BulkInsert(bulk) => self.rebuild_bulk_insert_request(bulk, table_info)?,
+ _ => {
+ return error::UnexpectedSnafu {
+ violated: "Only writes can be rebuilt",
+ }
+ .fail();
+ }
+ };
+ Ok(bodies
.into_iter()
- .map(
- |(region_number, (rows, partition_expr_version))| DeleteRequest {
- region_id: RegionId::new(table_id, region_number).into(),
+ .map(|body| RegionRequest {
+ header: header.clone(),
+ body: Some(body),
+ })
+ .collect())
+ }
+
+ /// Moves insert rows into requests for this snapshot's destination regions.
+ pub fn partition_insert_requests(&self, rows: Rows) -> Result> {
+ Ok(RowSplitter::new(self.rule.clone())
+ .split(rows)
+ .context(SplitInsertSnafu)?
+ .into_iter()
+ .map(|(region, rows)| InsertRequest {
+ region_id: RegionId::new(self.table_id, region).as_u64(),
+ rows: Some(rows),
+ partition_expr_version: self.version(region),
+ })
+ .collect())
+ }
+
+ /// Moves delete rows into requests for this snapshot's destination regions.
+ pub fn partition_delete_requests(&self, rows: Rows) -> Result> {
+ Ok(RowSplitter::new(self.rule.clone())
+ .split(rows)
+ .context(SplitDeleteSnafu)?
+ .into_iter()
+ .map(|(region, rows)| DeleteRequest {
+ region_id: RegionId::new(self.table_id, region).as_u64(),
+ rows: Some(rows),
+ partition_expr_version: self.version(region),
+ })
+ .collect())
+ }
+
+ /// Splits an Arrow batch, reusing the original IPC when one region selects all rows.
+ #[cfg(test)]
+ pub fn partition_bulk_insert_requests(
+ &self,
+ batch: RecordBatch,
+ original_ipc: Option,
+ ) -> Result> {
+ let masks = self
+ .rule
+ .split_record_batch(&batch)
+ .context(SplitInsertSnafu)?;
+ self.build_bulk_insert_requests(batch, masks, original_ipc)
+ }
+
+ fn build_bulk_insert_requests(
+ &self,
+ batch: RecordBatch,
+ masks: HashMap,
+ mut original_ipc: Option,
+ ) -> Result> {
+ let mut requests = Vec::with_capacity(masks.len());
+ for (region, mask) in masks {
+ if mask.select_none() {
+ continue;
+ }
+ let original = if mask.select_all() {
+ original_ipc.take()
+ } else {
+ None
+ };
+ let ipc = if let Some(ipc) = original {
+ ipc
+ } else {
+ let selected = if mask.select_all() {
+ batch.clone()
+ } else {
+ compute::filter_record_batch(&batch, mask.array())
+ .context(error::ComputeArrowSnafu)?
+ };
+ let (schema, data_header, payload) = flight::record_batch_to_ipc(selected)
+ .map_err(BoxedError::new)
+ .context(error::ExternalSnafu)?;
+ ArrowIpc {
+ schema,
+ data_header,
+ payload,
+ }
+ };
+ requests.push(BulkInsertRequest {
+ region_id: RegionId::new(self.table_id, region).as_u64(),
+ partition_expr_version: self.version(region),
+ // The destination datanode validates against its current schema.
+ aligned_schema_version: None,
+ body: Some(bulk_insert_request::Body::ArrowIpc(ipc)),
+ });
+ }
+ Ok(requests)
+ }
+
+ fn rebuild_insert_requests(&self, inserts: InsertRequests) -> Result> {
+ let mut bodies = Vec::new();
+ for insert in inserts.requests {
+ let region_id = RegionId::from_u64(insert.region_id);
+ if self.is_partition_expr_unchanged(region_id, insert.partition_expr_version) {
+ bodies.push(Body::Inserts(InsertRequests {
+ requests: vec![insert],
+ }));
+ continue;
+ }
+ let rows = insert.rows.context(error::UnexpectedSnafu {
+ violated: "Cannot rebuild an insert without rows",
+ })?;
+ for request in self.partition_insert_requests(rows)? {
+ bodies.push(Body::Inserts(InsertRequests {
+ requests: vec![request],
+ }));
+ }
+ }
+ Ok(bodies)
+ }
+
+ fn rebuild_delete_requests(&self, deletes: DeleteRequests) -> Result> {
+ let mut bodies = Vec::new();
+ for delete in deletes.requests {
+ let region_id = RegionId::from_u64(delete.region_id);
+ if self.is_partition_expr_unchanged(region_id, delete.partition_expr_version) {
+ bodies.push(Body::Deletes(DeleteRequests {
+ requests: vec![delete],
+ }));
+ continue;
+ }
+ let rows = delete.rows.context(error::UnexpectedSnafu {
+ violated: "Cannot rebuild a delete without rows",
+ })?;
+ for request in self.partition_delete_requests(rows)? {
+ bodies.push(Body::Deletes(DeleteRequests {
+ requests: vec![request],
+ }));
+ }
+ }
+ Ok(bodies)
+ }
+
+ fn rebuild_bulk_insert_request(
+ &self,
+ bulk: BulkInsertRequest,
+ table_info: &TableInfo,
+ ) -> Result> {
+ let region_id = RegionId::from_u64(bulk.region_id);
+ if self.is_partition_expr_unchanged(region_id, bulk.partition_expr_version) {
+ return Ok(vec![Body::BulkInsert(bulk)]);
+ }
+ let bulk_insert_request::Body::ArrowIpc(ipc) =
+ bulk.body.context(error::UnexpectedSnafu {
+ violated: "Cannot rebuild a bulk insert without Arrow IPC data",
+ })?;
+ let batch = FlightDecoder::try_from_schema_bytes(&ipc.schema)
+ .and_then(|mut decoder| decoder.try_decode_record_batch(&ipc.data_header, &ipc.payload))
+ .map_err(BoxedError::new)
+ .context(error::ExternalSnafu)?;
+ let routing_batch = self.restore_partition_tags(&batch, table_info)?;
+ let masks = self
+ .rule
+ .split_record_batch(routing_batch.as_ref().unwrap_or(&batch))
+ .context(SplitInsertSnafu)?;
+ Ok(self
+ .build_bulk_insert_requests(batch, masks, Some(ipc))?
+ .into_iter()
+ .map(Body::BulkInsert)
+ .collect())
+ }
+
+ /// Restores omitted physical-table tags for routing without changing the write payload.
+ fn restore_partition_tags(
+ &self,
+ batch: &RecordBatch,
+ table_info: &TableInfo,
+ ) -> Result