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