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, RetryHint};
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 object_store::error::retry_hint_from_opendal_error;
30use partition::error::Error as PartitionError;
31use prost::DecodeError;
32use snafu::{Location, Snafu};
33use store_api::ManifestVersion;
34use store_api::logstore::provider::Provider;
35use store_api::storage::{FileId, RegionId};
36use tokio::time::error::Elapsed;
37
38use crate::cache::file_cache::FileType;
39use crate::region::RegionRoleState;
40use crate::schedule::remote_job_scheduler::JobId;
41use crate::worker::WorkerId;
42
43#[derive(Snafu)]
44#[snafu(visibility(pub))]
45#[stack_trace_debug]
46pub enum Error {
47    #[snafu(display("Unexpected data type"))]
48    DataTypeMismatch {
49        source: datatypes::error::Error,
50        #[snafu(implicit)]
51        location: Location,
52    },
53
54    #[snafu(display("External error, context: {}", context))]
55    External {
56        source: BoxedError,
57        context: String,
58        #[snafu(implicit)]
59        location: Location,
60    },
61
62    #[snafu(display("OpenDAL operator failed"))]
63    OpenDal {
64        #[snafu(implicit)]
65        location: Location,
66        #[snafu(source)]
67        error: object_store::Error,
68    },
69
70    #[snafu(display("Source metadata file disappeared while copying {path}"))]
71    MetadataCopyFileNotFound {
72        path: String,
73        #[snafu(source)]
74        error: object_store::Error,
75        #[snafu(implicit)]
76        location: Location,
77    },
78
79    #[snafu(display(
80        "Manifest delta {} disappeared after it was listed, path: {}",
81        version,
82        path
83    ))]
84    ManifestDeltaNotFound {
85        version: ManifestVersion,
86        path: String,
87        #[snafu(source)]
88        error: object_store::Error,
89        #[snafu(implicit)]
90        location: Location,
91    },
92
93    #[snafu(display("Fail to compress object by {}, path: {}", compress_type, path))]
94    CompressObject {
95        compress_type: CompressionType,
96        path: String,
97        #[snafu(source)]
98        error: std::io::Error,
99    },
100
101    #[snafu(display("Fail to decompress object by {}, path: {}", compress_type, path))]
102    DecompressObject {
103        compress_type: CompressionType,
104        path: String,
105        #[snafu(source)]
106        error: std::io::Error,
107    },
108
109    #[snafu(display("Failed to ser/de json object"))]
110    SerdeJson {
111        #[snafu(implicit)]
112        location: Location,
113        #[snafu(source)]
114        error: serde_json::Error,
115    },
116
117    #[snafu(display("Failed to serialize column metadata"))]
118    SerializeColumnMetadata {
119        #[snafu(source)]
120        error: serde_json::Error,
121        #[snafu(implicit)]
122        location: Location,
123    },
124
125    #[snafu(display("Manifest version {version} conflicts in {manifest_dir}: {reason}"))]
126    ManifestVersionConflict {
127        version: ManifestVersion,
128        manifest_dir: String,
129        reason: String,
130        #[snafu(implicit)]
131        location: Location,
132    },
133
134    #[snafu(display(
135        "Manifest checkpoint {version} in {manifest_dir} was removed after it was listed"
136    ))]
137    ManifestCheckpointVanished {
138        version: ManifestVersion,
139        manifest_dir: String,
140        #[snafu(implicit)]
141        location: Location,
142    },
143
144    #[snafu(display(
145        "Manifest checkpoint {checkpoint_version} in {manifest_dir} covers replay start {replay_start_version}"
146    ))]
147    ManifestCheckpointAdvanced {
148        replay_start_version: ManifestVersion,
149        checkpoint_version: ManifestVersion,
150        manifest_dir: String,
151        #[snafu(implicit)]
152        location: Location,
153    },
154
155    #[snafu(display("Failed to serialize manifest, region_id: {}", region_id))]
156    SerializeManifest {
157        region_id: RegionId,
158        #[snafu(source)]
159        error: serde_json::Error,
160        #[snafu(implicit)]
161        location: Location,
162    },
163
164    #[snafu(display("Invalid scan index, start: {}, end: {}", start, end))]
165    InvalidScanIndex {
166        start: ManifestVersion,
167        end: ManifestVersion,
168        #[snafu(implicit)]
169        location: Location,
170    },
171
172    #[snafu(display("Invalid UTF-8 content"))]
173    Utf8 {
174        #[snafu(implicit)]
175        location: Location,
176        #[snafu(source)]
177        error: std::str::Utf8Error,
178    },
179
180    #[snafu(display("Cannot find RegionMetadata"))]
181    RegionMetadataNotFound {
182        #[snafu(implicit)]
183        location: Location,
184    },
185
186    #[snafu(display("Failed to join handle"))]
187    Join {
188        #[snafu(source)]
189        error: common_runtime::JoinError,
190        #[snafu(implicit)]
191        location: Location,
192    },
193
194    #[snafu(display("Worker {} is stopped", id))]
195    WorkerStopped {
196        id: WorkerId,
197        #[snafu(implicit)]
198        location: Location,
199    },
200
201    #[snafu(display("Engine is stopped"))]
202    EngineStopped {
203        #[snafu(implicit)]
204        location: Location,
205    },
206
207    #[snafu(display("Failed to recv result"))]
208    Recv {
209        #[snafu(source)]
210        error: tokio::sync::oneshot::error::RecvError,
211        #[snafu(implicit)]
212        location: Location,
213    },
214
215    #[snafu(display("Invalid metadata, {}", reason))]
216    InvalidMeta {
217        reason: String,
218        #[snafu(implicit)]
219        location: Location,
220    },
221
222    #[snafu(display("Invalid region metadata"))]
223    InvalidMetadata {
224        source: store_api::metadata::MetadataError,
225        #[snafu(implicit)]
226        location: Location,
227    },
228
229    #[snafu(display("Failed to create RecordBatch from vectors"))]
230    NewRecordBatch {
231        #[snafu(implicit)]
232        location: Location,
233        #[snafu(source)]
234        error: ArrowError,
235    },
236
237    #[snafu(display("Failed to read parquet file, path: {}", path))]
238    ReadParquet {
239        path: String,
240        #[snafu(source)]
241        error: parquet::errors::ParquetError,
242        #[snafu(implicit)]
243        location: Location,
244    },
245
246    #[snafu(display("Failed to load range result"))]
247    LoadRangeResult {
248        source: Arc<Error>,
249        #[snafu(implicit)]
250        location: Location,
251    },
252
253    #[snafu(display("Failed to load SST metadata"))]
254    LoadSstMeta {
255        source: Arc<Error>,
256        #[snafu(implicit)]
257        location: Location,
258    },
259
260    #[snafu(display("Failed to load Parquet page"))]
261    LoadParquetPage {
262        source: Arc<Error>,
263        #[snafu(implicit)]
264        location: Location,
265    },
266
267    #[snafu(display("Failed to write parquet file"))]
268    WriteParquet {
269        #[snafu(source)]
270        error: parquet::errors::ParquetError,
271        #[snafu(implicit)]
272        location: Location,
273    },
274
275    #[snafu(display(
276        "Cannot assign a stable field id to native histogram sub-field '{}' of column id {} (unknown sub-field name or derived id overflows i32)",
277        field_name,
278        column_id
279    ))]
280    InvalidNativeHistogramSubfield {
281        column_id: i32,
282        field_name: String,
283        #[snafu(implicit)]
284        location: Location,
285    },
286
287    #[snafu(display(
288        "Native histogram column '{}' has no usable PARQUET:field_id to namespace its sub-field ids (missing, malformed, or exceeds i32::MAX)",
289        field_name
290    ))]
291    InvalidNativeHistogramFieldId {
292        field_name: String,
293        #[snafu(implicit)]
294        location: Location,
295    },
296
297    #[snafu(display("Region {} not found", region_id))]
298    RegionNotFound {
299        region_id: RegionId,
300        #[snafu(implicit)]
301        location: Location,
302    },
303
304    #[snafu(display("Object store not found: {}", object_store))]
305    ObjectStoreNotFound {
306        object_store: String,
307        #[snafu(implicit)]
308        location: Location,
309    },
310
311    #[snafu(display("Region {} is corrupted, reason: {}", region_id, reason))]
312    RegionCorrupted {
313        region_id: RegionId,
314        reason: String,
315        #[snafu(implicit)]
316        location: Location,
317    },
318
319    #[snafu(display("Invalid request to region {}, reason: {}", region_id, reason))]
320    InvalidRequest {
321        region_id: RegionId,
322        reason: String,
323        #[snafu(implicit)]
324        location: Location,
325    },
326
327    #[snafu(display(
328        "STALE_CURSOR: incremental query stale, region: {}, given_seq: {}, min_readable_seq: {}, retry_hint: FALLBACK_FULL_RECOMPUTE",
329        region_id,
330        given_seq,
331        min_readable_seq
332    ))]
333    IncrementalQueryStale {
334        region_id: RegionId,
335        given_seq: u64,
336        min_readable_seq: u64,
337        #[snafu(implicit)]
338        location: Location,
339    },
340
341    #[snafu(display(
342        "STALE_SNAPSHOT_FENCE: snapshot upper bound stale, region: {}, given_seq: {}, min_enforceable_seq: {}, retry_hint: REBIND_SNAPSHOT_FENCE",
343        region_id,
344        given_seq,
345        min_enforceable_seq
346    ))]
347    SnapshotFenceStale {
348        region_id: RegionId,
349        given_seq: u64,
350        min_enforceable_seq: u64,
351        #[snafu(implicit)]
352        location: Location,
353    },
354
355    #[snafu(display(
356        "SEQUENCE_RANGE_UNSUPPORTED: exact sequence-range read unsupported, region: {}, min_seq: {}, max_seq: {}, reason: {}, retry_hint: FALLBACK_MEMTABLE_ONLY_OR_FULL_RECOMPUTE",
357        region_id,
358        min_seq,
359        max_seq,
360        reason
361    ))]
362    SequenceRangeUnsupported {
363        region_id: RegionId,
364        min_seq: u64,
365        max_seq: u64,
366        reason: String,
367        #[snafu(implicit)]
368        location: Location,
369    },
370
371    #[snafu(display(
372        "region {} is unusable for sequence reads: file {} declares region {}",
373        region_id,
374        file_id,
375        file_region_id
376    ))]
377    RegionSequenceDomainBroken {
378        region_id: RegionId,
379        file_region_id: RegionId,
380        file_id: FileId,
381        #[snafu(implicit)]
382        location: Location,
383    },
384
385    #[snafu(display("Old manifest missing for region {}", region_id))]
386    MissingOldManifest {
387        region_id: RegionId,
388        #[snafu(implicit)]
389        location: Location,
390    },
391
392    #[snafu(display("New manifest missing for region {}", region_id))]
393    MissingNewManifest {
394        region_id: RegionId,
395        #[snafu(implicit)]
396        location: Location,
397    },
398
399    #[snafu(display("Manifest missing for region {}", region_id))]
400    MissingManifest {
401        region_id: RegionId,
402        #[snafu(implicit)]
403        location: Location,
404    },
405
406    #[snafu(display("File consistency check failed for file {}: {}", file_id, reason))]
407    InconsistentFile {
408        file_id: FileId,
409        reason: String,
410        #[snafu(implicit)]
411        location: Location,
412    },
413
414    #[snafu(display(
415        "Cannot remap regions that hold files they did not create: {}",
416        offenders
417    ))]
418    ForeignFilePartitionExpr {
419        /// One entry per offending file: the holding region and the file it must settle.
420        offenders: String,
421        #[snafu(implicit)]
422        location: Location,
423    },
424
425    #[snafu(display("Files lost during remapping: old={}, new={}", old_count, new_count))]
426    FilesLost {
427        old_count: usize,
428        new_count: usize,
429        #[snafu(implicit)]
430        location: Location,
431    },
432
433    #[snafu(display("No old manifests provided (need at least one for template)"))]
434    NoOldManifests {
435        #[snafu(implicit)]
436        location: Location,
437    },
438
439    #[snafu(display("Failed to fetch manifests"))]
440    FetchManifests {
441        #[snafu(implicit)]
442        location: Location,
443        source: BoxedError,
444    },
445
446    #[snafu(display("Partition expression missing for region {}", region_id))]
447    MissingPartitionExpr {
448        region_id: RegionId,
449        #[snafu(implicit)]
450        location: Location,
451    },
452
453    #[snafu(display("Failed to serialize partition expression: {}", source))]
454    SerializePartitionExpr {
455        #[snafu(source)]
456        source: PartitionError,
457        #[snafu(implicit)]
458        location: Location,
459    },
460
461    #[snafu(display(
462        "Failed to convert ConcreteDataType to ColumnDataType, reason: {}",
463        reason
464    ))]
465    ConvertColumnDataType {
466        reason: String,
467        source: api::error::Error,
468        #[snafu(implicit)]
469        location: Location,
470    },
471
472    /// An error type to indicate that schema is changed and we need
473    /// to fill default values again.
474    #[snafu(display("Need to fill default value for region {}", region_id))]
475    FillDefault {
476        region_id: RegionId,
477        // The error is for internal use so we don't need a location.
478    },
479
480    #[snafu(display(
481        "Failed to create default value for column {} of region {}",
482        column,
483        region_id
484    ))]
485    CreateDefault {
486        region_id: RegionId,
487        column: String,
488        source: datatypes::Error,
489        #[snafu(implicit)]
490        location: Location,
491    },
492
493    #[snafu(display("Failed to build entry, region_id: {}", region_id))]
494    BuildEntry {
495        region_id: RegionId,
496        #[snafu(implicit)]
497        location: Location,
498        source: BoxedError,
499    },
500
501    #[snafu(display("Failed to write WAL"))]
502    WriteWal {
503        #[snafu(implicit)]
504        location: Location,
505        source: BoxedError,
506    },
507
508    #[snafu(display("Failed to read WAL, provider: {}", provider))]
509    ReadWal {
510        provider: Provider,
511        #[snafu(implicit)]
512        location: Location,
513        source: BoxedError,
514    },
515
516    #[snafu(display("Failed to read the WAL of node {} for region {}", node_id, region_id))]
517    ReadNodeWal {
518        region_id: RegionId,
519        node_id: u64,
520        #[snafu(implicit)]
521        location: Location,
522        source: BoxedError,
523    },
524
525    #[snafu(display("Failed to list the WAL of node {} for region {}", node_id, region_id))]
526    ListNodeWal {
527        region_id: RegionId,
528        node_id: u64,
529        #[snafu(implicit)]
530        location: Location,
531        /// Shared by the takeovers of a batch whose source's WAL failed to list.
532        source: Arc<BoxedError>,
533    },
534
535    #[snafu(display("Failed to decode WAL entry, region_id: {}", region_id))]
536    DecodeWal {
537        region_id: RegionId,
538        #[snafu(implicit)]
539        location: Location,
540        #[snafu(source)]
541        error: DecodeError,
542    },
543
544    #[snafu(display("Failed to delete WAL, region_id: {}", region_id))]
545    DeleteWal {
546        region_id: RegionId,
547        #[snafu(implicit)]
548        location: Location,
549        source: BoxedError,
550    },
551
552    #[snafu(display("Failed to wait for the WAL to be durable, region_id: {}", region_id))]
553    WaitWalDurable {
554        region_id: RegionId,
555        #[snafu(implicit)]
556        location: Location,
557        source: BoxedError,
558    },
559
560    #[snafu(display("Failed to check the WAL history, region_id: {}", region_id))]
561    CheckWalHistory {
562        region_id: RegionId,
563        #[snafu(implicit)]
564        location: Location,
565        source: BoxedError,
566    },
567
568    #[snafu(display("Failed to hand the WAL of region {} over to this node", region_id))]
569    HandoffWal {
570        region_id: RegionId,
571        #[snafu(implicit)]
572        location: Location,
573        source: BoxedError,
574    },
575
576    #[snafu(display("Failed to resolve the WAL provider, region_id: {}", region_id))]
577    ResolveWalProvider {
578        region_id: RegionId,
579        #[snafu(implicit)]
580        location: Location,
581        source: BoxedError,
582    },
583
584    // Shared error for each writer in the write group.
585    #[snafu(display("Failed to write region"))]
586    WriteGroup { source: Arc<Error> },
587
588    #[snafu(display("Invalid parquet SST file {}, reason: {}", file, reason))]
589    InvalidParquet {
590        file: String,
591        reason: String,
592        #[snafu(implicit)]
593        location: Location,
594    },
595
596    #[snafu(display("Invalid batch, {}", reason))]
597    InvalidBatch {
598        reason: String,
599        #[snafu(implicit)]
600        location: Location,
601    },
602
603    #[snafu(display("Invalid arrow record batch, {}", reason))]
604    InvalidRecordBatch {
605        reason: String,
606        #[snafu(implicit)]
607        location: Location,
608    },
609
610    #[snafu(display("Invalid wal read request, {}", reason))]
611    InvalidWalReadRequest {
612        reason: String,
613        #[snafu(implicit)]
614        location: Location,
615    },
616
617    #[snafu(display("Failed to convert array to vector"))]
618    ConvertVector {
619        #[snafu(implicit)]
620        location: Location,
621        source: datatypes::error::Error,
622    },
623
624    #[snafu(display("Failed to compute arrow arrays"))]
625    ComputeArrow {
626        #[snafu(implicit)]
627        location: Location,
628        #[snafu(source)]
629        error: datatypes::arrow::error::ArrowError,
630    },
631
632    #[snafu(display("Failed to evaluate partition filter"))]
633    EvalPartitionFilter {
634        #[snafu(implicit)]
635        location: Location,
636        #[snafu(source)]
637        error: datafusion::error::DataFusionError,
638    },
639
640    #[snafu(display("Scan memory exhausted"))]
641    ScanMemoryExhausted {
642        #[snafu(implicit)]
643        location: Location,
644        #[snafu(source)]
645        error: datafusion::error::DataFusionError,
646    },
647
648    #[snafu(display("Failed to compute vector"))]
649    ComputeVector {
650        #[snafu(implicit)]
651        location: Location,
652        source: datatypes::error::Error,
653    },
654
655    #[snafu(display("Primary key length mismatch, expect: {}, actual: {}", expect, actual))]
656    PrimaryKeyLengthMismatch {
657        expect: usize,
658        actual: usize,
659        #[snafu(implicit)]
660        location: Location,
661    },
662
663    #[snafu(display("Invalid sender",))]
664    InvalidSender {
665        #[snafu(implicit)]
666        location: Location,
667    },
668
669    #[snafu(display("Invalid scheduler state"))]
670    InvalidSchedulerState {
671        #[snafu(implicit)]
672        location: Location,
673    },
674
675    #[snafu(display("Failed to stop scheduler"))]
676    StopScheduler {
677        #[snafu(source)]
678        error: JoinError,
679        #[snafu(implicit)]
680        location: Location,
681    },
682
683    #[snafu(display(
684        "Failed to batch delete SST files, region id: {}, file ids: {:?}",
685        region_id,
686        file_ids
687    ))]
688    DeleteSsts {
689        region_id: RegionId,
690        file_ids: Vec<FileId>,
691        #[snafu(source)]
692        error: object_store::Error,
693        #[snafu(implicit)]
694        location: Location,
695    },
696
697    #[snafu(display("Failed to delete index file, file id: {}", file_id))]
698    DeleteIndex {
699        file_id: FileId,
700        #[snafu(source)]
701        error: object_store::Error,
702        #[snafu(implicit)]
703        location: Location,
704    },
705
706    #[snafu(display("Failed to batch delete index files, file ids: {:?}", file_ids))]
707    DeleteIndexes {
708        file_ids: Vec<FileId>,
709        #[snafu(source)]
710        error: object_store::Error,
711        #[snafu(implicit)]
712        location: Location,
713    },
714
715    #[snafu(display("Failed to flush region {}", region_id))]
716    FlushRegion {
717        region_id: RegionId,
718        source: Arc<Error>,
719        #[snafu(implicit)]
720        location: Location,
721    },
722
723    #[snafu(display("Region {} is dropped", region_id))]
724    RegionDropped {
725        region_id: RegionId,
726        #[snafu(implicit)]
727        location: Location,
728    },
729
730    #[snafu(display("Region {} is closed", region_id))]
731    RegionClosed {
732        region_id: RegionId,
733        #[snafu(implicit)]
734        location: Location,
735    },
736
737    #[snafu(display(
738        "Stale compaction execution for region {}, the region may have been reopened, truncated or the compaction was superseded",
739        region_id
740    ))]
741    StaleCompactionExecution {
742        region_id: RegionId,
743        #[snafu(implicit)]
744        location: Location,
745    },
746
747    #[snafu(display("Region {} is truncated", region_id))]
748    RegionTruncated {
749        region_id: RegionId,
750        #[snafu(implicit)]
751        location: Location,
752    },
753
754    #[snafu(display(
755        "Engine write buffer is full, rejecting write requests of region {}",
756        region_id,
757    ))]
758    RejectWrite {
759        region_id: RegionId,
760        #[snafu(implicit)]
761        location: Location,
762    },
763
764    #[snafu(display("Region {} rejects writes while in staging", region_id))]
765    RejectWriteInStaging {
766        region_id: RegionId,
767        #[snafu(implicit)]
768        location: Location,
769    },
770
771    #[snafu(display("Region {} still has WAL tails to recover", region_id))]
772    RegionPendingTails {
773        region_id: RegionId,
774        #[snafu(implicit)]
775        location: Location,
776    },
777
778    #[snafu(display(
779        "Region {} cannot read pending WAL tails of node {}",
780        region_id,
781        node_id
782    ))]
783    RemoteWalUnsupported {
784        region_id: RegionId,
785        node_id: u64,
786        #[snafu(implicit)]
787        location: Location,
788    },
789
790    #[snafu(display(
791        "Region {} cannot read entry {} of the WAL of node {}, where its pending tail ends",
792        region_id,
793        entry_id,
794        node_id
795    ))]
796    TailEntryMissing {
797        region_id: RegionId,
798        node_id: u64,
799        entry_id: u64,
800        #[snafu(implicit)]
801        location: Location,
802    },
803
804    #[snafu(display("Region {} does not hold a valid leader lease", region_id))]
805    RegionLeaseExpired {
806        region_id: RegionId,
807        #[snafu(implicit)]
808        location: Location,
809    },
810
811    #[snafu(display(
812        "Region {} has not received a leader lease since a catchup made it writable",
813        region_id
814    ))]
815    RegionLeaseNotReceived {
816        region_id: RegionId,
817        #[snafu(implicit)]
818        location: Location,
819    },
820
821    #[snafu(display(
822        "Region {} did not receive the lease of its migration candidate: {}",
823        region_id,
824        reason
825    ))]
826    CandidateLeaseNotReceived {
827        region_id: RegionId,
828        reason: String,
829        #[snafu(implicit)]
830        location: Location,
831    },
832
833    #[snafu(display(
834        "Region {} lost its leader lease while writing to the WAL, the write may have been applied",
835        region_id
836    ))]
837    UnacknowledgedWrite {
838        region_id: RegionId,
839        #[snafu(implicit)]
840        location: Location,
841    },
842
843    #[snafu(display("Failed to compact region {}", region_id))]
844    CompactRegion {
845        region_id: RegionId,
846        source: Arc<Error>,
847        #[snafu(implicit)]
848        location: Location,
849    },
850
851    #[snafu(display("Failed to edit region {}", region_id))]
852    EditRegion {
853        region_id: RegionId,
854        source: Arc<Error>,
855        #[snafu(implicit)]
856        location: Location,
857    },
858
859    #[snafu(display(
860        "Failed to end staging of region {}, which is still staging",
861        region_id
862    ))]
863    EndStaging {
864        region_id: RegionId,
865        source: Arc<Error>,
866        #[snafu(implicit)]
867        location: Location,
868    },
869
870    #[snafu(display("Region {} waits for a retry of its end-of-staging commit", region_id))]
871    EndStagingPending {
872        region_id: RegionId,
873        #[snafu(implicit)]
874        location: Location,
875    },
876
877    #[snafu(display(
878        "Failed to compat readers for region {}, reason: {}",
879        region_id,
880        reason,
881    ))]
882    CompatReader {
883        region_id: RegionId,
884        reason: String,
885        #[snafu(implicit)]
886        location: Location,
887    },
888
889    #[snafu(display("Invalue region req"))]
890    InvalidRegionRequest {
891        source: store_api::metadata::MetadataError,
892        #[snafu(implicit)]
893        location: Location,
894    },
895
896    #[snafu(display(
897        "Region {} is in {:?} state, which does not permit manifest updates.",
898        region_id,
899        state
900    ))]
901    UpdateManifest {
902        region_id: RegionId,
903        state: RegionRoleState,
904        #[snafu(implicit)]
905        location: Location,
906    },
907
908    #[snafu(display("Region {} is in {:?} state, expect: {:?}", region_id, state, expect))]
909    RegionState {
910        region_id: RegionId,
911        state: RegionRoleState,
912        expect: RegionRoleState,
913        #[snafu(implicit)]
914        location: Location,
915    },
916
917    #[snafu(display(
918        "Partition expr version mismatch for region {}: request {}, expected {}",
919        region_id,
920        request_version,
921        expected_version
922    ))]
923    PartitionExprVersionMismatch {
924        region_id: RegionId,
925        request_version: u64,
926        expected_version: u64,
927        #[snafu(implicit)]
928        location: Location,
929    },
930
931    #[snafu(display("Invalid options"))]
932    JsonOptions {
933        #[snafu(source)]
934        error: serde_json::Error,
935        #[snafu(implicit)]
936        location: Location,
937    },
938
939    #[snafu(display(
940        "Empty region directory, region_id: {}, region_dir: {}",
941        region_id,
942        region_dir,
943    ))]
944    EmptyRegionDir {
945        region_id: RegionId,
946        region_dir: String,
947        #[snafu(implicit)]
948        location: Location,
949    },
950
951    #[snafu(display("Empty manifest directory, manifest_dir: {}", manifest_dir,))]
952    EmptyManifestDir {
953        manifest_dir: String,
954        #[snafu(implicit)]
955        location: Location,
956    },
957
958    #[snafu(display("Column not found, column: {column}"))]
959    ColumnNotFound {
960        column: String,
961        #[snafu(implicit)]
962        location: Location,
963    },
964
965    #[snafu(display("Failed to build index applier"))]
966    BuildIndexApplier {
967        source: index::inverted_index::error::Error,
968        #[snafu(implicit)]
969        location: Location,
970    },
971
972    #[snafu(display("Failed to build index asynchronously in region {}", region_id))]
973    BuildIndexAsync {
974        region_id: RegionId,
975        source: Arc<Error>,
976        #[snafu(implicit)]
977        location: Location,
978    },
979
980    #[snafu(display(
981        "Index build did not complete for files {:?} in region {}",
982        file_ids,
983        region_id
984    ))]
985    IndexBuildIncomplete {
986        region_id: RegionId,
987        file_ids: Vec<FileId>,
988        #[snafu(implicit)]
989        location: Location,
990    },
991
992    #[snafu(display("Failed to convert value"))]
993    ConvertValue {
994        source: datatypes::error::Error,
995        #[snafu(implicit)]
996        location: Location,
997    },
998
999    #[snafu(display("Failed to apply inverted index"))]
1000    ApplyInvertedIndex {
1001        source: index::inverted_index::error::Error,
1002        #[snafu(implicit)]
1003        location: Location,
1004    },
1005
1006    #[snafu(display("Failed to apply bloom filter index"))]
1007    ApplyBloomFilterIndex {
1008        source: index::bloom_filter::error::Error,
1009        #[snafu(implicit)]
1010        location: Location,
1011    },
1012
1013    #[snafu(display("Failed to push index value"))]
1014    PushIndexValue {
1015        source: index::inverted_index::error::Error,
1016        #[snafu(implicit)]
1017        location: Location,
1018    },
1019
1020    #[snafu(display("Failed to write index completely"))]
1021    IndexFinish {
1022        source: index::inverted_index::error::Error,
1023        #[snafu(implicit)]
1024        location: Location,
1025    },
1026
1027    #[snafu(display("Operate on aborted index"))]
1028    OperateAbortedIndex {
1029        #[snafu(implicit)]
1030        location: Location,
1031    },
1032
1033    #[snafu(display("Failed to read puffin blob"))]
1034    PuffinReadBlob {
1035        source: puffin::error::Error,
1036        #[snafu(implicit)]
1037        location: Location,
1038    },
1039
1040    #[snafu(display("Failed to add blob to puffin file"))]
1041    PuffinAddBlob {
1042        source: puffin::error::Error,
1043        #[snafu(implicit)]
1044        location: Location,
1045    },
1046
1047    #[snafu(display("Failed to clean dir {dir}"))]
1048    CleanDir {
1049        dir: String,
1050        #[snafu(source)]
1051        error: std::io::Error,
1052        #[snafu(implicit)]
1053        location: Location,
1054    },
1055
1056    #[snafu(display("Invalid config, {reason}"))]
1057    InvalidConfig {
1058        reason: String,
1059        #[snafu(implicit)]
1060        location: Location,
1061    },
1062
1063    #[snafu(display(
1064        "Stale log entry found during replay, region: {}, flushed: {}, replayed: {}",
1065        region_id,
1066        flushed_entry_id,
1067        unexpected_entry_id
1068    ))]
1069    StaleLogEntry {
1070        region_id: RegionId,
1071        flushed_entry_id: u64,
1072        unexpected_entry_id: u64,
1073    },
1074
1075    #[snafu(display(
1076        "Failed to download file, region_id: {}, file_id: {}, file_type: {:?}",
1077        region_id,
1078        file_id,
1079        file_type,
1080    ))]
1081    Download {
1082        region_id: RegionId,
1083        file_id: FileId,
1084        file_type: FileType,
1085        #[snafu(source)]
1086        error: std::io::Error,
1087        #[snafu(implicit)]
1088        location: Location,
1089    },
1090
1091    #[snafu(display(
1092        "Failed to upload file, region_id: {}, file_id: {}, file_type: {:?}",
1093        region_id,
1094        file_id,
1095        file_type,
1096    ))]
1097    Upload {
1098        region_id: RegionId,
1099        file_id: FileId,
1100        file_type: FileType,
1101        #[snafu(source)]
1102        error: std::io::Error,
1103        #[snafu(implicit)]
1104        location: Location,
1105    },
1106
1107    #[snafu(display("Failed to create directory {}", dir))]
1108    CreateDir {
1109        dir: String,
1110        #[snafu(source)]
1111        error: std::io::Error,
1112    },
1113
1114    #[snafu(display("Record batch error"))]
1115    RecordBatch {
1116        source: common_recordbatch::error::Error,
1117        #[snafu(implicit)]
1118        location: Location,
1119    },
1120
1121    #[snafu(display("BiErrors, first: {first}, second: {second}"))]
1122    BiErrors {
1123        first: Box<Error>,
1124        second: Box<Error>,
1125        #[snafu(implicit)]
1126        location: Location,
1127    },
1128
1129    #[snafu(display("Failed to encode memtable to Parquet bytes"))]
1130    EncodeMemtable {
1131        #[snafu(source)]
1132        error: parquet::errors::ParquetError,
1133        #[snafu(implicit)]
1134        location: Location,
1135    },
1136
1137    #[snafu(display("Partition {} out of range, {} in total", given, all))]
1138    PartitionOutOfRange {
1139        given: usize,
1140        all: usize,
1141        #[snafu(implicit)]
1142        location: Location,
1143    },
1144
1145    #[snafu(display("Failed to iter data part"))]
1146    ReadDataPart {
1147        #[snafu(implicit)]
1148        location: Location,
1149        #[snafu(source)]
1150        error: parquet::errors::ParquetError,
1151    },
1152
1153    #[snafu(display("Failed to read row group in memtable"))]
1154    DecodeArrowRowGroup {
1155        #[snafu(source)]
1156        error: ArrowError,
1157        #[snafu(implicit)]
1158        location: Location,
1159    },
1160
1161    #[snafu(display("Invalid region options, {}", reason))]
1162    InvalidRegionOptions {
1163        reason: String,
1164        #[snafu(implicit)]
1165        location: Location,
1166    },
1167
1168    #[snafu(display("checksum mismatch (actual: {}, expected: {})", actual, expected))]
1169    ChecksumMismatch { actual: u32, expected: u32 },
1170
1171    #[snafu(display(
1172        "No checkpoint found, region: {}, last_version: {}",
1173        region_id,
1174        last_version
1175    ))]
1176    NoCheckpoint {
1177        region_id: RegionId,
1178        last_version: ManifestVersion,
1179        #[snafu(implicit)]
1180        location: Location,
1181    },
1182
1183    #[snafu(display(
1184        "No manifests found in range: [{}..{}), region: {}, last_version: {}",
1185        start_version,
1186        end_version,
1187        region_id,
1188        last_version
1189    ))]
1190    NoManifests {
1191        region_id: RegionId,
1192        start_version: ManifestVersion,
1193        end_version: ManifestVersion,
1194        last_version: ManifestVersion,
1195        #[snafu(implicit)]
1196        location: Location,
1197    },
1198
1199    #[snafu(display(
1200        "Failed to install manifest to {}, region: {}, available manifest version: {}, last version: {}",
1201        target_version,
1202        region_id,
1203        available_version,
1204        last_version
1205    ))]
1206    InstallManifestTo {
1207        region_id: RegionId,
1208        target_version: ManifestVersion,
1209        available_version: ManifestVersion,
1210        #[snafu(implicit)]
1211        location: Location,
1212        last_version: ManifestVersion,
1213    },
1214
1215    #[snafu(display("Region {} is stopped", region_id))]
1216    RegionStopped {
1217        region_id: RegionId,
1218        #[snafu(implicit)]
1219        location: Location,
1220    },
1221
1222    #[snafu(display(
1223        "Time range predicate overflows, timestamp: {:?}, target unit: {}",
1224        timestamp,
1225        unit
1226    ))]
1227    TimeRangePredicateOverflow {
1228        timestamp: Timestamp,
1229        unit: TimeUnit,
1230        #[snafu(implicit)]
1231        location: Location,
1232    },
1233
1234    #[snafu(display("Failed to open region"))]
1235    OpenRegion {
1236        #[snafu(implicit)]
1237        location: Location,
1238        source: Arc<Error>,
1239    },
1240
1241    #[snafu(display(
1242        "Region {} does not satisfy requirement '{}': {}",
1243        region_id,
1244        requirement,
1245        reason
1246    ))]
1247    RegionRequirement {
1248        region_id: RegionId,
1249        requirement: &'static str,
1250        reason: &'static str,
1251        #[snafu(implicit)]
1252        location: Location,
1253    },
1254
1255    #[snafu(display("Failed to parse job id"))]
1256    ParseJobId {
1257        #[snafu(implicit)]
1258        location: Location,
1259        #[snafu(source)]
1260        error: uuid::Error,
1261    },
1262
1263    #[snafu(display("Operation is not supported: {}", err_msg))]
1264    UnsupportedOperation {
1265        err_msg: String,
1266        #[snafu(implicit)]
1267        location: Location,
1268    },
1269
1270    #[snafu(display(
1271        "Failed to remotely compact region {} by job {:?} due to {}",
1272        region_id,
1273        job_id,
1274        reason
1275    ))]
1276    RemoteCompaction {
1277        region_id: RegionId,
1278        job_id: Option<JobId>,
1279        reason: String,
1280        #[snafu(implicit)]
1281        location: Location,
1282    },
1283
1284    #[snafu(display("Failed to initialize puffin stager"))]
1285    PuffinInitStager {
1286        source: puffin::error::Error,
1287        #[snafu(implicit)]
1288        location: Location,
1289    },
1290
1291    #[snafu(display("Failed to purge puffin stager"))]
1292    PuffinPurgeStager {
1293        source: puffin::error::Error,
1294        #[snafu(implicit)]
1295        location: Location,
1296    },
1297
1298    #[snafu(display("Failed to build puffin reader"))]
1299    PuffinBuildReader {
1300        source: puffin::error::Error,
1301        #[snafu(implicit)]
1302        location: Location,
1303    },
1304
1305    #[snafu(display("Failed to retrieve index options from column metadata"))]
1306    IndexOptions {
1307        #[snafu(implicit)]
1308        location: Location,
1309        source: datatypes::error::Error,
1310        column_name: String,
1311    },
1312
1313    #[snafu(display("Failed to retrieve compression options of column {column_name}"))]
1314    CompressionOptions {
1315        #[snafu(implicit)]
1316        location: Location,
1317        source: datatypes::error::Error,
1318        column_name: String,
1319    },
1320
1321    #[snafu(display("Failed to create fulltext index creator"))]
1322    CreateFulltextCreator {
1323        source: index::fulltext_index::error::Error,
1324        #[snafu(implicit)]
1325        location: Location,
1326    },
1327
1328    #[snafu(display("Failed to cast vector of {from} to {to}"))]
1329    CastVector {
1330        #[snafu(implicit)]
1331        location: Location,
1332        from: ConcreteDataType,
1333        to: ConcreteDataType,
1334        source: datatypes::error::Error,
1335    },
1336
1337    #[snafu(display("Failed to push text to fulltext index"))]
1338    FulltextPushText {
1339        source: index::fulltext_index::error::Error,
1340        #[snafu(implicit)]
1341        location: Location,
1342    },
1343
1344    #[snafu(display("Failed to finalize fulltext index creator"))]
1345    FulltextFinish {
1346        source: index::fulltext_index::error::Error,
1347        #[snafu(implicit)]
1348        location: Location,
1349    },
1350
1351    #[snafu(display("Failed to apply fulltext index"))]
1352    ApplyFulltextIndex {
1353        source: index::fulltext_index::error::Error,
1354        #[snafu(implicit)]
1355        location: Location,
1356    },
1357
1358    #[snafu(display("SST file {} does not contain valid stats info", file_path))]
1359    StatsNotPresent {
1360        file_path: String,
1361        #[snafu(implicit)]
1362        location: Location,
1363    },
1364
1365    #[snafu(display("Failed to decode stats of file {}", file_path))]
1366    DecodeStats {
1367        file_path: String,
1368        #[snafu(implicit)]
1369        location: Location,
1370    },
1371
1372    #[snafu(display("Invalid SST primary key range: {reason}"))]
1373    InvalidPrimaryKeyRange {
1374        reason: String,
1375        #[snafu(implicit)]
1376        location: Location,
1377    },
1378
1379    #[snafu(display("Failed to decode SST primary key range {endpoint} endpoint"))]
1380    DecodePrimaryKeyRange {
1381        endpoint: &'static str,
1382        source: mito_codec::error::Error,
1383        #[snafu(implicit)]
1384        location: Location,
1385    },
1386
1387    #[snafu(display("Region {} is busy", region_id))]
1388    RegionBusy {
1389        region_id: RegionId,
1390        #[snafu(implicit)]
1391        location: Location,
1392    },
1393
1394    #[snafu(display("Failed to get schema metadata"))]
1395    GetSchemaMetadata {
1396        source: common_meta::error::Error,
1397        #[snafu(implicit)]
1398        location: Location,
1399    },
1400
1401    #[snafu(display("Timeout"))]
1402    Timeout {
1403        #[snafu(source)]
1404        error: Elapsed,
1405        #[snafu(implicit)]
1406        location: Location,
1407    },
1408
1409    #[snafu(display("Failed to read file metadata"))]
1410    Metadata {
1411        #[snafu(source)]
1412        error: std::io::Error,
1413        #[snafu(implicit)]
1414        location: Location,
1415    },
1416
1417    #[snafu(display("Failed to push value to bloom filter"))]
1418    PushBloomFilterValue {
1419        source: index::bloom_filter::error::Error,
1420        #[snafu(implicit)]
1421        location: Location,
1422    },
1423
1424    #[snafu(display("Failed to finish bloom filter"))]
1425    BloomFilterFinish {
1426        source: index::bloom_filter::error::Error,
1427        #[snafu(implicit)]
1428        location: Location,
1429    },
1430
1431    #[snafu(display("Manual compaction is override by following operations."))]
1432    ManualCompactionOverride {},
1433
1434    #[snafu(display("Manual compaction is already running for region {region_id}."))]
1435    ManualCompactionAlreadyRunning { region_id: RegionId },
1436
1437    #[snafu(display("Compaction is cancelled."))]
1438    CompactionCancelled {},
1439
1440    #[snafu(display("SST write is cancelled."))]
1441    SstWriteCancelled {},
1442
1443    #[snafu(display("Flush is cancelled."))]
1444    FlushCancelled {},
1445
1446    #[snafu(display("Compaction memory exhausted for region {region_id} (policy: {policy})",))]
1447    CompactionMemoryExhausted {
1448        region_id: RegionId,
1449        policy: String,
1450        #[snafu(source)]
1451        source: common_memory_manager::Error,
1452        #[snafu(implicit)]
1453        location: Location,
1454    },
1455
1456    #[snafu(display(
1457        "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: {}",
1458        global,
1459        region
1460    ))]
1461    IncompatibleWalProviderChange { global: String, region: String },
1462
1463    #[snafu(display("Expected mito manifest info"))]
1464    MitoManifestInfo {
1465        #[snafu(implicit)]
1466        location: Location,
1467    },
1468
1469    #[snafu(display("Failed to scan series"))]
1470    ScanSeries {
1471        #[snafu(implicit)]
1472        location: Location,
1473        source: Arc<Error>,
1474    },
1475
1476    #[snafu(display("Partition {} scan multiple times", partition))]
1477    ScanMultiTimes {
1478        partition: usize,
1479        #[snafu(implicit)]
1480        location: Location,
1481    },
1482
1483    #[snafu(display("Invalid partition expression: {}", expr))]
1484    InvalidPartitionExpr {
1485        expr: String,
1486        #[snafu(implicit)]
1487        location: Location,
1488        source: partition::error::Error,
1489    },
1490
1491    #[snafu(display("Failed to decode bulk wal entry"))]
1492    ConvertBulkWalEntry {
1493        #[snafu(implicit)]
1494        location: Location,
1495        source: common_grpc::Error,
1496    },
1497
1498    #[snafu(display("Failed to encode"))]
1499    Encode {
1500        #[snafu(implicit)]
1501        location: Location,
1502        source: mito_codec::error::Error,
1503    },
1504
1505    #[snafu(display("Failed to decode"))]
1506    Decode {
1507        #[snafu(implicit)]
1508        location: Location,
1509        source: mito_codec::error::Error,
1510    },
1511
1512    #[snafu(display("Unexpected: {reason}"))]
1513    Unexpected {
1514        reason: String,
1515        #[snafu(implicit)]
1516        location: Location,
1517    },
1518
1519    #[cfg(feature = "enterprise")]
1520    #[snafu(display("Failed to scan external range"))]
1521    ScanExternalRange {
1522        source: BoxedError,
1523        #[snafu(implicit)]
1524        location: Location,
1525    },
1526
1527    #[snafu(display(
1528        "Inconsistent timestamp column length, expect: {}, actual: {}",
1529        expected,
1530        actual
1531    ))]
1532    InconsistentTimestampLength {
1533        expected: usize,
1534        actual: usize,
1535        #[snafu(implicit)]
1536        location: Location,
1537    },
1538
1539    #[snafu(display(
1540        "Too many files to read concurrently: {}, max allowed: {}",
1541        actual,
1542        max
1543    ))]
1544    TooManyFilesToRead {
1545        actual: usize,
1546        max: usize,
1547        #[snafu(implicit)]
1548        location: Location,
1549    },
1550
1551    #[snafu(display("Duration out of range: {input:?}"))]
1552    DurationOutOfRange {
1553        input: std::time::Duration,
1554        #[snafu(source)]
1555        error: chrono::OutOfRangeError,
1556        #[snafu(implicit)]
1557        location: Location,
1558    },
1559
1560    #[snafu(display("GC job permit exhausted"))]
1561    TooManyGcJobs {
1562        #[snafu(implicit)]
1563        location: Location,
1564    },
1565
1566    #[snafu(display(
1567        "Staging partition expr mismatch, manifest: {:?}, request: {}",
1568        manifest_expr,
1569        request_expr
1570    ))]
1571    StagingPartitionExprMismatch {
1572        manifest_expr: Option<String>,
1573        request_expr: String,
1574        #[snafu(implicit)]
1575        location: Location,
1576    },
1577
1578    #[snafu(display(
1579        "Invalid source and target region, source: {}, target: {}",
1580        source_region_id,
1581        target_region_id
1582    ))]
1583    InvalidSourceAndTargetRegion {
1584        source_region_id: RegionId,
1585        target_region_id: RegionId,
1586        #[snafu(implicit)]
1587        location: Location,
1588    },
1589
1590    #[snafu(display("Failed to prune file"))]
1591    PruneFile {
1592        source: Arc<Error>,
1593        #[snafu(implicit)]
1594        location: Location,
1595    },
1596
1597    #[snafu(display("Failed to cast column"))]
1598    CastColumn {
1599        #[snafu(source)]
1600        error: datafusion::error::DataFusionError,
1601        #[snafu(implicit)]
1602        location: Location,
1603    },
1604
1605    #[snafu(display("Failed to generate Arrow schema from Parquet file: {}", file))]
1606    ParquetToArrowSchema {
1607        file: String,
1608        #[snafu(source)]
1609        error: parquet::errors::ParquetError,
1610        #[snafu(implicit)]
1611        location: Location,
1612    },
1613
1614    #[snafu(display(
1615        "Region {} is in {:?} state, expect: Writable, Staging or Downgrading",
1616        region_id,
1617        state
1618    ))]
1619    FlushableRegionState {
1620        region_id: RegionId,
1621        state: RegionRoleState,
1622        #[snafu(implicit)]
1623        location: Location,
1624    },
1625}
1626
1627pub type Result<T, E = Error> = std::result::Result<T, E>;
1628
1629impl Error {
1630    /// Returns true if we need to fill default value for a region.
1631    pub(crate) fn is_fill_default(&self) -> bool {
1632        matches!(self, Error::FillDefault { .. })
1633    }
1634
1635    /// Returns true if the file is not found on the object store.
1636    pub(crate) fn is_object_not_found(&self) -> bool {
1637        match self {
1638            Error::OpenDal { error, .. } => error.kind() == ErrorKind::NotFound,
1639            Error::ManifestDeltaNotFound { .. } => true,
1640            Error::LoadSstMeta { source, .. }
1641            | Error::ScanSeries { source, .. }
1642            | Error::LoadParquetPage { source, .. }
1643            | Error::LoadRangeResult { source, .. } => source.is_object_not_found(),
1644            _ => false,
1645        }
1646    }
1647
1648    /// Returns whether a failed manifest update may have been persisted.
1649    ///
1650    /// Unknown errors are treated conservatively because deleting output SSTs after an ambiguous
1651    /// manifest write could leave the manifest referencing missing files. The retry layer returns
1652    /// the last attempt's error, so an error that can follow a stored attempt (throttling, or a 403
1653    /// from a revoked key, a changed bucket policy or clock skew) never proves nothing was written.
1654    pub(crate) fn may_have_persisted_manifest_update(&self) -> bool {
1655        match self {
1656            // Applicability and capability checks reject the edit before storage I/O.
1657            Error::InvalidRequest { .. }
1658            | Error::UpdateManifest { .. }
1659            | Error::RegionState { .. }
1660            | Error::RegionTruncated { .. }
1661            | Error::RegionStopped { .. }
1662            | Error::RegionLeaseExpired { .. }
1663            | Error::RegionLeaseNotReceived { .. }
1664            | Error::EndStagingPending { .. }
1665            | Error::SerdeJson { .. }
1666            | Error::CompressObject { .. } => false,
1667            Error::OpenDal { error, .. } => !matches!(
1668                error.kind(),
1669                ErrorKind::Unsupported
1670                    | ErrorKind::ConfigInvalid
1671                    | ErrorKind::NotFound
1672                    | ErrorKind::IsADirectory
1673                    | ErrorKind::NotADirectory
1674                    | ErrorKind::AlreadyExists
1675                    | ErrorKind::IsSameFile
1676                    | ErrorKind::ConditionNotMatch
1677                    | ErrorKind::RangeNotSatisfied
1678            ),
1679            _ => true,
1680        }
1681    }
1682}
1683
1684impl ErrorExt for Error {
1685    fn status_code(&self) -> StatusCode {
1686        use Error::*;
1687
1688        match self {
1689            DataTypeMismatch { source, .. } => source.status_code(),
1690            OpenDal { .. }
1691            | MetadataCopyFileNotFound { .. }
1692            | ManifestDeltaNotFound { .. }
1693            | ManifestVersionConflict { .. }
1694            | ManifestCheckpointAdvanced { .. }
1695            | ManifestCheckpointVanished { .. }
1696            | ReadParquet { .. } => StatusCode::StorageUnavailable,
1697            WriteWal { source, .. }
1698            | ReadWal { source, .. }
1699            | ReadNodeWal { source, .. }
1700            | DeleteWal { source, .. }
1701            | WaitWalDurable { source, .. }
1702            | ResolveWalProvider { source, .. }
1703            | CheckWalHistory { source, .. }
1704            | HandoffWal { source, .. } => source.status_code(),
1705            CompressObject { .. }
1706            | DecompressObject { .. }
1707            | SerdeJson { .. }
1708            | Utf8 { .. }
1709            | NewRecordBatch { .. }
1710            | RegionCorrupted { .. }
1711            | InconsistentFile { .. }
1712            | CreateDefault { .. }
1713            | InvalidParquet { .. }
1714            | OperateAbortedIndex { .. }
1715            | NoCheckpoint { .. }
1716            | NoManifests { .. }
1717            | FilesLost { .. }
1718            | InstallManifestTo { .. }
1719            | Unexpected { .. }
1720            | SerializeColumnMetadata { .. }
1721            | SerializeManifest { .. }
1722            | StagingPartitionExprMismatch { .. } => StatusCode::Unexpected,
1723
1724            RegionNotFound { .. } => StatusCode::RegionNotFound,
1725            ObjectStoreNotFound { .. }
1726            | InvalidScanIndex { .. }
1727            | InvalidMeta { .. }
1728            | InvalidRequest { .. }
1729            | PartitionExprVersionMismatch { .. }
1730            | FillDefault { .. }
1731            | ConvertColumnDataType { .. }
1732            | ColumnNotFound { .. }
1733            | InvalidMetadata { .. }
1734            | InvalidRegionOptions { .. }
1735            | InvalidWalReadRequest { .. }
1736            | PartitionOutOfRange { .. }
1737            | ParseJobId { .. }
1738            | DurationOutOfRange { .. }
1739            | MissingOldManifest { .. }
1740            | MissingNewManifest { .. }
1741            | MissingManifest { .. }
1742            | NoOldManifests { .. }
1743            | MissingPartitionExpr { .. }
1744            | SerializePartitionExpr { .. }
1745            | InvalidSourceAndTargetRegion { .. } => StatusCode::InvalidArguments,
1746
1747            IncrementalQueryStale { .. } | SnapshotFenceStale { .. } => StatusCode::RequestOutdated,
1748
1749            SequenceRangeUnsupported { .. } => StatusCode::Unsupported,
1750
1751            RegionSequenceDomainBroken { .. }
1752            | RegionMetadataNotFound { .. }
1753            | Join { .. }
1754            | WorkerStopped { .. }
1755            | EngineStopped { .. }
1756            | Recv { .. }
1757            | DecodeWal { .. }
1758            | ComputeArrow { .. }
1759            | EvalPartitionFilter { .. }
1760            | BiErrors { .. }
1761            | StopScheduler { .. }
1762            | ComputeVector { .. }
1763            | EncodeMemtable { .. }
1764            | CreateDir { .. }
1765            | ReadDataPart { .. }
1766            | BuildEntry { .. }
1767            | Metadata { .. }
1768            | CastColumn { .. }
1769            | MitoManifestInfo { .. }
1770            | ParquetToArrowSchema { .. } => StatusCode::Internal,
1771
1772            FetchManifests { source, .. } => source.status_code(),
1773
1774            OpenRegion { source, .. } => source.status_code(),
1775
1776            WriteParquet { .. } => StatusCode::StorageUnavailable,
1777            WriteGroup { source, .. }
1778            | LoadSstMeta { source, .. }
1779            | LoadParquetPage { source, .. }
1780            | LoadRangeResult { source, .. } => source.status_code(),
1781            InvalidBatch { .. } => StatusCode::InvalidArguments,
1782            InvalidRecordBatch { .. } => StatusCode::InvalidArguments,
1783            ConvertVector { source, .. } => source.status_code(),
1784
1785            PrimaryKeyLengthMismatch { .. } => StatusCode::InvalidArguments,
1786            InvalidSender { .. } => StatusCode::InvalidArguments,
1787            InvalidSchedulerState { .. } => StatusCode::InvalidArguments,
1788            RegionRequirement { .. } => StatusCode::InvalidArguments,
1789            DeleteSsts { .. } | DeleteIndex { .. } | DeleteIndexes { .. } => {
1790                StatusCode::StorageUnavailable
1791            }
1792            FlushRegion { source, .. } | BuildIndexAsync { source, .. } => source.status_code(),
1793            IndexBuildIncomplete { .. } => StatusCode::IllegalState,
1794            ForeignFilePartitionExpr { .. } => StatusCode::IllegalState,
1795            RegionDropped { .. } => StatusCode::Cancelled,
1796            RegionClosed { .. } => StatusCode::Cancelled,
1797            StaleCompactionExecution { .. } => StatusCode::Cancelled,
1798            RegionTruncated { .. } => StatusCode::Cancelled,
1799            RejectWrite { .. } | RejectWriteInStaging { .. } => StatusCode::StorageUnavailable,
1800            CompactRegion { source, .. } => source.status_code(),
1801            EditRegion { source, .. } | EndStaging { source, .. } => source.status_code(),
1802            CompatReader { .. } => StatusCode::Unexpected,
1803            InvalidRegionRequest { source, .. } => source.status_code(),
1804            RegionState { .. } | UpdateManifest { .. } => StatusCode::RegionNotReady,
1805            RegionLeaseExpired { .. }
1806            | RegionLeaseNotReceived { .. }
1807            | CandidateLeaseNotReceived { .. }
1808            | UnacknowledgedWrite { .. } => StatusCode::RegionNotReady,
1809            ListNodeWal { source, .. } => source.status_code(),
1810            RegionPendingTails { .. } => StatusCode::RegionNotReady,
1811            RemoteWalUnsupported { .. } => StatusCode::Unsupported,
1812            TailEntryMissing { .. } => StatusCode::StorageUnavailable,
1813            JsonOptions { .. } => StatusCode::InvalidArguments,
1814            EmptyRegionDir { .. } | EmptyManifestDir { .. } => StatusCode::RegionNotFound,
1815            ConvertValue { source, .. } => source.status_code(),
1816            ApplyBloomFilterIndex { source, .. } => source.status_code(),
1817            InvalidPartitionExpr { source, .. } => source.status_code(),
1818            BuildIndexApplier { source, .. }
1819            | PushIndexValue { source, .. }
1820            | ApplyInvertedIndex { source, .. }
1821            | IndexFinish { source, .. } => source.status_code(),
1822            PuffinReadBlob { source, .. }
1823            | PuffinAddBlob { source, .. }
1824            | PuffinInitStager { source, .. }
1825            | PuffinBuildReader { source, .. }
1826            | PuffinPurgeStager { source, .. } => source.status_code(),
1827            CleanDir { .. } => StatusCode::Unexpected,
1828            InvalidConfig { .. } => StatusCode::InvalidArguments,
1829            StaleLogEntry { .. }
1830            | InvalidNativeHistogramSubfield { .. }
1831            | InvalidNativeHistogramFieldId { .. } => StatusCode::Unexpected,
1832
1833            External { source, .. } => source.status_code(),
1834
1835            RecordBatch { source, .. } => source.status_code(),
1836
1837            Download { .. } | Upload { .. } => StatusCode::StorageUnavailable,
1838            ChecksumMismatch { .. } => StatusCode::Unexpected,
1839            RegionStopped { .. } => StatusCode::RegionNotReady,
1840            TimeRangePredicateOverflow { .. } => StatusCode::InvalidArguments,
1841            UnsupportedOperation { .. } => StatusCode::Unsupported,
1842            RemoteCompaction { .. } => StatusCode::Unexpected,
1843
1844            IndexOptions { source, .. } => source.status_code(),
1845            CompressionOptions { source, .. } => source.status_code(),
1846            CreateFulltextCreator { source, .. } => source.status_code(),
1847            CastVector { source, .. } => source.status_code(),
1848            FulltextPushText { source, .. }
1849            | FulltextFinish { source, .. }
1850            | ApplyFulltextIndex { source, .. } => source.status_code(),
1851            DecodeStats { .. }
1852            | StatsNotPresent { .. }
1853            | InvalidPrimaryKeyRange { .. }
1854            | DecodePrimaryKeyRange { .. } => StatusCode::Internal,
1855            RegionBusy { .. } | EndStagingPending { .. } => StatusCode::RegionBusy,
1856            GetSchemaMetadata { source, .. } => source.status_code(),
1857            Timeout { .. } => StatusCode::Cancelled,
1858
1859            DecodeArrowRowGroup { .. } => StatusCode::Internal,
1860
1861            PushBloomFilterValue { source, .. } | BloomFilterFinish { source, .. } => {
1862                source.status_code()
1863            }
1864
1865            ManualCompactionOverride {}
1866            | CompactionCancelled {}
1867            | FlushCancelled {}
1868            | SstWriteCancelled {} => StatusCode::Cancelled,
1869
1870            // A concurrent manual compaction fails fast instead of being queued;
1871            // the conflict is reported to the caller, which decides whether to
1872            // issue a new request after the running one finishes.
1873            ManualCompactionAlreadyRunning { .. } => StatusCode::RegionBusy,
1874
1875            ScanMemoryExhausted { .. } => StatusCode::RuntimeResourcesExhausted,
1876
1877            CompactionMemoryExhausted { source, .. } => source.status_code(),
1878
1879            IncompatibleWalProviderChange { .. } => StatusCode::InvalidArguments,
1880
1881            ScanSeries { source, .. } => source.status_code(),
1882
1883            ScanMultiTimes { .. } => StatusCode::InvalidArguments,
1884            ConvertBulkWalEntry { source, .. } => source.status_code(),
1885
1886            Encode { source, .. } | Decode { source, .. } => source.status_code(),
1887
1888            #[cfg(feature = "enterprise")]
1889            ScanExternalRange { source, .. } => source.status_code(),
1890
1891            InconsistentTimestampLength { .. } => StatusCode::InvalidArguments,
1892
1893            TooManyFilesToRead { .. } | TooManyGcJobs { .. } => StatusCode::RateLimited,
1894
1895            PruneFile { source, .. } => source.status_code(),
1896
1897            FlushableRegionState { .. } => StatusCode::RegionNotReady,
1898        }
1899    }
1900
1901    fn as_any(&self) -> &dyn Any {
1902        self
1903    }
1904
1905    fn retry_hint(&self) -> RetryHint {
1906        use Error::*;
1907
1908        match self {
1909            PartitionExprVersionMismatch { .. }
1910            | RegionNotFound { .. }
1911            | RegionClosed { .. }
1912            | RejectWriteInStaging { .. }
1913            | RegionLeaseExpired { .. }
1914            | RegionLeaseNotReceived { .. }
1915            | CandidateLeaseNotReceived { .. }
1916            | UnacknowledgedWrite { .. }
1917            | RegionState {
1918                state: RegionRoleState::Follower,
1919                ..
1920            } => RetryHint::RetryAfterRouteRefresh,
1921            ReadParquet { .. }
1922            | WriteParquet { .. }
1923            | RejectWrite { .. }
1924            | Download { .. }
1925            | Upload { .. }
1926            | RegionState { .. }
1927            | UpdateManifest { .. }
1928            | RegionStopped { .. }
1929            | RegionBusy { .. }
1930            | RegionPendingTails { .. }
1931            | EndStaging { .. }
1932            | EndStagingPending { .. }
1933            | ManualCompactionAlreadyRunning { .. }
1934            | FlushableRegionState { .. }
1935            | MetadataCopyFileNotFound { .. }
1936            | ManifestDeltaNotFound { .. }
1937            | ManifestVersionConflict { .. }
1938            | ManifestCheckpointAdvanced { .. }
1939            | ManifestCheckpointVanished { .. } => RetryHint::Retryable,
1940
1941            OpenDal { error, .. }
1942            | DeleteSsts { error, .. }
1943            | DeleteIndex { error, .. }
1944            | DeleteIndexes { error, .. } => retry_hint_from_opendal_error(error),
1945
1946            WriteWal { source, .. }
1947            | ReadWal { source, .. }
1948            | ReadNodeWal { source, .. }
1949            | DeleteWal { source, .. }
1950            | WaitWalDurable { source, .. }
1951            | ResolveWalProvider { source, .. }
1952            | CheckWalHistory { source, .. }
1953            | HandoffWal { source, .. }
1954            | FetchManifests { source, .. }
1955            | External { source, .. } => source.retry_hint(),
1956            ListNodeWal { source, .. } => source.retry_hint(),
1957
1958            OpenRegion { source, .. }
1959            | LoadSstMeta { source, .. }
1960            | LoadParquetPage { source, .. }
1961            | LoadRangeResult { source, .. }
1962            | WriteGroup { source, .. }
1963            | FlushRegion { source, .. }
1964            | BuildIndexAsync { source, .. }
1965            | CompactRegion { source, .. }
1966            | EditRegion { source, .. }
1967            | ScanSeries { source, .. }
1968            | PruneFile { source, .. } => source.retry_hint(),
1969
1970            DataTypeMismatch { source, .. }
1971            | ConvertVector { source, .. }
1972            | ConvertValue { source, .. }
1973            | IndexOptions { source, .. }
1974            | CompressionOptions { source, .. }
1975            | CastVector { source, .. } => source.retry_hint(),
1976
1977            BuildIndexApplier { source, .. }
1978            | PushIndexValue { source, .. }
1979            | ApplyInvertedIndex { source, .. }
1980            | IndexFinish { source, .. } => source.retry_hint(),
1981
1982            ApplyBloomFilterIndex { source, .. }
1983            | PushBloomFilterValue { source, .. }
1984            | BloomFilterFinish { source, .. } => source.retry_hint(),
1985
1986            PuffinReadBlob { source, .. }
1987            | PuffinAddBlob { source, .. }
1988            | PuffinInitStager { source, .. }
1989            | PuffinBuildReader { source, .. }
1990            | PuffinPurgeStager { source, .. } => source.retry_hint(),
1991
1992            CreateFulltextCreator { source, .. }
1993            | FulltextPushText { source, .. }
1994            | FulltextFinish { source, .. }
1995            | ApplyFulltextIndex { source, .. } => source.retry_hint(),
1996
1997            InvalidRegionRequest { source, .. } => source.retry_hint(),
1998            InvalidPartitionExpr { source, .. } => source.retry_hint(),
1999            RecordBatch { source, .. } => source.retry_hint(),
2000            GetSchemaMetadata { source, .. } => source.retry_hint(),
2001            CompactionMemoryExhausted { source, .. } => source.retry_hint(),
2002            ConvertBulkWalEntry { source, .. } => source.retry_hint(),
2003            Encode { source, .. } | Decode { source, .. } => source.retry_hint(),
2004
2005            #[cfg(feature = "enterprise")]
2006            ScanExternalRange { source, .. } => source.retry_hint(),
2007
2008            _ => RetryHint::NonRetryable,
2009        }
2010    }
2011}
2012
2013#[cfg(test)]
2014mod tests {
2015    use snafu::IntoError;
2016
2017    use super::*;
2018    use crate::region::RegionLeaderState;
2019
2020    #[test]
2021    fn test_partition_version_mismatch_retry_hint() {
2022        let error = PartitionExprVersionMismatchSnafu {
2023            region_id: RegionId::new(1, 1),
2024            request_version: 1u64,
2025            expected_version: 2u64,
2026        }
2027        .build();
2028        assert_eq!(error.status_code(), StatusCode::InvalidArguments);
2029        assert_eq!(error.retry_hint(), RetryHint::RetryAfterRouteRefresh);
2030    }
2031
2032    #[test]
2033    fn test_region_state_retry_hint() {
2034        let region_id = RegionId::new(1, 1);
2035        let writable = RegionRoleState::Leader(RegionLeaderState::Writable);
2036        let follower_error = RegionStateSnafu {
2037            region_id,
2038            state: RegionRoleState::Follower,
2039            expect: writable,
2040        }
2041        .build();
2042        assert_eq!(
2043            follower_error.retry_hint(),
2044            RetryHint::RetryAfterRouteRefresh
2045        );
2046        assert_eq!(follower_error.status_code(), StatusCode::RegionNotReady);
2047        let leader_error = RegionStateSnafu {
2048            region_id,
2049            state: writable,
2050            expect: RegionRoleState::Follower,
2051        }
2052        .build();
2053        assert_eq!(leader_error.retry_hint(), RetryHint::Retryable);
2054        for (error, status, hint) in [
2055            (
2056                RejectWriteSnafu { region_id }.build(),
2057                StatusCode::StorageUnavailable,
2058                RetryHint::Retryable,
2059            ),
2060            (
2061                RejectWriteInStagingSnafu { region_id }.build(),
2062                StatusCode::StorageUnavailable,
2063                RetryHint::RetryAfterRouteRefresh,
2064            ),
2065            (
2066                RegionNotFoundSnafu { region_id }.build(),
2067                StatusCode::RegionNotFound,
2068                RetryHint::RetryAfterRouteRefresh,
2069            ),
2070            (
2071                RegionClosedSnafu { region_id }.build(),
2072                StatusCode::Cancelled,
2073                RetryHint::RetryAfterRouteRefresh,
2074            ),
2075            (
2076                RegionDroppedSnafu { region_id }.build(),
2077                StatusCode::Cancelled,
2078                RetryHint::NonRetryable,
2079            ),
2080            (
2081                RegionTruncatedSnafu { region_id }.build(),
2082                StatusCode::Cancelled,
2083                RetryHint::NonRetryable,
2084            ),
2085        ] {
2086            assert_eq!(error.status_code(), status);
2087            assert_eq!(error.retry_hint(), hint);
2088        }
2089    }
2090
2091    #[test]
2092    fn test_shared_sst_metadata_preserves_error_semantics() {
2093        for source in [
2094            OpenDalSnafu {}
2095                .into_error(object_store::Error::new(ErrorKind::NotFound, "missing SST")),
2096            OpenDalSnafu {}.into_error(object_store::Error::new(
2097                ErrorKind::Unexpected,
2098                "read failed",
2099            )),
2100            RejectWriteSnafu {
2101                region_id: RegionId::new(1, 1),
2102            }
2103            .build(),
2104        ] {
2105            let expected_not_found = source.is_object_not_found();
2106            let expected_status = source.status_code();
2107            let expected_retry = source.retry_hint();
2108            let source = Arc::new(source);
2109            for wrapped in [
2110                LoadSstMetaSnafu.into_error(source.clone()),
2111                LoadRangeResultSnafu.into_error(source),
2112            ] {
2113                assert_eq!(expected_not_found, wrapped.is_object_not_found());
2114                assert_eq!(expected_status, wrapped.status_code());
2115                assert_eq!(expected_retry, wrapped.retry_hint());
2116            }
2117        }
2118    }
2119
2120    #[test]
2121    fn test_manifest_update_persistence() {
2122        let rejected_kinds = [
2123            ErrorKind::Unsupported,
2124            ErrorKind::ConfigInvalid,
2125            ErrorKind::NotFound,
2126            ErrorKind::IsADirectory,
2127            ErrorKind::NotADirectory,
2128            ErrorKind::AlreadyExists,
2129            ErrorKind::IsSameFile,
2130            ErrorKind::ConditionNotMatch,
2131            ErrorKind::RangeNotSatisfied,
2132        ];
2133        for kind in rejected_kinds {
2134            let error = OpenDalSnafu {}.into_error(object_store::Error::new(kind, "test"));
2135            assert!(
2136                !error.may_have_persisted_manifest_update(),
2137                "error kind {kind:?} should prove the manifest was not persisted"
2138            );
2139        }
2140
2141        // The last retry can fail with these kinds even though an earlier attempt was stored.
2142        for kind in [
2143            ErrorKind::Unexpected,
2144            ErrorKind::RateLimited,
2145            ErrorKind::PermissionDenied,
2146        ] {
2147            let error = OpenDalSnafu {}.into_error(object_store::Error::new(kind, "test"));
2148            assert!(
2149                error.may_have_persisted_manifest_update(),
2150                "error kind {kind:?} should not prove the manifest was not persisted"
2151            );
2152        }
2153
2154        let region_id = RegionId::new(1, 1);
2155        let error = RegionTruncatedSnafu { region_id }.build();
2156        assert!(!error.may_have_persisted_manifest_update());
2157        let error = InvalidRequestSnafu {
2158            region_id,
2159            reason: "manifest applicability check rejected the edit",
2160        }
2161        .build();
2162        assert!(!error.may_have_persisted_manifest_update());
2163        // Staging that waits for a retried end commit refuses before storage I/O.
2164        let error = EndStagingPendingSnafu { region_id }.build();
2165        assert!(!error.may_have_persisted_manifest_update());
2166        assert!(error.retry_hint().is_retryable());
2167        assert_eq!(error.status_code(), StatusCode::RegionBusy);
2168        // Other busy errors keep the conservative classification.
2169        let error = RegionBusySnafu { region_id }.build();
2170        assert!(error.may_have_persisted_manifest_update());
2171
2172        // A commit refused before its PUT because the Leader deadline has passed.
2173        let error = RegionLeaseExpiredSnafu { region_id }.build();
2174        assert!(!error.may_have_persisted_manifest_update());
2175
2176        // A commit refused before its PUT because no Leader lease has confirmed the catchup.
2177        let error = RegionLeaseNotReceivedSnafu { region_id }.build();
2178        assert!(!error.may_have_persisted_manifest_update());
2179        assert_eq!(error.status_code(), StatusCode::RegionNotReady);
2180        assert!(error.retry_hint().is_retryable());
2181
2182        // This can be raised while applying an edit after its manifest file was saved.
2183        let error = RegionMetadataNotFoundSnafu {}.build();
2184        assert!(error.may_have_persisted_manifest_update());
2185
2186        let error = ManifestVersionConflictSnafu {
2187            version: 1u64,
2188            manifest_dir: "manifest/",
2189            reason: "test",
2190        }
2191        .build();
2192        assert!(error.may_have_persisted_manifest_update());
2193        assert!(error.retry_hint().is_retryable());
2194    }
2195}