Skip to main content

hawdb_core/
error.rs

1// Copyright 2026 Nowledge
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 crate::RuntimeCapability;
16use std::fmt::{Display, Formatter};
17
18mod resource;
19pub use resource::{ResourceBudgetError, ResourceBudgetKind, ResourceBudgetScope};
20mod transaction;
21pub use transaction::{TransactionRetryError, TransactionRetryReason};
22mod storage_format;
23pub use storage_format::{
24    StorageFormatError, APPEND_WAL_FORMAT, LOGICAL_DUMP_FORMAT,
25    RELATIONAL_CHECKPOINT_LAYOUT_FORMAT, RELATIONAL_DURABLE_CODEC_FORMAT,
26    RELATIONAL_ROW_PAGE_FORMAT, RELATIONAL_SCHEMA_FORMAT, SEARCH_PROJECTION_MANIFEST_FORMAT,
27    STORAGE_MANIFEST_FORMAT,
28};
29mod relational;
30mod wal_record;
31pub use relational::{find_relational_error_kind, RelationalErrorKind, RelationalErrorSurface};
32pub use wal_record::{WalRecordLimit, WalRecordLimitError};
33
34/// Descriptor admission failures are distinct from corrupt storage or a busy
35/// branch. Project quota counts belong to one engine resource domain; OS-limit
36/// failures can additionally report the process allowance when it is known.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum FileDescriptorError {
39    InvalidBudget {
40        limit: usize,
41    },
42    ConfigurationConflict {
43        configured: usize,
44        requested: usize,
45    },
46    CapacityPolicyConflict {
47        configured: bool,
48        requested: bool,
49    },
50    BudgetExceeded {
51        requested: usize,
52        available: usize,
53        limit: usize,
54    },
55    OsLimit {
56        requested: usize,
57        os_code: Option<i32>,
58        soft: Option<u64>,
59        hard: Option<u64>,
60    },
61}
62
63impl Display for FileDescriptorError {
64    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
65        match self {
66            Self::InvalidBudget { limit } => write!(formatter, "invalid file descriptor budget: {limit}"),
67            Self::ConfigurationConflict { configured, requested } => write!(formatter,
68                "project file descriptor budget conflict: configured {configured}, requested {requested}"),
69            Self::CapacityPolicyConflict { configured, requested } => write!(formatter,
70                "project strict_capacity_limit conflict: configured {configured}, requested {requested}"),
71            Self::BudgetExceeded { requested, available, limit } => write!(formatter,
72                "project file descriptor budget exceeded: requested {requested}, available {available}, limit {limit}"),
73            Self::OsLimit { requested, os_code, soft, hard } => write!(formatter,
74                "operating system file descriptor limit: requested {requested}, soft {soft:?}, hard {hard:?}, OS code {os_code:?}"),
75        }
76    }
77}
78
79impl std::error::Error for FileDescriptorError {}
80
81/// The result resource whose selected read limit rejected delivery.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum ReadBudgetResource {
84    Rows,
85    PayloadBytes,
86}
87
88impl ReadBudgetResource {
89    pub const fn as_str(self) -> &'static str {
90        match self {
91            Self::Rows => "result_rows",
92            Self::PayloadBytes => "result_payload_bytes",
93        }
94    }
95
96    /// The `DatabaseConfig` read ceiling that bounds this resource. A
97    /// per-request limit or an admitted runtime result budget can be smaller;
98    /// the refusal's `limit` is the effective one.
99    pub const fn budget_option(self) -> &'static str {
100        match self {
101            Self::Rows => "max_read_result_rows",
102            Self::PayloadBytes => "max_read_result_payload_bytes",
103        }
104    }
105}
106
107/// Retains budget identity independently of the execution diagnostic text.
108#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct ReadBudgetError {
110    pub resource: ReadBudgetResource,
111    pub limit: usize,
112    pub message: String,
113}
114
115impl Display for ReadBudgetError {
116    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
117        formatter.write_str(&self.message)
118    }
119}
120
121impl std::error::Error for ReadBudgetError {}
122
123/// Why a search projection rebuild was refused before it installed anything.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum SearchProjectionRebuildRefusal {
126    /// The target name already exists; the rebuild writes only to a new directory.
127    TargetExists,
128    /// The target's parent directory does not exist.
129    TargetParentMissing,
130    /// The target path has no final component.
131    TargetInvalid,
132    /// Another entry appeared at the target name before the no-replace install.
133    TargetAppeared,
134    /// The built generation differs from the pinned graph scan.
135    VerificationMismatch,
136}
137
138impl SearchProjectionRebuildRefusal {
139    pub const fn as_str(self) -> &'static str {
140        match self {
141            Self::TargetExists => "target_exists",
142            Self::TargetParentMissing => "target_parent_missing",
143            Self::TargetInvalid => "target_invalid",
144            Self::TargetAppeared => "target_appeared",
145            Self::VerificationMismatch => "verification_mismatch",
146        }
147    }
148}
149
150/// Why a metadata-only search projection epoch advance was refused before it
151/// published anything. The projection keeps its previous epoch; the host can
152/// fall back to an ordinary apply or catch-up.
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum SearchProjectionEpochAdvanceRefusal {
155    /// A graph commit in the range changed something that maps to a search
156    /// projection document, so the projection content may differ at the target.
157    ProjectionChanged,
158    /// The retained search change log does not cover the whole range: a
159    /// commit in it could not be captured, or its entries were trimmed.
160    ChangeLogGap,
161    /// The range cannot be checked: the projection has no source epoch, or the
162    /// target is beyond the graph's current commit epoch.
163    RangeUnavailable,
164    /// The resident projection holds changes that are not checkpointed, so its
165    /// durable files do not describe the in-memory projection.
166    UncheckpointedChanges,
167}
168
169impl SearchProjectionEpochAdvanceRefusal {
170    pub const fn as_str(self) -> &'static str {
171        match self {
172            Self::ProjectionChanged => "projection_changed",
173            Self::ChangeLogGap => "change_log_gap",
174            Self::RangeUnavailable => "range_unavailable",
175            Self::UncheckpointedChanges => "uncheckpointed_changes",
176        }
177    }
178}
179
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub enum HawDBError {
182    Parse(String),
183    Semantic(String),
184    Storage(String),
185    /// A relational constraint violation, such as a duplicate key or a NULL
186    /// in a NOT NULL column. It displays as `Storage` or `Execution` would,
187    /// by `surface`; `message` is the relational text after that prefix.
188    Constraint {
189        surface: RelationalErrorSurface,
190        message: String,
191    },
192    /// A relational schema refusal, such as a value of the wrong type for its
193    /// column. Displays like [`HawDBError::Constraint`].
194    Schema {
195        surface: RelationalErrorSurface,
196        message: String,
197    },
198    FileDescriptors(FileDescriptorError),
199    StorageIntegrity(String),
200    /// Recovery IO may have completed an effect; reopen to resume its audit.
201    WalRecoveryIo {
202        operation: &'static str,
203        kind: std::io::ErrorKind,
204        os_code: Option<i32>,
205        message: String,
206    },
207    UnsupportedStorageFormat(StorageFormatError),
208    /// A directory publication reached the point where its result may be
209    /// visible at `destination`, then failed before success was durable (for
210    /// example the parent-directory sync). The destination is not a failed
211    /// attempt: never remove it on the strength of this error. Reconcile it
212    /// instead (docs/LOGICAL_DUMP.md, "Unknown publication outcome").
213    PublishOutcomeUnknown {
214        destination: std::path::PathBuf,
215        message: String,
216    },
217    /// A registered Search target is retained by another native operation.
218    ProjectionBusy,
219    /// A search projection's resident snapshot disagrees with the immutable
220    /// projection its selector publishes, for example after a crash inside a
221    /// resident checkpoint written by HawDB 0.31.0 or earlier (#1711). The
222    /// projection is refused as a whole and is not retryable as-is: rebuild it
223    /// from the authoritative graph. The check reads only the projection's own
224    /// directory; the graph opens first and is not affected. `projection` is
225    /// the projection directory when the refusing open knows it. Displays as
226    /// a `storage error`.
227    SearchProjectionMismatch {
228        projection: Option<std::path::PathBuf>,
229        message: String,
230    },
231    /// A search projection rebuild was refused and installed nothing. The
232    /// graph, the current projection directory and the target name are
233    /// unchanged; only this attempt is void. This is not a storage failure:
234    /// fix the precondition named by `reason` (or retry a verification
235    /// mismatch after investigating the host source) and rebuild again.
236    SearchProjectionRebuildRefused {
237        reason: SearchProjectionRebuildRefusal,
238        target: std::path::PathBuf,
239        message: String,
240    },
241    /// A metadata-only search projection epoch advance was refused and
242    /// published nothing: the projection keeps `source_graph_commit_epoch`.
243    /// This is not a storage failure. The graph and the projection are
244    /// unchanged; apply or catch up the range normally instead.
245    SearchProjectionEpochAdvanceRefused {
246        reason: SearchProjectionEpochAdvanceRefusal,
247        source_graph_commit_epoch: Option<u64>,
248        target_graph_commit_epoch: u64,
249        message: String,
250    },
251    /// The externally owned search projection kinds requested at open differ
252    /// from the set recorded with the projection (#1814). The open is refused
253    /// and nothing is changed. Kinds are their lowercase projection names,
254    /// sorted. Pass the recorded set again, or rebuild the projection into a
255    /// new directory to change it. Not a storage failure.
256    SearchProjectionOwnershipMismatch {
257        projection: std::path::PathBuf,
258        recorded: Vec<String>,
259        requested: Vec<String>,
260    },
261    /// An externally owned search projection record (#1814) in the
262    /// projection directory cannot be parsed. Not a storage failure and not
263    /// poisoning: nothing was changed. Reopen with
264    /// `EmbeddedStoreOpenOptions::with_externally_owned_search_kinds_reset`
265    /// to rewrite both records from the passed set; that creates a fresh
266    /// rows-required fence so the host re-pushes its rows.
267    SearchProjectionOwnershipMarkerCorrupt {
268        projection: std::path::PathBuf,
269        marker: String,
270        message: String,
271    },
272    Execution(String),
273    /// Box the diagnostic so successful Result values do not grow with its fields.
274    ResourceBudgetExceeded(Box<ResourceBudgetError>),
275    ReadBudgetExceeded(ReadBudgetError),
276    /// A commit's WAL record would exceed a configured per-record limit. It
277    /// is refused before anything is written and leaves the handle usable;
278    /// see [`WalRecordLimitError`]. Not a storage failure.
279    WalRecordLimitExceeded(Box<WalRecordLimitError>),
280    GraphExpansionCandidateLimitExceeded {
281        requested: usize,
282        limit: usize,
283    },
284    GraphExpansionPayloadLimitExceeded {
285        requested: usize,
286        limit: usize,
287    },
288    TransactionConflict {
289        read_epoch: u64,
290        committed_epoch: u64,
291        key: String,
292    },
293    /// A pessimistic conflict requires retrying the complete transaction.
294    TransactionRetryRequired(Box<TransactionRetryError>),
295    /// Requested read validation cannot be proved; never downgrade isolation.
296    TransactionReadDependencyRefused {
297        reason: String,
298    },
299    AppendSequenceExhausted {
300        table: String,
301        watermark: i64,
302        requested: usize,
303    },
304    CapabilityUnavailable {
305        capability: RuntimeCapability,
306    },
307    /// A write was refused because the handle is read-only (for example an
308    /// embedded store opened in `GraphMode::ShadowReadOnly`). Nothing was
309    /// written. This is a caller error, not a storage failure: reopen the
310    /// store writable to perform `operation`.
311    ReadOnly {
312        operation: &'static str,
313    },
314    BranchCommandUnsupported {
315        command: &'static str,
316        context: &'static str,
317    },
318    BranchBusy {
319        resource: &'static str,
320    },
321    BranchEvidenceBudgetExceeded {
322        resource: &'static str,
323        requested: u64,
324        limit: u64,
325    },
326    /// An unleased pending create prevents a complete reclamation mark.
327    /// This identifies retained evidence, not authorization to discard it.
328    BranchReclamationBlocked {
329        branch_id: crate::Uuid,
330        catalog_revision: u64,
331        metadata_revision: u64,
332        cause: Box<HawDBError>,
333    },
334}
335
336impl Display for HawDBError {
337    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
338        match self {
339            HawDBError::Parse(message) => write!(f, "parse error: {message}"),
340            HawDBError::Semantic(message) => write!(f, "semantic error: {message}"),
341            HawDBError::Storage(message) => write!(f, "storage error: {message}"),
342            HawDBError::Constraint { surface, message }
343            | HawDBError::Schema { surface, message } => {
344                write!(f, "{}: {message}", surface.prefix())
345            }
346            HawDBError::FileDescriptors(error) => Display::fmt(error, f),
347            HawDBError::WalRecoveryIo { operation, message, .. } => write!(f, "WAL recovery {operation} failed; retain evidence and retry open: {message}"),
348            HawDBError::StorageIntegrity(message) => {
349                write!(f, "storage integrity error: {message}")
350            }
351            HawDBError::UnsupportedStorageFormat(error) => Display::fmt(error, f),
352            HawDBError::PublishOutcomeUnknown { destination, message } => write!(
353                f,
354                "publication of {} has an unknown outcome; keep the destination and reconcile it before retrying: {message}",
355                destination.display()
356            ),
357            HawDBError::ProjectionBusy => f.write_str("search projection operation is busy"),
358            HawDBError::SearchProjectionMismatch { message, .. } => {
359                write!(f, "storage error: {message}")
360            }
361            HawDBError::SearchProjectionRebuildRefused {
362                reason, message, ..
363            } => write!(
364                f,
365                "search projection rebuild refused ({}): {message}",
366                reason.as_str()
367            ),
368            HawDBError::SearchProjectionEpochAdvanceRefused {
369                reason, message, ..
370            } => write!(
371                f,
372                "search projection epoch advance refused ({}): {message}",
373                reason.as_str()
374            ),
375            HawDBError::SearchProjectionOwnershipMismatch {
376                projection,
377                recorded,
378                requested,
379            } => write!(
380                f,
381                "search projection ownership mismatch: {} records externally owned kinds [{}], open requested [{}]; pass the recorded set or rebuild the projection into a new directory",
382                projection.display(),
383                recorded.join(", "),
384                requested.join(", ")
385            ),
386            HawDBError::SearchProjectionOwnershipMarkerCorrupt {
387                projection,
388                marker,
389                message,
390            } => write!(
391                f,
392                "search projection ownership record {marker} in {} is unreadable ({message}); reopen with the externally owned search kinds reset to rewrite it",
393                projection.display()
394            ),
395            HawDBError::Execution(message) => write!(f, "execution error: {message}"),
396            HawDBError::ResourceBudgetExceeded(error) => write!(f, "execution error: {error}"),
397            HawDBError::ReadBudgetExceeded(error) => write!(f, "execution error: {error}"),
398            HawDBError::GraphExpansionCandidateLimitExceeded { requested, limit } => write!(
399                f,
400                "graph expansion candidate_limit exceeded: requested {requested} rows, limit {limit} rows; configure ExecutionMemoryConfig.graph_expansion_budget.candidate_limit"
401            ),
402            HawDBError::WalRecordLimitExceeded(error) => write!(f, "execution error: {error}"),
403            HawDBError::GraphExpansionPayloadLimitExceeded { requested, limit } => write!(
404                f,
405                "graph expansion payload_byte_limit exceeded: requested {requested} bytes, limit {limit} bytes; configure ExecutionMemoryConfig.graph_expansion_budget.payload_byte_limit"
406            ),
407            HawDBError::TransactionConflict {
408                read_epoch,
409                committed_epoch,
410                key,
411            } => write!(
412                f,
413                "transaction conflict on {key}: transaction read epoch {read_epoch}, conflicting commit epoch {committed_epoch}"
414            ),
415            HawDBError::TransactionRetryRequired(error) => Display::fmt(error, f),
416            HawDBError::AppendSequenceExhausted {
417                table,
418                watermark,
419                requested,
420            } => write!(
421                f,
422                "append commit sequence exhausted for table {table}: watermark={watermark}, requested={requested}"
423            ),
424            HawDBError::TransactionReadDependencyRefused { reason } => {
425                write!(f, "transaction read dependency capture refused: {reason}")
426            }
427            HawDBError::CapabilityUnavailable { capability } => {
428                write!(f, "capability unavailable: {}", capability.as_str())
429            }
430            HawDBError::ReadOnly { operation } => {
431                write!(f, "execution error: {operation} requires a writable handle; this handle is read-only")
432            }
433            HawDBError::BranchCommandUnsupported { command, context } => {
434                write!(f, "{command} is unavailable in {context}")
435            }
436            HawDBError::BranchBusy { resource } => write!(f, "branch is busy: {resource}"),
437            HawDBError::BranchEvidenceBudgetExceeded { resource, requested, limit } => write!(
438                f,
439                "branch quarantine evidence {resource} budget exceeded: requested {requested}, limit {limit}"
440            ),
441            HawDBError::BranchReclamationBlocked {
442                branch_id,
443                catalog_revision,
444                metadata_revision,
445                cause,
446            } => write!(
447                f,
448                "pending branch {branch_id} blocks reclamation at catalog revision {catalog_revision}, branch revision {metadata_revision}: {cause}"
449            ),
450        }
451    }
452}
453
454impl std::error::Error for HawDBError {
455    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
456        match self {
457            Self::FileDescriptors(error) => Some(error),
458            Self::ResourceBudgetExceeded(error) => Some(error.as_ref()),
459            Self::ReadBudgetExceeded(error) => Some(error),
460            Self::WalRecordLimitExceeded(error) => Some(error.as_ref()),
461            Self::TransactionRetryRequired(error) => Some(error.as_ref()),
462            Self::UnsupportedStorageFormat(error) => Some(error),
463            Self::BranchReclamationBlocked { cause, .. } => Some(cause.as_ref()),
464            _ => None,
465        }
466    }
467}
468
469impl HawDBError {
470    pub fn read_budget_exceeded(
471        resource: ReadBudgetResource,
472        limit: usize,
473        message: impl Into<String>,
474    ) -> Self {
475        Self::ReadBudgetExceeded(ReadBudgetError {
476            resource,
477            limit,
478            message: message.into(),
479        })
480    }
481
482    /// A relational refusal of `kind`, reported by `surface`.
483    pub fn relational(
484        kind: RelationalErrorKind,
485        surface: RelationalErrorSurface,
486        message: impl Into<String>,
487    ) -> Self {
488        let message = message.into();
489        match kind {
490            RelationalErrorKind::Constraint => Self::Constraint { surface, message },
491            RelationalErrorKind::Schema => Self::Schema { surface, message },
492        }
493    }
494
495    /// The relational refusal kind, for `Constraint` and `Schema` only.
496    pub const fn relational_error_kind(&self) -> Option<RelationalErrorKind> {
497        match self {
498            Self::Constraint { .. } => Some(RelationalErrorKind::Constraint),
499            Self::Schema { .. } => Some(RelationalErrorKind::Schema),
500            _ => None,
501        }
502    }
503
504    /// The layer that reported a `Constraint` or `Schema` refusal.
505    pub const fn relational_error_surface(&self) -> Option<RelationalErrorSurface> {
506        match self {
507            Self::Constraint { surface, .. } | Self::Schema { surface, .. } => Some(*surface),
508            _ => None,
509        }
510    }
511
512    /// Preserve typed storage refusals through nested error wrappers.
513    pub fn from_storage_error(error: impl std::error::Error + 'static) -> Self {
514        if let Some(error) = (&error as &dyn std::error::Error).downcast_ref::<Self>() {
515            return error.clone();
516        }
517        if let Some(resource) = file_descriptor_error(&error) {
518            Self::FileDescriptors(resource)
519        } else if let Some(resource) = resource::find_resource_budget_error(&error) {
520            Self::from(resource)
521        } else if let Some(error) = storage_format::find_storage_format_error(&error) {
522            Self::UnsupportedStorageFormat(error)
523        } else if let Some(kind) = find_relational_error_kind(&error) {
524            Self::relational(kind, RelationalErrorSurface::Storage, error.to_string())
525        } else {
526            Self::Storage(error.to_string())
527        }
528    }
529
530    /// `from_storage_error`, prefixing a generic `Storage` message with
531    /// `context` and leaving a preserved typed cause (e.g. `FileDescriptors`)
532    /// unprefixed and unchanged.
533    pub fn from_storage_error_with_context(
534        error: impl std::error::Error + 'static,
535        context: &str,
536    ) -> Self {
537        match Self::from_storage_error(error) {
538            Self::Storage(message) => Self::Storage(format!("{context}: {message}")),
539            Self::Constraint {
540                surface: surface @ RelationalErrorSurface::Storage,
541                message,
542            } => Self::Constraint {
543                surface,
544                message: format!("{context}: {message}"),
545            },
546            Self::Schema {
547                surface: surface @ RelationalErrorSurface::Storage,
548                message,
549            } => Self::Schema {
550                surface,
551                message: format!("{context}: {message}"),
552            },
553            error => error,
554        }
555    }
556
557    /// Retry the complete transaction, never only the failed statement.
558    /// Lock timeouts and generic execution/storage failures are not classified here.
559    pub const fn is_retryable_transaction_conflict(&self) -> bool {
560        matches!(
561            self,
562            Self::TransactionConflict { .. } | Self::TransactionRetryRequired(_)
563        )
564    }
565}
566
567pub type Result<T> = std::result::Result<T, HawDBError>;
568
569impl From<ResourceBudgetError> for HawDBError {
570    fn from(error: ResourceBudgetError) -> Self {
571        Self::ResourceBudgetExceeded(Box::new(error))
572    }
573}
574
575impl From<std::io::Error> for HawDBError {
576    fn from(error: std::io::Error) -> Self {
577        Self::from_storage_error(error)
578    }
579}
580
581pub fn file_descriptor_error(
582    error: &(dyn std::error::Error + 'static),
583) -> Option<FileDescriptorError> {
584    let mut current = Some(error);
585    while let Some(error) = current {
586        if let Some(resource) = error.downcast_ref::<FileDescriptorError>() {
587            return Some(resource.clone());
588        }
589        if let Some(HawDBError::FileDescriptors(resource)) = error.downcast_ref::<HawDBError>() {
590            return Some(resource.clone());
591        }
592        if let Some(error) = error.downcast_ref::<std::io::Error>() {
593            if let Some(code) = error.raw_os_error()
594                && descriptor_os_limit(code)
595            {
596                return Some(FileDescriptorError::OsLimit {
597                    requested: 1,
598                    os_code: Some(code),
599                    soft: None,
600                    hard: None,
601                });
602            }
603            // io::Error::source can skip its boxed concrete error. Inspect it
604            // explicitly so typed capacity rejections survive each IO layer.
605            if let Some(inner) = error.get_ref()
606                && let Some(resource) = file_descriptor_error(inner)
607            {
608                return Some(resource);
609            }
610        }
611        current = error.source();
612    }
613    None
614}
615
616fn descriptor_os_limit(code: i32) -> bool {
617    #[cfg(unix)]
618    {
619        matches!(code, 23 | 24)
620    }
621    #[cfg(windows)]
622    {
623        code == 4
624    }
625    #[cfg(not(any(unix, windows)))]
626    {
627        let _ = code;
628        false
629    }
630}