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 cast array to {:?}", typ))]
87    TypeCast {
88        #[snafu(source)]
89        error: ArrowError,
90        typ: arrow::datatypes::DataType,
91        #[snafu(implicit)]
92        location: Location,
93    },
94
95    #[snafu(display("Failed to perform compute operation on arrow arrays"))]
96    ArrowCompute {
97        #[snafu(source)]
98        error: ArrowError,
99        #[snafu(implicit)]
100        location: Location,
101    },
102
103    #[snafu(display("Failed to get scalar vector"))]
104    GetScalarVector {
105        #[snafu(implicit)]
106        location: Location,
107        source: DataTypeError,
108    },
109
110    #[snafu(display("Failed to execute function: {source}"))]
111    Execute {
112        #[snafu(implicit)]
113        location: Location,
114        source: BoxedError,
115    },
116
117    #[snafu(display("Failed to decode logical plan: {source}"))]
118    DecodePlan {
119        #[snafu(implicit)]
120        location: Location,
121        source: BoxedError,
122    },
123
124    #[snafu(display("Failed to do table mutation"))]
125    TableMutation {
126        source: BoxedError,
127        #[snafu(implicit)]
128        location: Location,
129    },
130
131    #[snafu(display("Failed to do procedure task"))]
132    ProcedureService {
133        source: BoxedError,
134        #[snafu(implicit)]
135        location: Location,
136    },
137
138    #[snafu(display("Missing TableMutationHandler, not expected"))]
139    MissingTableMutationHandler {
140        #[snafu(implicit)]
141        location: Location,
142    },
143
144    #[snafu(display("Missing ProcedureServiceHandler, not expected"))]
145    MissingProcedureServiceHandler {
146        #[snafu(implicit)]
147        location: Location,
148    },
149
150    #[snafu(display("Missing FlowServiceHandler, not expected"))]
151    MissingFlowServiceHandler {
152        #[snafu(implicit)]
153        location: Location,
154    },
155
156    #[snafu(display("Invalid function args: {}", err_msg))]
157    InvalidFuncArgs {
158        err_msg: String,
159        #[snafu(implicit)]
160        location: Location,
161    },
162
163    #[snafu(display("Permission denied: {}", err_msg))]
164    PermissionDenied {
165        err_msg: String,
166        #[snafu(implicit)]
167        location: Location,
168    },
169
170    #[snafu(display("Can't found alive flownode"))]
171    FlownodeNotFound {
172        #[snafu(implicit)]
173        location: Location,
174    },
175
176    #[snafu(display("Invalid vector string: {}", vec_str))]
177    InvalidVectorString {
178        vec_str: String,
179        source: DataTypeError,
180        #[snafu(implicit)]
181        location: Location,
182    },
183
184    #[snafu(display("Failed to register UDF: {}", name))]
185    RegisterUdf {
186        name: String,
187        #[snafu(source)]
188        error: DataFusionError,
189        #[snafu(implicit)]
190        location: Location,
191    },
192
193    #[snafu(display("Invalid character in prefix config: {}", prefix))]
194    InvalidColumnPrefix { prefix: String },
195
196    #[snafu(display(
197        "DynFilterPayload::Datafusion is {} bytes, which exceeds the configured limit of {} bytes",
198        payload_size_bytes,
199        max_payload_bytes
200    ))]
201    DynFilterPayloadTooLarge {
202        payload_size_bytes: usize,
203        max_payload_bytes: usize,
204        #[snafu(implicit)]
205        location: Location,
206    },
207
208    #[snafu(display(
209        "Remote dynamic filter predicate cannot be represented on the wire: {}",
210        reason
211    ))]
212    DynFilterUnsupported {
213        reason: String,
214        #[snafu(implicit)]
215        location: Location,
216    },
217}
218
219impl Error {
220    /// Whether the error reports a dynamic filter predicate with no wire form.
221    ///
222    /// Initial capture omits the refused snapshot; ongoing fanout sends an explicit
223    /// `true` reset to invalidate any stale region-side predicate. Neither path fails
224    /// the query.
225    pub fn is_dyn_filter_unsupported(&self) -> bool {
226        matches!(self, Error::DynFilterUnsupported { .. })
227    }
228}
229
230pub type Result<T> = std::result::Result<T, Error>;
231
232impl ErrorExt for Error {
233    fn status_code(&self) -> StatusCode {
234        match self {
235            Error::StorageWrite { source, .. } => source.status_code(),
236            Error::InvalidInputState { .. }
237            | Error::GetScalarVector { .. }
238            | Error::ArrowCompute { .. }
239            | Error::FlownodeNotFound { .. } => StatusCode::EngineExecuteQuery,
240
241            Error::GeneralDataFusion { error, .. } => datafusion_status_code::<Self>(error, None),
242
243            Error::InvalidInputType { source, .. }
244            | Error::IntoVector { source, .. }
245            | Error::FromScalarValue { source, .. }
246            | Error::InvalidVectorString { source, .. } => source.status_code(),
247
248            Error::MissingTableMutationHandler { .. }
249            | Error::MissingProcedureServiceHandler { .. }
250            | Error::MissingFlowServiceHandler { .. }
251            | Error::RegisterUdf { .. } => StatusCode::Unexpected,
252
253            Error::UnsupportedInputDataType { .. }
254            | Error::TypeCast { .. }
255            | Error::InvalidFuncArgs { .. }
256            | Error::InvalidColumnPrefix { .. } => StatusCode::InvalidArguments,
257
258            Error::DynFilterPayloadTooLarge { .. } => StatusCode::PlanQuery,
259            // An unrepresentable dynamic predicate is a transport limitation, not a
260            // server failure: callers omit the initial snapshot or reset the remote predicate.
261            Error::DynFilterUnsupported { .. } => StatusCode::Unsupported,
262
263            Error::DecodePlan { source, .. }
264            | Error::Execute { source, .. }
265            | Error::ProcedureService { source, .. }
266            | Error::TableMutation { source, .. } => source.status_code(),
267
268            Error::PermissionDenied { .. } => StatusCode::PermissionDenied,
269        }
270    }
271
272    fn as_any(&self) -> &dyn Any {
273        self
274    }
275
276    fn retry_hint(&self) -> RetryHint {
277        match self {
278            Error::StorageWrite { source, .. } => source.retry_hint(),
279            _ => RetryHint::NonRetryable,
280        }
281    }
282}
283
284impl From<Error> for DataFusionError {
285    fn from(e: Error) -> DataFusionError {
286        DataFusionError::External(Box::new(e))
287    }
288}
289
290/// Try to get the proper [`StatusCode`] of [`DataFusionError].
291pub fn datafusion_status_code<T: ErrorExt + 'static>(
292    e: &DataFusionError,
293    default_status: Option<StatusCode>,
294) -> StatusCode {
295    let mut error = e;
296    loop {
297        error = match error {
298            DataFusionError::Shared(inner) => inner,
299            DataFusionError::Context(_, inner) | DataFusionError::Diagnostic(_, inner) => inner,
300            _ => break,
301        };
302    }
303
304    match error {
305        DataFusionError::Internal(_) => StatusCode::Internal,
306        DataFusionError::NotImplemented(_) => StatusCode::Unsupported,
307        DataFusionError::Plan(_) => StatusCode::PlanQuery,
308        DataFusionError::External(error) => {
309            if let Some(ext) = (*error).downcast_ref::<T>() {
310                ext.status_code()
311            } else if let Some(ext) = (*error).downcast_ref::<BoxedError>() {
312                ext.status_code()
313            } else {
314                default_status.unwrap_or(StatusCode::EngineExecuteQuery)
315            }
316        }
317        _ => default_status.unwrap_or(StatusCode::EngineExecuteQuery),
318    }
319}
320
321#[cfg(test)]
322mod tests {
323    use std::sync::Arc;
324
325    use common_error::ext::PlainError;
326    use common_error::mock::MockError;
327
328    use super::*;
329
330    #[tokio::test]
331    async fn test_write_completion_preserves_retry_hint() {
332        for hint in [
333            RetryHint::NonRetryable,
334            RetryHint::Retryable,
335            RetryHint::RetryAfterRouteRefresh,
336        ] {
337            let source =
338                || BoxedError::new(MockError::new(StatusCode::RegionBusy).with_retry_hint(hint));
339            let progress = crate::WriteProgress::failed(source());
340            let error = progress.clone().into_result().unwrap_err();
341            assert_eq!(error.status_code(), StatusCode::RegionBusy);
342            assert_eq!(error.retry_hint(), hint);
343            assert_eq!(progress.error.unwrap().retry_hint(), hint);
344
345            let error = crate::WriteCompletion::new(std::future::ready(Err(source())))
346                .wait()
347                .await
348                .unwrap_err();
349            assert_eq!(error.status_code(), StatusCode::RegionBusy);
350            assert_eq!(error.retry_hint(), hint);
351        }
352    }
353
354    #[test]
355    fn test_datafusion_status_code_preserves_external_errors_through_wrappers() {
356        let boxed_error = |status| {
357            DataFusionError::External(Box::new(BoxedError::new(PlainError::new(
358                "neutral error".to_string(),
359                status,
360            ))))
361        };
362
363        for status in [
364            StatusCode::RequestOutdated,
365            StatusCode::Unknown,
366            StatusCode::Unsupported,
367        ] {
368            let errors = [
369                boxed_error(status),
370                DataFusionError::Shared(Arc::new(boxed_error(status))),
371                DataFusionError::Context("context".to_string(), Box::new(boxed_error(status))),
372                DataFusionError::Diagnostic(
373                    Box::new(datafusion_common::Diagnostic::new_error("diagnostic", None)),
374                    Box::new(boxed_error(status)),
375                ),
376                DataFusionError::Shared(Arc::new(DataFusionError::Context(
377                    "context".to_string(),
378                    Box::new(DataFusionError::Diagnostic(
379                        Box::new(datafusion_common::Diagnostic::new_error("diagnostic", None)),
380                        Box::new(boxed_error(status)),
381                    )),
382                ))),
383            ];
384
385            for error in errors {
386                assert_eq!(datafusion_status_code::<Error>(&error, None), status);
387                assert_eq!(
388                    datafusion_status_code::<Error>(&error, Some(StatusCode::PlanQuery)),
389                    status
390                );
391            }
392        }
393
394        let direct_error = DataFusionError::External(Box::new(Error::DynFilterPayloadTooLarge {
395            payload_size_bytes: 2,
396            max_payload_bytes: 1,
397            location: Location::default(),
398        }));
399        assert_eq!(
400            datafusion_status_code::<Error>(&direct_error, Some(StatusCode::Internal)),
401            StatusCode::PlanQuery
402        );
403
404        let unsupported_error = DataFusionError::External(Box::new(Error::DynFilterUnsupported {
405            reason: "no wire form".to_string(),
406            location: Location::default(),
407        }));
408        assert_eq!(
409            datafusion_status_code::<Error>(&unsupported_error, Some(StatusCode::Internal)),
410            StatusCode::Unsupported
411        );
412
413        let boundary_error =
414            DataFusionError::Shared(Arc::new(DataFusionError::External(Box::new(
415                BoxedError::new(common_recordbatch::error::Error::PhysicalExpr {
416                    error: DataFusionError::NotImplemented("inner error".to_string()),
417                    location: Location::default(),
418                }),
419            ))));
420        assert_eq!(
421            datafusion_status_code::<Error>(&boundary_error, Some(StatusCode::PlanQuery)),
422            StatusCode::Internal
423        );
424    }
425
426    #[test]
427    fn test_datafusion_status_code_uses_default_for_untyped_errors() {
428        let wrap = |error| {
429            DataFusionError::Shared(Arc::new(DataFusionError::Context(
430                "context".to_string(),
431                Box::new(DataFusionError::Diagnostic(
432                    Box::new(datafusion_common::Diagnostic::new_error("diagnostic", None)),
433                    Box::new(error),
434                )),
435            )))
436        };
437        let errors = || {
438            [
439                (
440                    DataFusionError::External(Box::new(std::io::Error::other("neutral io error"))),
441                    StatusCode::EngineExecuteQuery,
442                    StatusCode::Unknown,
443                ),
444                (
445                    DataFusionError::Internal("neutral internal error".to_string()),
446                    StatusCode::Internal,
447                    StatusCode::Internal,
448                ),
449                (
450                    DataFusionError::NotImplemented("neutral not implemented error".to_string()),
451                    StatusCode::Unsupported,
452                    StatusCode::Unsupported,
453                ),
454                (
455                    DataFusionError::Plan("neutral plan error".to_string()),
456                    StatusCode::PlanQuery,
457                    StatusCode::PlanQuery,
458                ),
459                (
460                    DataFusionError::External(Box::new(DataFusionError::Internal(
461                        "inner error".to_string(),
462                    ))),
463                    StatusCode::EngineExecuteQuery,
464                    StatusCode::Unknown,
465                ),
466            ]
467        };
468
469        for (error, none_expected, default_expected) in
470            errors()
471                .into_iter()
472                .chain(errors().map(|(error, none_expected, default_expected)| {
473                    (wrap(error), none_expected, default_expected)
474                }))
475        {
476            assert_eq!(datafusion_status_code::<Error>(&error, None), none_expected);
477            assert_eq!(
478                datafusion_status_code::<Error>(&error, Some(StatusCode::Unknown)),
479                default_expected
480            );
481        }
482    }
483}