Skip to main content

mito2/
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 common_datasource::compression::CompressionType;
19use common_error::ext::{BoxedError, ErrorExt};
20use common_error::status_code::StatusCode;
21use common_macro::stack_trace_debug;
22use common_memory_manager;
23use common_runtime::JoinError;
24use common_time::Timestamp;
25use common_time::timestamp::TimeUnit;
26use datatypes::arrow::error::ArrowError;
27use datatypes::prelude::ConcreteDataType;
28use object_store::ErrorKind;
29use partition::error::Error as PartitionError;
30use prost::DecodeError;
31use snafu::{Location, Snafu};
32use store_api::ManifestVersion;
33use store_api::logstore::provider::Provider;
34use store_api::storage::{FileId, RegionId};
35use tokio::time::error::Elapsed;
36
37use crate::cache::file_cache::FileType;
38use crate::region::RegionRoleState;
39use crate::schedule::remote_job_scheduler::JobId;
40use crate::worker::WorkerId;
41
42#[derive(Snafu)]
43#[snafu(visibility(pub))]
44#[stack_trace_debug]
45pub enum Error {
46    #[snafu(display("Unexpected data type"))]
47    DataTypeMismatch {
48        source: datatypes::error::Error,
49        #[snafu(implicit)]
50        location: Location,
51    },
52
53    #[snafu(display("External error, context: {}", context))]
54    External {
55        source: BoxedError,
56        context: String,
57        #[snafu(implicit)]
58        location: Location,
59    },
60
61    #[snafu(display("OpenDAL operator failed"))]
62    OpenDal {
63        #[snafu(implicit)]
64        location: Location,
65        #[snafu(source)]
66        error: object_store::Error,
67    },
68
69    #[snafu(display("Fail to compress object by {}, path: {}", compress_type, path))]
70    CompressObject {
71        compress_type: CompressionType,
72        path: String,
73        #[snafu(source)]
74        error: std::io::Error,
75    },
76
77    #[snafu(display("Fail to decompress object by {}, path: {}", compress_type, path))]
78    DecompressObject {
79        compress_type: CompressionType,
80        path: String,
81        #[snafu(source)]
82        error: std::io::Error,
83    },
84
85    #[snafu(display("Failed to ser/de json object"))]
86    SerdeJson {
87        #[snafu(implicit)]
88        location: Location,
89        #[snafu(source)]
90        error: serde_json::Error,
91    },
92
93    #[snafu(display("Failed to serialize column metadata"))]
94    SerializeColumnMetadata {
95        #[snafu(source)]
96        error: serde_json::Error,
97        #[snafu(implicit)]
98        location: Location,
99    },
100
101    #[snafu(display("Failed to serialize manifest, region_id: {}", region_id))]
102    SerializeManifest {
103        region_id: RegionId,
104        #[snafu(source)]
105        error: serde_json::Error,
106        #[snafu(implicit)]
107        location: Location,
108    },
109
110    #[snafu(display("Invalid scan index, start: {}, end: {}", start, end))]
111    InvalidScanIndex {
112        start: ManifestVersion,
113        end: ManifestVersion,
114        #[snafu(implicit)]
115        location: Location,
116    },
117
118    #[snafu(display("Invalid UTF-8 content"))]
119    Utf8 {
120        #[snafu(implicit)]
121        location: Location,
122        #[snafu(source)]
123        error: std::str::Utf8Error,
124    },
125
126    #[snafu(display("Cannot find RegionMetadata"))]
127    RegionMetadataNotFound {
128        #[snafu(implicit)]
129        location: Location,
130    },
131
132    #[snafu(display("Failed to join handle"))]
133    Join {
134        #[snafu(source)]
135        error: common_runtime::JoinError,
136        #[snafu(implicit)]
137        location: Location,
138    },
139
140    #[snafu(display("Worker {} is stopped", id))]
141    WorkerStopped {
142        id: WorkerId,
143        #[snafu(implicit)]
144        location: Location,
145    },
146
147    #[snafu(display("Failed to recv result"))]
148    Recv {
149        #[snafu(source)]
150        error: tokio::sync::oneshot::error::RecvError,
151        #[snafu(implicit)]
152        location: Location,
153    },
154
155    #[snafu(display("Invalid metadata, {}", reason))]
156    InvalidMeta {
157        reason: String,
158        #[snafu(implicit)]
159        location: Location,
160    },
161
162    #[snafu(display("Invalid region metadata"))]
163    InvalidMetadata {
164        source: store_api::metadata::MetadataError,
165        #[snafu(implicit)]
166        location: Location,
167    },
168
169    #[snafu(display("Failed to create RecordBatch from vectors"))]
170    NewRecordBatch {
171        #[snafu(implicit)]
172        location: Location,
173        #[snafu(source)]
174        error: ArrowError,
175    },
176
177    #[snafu(display("Failed to read parquet file, path: {}", path))]
178    ReadParquet {
179        path: String,
180        #[snafu(source)]
181        error: parquet::errors::ParquetError,
182        #[snafu(implicit)]
183        location: Location,
184    },
185
186    #[snafu(display("Failed to write parquet file"))]
187    WriteParquet {
188        #[snafu(source)]
189        error: parquet::errors::ParquetError,
190        #[snafu(implicit)]
191        location: Location,
192    },
193
194    #[snafu(display("Region {} not found", region_id))]
195    RegionNotFound {
196        region_id: RegionId,
197        #[snafu(implicit)]
198        location: Location,
199    },
200
201    #[snafu(display("Object store not found: {}", object_store))]
202    ObjectStoreNotFound {
203        object_store: String,
204        #[snafu(implicit)]
205        location: Location,
206    },
207
208    #[snafu(display("Region {} is corrupted, reason: {}", region_id, reason))]
209    RegionCorrupted {
210        region_id: RegionId,
211        reason: String,
212        #[snafu(implicit)]
213        location: Location,
214    },
215
216    #[snafu(display("Invalid request to region {}, reason: {}", region_id, reason))]
217    InvalidRequest {
218        region_id: RegionId,
219        reason: String,
220        #[snafu(implicit)]
221        location: Location,
222    },
223
224    #[snafu(display(
225        "STALE_CURSOR: incremental query stale, region: {}, given_seq: {}, min_readable_seq: {}, retry_hint: FALLBACK_FULL_RECOMPUTE",
226        region_id,
227        given_seq,
228        min_readable_seq
229    ))]
230    IncrementalQueryStale {
231        region_id: RegionId,
232        given_seq: u64,
233        min_readable_seq: u64,
234        #[snafu(implicit)]
235        location: Location,
236    },
237
238    #[snafu(display("Old manifest missing for region {}", region_id))]
239    MissingOldManifest {
240        region_id: RegionId,
241        #[snafu(implicit)]
242        location: Location,
243    },
244
245    #[snafu(display("New manifest missing for region {}", region_id))]
246    MissingNewManifest {
247        region_id: RegionId,
248        #[snafu(implicit)]
249        location: Location,
250    },
251
252    #[snafu(display("Manifest missing for region {}", region_id))]
253    MissingManifest {
254        region_id: RegionId,
255        #[snafu(implicit)]
256        location: Location,
257    },
258
259    #[snafu(display("File consistency check failed for file {}: {}", file_id, reason))]
260    InconsistentFile {
261        file_id: FileId,
262        reason: String,
263        #[snafu(implicit)]
264        location: Location,
265    },
266
267    #[snafu(display("Files lost during remapping: old={}, new={}", old_count, new_count))]
268    FilesLost {
269        old_count: usize,
270        new_count: usize,
271        #[snafu(implicit)]
272        location: Location,
273    },
274
275    #[snafu(display("No old manifests provided (need at least one for template)"))]
276    NoOldManifests {
277        #[snafu(implicit)]
278        location: Location,
279    },
280
281    #[snafu(display("Failed to fetch manifests"))]
282    FetchManifests {
283        #[snafu(implicit)]
284        location: Location,
285        source: BoxedError,
286    },
287
288    #[snafu(display("Partition expression missing for region {}", region_id))]
289    MissingPartitionExpr {
290        region_id: RegionId,
291        #[snafu(implicit)]
292        location: Location,
293    },
294
295    #[snafu(display("Failed to serialize partition expression: {}", source))]
296    SerializePartitionExpr {
297        #[snafu(source)]
298        source: PartitionError,
299        #[snafu(implicit)]
300        location: Location,
301    },
302
303    #[snafu(display(
304        "Failed to convert ConcreteDataType to ColumnDataType, reason: {}",
305        reason
306    ))]
307    ConvertColumnDataType {
308        reason: String,
309        source: api::error::Error,
310        #[snafu(implicit)]
311        location: Location,
312    },
313
314    /// An error type to indicate that schema is changed and we need
315    /// to fill default values again.
316    #[snafu(display("Need to fill default value for region {}", region_id))]
317    FillDefault {
318        region_id: RegionId,
319        // The error is for internal use so we don't need a location.
320    },
321
322    #[snafu(display(
323        "Failed to create default value for column {} of region {}",
324        column,
325        region_id
326    ))]
327    CreateDefault {
328        region_id: RegionId,
329        column: String,
330        source: datatypes::Error,
331        #[snafu(implicit)]
332        location: Location,
333    },
334
335    #[snafu(display("Failed to build entry, region_id: {}", region_id))]
336    BuildEntry {
337        region_id: RegionId,
338        #[snafu(implicit)]
339        location: Location,
340        source: BoxedError,
341    },
342
343    #[snafu(display("Failed to write WAL"))]
344    WriteWal {
345        #[snafu(implicit)]
346        location: Location,
347        source: BoxedError,
348    },
349
350    #[snafu(display("Failed to read WAL, provider: {}", provider))]
351    ReadWal {
352        provider: Provider,
353        #[snafu(implicit)]
354        location: Location,
355        source: BoxedError,
356    },
357
358    #[snafu(display("Failed to decode WAL entry, region_id: {}", region_id))]
359    DecodeWal {
360        region_id: RegionId,
361        #[snafu(implicit)]
362        location: Location,
363        #[snafu(source)]
364        error: DecodeError,
365    },
366
367    #[snafu(display("Failed to delete WAL, region_id: {}", region_id))]
368    DeleteWal {
369        region_id: RegionId,
370        #[snafu(implicit)]
371        location: Location,
372        source: BoxedError,
373    },
374
375    // Shared error for each writer in the write group.
376    #[snafu(display("Failed to write region"))]
377    WriteGroup { source: Arc<Error> },
378
379    #[snafu(display("Invalid parquet SST file {}, reason: {}", file, reason))]
380    InvalidParquet {
381        file: String,
382        reason: String,
383        #[snafu(implicit)]
384        location: Location,
385    },
386
387    #[snafu(display("Invalid batch, {}", reason))]
388    InvalidBatch {
389        reason: String,
390        #[snafu(implicit)]
391        location: Location,
392    },
393
394    #[snafu(display("Invalid arrow record batch, {}", reason))]
395    InvalidRecordBatch {
396        reason: String,
397        #[snafu(implicit)]
398        location: Location,
399    },
400
401    #[snafu(display("Invalid wal read request, {}", reason))]
402    InvalidWalReadRequest {
403        reason: String,
404        #[snafu(implicit)]
405        location: Location,
406    },
407
408    #[snafu(display("Failed to convert array to vector"))]
409    ConvertVector {
410        #[snafu(implicit)]
411        location: Location,
412        source: datatypes::error::Error,
413    },
414
415    #[snafu(display("Failed to compute arrow arrays"))]
416    ComputeArrow {
417        #[snafu(implicit)]
418        location: Location,
419        #[snafu(source)]
420        error: datatypes::arrow::error::ArrowError,
421    },
422
423    #[snafu(display("Failed to evaluate partition filter"))]
424    EvalPartitionFilter {
425        #[snafu(implicit)]
426        location: Location,
427        #[snafu(source)]
428        error: datafusion::error::DataFusionError,
429    },
430
431    #[snafu(display("Failed to compute vector"))]
432    ComputeVector {
433        #[snafu(implicit)]
434        location: Location,
435        source: datatypes::error::Error,
436    },
437
438    #[snafu(display("Primary key length mismatch, expect: {}, actual: {}", expect, actual))]
439    PrimaryKeyLengthMismatch {
440        expect: usize,
441        actual: usize,
442        #[snafu(implicit)]
443        location: Location,
444    },
445
446    #[snafu(display("Invalid sender",))]
447    InvalidSender {
448        #[snafu(implicit)]
449        location: Location,
450    },
451
452    #[snafu(display("Invalid scheduler state"))]
453    InvalidSchedulerState {
454        #[snafu(implicit)]
455        location: Location,
456    },
457
458    #[snafu(display("Failed to stop scheduler"))]
459    StopScheduler {
460        #[snafu(source)]
461        error: JoinError,
462        #[snafu(implicit)]
463        location: Location,
464    },
465
466    #[snafu(display(
467        "Failed to batch delete SST files, region id: {}, file ids: {:?}",
468        region_id,
469        file_ids
470    ))]
471    DeleteSsts {
472        region_id: RegionId,
473        file_ids: Vec<FileId>,
474        #[snafu(source)]
475        error: object_store::Error,
476        #[snafu(implicit)]
477        location: Location,
478    },
479
480    #[snafu(display("Failed to delete index file, file id: {}", file_id))]
481    DeleteIndex {
482        file_id: FileId,
483        #[snafu(source)]
484        error: object_store::Error,
485        #[snafu(implicit)]
486        location: Location,
487    },
488
489    #[snafu(display("Failed to batch delete index files, file ids: {:?}", file_ids))]
490    DeleteIndexes {
491        file_ids: Vec<FileId>,
492        #[snafu(source)]
493        error: object_store::Error,
494        #[snafu(implicit)]
495        location: Location,
496    },
497
498    #[snafu(display("Failed to flush region {}", region_id))]
499    FlushRegion {
500        region_id: RegionId,
501        source: Arc<Error>,
502        #[snafu(implicit)]
503        location: Location,
504    },
505
506    #[snafu(display("Region {} is dropped", region_id))]
507    RegionDropped {
508        region_id: RegionId,
509        #[snafu(implicit)]
510        location: Location,
511    },
512
513    #[snafu(display("Region {} is closed", region_id))]
514    RegionClosed {
515        region_id: RegionId,
516        #[snafu(implicit)]
517        location: Location,
518    },
519
520    #[snafu(display("Region {} is truncated", region_id))]
521    RegionTruncated {
522        region_id: RegionId,
523        #[snafu(implicit)]
524        location: Location,
525    },
526
527    #[snafu(display(
528        "Engine write buffer is full, rejecting write requests of region {}",
529        region_id,
530    ))]
531    RejectWrite {
532        region_id: RegionId,
533        #[snafu(implicit)]
534        location: Location,
535    },
536
537    #[snafu(display("Failed to compact region {}", region_id))]
538    CompactRegion {
539        region_id: RegionId,
540        source: Arc<Error>,
541        #[snafu(implicit)]
542        location: Location,
543    },
544
545    #[snafu(display("Failed to edit region {}", region_id))]
546    EditRegion {
547        region_id: RegionId,
548        source: Arc<Error>,
549        #[snafu(implicit)]
550        location: Location,
551    },
552
553    #[snafu(display(
554        "Failed to compat readers for region {}, reason: {}",
555        region_id,
556        reason,
557    ))]
558    CompatReader {
559        region_id: RegionId,
560        reason: String,
561        #[snafu(implicit)]
562        location: Location,
563    },
564
565    #[snafu(display("Invalue region req"))]
566    InvalidRegionRequest {
567        source: store_api::metadata::MetadataError,
568        #[snafu(implicit)]
569        location: Location,
570    },
571
572    #[snafu(display(
573        "Region {} is in {:?} state, which does not permit manifest updates.",
574        region_id,
575        state
576    ))]
577    UpdateManifest {
578        region_id: RegionId,
579        state: RegionRoleState,
580        #[snafu(implicit)]
581        location: Location,
582    },
583
584    #[snafu(display("Region {} is in {:?} state, expect: {:?}", region_id, state, expect))]
585    RegionState {
586        region_id: RegionId,
587        state: RegionRoleState,
588        expect: RegionRoleState,
589        #[snafu(implicit)]
590        location: Location,
591    },
592
593    #[snafu(display(
594        "Partition expr version mismatch for region {}: request {}, expected {}",
595        region_id,
596        request_version,
597        expected_version
598    ))]
599    PartitionExprVersionMismatch {
600        region_id: RegionId,
601        request_version: u64,
602        expected_version: u64,
603        #[snafu(implicit)]
604        location: Location,
605    },
606
607    #[snafu(display("Invalid options"))]
608    JsonOptions {
609        #[snafu(source)]
610        error: serde_json::Error,
611        #[snafu(implicit)]
612        location: Location,
613    },
614
615    #[snafu(display(
616        "Empty region directory, region_id: {}, region_dir: {}",
617        region_id,
618        region_dir,
619    ))]
620    EmptyRegionDir {
621        region_id: RegionId,
622        region_dir: String,
623        #[snafu(implicit)]
624        location: Location,
625    },
626
627    #[snafu(display("Empty manifest directory, manifest_dir: {}", manifest_dir,))]
628    EmptyManifestDir {
629        manifest_dir: String,
630        #[snafu(implicit)]
631        location: Location,
632    },
633
634    #[snafu(display("Column not found, column: {column}"))]
635    ColumnNotFound {
636        column: String,
637        #[snafu(implicit)]
638        location: Location,
639    },
640
641    #[snafu(display("Failed to build index applier"))]
642    BuildIndexApplier {
643        source: index::inverted_index::error::Error,
644        #[snafu(implicit)]
645        location: Location,
646    },
647
648    #[snafu(display("Failed to build index asynchronously in region {}", region_id))]
649    BuildIndexAsync {
650        region_id: RegionId,
651        source: Arc<Error>,
652        #[snafu(implicit)]
653        location: Location,
654    },
655
656    #[snafu(display("Failed to convert value"))]
657    ConvertValue {
658        source: datatypes::error::Error,
659        #[snafu(implicit)]
660        location: Location,
661    },
662
663    #[snafu(display("Failed to apply inverted index"))]
664    ApplyInvertedIndex {
665        source: index::inverted_index::error::Error,
666        #[snafu(implicit)]
667        location: Location,
668    },
669
670    #[snafu(display("Failed to apply bloom filter index"))]
671    ApplyBloomFilterIndex {
672        source: index::bloom_filter::error::Error,
673        #[snafu(implicit)]
674        location: Location,
675    },
676
677    #[cfg(feature = "vector_index")]
678    #[snafu(display("Failed to apply vector index: {}", reason))]
679    ApplyVectorIndex {
680        reason: String,
681        #[snafu(implicit)]
682        location: Location,
683    },
684
685    #[snafu(display("Failed to push index value"))]
686    PushIndexValue {
687        source: index::inverted_index::error::Error,
688        #[snafu(implicit)]
689        location: Location,
690    },
691
692    #[snafu(display("Failed to write index completely"))]
693    IndexFinish {
694        source: index::inverted_index::error::Error,
695        #[snafu(implicit)]
696        location: Location,
697    },
698
699    #[snafu(display("Operate on aborted index"))]
700    OperateAbortedIndex {
701        #[snafu(implicit)]
702        location: Location,
703    },
704
705    #[snafu(display("Failed to read puffin blob"))]
706    PuffinReadBlob {
707        source: puffin::error::Error,
708        #[snafu(implicit)]
709        location: Location,
710    },
711
712    #[snafu(display("Failed to add blob to puffin file"))]
713    PuffinAddBlob {
714        source: puffin::error::Error,
715        #[snafu(implicit)]
716        location: Location,
717    },
718
719    #[snafu(display("Failed to clean dir {dir}"))]
720    CleanDir {
721        dir: String,
722        #[snafu(source)]
723        error: std::io::Error,
724        #[snafu(implicit)]
725        location: Location,
726    },
727
728    #[snafu(display("Invalid config, {reason}"))]
729    InvalidConfig {
730        reason: String,
731        #[snafu(implicit)]
732        location: Location,
733    },
734
735    #[snafu(display(
736        "Stale log entry found during replay, region: {}, flushed: {}, replayed: {}",
737        region_id,
738        flushed_entry_id,
739        unexpected_entry_id
740    ))]
741    StaleLogEntry {
742        region_id: RegionId,
743        flushed_entry_id: u64,
744        unexpected_entry_id: u64,
745    },
746
747    #[snafu(display(
748        "Failed to download file, region_id: {}, file_id: {}, file_type: {:?}",
749        region_id,
750        file_id,
751        file_type,
752    ))]
753    Download {
754        region_id: RegionId,
755        file_id: FileId,
756        file_type: FileType,
757        #[snafu(source)]
758        error: std::io::Error,
759        #[snafu(implicit)]
760        location: Location,
761    },
762
763    #[snafu(display(
764        "Failed to upload file, region_id: {}, file_id: {}, file_type: {:?}",
765        region_id,
766        file_id,
767        file_type,
768    ))]
769    Upload {
770        region_id: RegionId,
771        file_id: FileId,
772        file_type: FileType,
773        #[snafu(source)]
774        error: std::io::Error,
775        #[snafu(implicit)]
776        location: Location,
777    },
778
779    #[snafu(display("Failed to create directory {}", dir))]
780    CreateDir {
781        dir: String,
782        #[snafu(source)]
783        error: std::io::Error,
784    },
785
786    #[snafu(display("Record batch error"))]
787    RecordBatch {
788        source: common_recordbatch::error::Error,
789        #[snafu(implicit)]
790        location: Location,
791    },
792
793    #[snafu(display("BiErrors, first: {first}, second: {second}"))]
794    BiErrors {
795        first: Box<Error>,
796        second: Box<Error>,
797        #[snafu(implicit)]
798        location: Location,
799    },
800
801    #[snafu(display("Encode null value"))]
802    IndexEncodeNull {
803        #[snafu(implicit)]
804        location: Location,
805    },
806
807    #[snafu(display("Failed to encode memtable to Parquet bytes"))]
808    EncodeMemtable {
809        #[snafu(source)]
810        error: parquet::errors::ParquetError,
811        #[snafu(implicit)]
812        location: Location,
813    },
814
815    #[snafu(display("Partition {} out of range, {} in total", given, all))]
816    PartitionOutOfRange {
817        given: usize,
818        all: usize,
819        #[snafu(implicit)]
820        location: Location,
821    },
822
823    #[snafu(display("Failed to iter data part"))]
824    ReadDataPart {
825        #[snafu(implicit)]
826        location: Location,
827        #[snafu(source)]
828        error: parquet::errors::ParquetError,
829    },
830
831    #[snafu(display("Failed to read row group in memtable"))]
832    DecodeArrowRowGroup {
833        #[snafu(source)]
834        error: ArrowError,
835        #[snafu(implicit)]
836        location: Location,
837    },
838
839    #[snafu(display("Invalid region options, {}", reason))]
840    InvalidRegionOptions {
841        reason: String,
842        #[snafu(implicit)]
843        location: Location,
844    },
845
846    #[snafu(display("checksum mismatch (actual: {}, expected: {})", actual, expected))]
847    ChecksumMismatch { actual: u32, expected: u32 },
848
849    #[snafu(display(
850        "No checkpoint found, region: {}, last_version: {}",
851        region_id,
852        last_version
853    ))]
854    NoCheckpoint {
855        region_id: RegionId,
856        last_version: ManifestVersion,
857        #[snafu(implicit)]
858        location: Location,
859    },
860
861    #[snafu(display(
862        "No manifests found in range: [{}..{}), region: {}, last_version: {}",
863        start_version,
864        end_version,
865        region_id,
866        last_version
867    ))]
868    NoManifests {
869        region_id: RegionId,
870        start_version: ManifestVersion,
871        end_version: ManifestVersion,
872        last_version: ManifestVersion,
873        #[snafu(implicit)]
874        location: Location,
875    },
876
877    #[snafu(display(
878        "Failed to install manifest to {}, region: {}, available manifest version: {}, last version: {}",
879        target_version,
880        region_id,
881        available_version,
882        last_version
883    ))]
884    InstallManifestTo {
885        region_id: RegionId,
886        target_version: ManifestVersion,
887        available_version: ManifestVersion,
888        #[snafu(implicit)]
889        location: Location,
890        last_version: ManifestVersion,
891    },
892
893    #[snafu(display("Region {} is stopped", region_id))]
894    RegionStopped {
895        region_id: RegionId,
896        #[snafu(implicit)]
897        location: Location,
898    },
899
900    #[snafu(display(
901        "Time range predicate overflows, timestamp: {:?}, target unit: {}",
902        timestamp,
903        unit
904    ))]
905    TimeRangePredicateOverflow {
906        timestamp: Timestamp,
907        unit: TimeUnit,
908        #[snafu(implicit)]
909        location: Location,
910    },
911
912    #[snafu(display("Failed to open region"))]
913    OpenRegion {
914        #[snafu(implicit)]
915        location: Location,
916        source: Arc<Error>,
917    },
918
919    #[snafu(display(
920        "Region {} does not satisfy open requirement '{}': {}",
921        region_id,
922        requirement,
923        reason
924    ))]
925    OpenRegionRequirement {
926        region_id: RegionId,
927        requirement: &'static str,
928        reason: &'static str,
929        #[snafu(implicit)]
930        location: Location,
931    },
932
933    #[snafu(display("Failed to parse job id"))]
934    ParseJobId {
935        #[snafu(implicit)]
936        location: Location,
937        #[snafu(source)]
938        error: uuid::Error,
939    },
940
941    #[snafu(display("Operation is not supported: {}", err_msg))]
942    UnsupportedOperation {
943        err_msg: String,
944        #[snafu(implicit)]
945        location: Location,
946    },
947
948    #[snafu(display(
949        "Failed to remotely compact region {} by job {:?} due to {}",
950        region_id,
951        job_id,
952        reason
953    ))]
954    RemoteCompaction {
955        region_id: RegionId,
956        job_id: Option<JobId>,
957        reason: String,
958        #[snafu(implicit)]
959        location: Location,
960    },
961
962    #[snafu(display("Failed to initialize puffin stager"))]
963    PuffinInitStager {
964        source: puffin::error::Error,
965        #[snafu(implicit)]
966        location: Location,
967    },
968
969    #[snafu(display("Failed to purge puffin stager"))]
970    PuffinPurgeStager {
971        source: puffin::error::Error,
972        #[snafu(implicit)]
973        location: Location,
974    },
975
976    #[snafu(display("Failed to build puffin reader"))]
977    PuffinBuildReader {
978        source: puffin::error::Error,
979        #[snafu(implicit)]
980        location: Location,
981    },
982
983    #[snafu(display("Failed to retrieve index options from column metadata"))]
984    IndexOptions {
985        #[snafu(implicit)]
986        location: Location,
987        source: datatypes::error::Error,
988        column_name: String,
989    },
990
991    #[snafu(display("Failed to create fulltext index creator"))]
992    CreateFulltextCreator {
993        source: index::fulltext_index::error::Error,
994        #[snafu(implicit)]
995        location: Location,
996    },
997
998    #[snafu(display("Failed to cast vector of {from} to {to}"))]
999    CastVector {
1000        #[snafu(implicit)]
1001        location: Location,
1002        from: ConcreteDataType,
1003        to: ConcreteDataType,
1004        source: datatypes::error::Error,
1005    },
1006
1007    #[snafu(display("Failed to push text to fulltext index"))]
1008    FulltextPushText {
1009        source: index::fulltext_index::error::Error,
1010        #[snafu(implicit)]
1011        location: Location,
1012    },
1013
1014    #[snafu(display("Failed to finalize fulltext index creator"))]
1015    FulltextFinish {
1016        source: index::fulltext_index::error::Error,
1017        #[snafu(implicit)]
1018        location: Location,
1019    },
1020
1021    #[snafu(display("Failed to apply fulltext index"))]
1022    ApplyFulltextIndex {
1023        source: index::fulltext_index::error::Error,
1024        #[snafu(implicit)]
1025        location: Location,
1026    },
1027
1028    #[snafu(display("SST file {} does not contain valid stats info", file_path))]
1029    StatsNotPresent {
1030        file_path: String,
1031        #[snafu(implicit)]
1032        location: Location,
1033    },
1034
1035    #[snafu(display("Failed to decode stats of file {}", file_path))]
1036    DecodeStats {
1037        file_path: String,
1038        #[snafu(implicit)]
1039        location: Location,
1040    },
1041
1042    #[snafu(display("Region {} is busy", region_id))]
1043    RegionBusy {
1044        region_id: RegionId,
1045        #[snafu(implicit)]
1046        location: Location,
1047    },
1048
1049    #[snafu(display("Failed to get schema metadata"))]
1050    GetSchemaMetadata {
1051        source: common_meta::error::Error,
1052        #[snafu(implicit)]
1053        location: Location,
1054    },
1055
1056    #[snafu(display("Timeout"))]
1057    Timeout {
1058        #[snafu(source)]
1059        error: Elapsed,
1060        #[snafu(implicit)]
1061        location: Location,
1062    },
1063
1064    #[snafu(display("Failed to read file metadata"))]
1065    Metadata {
1066        #[snafu(source)]
1067        error: std::io::Error,
1068        #[snafu(implicit)]
1069        location: Location,
1070    },
1071
1072    #[snafu(display("Failed to push value to bloom filter"))]
1073    PushBloomFilterValue {
1074        source: index::bloom_filter::error::Error,
1075        #[snafu(implicit)]
1076        location: Location,
1077    },
1078
1079    #[snafu(display("Failed to finish bloom filter"))]
1080    BloomFilterFinish {
1081        source: index::bloom_filter::error::Error,
1082        #[snafu(implicit)]
1083        location: Location,
1084    },
1085
1086    #[cfg(feature = "vector_index")]
1087    #[snafu(display("Failed to build vector index: {}", reason))]
1088    VectorIndexBuild {
1089        reason: String,
1090        #[snafu(implicit)]
1091        location: Location,
1092    },
1093
1094    #[cfg(feature = "vector_index")]
1095    #[snafu(display("Failed to finish vector index: {}", reason))]
1096    VectorIndexFinish {
1097        reason: String,
1098        #[snafu(implicit)]
1099        location: Location,
1100    },
1101
1102    #[snafu(display("Manual compaction is override by following operations."))]
1103    ManualCompactionOverride {},
1104
1105    #[snafu(display("Compaction is cancelled."))]
1106    CompactionCancelled {},
1107
1108    #[snafu(display("Compaction memory exhausted for region {region_id} (policy: {policy})",))]
1109    CompactionMemoryExhausted {
1110        region_id: RegionId,
1111        policy: String,
1112        #[snafu(source)]
1113        source: common_memory_manager::Error,
1114        #[snafu(implicit)]
1115        location: Location,
1116    },
1117
1118    #[snafu(display(
1119        "Incompatible WAL provider change. This is typically caused by changing WAL provider in database config file without completely cleaning existing files. Global provider: {}, region provider: {}",
1120        global,
1121        region
1122    ))]
1123    IncompatibleWalProviderChange { global: String, region: String },
1124
1125    #[snafu(display("Expected mito manifest info"))]
1126    MitoManifestInfo {
1127        #[snafu(implicit)]
1128        location: Location,
1129    },
1130
1131    #[snafu(display("Failed to scan series"))]
1132    ScanSeries {
1133        #[snafu(implicit)]
1134        location: Location,
1135        source: Arc<Error>,
1136    },
1137
1138    #[snafu(display("Partition {} scan multiple times", partition))]
1139    ScanMultiTimes {
1140        partition: usize,
1141        #[snafu(implicit)]
1142        location: Location,
1143    },
1144
1145    #[snafu(display("Invalid partition expression: {}", expr))]
1146    InvalidPartitionExpr {
1147        expr: String,
1148        #[snafu(implicit)]
1149        location: Location,
1150        source: partition::error::Error,
1151    },
1152
1153    #[snafu(display("Failed to decode bulk wal entry"))]
1154    ConvertBulkWalEntry {
1155        #[snafu(implicit)]
1156        location: Location,
1157        source: common_grpc::Error,
1158    },
1159
1160    #[snafu(display("Failed to encode"))]
1161    Encode {
1162        #[snafu(implicit)]
1163        location: Location,
1164        source: mito_codec::error::Error,
1165    },
1166
1167    #[snafu(display("Failed to decode"))]
1168    Decode {
1169        #[snafu(implicit)]
1170        location: Location,
1171        source: mito_codec::error::Error,
1172    },
1173
1174    #[snafu(display("Unexpected: {reason}"))]
1175    Unexpected {
1176        reason: String,
1177        #[snafu(implicit)]
1178        location: Location,
1179    },
1180
1181    #[cfg(feature = "enterprise")]
1182    #[snafu(display("Failed to scan external range"))]
1183    ScanExternalRange {
1184        source: BoxedError,
1185        #[snafu(implicit)]
1186        location: Location,
1187    },
1188
1189    #[snafu(display(
1190        "Inconsistent timestamp column length, expect: {}, actual: {}",
1191        expected,
1192        actual
1193    ))]
1194    InconsistentTimestampLength {
1195        expected: usize,
1196        actual: usize,
1197        #[snafu(implicit)]
1198        location: Location,
1199    },
1200
1201    #[snafu(display(
1202        "Too many files to read concurrently: {}, max allowed: {}",
1203        actual,
1204        max
1205    ))]
1206    TooManyFilesToRead {
1207        actual: usize,
1208        max: usize,
1209        #[snafu(implicit)]
1210        location: Location,
1211    },
1212
1213    #[snafu(display("Duration out of range: {input:?}"))]
1214    DurationOutOfRange {
1215        input: std::time::Duration,
1216        #[snafu(source)]
1217        error: chrono::OutOfRangeError,
1218        #[snafu(implicit)]
1219        location: Location,
1220    },
1221
1222    #[snafu(display("GC job permit exhausted"))]
1223    TooManyGcJobs {
1224        #[snafu(implicit)]
1225        location: Location,
1226    },
1227
1228    #[snafu(display(
1229        "Staging partition expr mismatch, manifest: {:?}, request: {}",
1230        manifest_expr,
1231        request_expr
1232    ))]
1233    StagingPartitionExprMismatch {
1234        manifest_expr: Option<String>,
1235        request_expr: String,
1236        #[snafu(implicit)]
1237        location: Location,
1238    },
1239
1240    #[snafu(display(
1241        "Invalid source and target region, source: {}, target: {}",
1242        source_region_id,
1243        target_region_id
1244    ))]
1245    InvalidSourceAndTargetRegion {
1246        source_region_id: RegionId,
1247        target_region_id: RegionId,
1248        #[snafu(implicit)]
1249        location: Location,
1250    },
1251
1252    #[snafu(display("Failed to prune file"))]
1253    PruneFile {
1254        source: Arc<Error>,
1255        #[snafu(implicit)]
1256        location: Location,
1257    },
1258
1259    #[snafu(display("Failed to cast column"))]
1260    CastColumn {
1261        #[snafu(source)]
1262        error: datafusion::error::DataFusionError,
1263        #[snafu(implicit)]
1264        location: Location,
1265    },
1266
1267    #[snafu(display("Failed to generate Arrow schema from Parquet file: {}", file))]
1268    ParquetToArrowSchema {
1269        file: String,
1270        #[snafu(source)]
1271        error: parquet::errors::ParquetError,
1272        #[snafu(implicit)]
1273        location: Location,
1274    },
1275
1276    #[snafu(display(
1277        "Region {} is in {:?} state, expect: Writable, Staging or Downgrading",
1278        region_id,
1279        state
1280    ))]
1281    FlushableRegionState {
1282        region_id: RegionId,
1283        state: RegionRoleState,
1284        #[snafu(implicit)]
1285        location: Location,
1286    },
1287}
1288
1289pub type Result<T, E = Error> = std::result::Result<T, E>;
1290
1291impl Error {
1292    /// Returns true if we need to fill default value for a region.
1293    pub(crate) fn is_fill_default(&self) -> bool {
1294        matches!(self, Error::FillDefault { .. })
1295    }
1296
1297    /// Returns true if the file is not found on the object store.
1298    pub(crate) fn is_object_not_found(&self) -> bool {
1299        match self {
1300            Error::OpenDal { error, .. } => error.kind() == ErrorKind::NotFound,
1301            _ => false,
1302        }
1303    }
1304}
1305
1306impl ErrorExt for Error {
1307    fn status_code(&self) -> StatusCode {
1308        use Error::*;
1309
1310        match self {
1311            DataTypeMismatch { source, .. } => source.status_code(),
1312            OpenDal { .. } | ReadParquet { .. } => StatusCode::StorageUnavailable,
1313            WriteWal { source, .. } | ReadWal { source, .. } | DeleteWal { source, .. } => {
1314                source.status_code()
1315            }
1316            CompressObject { .. }
1317            | DecompressObject { .. }
1318            | SerdeJson { .. }
1319            | Utf8 { .. }
1320            | NewRecordBatch { .. }
1321            | RegionCorrupted { .. }
1322            | InconsistentFile { .. }
1323            | CreateDefault { .. }
1324            | InvalidParquet { .. }
1325            | OperateAbortedIndex { .. }
1326            | IndexEncodeNull { .. }
1327            | NoCheckpoint { .. }
1328            | NoManifests { .. }
1329            | FilesLost { .. }
1330            | InstallManifestTo { .. }
1331            | Unexpected { .. }
1332            | SerializeColumnMetadata { .. }
1333            | SerializeManifest { .. }
1334            | StagingPartitionExprMismatch { .. } => StatusCode::Unexpected,
1335
1336            RegionNotFound { .. } => StatusCode::RegionNotFound,
1337            ObjectStoreNotFound { .. }
1338            | InvalidScanIndex { .. }
1339            | InvalidMeta { .. }
1340            | InvalidRequest { .. }
1341            | PartitionExprVersionMismatch { .. }
1342            | FillDefault { .. }
1343            | ConvertColumnDataType { .. }
1344            | ColumnNotFound { .. }
1345            | InvalidMetadata { .. }
1346            | InvalidRegionOptions { .. }
1347            | InvalidWalReadRequest { .. }
1348            | PartitionOutOfRange { .. }
1349            | ParseJobId { .. }
1350            | DurationOutOfRange { .. }
1351            | MissingOldManifest { .. }
1352            | MissingNewManifest { .. }
1353            | MissingManifest { .. }
1354            | NoOldManifests { .. }
1355            | MissingPartitionExpr { .. }
1356            | SerializePartitionExpr { .. }
1357            | InvalidSourceAndTargetRegion { .. } => StatusCode::InvalidArguments,
1358
1359            IncrementalQueryStale { .. } => StatusCode::RequestOutdated,
1360
1361            RegionMetadataNotFound { .. }
1362            | Join { .. }
1363            | WorkerStopped { .. }
1364            | Recv { .. }
1365            | DecodeWal { .. }
1366            | ComputeArrow { .. }
1367            | EvalPartitionFilter { .. }
1368            | BiErrors { .. }
1369            | StopScheduler { .. }
1370            | ComputeVector { .. }
1371            | EncodeMemtable { .. }
1372            | CreateDir { .. }
1373            | ReadDataPart { .. }
1374            | BuildEntry { .. }
1375            | Metadata { .. }
1376            | CastColumn { .. }
1377            | MitoManifestInfo { .. }
1378            | ParquetToArrowSchema { .. } => StatusCode::Internal,
1379
1380            FetchManifests { source, .. } => source.status_code(),
1381
1382            OpenRegion { source, .. } => source.status_code(),
1383
1384            WriteParquet { .. } => StatusCode::StorageUnavailable,
1385            WriteGroup { source, .. } => source.status_code(),
1386            InvalidBatch { .. } => StatusCode::InvalidArguments,
1387            InvalidRecordBatch { .. } => StatusCode::InvalidArguments,
1388            ConvertVector { source, .. } => source.status_code(),
1389
1390            PrimaryKeyLengthMismatch { .. } => StatusCode::InvalidArguments,
1391            InvalidSender { .. } => StatusCode::InvalidArguments,
1392            InvalidSchedulerState { .. } => StatusCode::InvalidArguments,
1393            OpenRegionRequirement { .. } => StatusCode::InvalidArguments,
1394            DeleteSsts { .. } | DeleteIndex { .. } | DeleteIndexes { .. } => {
1395                StatusCode::StorageUnavailable
1396            }
1397            FlushRegion { source, .. } | BuildIndexAsync { source, .. } => source.status_code(),
1398            RegionDropped { .. } => StatusCode::Cancelled,
1399            RegionClosed { .. } => StatusCode::Cancelled,
1400            RegionTruncated { .. } => StatusCode::Cancelled,
1401            RejectWrite { .. } => StatusCode::StorageUnavailable,
1402            CompactRegion { source, .. } => source.status_code(),
1403            EditRegion { source, .. } => source.status_code(),
1404            CompatReader { .. } => StatusCode::Unexpected,
1405            InvalidRegionRequest { source, .. } => source.status_code(),
1406            RegionState { .. } | UpdateManifest { .. } => StatusCode::RegionNotReady,
1407            JsonOptions { .. } => StatusCode::InvalidArguments,
1408            EmptyRegionDir { .. } | EmptyManifestDir { .. } => StatusCode::RegionNotFound,
1409            ConvertValue { source, .. } => source.status_code(),
1410            ApplyBloomFilterIndex { source, .. } => source.status_code(),
1411            InvalidPartitionExpr { source, .. } => source.status_code(),
1412            BuildIndexApplier { source, .. }
1413            | PushIndexValue { source, .. }
1414            | ApplyInvertedIndex { source, .. }
1415            | IndexFinish { source, .. } => source.status_code(),
1416            #[cfg(feature = "vector_index")]
1417            ApplyVectorIndex { .. } => StatusCode::Internal,
1418            PuffinReadBlob { source, .. }
1419            | PuffinAddBlob { source, .. }
1420            | PuffinInitStager { source, .. }
1421            | PuffinBuildReader { source, .. }
1422            | PuffinPurgeStager { source, .. } => source.status_code(),
1423            CleanDir { .. } => StatusCode::Unexpected,
1424            InvalidConfig { .. } => StatusCode::InvalidArguments,
1425            StaleLogEntry { .. } => StatusCode::Unexpected,
1426
1427            External { source, .. } => source.status_code(),
1428
1429            RecordBatch { source, .. } => source.status_code(),
1430
1431            Download { .. } | Upload { .. } => StatusCode::StorageUnavailable,
1432            ChecksumMismatch { .. } => StatusCode::Unexpected,
1433            RegionStopped { .. } => StatusCode::RegionNotReady,
1434            TimeRangePredicateOverflow { .. } => StatusCode::InvalidArguments,
1435            UnsupportedOperation { .. } => StatusCode::Unsupported,
1436            RemoteCompaction { .. } => StatusCode::Unexpected,
1437
1438            IndexOptions { source, .. } => source.status_code(),
1439            CreateFulltextCreator { source, .. } => source.status_code(),
1440            CastVector { source, .. } => source.status_code(),
1441            FulltextPushText { source, .. }
1442            | FulltextFinish { source, .. }
1443            | ApplyFulltextIndex { source, .. } => source.status_code(),
1444            DecodeStats { .. } | StatsNotPresent { .. } => StatusCode::Internal,
1445            RegionBusy { .. } => StatusCode::RegionBusy,
1446            GetSchemaMetadata { source, .. } => source.status_code(),
1447            Timeout { .. } => StatusCode::Cancelled,
1448
1449            DecodeArrowRowGroup { .. } => StatusCode::Internal,
1450
1451            PushBloomFilterValue { source, .. } | BloomFilterFinish { source, .. } => {
1452                source.status_code()
1453            }
1454
1455            #[cfg(feature = "vector_index")]
1456            VectorIndexBuild { .. } | VectorIndexFinish { .. } => StatusCode::Internal,
1457
1458            ManualCompactionOverride {} | CompactionCancelled {} => StatusCode::Cancelled,
1459
1460            CompactionMemoryExhausted { source, .. } => source.status_code(),
1461
1462            IncompatibleWalProviderChange { .. } => StatusCode::InvalidArguments,
1463
1464            ScanSeries { source, .. } => source.status_code(),
1465
1466            ScanMultiTimes { .. } => StatusCode::InvalidArguments,
1467            ConvertBulkWalEntry { source, .. } => source.status_code(),
1468
1469            Encode { source, .. } | Decode { source, .. } => source.status_code(),
1470
1471            #[cfg(feature = "enterprise")]
1472            ScanExternalRange { source, .. } => source.status_code(),
1473
1474            InconsistentTimestampLength { .. } => StatusCode::InvalidArguments,
1475
1476            TooManyFilesToRead { .. } | TooManyGcJobs { .. } => StatusCode::RateLimited,
1477
1478            PruneFile { source, .. } => source.status_code(),
1479
1480            FlushableRegionState { .. } => StatusCode::RegionNotReady,
1481        }
1482    }
1483
1484    fn as_any(&self) -> &dyn Any {
1485        self
1486    }
1487}