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