Skip to main content

common_query/
error.rs

1// Copyright 2023 Greptime Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::any::Any;
16use std::sync::Arc;
17
18use arrow::error::ArrowError;
19use common_error::ext::{BoxedError, ErrorExt, RetryHint};
20use common_error::status_code::StatusCode;
21use common_macro::stack_trace_debug;
22use datafusion_common::DataFusionError;
23use datatypes::arrow;
24use datatypes::arrow::datatypes::DataType as ArrowDatatype;
25use datatypes::error::Error as DataTypeError;
26use datatypes::prelude::ConcreteDataType;
27use snafu::{Location, Snafu};
28
29#[derive(Snafu)]
30#[snafu(visibility(pub))]
31#[stack_trace_debug]
32pub enum Error {
33    #[snafu(display("Storage write did not complete: {source}"))]
34    StorageWrite {
35        source: Arc<BoxedError>,
36        #[snafu(implicit)]
37        location: Location,
38    },
39    #[snafu(display("Unsupported input datatypes {:?} in function {}", datatypes, function))]
40    UnsupportedInputDataType {
41        function: String,
42        datatypes: Vec<ConcreteDataType>,
43        #[snafu(implicit)]
44        location: Location,
45    },
46
47    #[snafu(display("Failed to cast scalar value into vector"))]
48    FromScalarValue {
49        #[snafu(implicit)]
50        location: Location,
51        source: DataTypeError,
52    },
53
54    #[snafu(display("Failed to cast arrow array into vector: {:?}", data_type))]
55    IntoVector {
56        #[snafu(implicit)]
57        location: Location,
58        source: DataTypeError,
59        data_type: ArrowDatatype,
60    },
61
62    #[snafu(display("Invalid input type: {}", err_msg))]
63    InvalidInputType {
64        #[snafu(implicit)]
65        location: Location,
66        source: DataTypeError,
67        err_msg: String,
68    },
69
70    #[snafu(display(
71        "Illegal input_types status, check if DataFusion has changed its UDAF execution logic"
72    ))]
73    InvalidInputState {
74        #[snafu(implicit)]
75        location: Location,
76    },
77
78    #[snafu(transparent)]
79    GeneralDataFusion {
80        #[snafu(source)]
81        error: DataFusionError,
82        #[snafu(implicit)]
83        location: Location,
84    },
85
86    #[snafu(display("Failed to convert DataFusion's recordbatch stream"))]
87    ConvertDfRecordBatchStream {
88        #[snafu(implicit)]
89        location: Location,
90        source: common_recordbatch::error::Error,
91    },
92
93    #[snafu(display("Failed to cast array to {:?}", typ))]
94    TypeCast {
95        #[snafu(source)]
96        error: ArrowError,
97        typ: arrow::datatypes::DataType,
98        #[snafu(implicit)]
99        location: Location,
100    },
101
102    #[snafu(display("Failed to perform compute operation on arrow arrays"))]
103    ArrowCompute {
104        #[snafu(source)]
105        error: ArrowError,
106        #[snafu(implicit)]
107        location: Location,
108    },
109
110    #[snafu(display("Query engine fail to cast value"))]
111    ToScalarValue {
112        #[snafu(implicit)]
113        location: Location,
114        source: DataTypeError,
115    },
116
117    #[snafu(display("Failed to get scalar vector"))]
118    GetScalarVector {
119        #[snafu(implicit)]
120        location: Location,
121        source: DataTypeError,
122    },
123
124    #[snafu(display("Failed to execute function: {source}"))]
125    Execute {
126        #[snafu(implicit)]
127        location: Location,
128        source: BoxedError,
129    },
130
131    #[snafu(display("Failed to decode logical plan: {source}"))]
132    DecodePlan {
133        #[snafu(implicit)]
134        location: Location,
135        source: BoxedError,
136    },
137
138    #[snafu(display("Failed to do table mutation"))]
139    TableMutation {
140        source: BoxedError,
141        #[snafu(implicit)]
142        location: Location,
143    },
144
145    #[snafu(display("Failed to do procedure task"))]
146    ProcedureService {
147        source: BoxedError,
148        #[snafu(implicit)]
149        location: Location,
150    },
151
152    #[snafu(display("Missing TableMutationHandler, not expected"))]
153    MissingTableMutationHandler {
154        #[snafu(implicit)]
155        location: Location,
156    },
157
158    #[snafu(display("Missing ProcedureServiceHandler, not expected"))]
159    MissingProcedureServiceHandler {
160        #[snafu(implicit)]
161        location: Location,
162    },
163
164    #[snafu(display("Missing FlowServiceHandler, not expected"))]
165    MissingFlowServiceHandler {
166        #[snafu(implicit)]
167        location: Location,
168    },
169
170    #[snafu(display("Invalid function args: {}", err_msg))]
171    InvalidFuncArgs {
172        err_msg: String,
173        #[snafu(implicit)]
174        location: Location,
175    },
176
177    #[snafu(display("Permission denied: {}", err_msg))]
178    PermissionDenied {
179        err_msg: String,
180        #[snafu(implicit)]
181        location: Location,
182    },
183
184    #[snafu(display("Can't found alive flownode"))]
185    FlownodeNotFound {
186        #[snafu(implicit)]
187        location: Location,
188    },
189
190    #[snafu(display("Invalid vector string: {}", vec_str))]
191    InvalidVectorString {
192        vec_str: String,
193        source: DataTypeError,
194        #[snafu(implicit)]
195        location: Location,
196    },
197
198    #[snafu(display("Failed to register UDF: {}", name))]
199    RegisterUdf {
200        name: String,
201        #[snafu(source)]
202        error: DataFusionError,
203        #[snafu(implicit)]
204        location: Location,
205    },
206
207    #[snafu(display("Invalid character in prefix config: {}", prefix))]
208    InvalidColumnPrefix { prefix: String },
209
210    #[snafu(display(
211        "DynFilterPayload::Datafusion is {} bytes, which exceeds the configured limit of {} bytes",
212        payload_size_bytes,
213        max_payload_bytes
214    ))]
215    DynFilterPayloadTooLarge {
216        payload_size_bytes: usize,
217        max_payload_bytes: usize,
218        #[snafu(implicit)]
219        location: Location,
220    },
221
222    #[snafu(display(
223        "Remote dynamic filter predicate cannot be represented on the wire: {}",
224        reason
225    ))]
226    DynFilterUnsupported {
227        reason: String,
228        #[snafu(implicit)]
229        location: Location,
230    },
231}
232
233impl Error {
234    /// Whether the error reports a dynamic filter predicate with no wire form.
235    ///
236    /// Initial capture omits the refused snapshot; ongoing fanout sends an explicit
237    /// `true` reset to invalidate any stale region-side predicate. Neither path fails
238    /// the query.
239    pub fn is_dyn_filter_unsupported(&self) -> bool {
240        matches!(self, Error::DynFilterUnsupported { .. })
241    }
242}
243
244pub type Result<T> = std::result::Result<T, Error>;
245
246impl ErrorExt for Error {
247    fn status_code(&self) -> StatusCode {
248        match self {
249            Error::StorageWrite { source, .. } => source.status_code(),
250            Error::InvalidInputState { .. }
251            | Error::ToScalarValue { .. }
252            | Error::GetScalarVector { .. }
253            | Error::ArrowCompute { .. }
254            | Error::FlownodeNotFound { .. } => StatusCode::EngineExecuteQuery,
255
256            Error::GeneralDataFusion { error, .. } => datafusion_status_code::<Self>(error, None),
257
258            Error::InvalidInputType { source, .. }
259            | Error::IntoVector { source, .. }
260            | Error::FromScalarValue { source, .. }
261            | Error::InvalidVectorString { source, .. } => source.status_code(),
262
263            Error::MissingTableMutationHandler { .. }
264            | Error::MissingProcedureServiceHandler { .. }
265            | Error::MissingFlowServiceHandler { .. }
266            | Error::RegisterUdf { .. } => StatusCode::Unexpected,
267
268            Error::UnsupportedInputDataType { .. }
269            | Error::TypeCast { .. }
270            | Error::InvalidFuncArgs { .. }
271            | Error::InvalidColumnPrefix { .. } => StatusCode::InvalidArguments,
272
273            Error::DynFilterPayloadTooLarge { .. } => StatusCode::PlanQuery,
274            // An unrepresentable dynamic predicate is a transport limitation, not a
275            // server failure: callers omit the initial snapshot or reset the remote predicate.
276            Error::DynFilterUnsupported { .. } => StatusCode::Unsupported,
277
278            Error::ConvertDfRecordBatchStream { source, .. } => source.status_code(),
279
280            Error::DecodePlan { source, .. }
281            | Error::Execute { source, .. }
282            | Error::ProcedureService { source, .. }
283            | Error::TableMutation { source, .. } => source.status_code(),
284
285            Error::PermissionDenied { .. } => StatusCode::PermissionDenied,
286        }
287    }
288
289    fn as_any(&self) -> &dyn Any {
290        self
291    }
292
293    fn retry_hint(&self) -> RetryHint {
294        match self {
295            Error::StorageWrite { source, .. } => source.retry_hint(),
296            _ => RetryHint::NonRetryable,
297        }
298    }
299}
300
301impl From<Error> for DataFusionError {
302    fn from(e: Error) -> DataFusionError {
303        DataFusionError::External(Box::new(e))
304    }
305}
306
307/// Try to get the proper [`StatusCode`] of [`DataFusionError].
308pub fn datafusion_status_code<T: ErrorExt + 'static>(
309    e: &DataFusionError,
310    default_status: Option<StatusCode>,
311) -> StatusCode {
312    let mut error = e;
313    loop {
314        error = match error {
315            DataFusionError::Shared(inner) => inner,
316            DataFusionError::Context(_, inner) | DataFusionError::Diagnostic(_, inner) => inner,
317            _ => break,
318        };
319    }
320
321    match error {
322        DataFusionError::Internal(_) => StatusCode::Internal,
323        DataFusionError::NotImplemented(_) => StatusCode::Unsupported,
324        DataFusionError::Plan(_) => StatusCode::PlanQuery,
325        DataFusionError::External(error) => {
326            if let Some(ext) = (*error).downcast_ref::<T>() {
327                ext.status_code()
328            } else if let Some(ext) = (*error).downcast_ref::<BoxedError>() {
329                ext.status_code()
330            } else {
331                default_status.unwrap_or(StatusCode::EngineExecuteQuery)
332            }
333        }
334        _ => default_status.unwrap_or(StatusCode::EngineExecuteQuery),
335    }
336}
337
338#[cfg(test)]
339mod tests {
340    use std::sync::Arc;
341
342    use common_error::ext::PlainError;
343    use common_error::mock::MockError;
344
345    use super::*;
346
347    #[tokio::test]
348    async fn test_write_completion_preserves_retry_hint() {
349        for hint in [
350            RetryHint::NonRetryable,
351            RetryHint::Retryable,
352            RetryHint::RetryAfterRouteRefresh,
353        ] {
354            let source =
355                || BoxedError::new(MockError::new(StatusCode::RegionBusy).with_retry_hint(hint));
356            let progress = crate::WriteProgress::failed(source());
357            let error = progress.clone().into_result().unwrap_err();
358            assert_eq!(error.status_code(), StatusCode::RegionBusy);
359            assert_eq!(error.retry_hint(), hint);
360            assert_eq!(progress.error.unwrap().retry_hint(), hint);
361
362            let error = crate::WriteCompletion::new(std::future::ready(Err(source())))
363                .wait()
364                .await
365                .unwrap_err();
366            assert_eq!(error.status_code(), StatusCode::RegionBusy);
367            assert_eq!(error.retry_hint(), hint);
368        }
369    }
370
371    #[test]
372    fn test_datafusion_status_code_preserves_external_errors_through_wrappers() {
373        let boxed_error = |status| {
374            DataFusionError::External(Box::new(BoxedError::new(PlainError::new(
375                "neutral error".to_string(),
376                status,
377            ))))
378        };
379
380        for status in [
381            StatusCode::RequestOutdated,
382            StatusCode::Unknown,
383            StatusCode::Unsupported,
384        ] {
385            let errors = [
386                boxed_error(status),
387                DataFusionError::Shared(Arc::new(boxed_error(status))),
388                DataFusionError::Context("context".to_string(), Box::new(boxed_error(status))),
389                DataFusionError::Diagnostic(
390                    Box::new(datafusion_common::Diagnostic::new_error("diagnostic", None)),
391                    Box::new(boxed_error(status)),
392                ),
393                DataFusionError::Shared(Arc::new(DataFusionError::Context(
394                    "context".to_string(),
395                    Box::new(DataFusionError::Diagnostic(
396                        Box::new(datafusion_common::Diagnostic::new_error("diagnostic", None)),
397                        Box::new(boxed_error(status)),
398                    )),
399                ))),
400            ];
401
402            for error in errors {
403                assert_eq!(datafusion_status_code::<Error>(&error, None), status);
404                assert_eq!(
405                    datafusion_status_code::<Error>(&error, Some(StatusCode::PlanQuery)),
406                    status
407                );
408            }
409        }
410
411        let direct_error = DataFusionError::External(Box::new(Error::DynFilterPayloadTooLarge {
412            payload_size_bytes: 2,
413            max_payload_bytes: 1,
414            location: Location::default(),
415        }));
416        assert_eq!(
417            datafusion_status_code::<Error>(&direct_error, Some(StatusCode::Internal)),
418            StatusCode::PlanQuery
419        );
420
421        let unsupported_error = DataFusionError::External(Box::new(Error::DynFilterUnsupported {
422            reason: "no wire form".to_string(),
423            location: Location::default(),
424        }));
425        assert_eq!(
426            datafusion_status_code::<Error>(&unsupported_error, Some(StatusCode::Internal)),
427            StatusCode::Unsupported
428        );
429
430        let boundary_error =
431            DataFusionError::Shared(Arc::new(DataFusionError::External(Box::new(
432                BoxedError::new(common_recordbatch::error::Error::PhysicalExpr {
433                    error: DataFusionError::NotImplemented("inner error".to_string()),
434                    location: Location::default(),
435                }),
436            ))));
437        assert_eq!(
438            datafusion_status_code::<Error>(&boundary_error, Some(StatusCode::PlanQuery)),
439            StatusCode::Internal
440        );
441    }
442
443    #[test]
444    fn test_datafusion_status_code_uses_default_for_untyped_errors() {
445        let wrap = |error| {
446            DataFusionError::Shared(Arc::new(DataFusionError::Context(
447                "context".to_string(),
448                Box::new(DataFusionError::Diagnostic(
449                    Box::new(datafusion_common::Diagnostic::new_error("diagnostic", None)),
450                    Box::new(error),
451                )),
452            )))
453        };
454        let errors = || {
455            [
456                (
457                    DataFusionError::External(Box::new(std::io::Error::other("neutral io error"))),
458                    StatusCode::EngineExecuteQuery,
459                    StatusCode::Unknown,
460                ),
461                (
462                    DataFusionError::Internal("neutral internal error".to_string()),
463                    StatusCode::Internal,
464                    StatusCode::Internal,
465                ),
466                (
467                    DataFusionError::NotImplemented("neutral not implemented error".to_string()),
468                    StatusCode::Unsupported,
469                    StatusCode::Unsupported,
470                ),
471                (
472                    DataFusionError::Plan("neutral plan error".to_string()),
473                    StatusCode::PlanQuery,
474                    StatusCode::PlanQuery,
475                ),
476                (
477                    DataFusionError::External(Box::new(DataFusionError::Internal(
478                        "inner error".to_string(),
479                    ))),
480                    StatusCode::EngineExecuteQuery,
481                    StatusCode::Unknown,
482                ),
483            ]
484        };
485
486        for (error, none_expected, default_expected) in
487            errors()
488                .into_iter()
489                .chain(errors().map(|(error, none_expected, default_expected)| {
490                    (wrap(error), none_expected, default_expected)
491                }))
492        {
493            assert_eq!(datafusion_status_code::<Error>(&error, None), none_expected);
494            assert_eq!(
495                datafusion_status_code::<Error>(&error, Some(StatusCode::Unknown)),
496                default_expected
497            );
498        }
499    }
500}