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