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 admission;
30mod relational;
31mod wal_record;
32pub use admission::RuntimeAdmissionRefusal;
33pub use relational::{find_relational_error_kind, RelationalErrorKind, RelationalErrorSurface};
34pub use wal_record::{WalRecordLimit, WalRecordLimitError};
35
36/// Descriptor admission failures are distinct from corrupt storage or a busy
37/// branch. Project quota counts belong to one engine resource domain; OS-limit
38/// failures can additionally report the process allowance when it is known.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub enum FileDescriptorError {
41    InvalidBudget {
42        limit: usize,
43    },
44    ConfigurationConflict {
45        configured: usize,
46        requested: usize,
47    },
48    CapacityPolicyConflict {
49        configured: bool,
50        requested: bool,
51    },
52    BudgetExceeded {
53        requested: usize,
54        available: usize,
55        limit: usize,
56    },
57    OsLimit {
58        requested: usize,
59        os_code: Option<i32>,
60        soft: Option<u64>,
61        hard: Option<u64>,
62    },
63}
64
65impl Display for FileDescriptorError {
66    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
67        match self {
68            Self::InvalidBudget { limit } => write!(formatter, "invalid file descriptor budget: {limit}"),
69            Self::ConfigurationConflict { configured, requested } => write!(formatter,
70                "project file descriptor budget conflict: configured {configured}, requested {requested}"),
71            Self::CapacityPolicyConflict { configured, requested } => write!(formatter,
72                "project strict_capacity_limit conflict: configured {configured}, requested {requested}"),
73            Self::BudgetExceeded { requested, available, limit } => write!(formatter,
74                "project file descriptor budget exceeded: requested {requested}, available {available}, limit {limit}"),
75            Self::OsLimit { requested, os_code, soft, hard } => write!(formatter,
76                "operating system file descriptor limit: requested {requested}, soft {soft:?}, hard {hard:?}, OS code {os_code:?}"),
77        }
78    }
79}
80
81impl std::error::Error for FileDescriptorError {}
82
83/// The result resource whose selected read limit rejected delivery.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum ReadBudgetResource {
86    Rows,
87    PayloadBytes,
88}
89
90impl ReadBudgetResource {
91    pub const fn as_str(self) -> &'static str {
92        match self {
93            Self::Rows => "result_rows",
94            Self::PayloadBytes => "result_payload_bytes",
95        }
96    }
97
98    /// The `DatabaseConfig` read ceiling that bounds this resource. A
99    /// per-request limit or an admitted runtime result budget can be smaller;
100    /// the refusal's `limit` is the effective one.
101    pub const fn budget_option(self) -> &'static str {
102        match self {
103            Self::Rows => "max_read_result_rows",
104            Self::PayloadBytes => "max_read_result_payload_bytes",
105        }
106    }
107}
108
109/// Retains budget identity independently of the execution diagnostic text.
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct ReadBudgetError {
112    pub resource: ReadBudgetResource,
113    pub limit: usize,
114    pub message: String,
115}
116
117impl Display for ReadBudgetError {
118    fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
119        formatter.write_str(&self.message)
120    }
121}
122
123impl std::error::Error for ReadBudgetError {}
124
125/// Why a search projection rebuild was refused before it installed anything.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub enum SearchProjectionRebuildRefusal {
128    /// The target name already exists; the rebuild writes only to a new directory.
129    TargetExists,
130    /// The target's parent directory does not exist.
131    TargetParentMissing,
132    /// The target path has no final component.
133    TargetInvalid,
134    /// Another entry appeared at the target name before the no-replace install.
135    TargetAppeared,
136    /// The built generation differs from the pinned graph scan.
137    VerificationMismatch,
138}
139
140impl SearchProjectionRebuildRefusal {
141    pub const fn as_str(self) -> &'static str {
142        match self {
143            Self::TargetExists => "target_exists",
144            Self::TargetParentMissing => "target_parent_missing",
145            Self::TargetInvalid => "target_invalid",
146            Self::TargetAppeared => "target_appeared",
147            Self::VerificationMismatch => "verification_mismatch",
148        }
149    }
150}
151
152/// Why a metadata-only search projection epoch advance was refused before it
153/// published anything. The projection keeps its previous epoch; the host can
154/// fall back to an ordinary apply or catch-up.
155#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156pub enum SearchProjectionEpochAdvanceRefusal {
157    /// A graph commit in the range changed something that maps to a search
158    /// projection document, so the projection content may differ at the target.
159    ProjectionChanged,
160    /// The retained search change log does not cover the whole range: a
161    /// commit in it could not be captured, or its entries were trimmed.
162    ChangeLogGap,
163    /// The range cannot be checked: the projection has no source epoch, or the
164    /// target is beyond the graph's current commit epoch.
165    RangeUnavailable,
166    /// The resident projection holds changes that are not checkpointed, so its
167    /// durable files do not describe the in-memory projection.
168    UncheckpointedChanges,
169}
170
171impl SearchProjectionEpochAdvanceRefusal {
172    pub const fn as_str(self) -> &'static str {
173        match self {
174            Self::ProjectionChanged => "projection_changed",
175            Self::ChangeLogGap => "change_log_gap",
176            Self::RangeUnavailable => "range_unavailable",
177            Self::UncheckpointedChanges => "uncheckpointed_changes",
178        }
179    }
180}
181
182#[derive(Debug, Clone, PartialEq, Eq)]
183pub enum HawDBError {
184    Parse(String),
185    Semantic(String),
186    Storage(String),
187    /// A relational constraint violation, such as a duplicate key or a NULL
188    /// in a NOT NULL column. It displays as `Storage` or `Execution` would,
189    /// by `surface`; `message` is the relational text after that prefix.
190    Constraint {
191        surface: RelationalErrorSurface,
192        message: String,
193    },
194    /// A relational schema refusal, such as a value of the wrong type for its
195    /// column. Displays like [`HawDBError::Constraint`].
196    Schema {
197        surface: RelationalErrorSurface,
198        message: String,
199    },
200    FileDescriptors(FileDescriptorError),
201    StorageIntegrity(String),
202    /// Recovery IO may have completed an effect; reopen to resume its audit.
203    WalRecoveryIo {
204        operation: &'static str,
205        kind: std::io::ErrorKind,
206        os_code: Option<i32>,
207        message: String,
208    },
209    UnsupportedStorageFormat(StorageFormatError),
210    /// A directory publication reached the point where its result may be
211    /// visible at `destination`, then failed before success was durable (for
212    /// example the parent-directory sync). The destination is not a failed
213    /// attempt: never remove it on the strength of this error. Reconcile it
214    /// instead (docs/LOGICAL_DUMP.md, "Unknown publication outcome").
215    PublishOutcomeUnknown {
216        destination: std::path::PathBuf,
217        message: String,
218    },
219    /// A registered Search target is retained by another native operation.
220    ProjectionBusy,
221    /// A search projection's resident snapshot disagrees with the immutable
222    /// projection its selector publishes, for example after a crash inside a
223    /// resident checkpoint written by HawDB 0.31.0 or earlier (#1711). The
224    /// projection is refused as a whole and is not retryable as-is: rebuild it
225    /// from the authoritative graph. The check reads only the projection's own
226    /// directory; the graph opens first and is not affected. `projection` is
227    /// the projection directory when the refusing open knows it. Displays as
228    /// a `storage error`.
229    SearchProjectionMismatch {
230        projection: Option<std::path::PathBuf>,
231        message: String,
232    },
233    /// A search projection rebuild was refused and installed nothing. The
234    /// graph, the current projection directory and the target name are
235    /// unchanged; only this attempt is void. This is not a storage failure:
236    /// fix the precondition named by `reason` (or retry a verification
237    /// mismatch after investigating the host source) and rebuild again.
238    SearchProjectionRebuildRefused {
239        reason: SearchProjectionRebuildRefusal,
240        target: std::path::PathBuf,
241        message: String,
242    },
243    /// A metadata-only search projection epoch advance was refused and
244    /// published nothing: the projection keeps `source_graph_commit_epoch`.
245    /// This is not a storage failure. The graph and the projection are
246    /// unchanged; apply or catch up the range normally instead.
247    SearchProjectionEpochAdvanceRefused {
248        reason: SearchProjectionEpochAdvanceRefusal,
249        source_graph_commit_epoch: Option<u64>,
250        target_graph_commit_epoch: u64,
251        message: String,
252    },
253    /// The externally owned search projection kinds requested at open differ
254    /// from the set recorded with the projection (#1814). The open is refused
255    /// and nothing is changed. Kinds are their lowercase projection names,
256    /// sorted. Pass the recorded set again, or rebuild the projection into a
257    /// new directory to change it. Not a storage failure.
258    SearchProjectionOwnershipMismatch {
259        projection: std::path::PathBuf,
260        recorded: Vec<String>,
261        requested: Vec<String>,
262    },
263    /// An externally owned search projection record (#1814) in the
264    /// projection directory cannot be parsed. Not a storage failure and not
265    /// poisoning: nothing was changed. Reopen with
266    /// `EmbeddedStoreOpenOptions::with_externally_owned_search_kinds_reset`
267    /// to rewrite both records from the passed set; that creates a fresh
268    /// rows-required fence so the host re-pushes its rows.
269    SearchProjectionOwnershipMarkerCorrupt {
270        projection: std::path::PathBuf,
271        marker: String,
272        message: String,
273    },
274    Execution(String),
275    /// Box the diagnostic so successful Result values do not grow with its fields.
276    ResourceBudgetExceeded(Box<ResourceBudgetError>),
277    ReadBudgetExceeded(ReadBudgetError),
278    /// A commit's WAL record would exceed a configured per-record limit. It
279    /// is refused before anything is written and leaves the handle usable;
280    /// see [`WalRecordLimitError`]. Not a storage failure.
281    WalRecordLimitExceeded(Box<WalRecordLimitError>),
282    /// The runtime governor refused admission or retained-memory funding;
283    /// nothing ran. Not a storage failure and never poisoning. See
284    /// [`RuntimeAdmissionRefusal::retryable`].
285    RuntimeAdmissionRefused(RuntimeAdmissionRefusal),
286    /// The task asked for more concurrent I/O slots than its successful
287    /// runtime admission reserved. Nothing ran and retrying the same task
288    /// unchanged cannot succeed; admit it again with a larger I/O reservation.
289    /// This is not transient I/O saturation: admitted callers wait for held
290    /// slots until their task stops.
291    RuntimeIoWaveReservationExceeded {
292        requested_slots: usize,
293        reserved_slots: usize,
294    },
295    /// The caller's `RuntimeTaskContext` was cancelled or passed its deadline
296    /// (or its resource budget was exhausted) before the work completed.
297    /// Nothing from the stopped work was committed. Not a storage failure and
298    /// never poisoning; the caller decides whether to retry.
299    RuntimeTaskStopped(crate::RuntimeCancellationReason),
300    GraphExpansionCandidateLimitExceeded {
301        requested: usize,
302        limit: usize,
303    },
304    GraphExpansionPayloadLimitExceeded {
305        requested: usize,
306        limit: usize,
307    },
308    TransactionConflict {
309        read_epoch: u64,
310        committed_epoch: u64,
311        key: String,
312    },
313    /// A pessimistic conflict requires retrying the complete transaction.
314    TransactionRetryRequired(Box<TransactionRetryError>),
315    /// Requested read validation cannot be proved; never downgrade isolation.
316    TransactionReadDependencyRefused {
317        reason: String,
318    },
319    AppendSequenceExhausted {
320        table: String,
321        watermark: i64,
322        requested: usize,
323    },
324    CapabilityUnavailable {
325        capability: RuntimeCapability,
326    },
327    /// A write was refused because the handle is read-only (for example an
328    /// embedded store opened in `GraphMode::ShadowReadOnly`). Nothing was
329    /// written. This is a caller error, not a storage failure: reopen the
330    /// store writable to perform `operation`.
331    ReadOnly {
332        operation: &'static str,
333    },
334    BranchCommandUnsupported {
335        command: &'static str,
336        context: &'static str,
337    },
338    BranchBusy {
339        resource: &'static str,
340    },
341    BranchEvidenceBudgetExceeded {
342        resource: &'static str,
343        requested: u64,
344        limit: u64,
345    },
346    /// An unleased pending create prevents a complete reclamation mark.
347    /// This identifies retained evidence, not authorization to discard it.
348    BranchReclamationBlocked {
349        branch_id: crate::Uuid,
350        catalog_revision: u64,
351        metadata_revision: u64,
352        cause: Box<HawDBError>,
353    },
354}
355
356impl Display for HawDBError {
357    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
358        match self {
359            HawDBError::Parse(message) => write!(f, "parse error: {message}"),
360            HawDBError::Semantic(message) => write!(f, "semantic error: {message}"),
361            HawDBError::Storage(message) => write!(f, "storage error: {message}"),
362            HawDBError::Constraint { surface, message }
363            | HawDBError::Schema { surface, message } => {
364                write!(f, "{}: {message}", surface.prefix())
365            }
366            HawDBError::FileDescriptors(error) => Display::fmt(error, f),
367            HawDBError::WalRecoveryIo { operation, message, .. } => write!(f, "WAL recovery {operation} failed; retain evidence and retry open: {message}"),
368            HawDBError::StorageIntegrity(message) => {
369                write!(f, "storage integrity error: {message}")
370            }
371            HawDBError::UnsupportedStorageFormat(error) => Display::fmt(error, f),
372            HawDBError::PublishOutcomeUnknown { destination, message } => write!(
373                f,
374                "publication of {} has an unknown outcome; keep the destination and reconcile it before retrying: {message}",
375                destination.display()
376            ),
377            HawDBError::ProjectionBusy => f.write_str("search projection operation is busy"),
378            HawDBError::SearchProjectionMismatch { message, .. } => {
379                write!(f, "storage error: {message}")
380            }
381            HawDBError::SearchProjectionRebuildRefused {
382                reason, message, ..
383            } => write!(
384                f,
385                "search projection rebuild refused ({}): {message}",
386                reason.as_str()
387            ),
388            HawDBError::SearchProjectionEpochAdvanceRefused {
389                reason, message, ..
390            } => write!(
391                f,
392                "search projection epoch advance refused ({}): {message}",
393                reason.as_str()
394            ),
395            HawDBError::SearchProjectionOwnershipMismatch {
396                projection,
397                recorded,
398                requested,
399            } => write!(
400                f,
401                "search projection ownership mismatch: {} records externally owned kinds [{}], open requested [{}]; pass the recorded set or rebuild the projection into a new directory",
402                projection.display(),
403                recorded.join(", "),
404                requested.join(", ")
405            ),
406            HawDBError::SearchProjectionOwnershipMarkerCorrupt {
407                projection,
408                marker,
409                message,
410            } => write!(
411                f,
412                "search projection ownership record {marker} in {} is unreadable ({message}); reopen with the externally owned search kinds reset to rewrite it",
413                projection.display()
414            ),
415            HawDBError::Execution(message) => write!(f, "execution error: {message}"),
416            HawDBError::ResourceBudgetExceeded(error) => write!(f, "execution error: {error}"),
417            HawDBError::ReadBudgetExceeded(error) => write!(f, "execution error: {error}"),
418            HawDBError::GraphExpansionCandidateLimitExceeded { requested, limit } => write!(
419                f,
420                "graph expansion candidate_limit exceeded: requested {requested} rows, limit {limit} rows; configure ExecutionMemoryConfig.graph_expansion_budget.candidate_limit"
421            ),
422            HawDBError::WalRecordLimitExceeded(error) => write!(f, "execution error: {error}"),
423            HawDBError::RuntimeAdmissionRefused(error) => write!(f, "execution error: {error}"),
424            HawDBError::RuntimeIoWaveReservationExceeded {
425                requested_slots,
426                reserved_slots,
427            } => write!(
428                f,
429                "execution error: runtime I/O wave requested {requested_slots} slots, exceeding the {reserved_slots}-slot reservation"
430            ),
431            HawDBError::RuntimeTaskStopped(reason) => {
432                write!(f, "execution error: runtime task stopped: {reason}")
433            }
434            HawDBError::GraphExpansionPayloadLimitExceeded { requested, limit } => write!(
435                f,
436                "graph expansion payload_byte_limit exceeded: requested {requested} bytes, limit {limit} bytes; configure ExecutionMemoryConfig.graph_expansion_budget.payload_byte_limit"
437            ),
438            HawDBError::TransactionConflict {
439                read_epoch,
440                committed_epoch,
441                key,
442            } => write!(
443                f,
444                "transaction conflict on {key}: transaction read epoch {read_epoch}, conflicting commit epoch {committed_epoch}"
445            ),
446            HawDBError::TransactionRetryRequired(error) => Display::fmt(error, f),
447            HawDBError::AppendSequenceExhausted {
448                table,
449                watermark,
450                requested,
451            } => write!(
452                f,
453                "append commit sequence exhausted for table {table}: watermark={watermark}, requested={requested}"
454            ),
455            HawDBError::TransactionReadDependencyRefused { reason } => {
456                write!(f, "transaction read dependency capture refused: {reason}")
457            }
458            HawDBError::CapabilityUnavailable { capability } => {
459                write!(f, "capability unavailable: {}", capability.as_str())
460            }
461            HawDBError::ReadOnly { operation } => {
462                write!(f, "execution error: {operation} requires a writable handle; this handle is read-only")
463            }
464            HawDBError::BranchCommandUnsupported { command, context } => {
465                write!(f, "{command} is unavailable in {context}")
466            }
467            HawDBError::BranchBusy { resource } => write!(f, "branch is busy: {resource}"),
468            HawDBError::BranchEvidenceBudgetExceeded { resource, requested, limit } => write!(
469                f,
470                "branch quarantine evidence {resource} budget exceeded: requested {requested}, limit {limit}"
471            ),
472            HawDBError::BranchReclamationBlocked {
473                branch_id,
474                catalog_revision,
475                metadata_revision,
476                cause,
477            } => write!(
478                f,
479                "pending branch {branch_id} blocks reclamation at catalog revision {catalog_revision}, branch revision {metadata_revision}: {cause}"
480            ),
481        }
482    }
483}
484
485impl std::error::Error for HawDBError {
486    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
487        match self {
488            Self::FileDescriptors(error) => Some(error),
489            Self::ResourceBudgetExceeded(error) => Some(error.as_ref()),
490            Self::ReadBudgetExceeded(error) => Some(error),
491            Self::WalRecordLimitExceeded(error) => Some(error.as_ref()),
492            Self::RuntimeAdmissionRefused(error) => Some(error),
493            Self::RuntimeTaskStopped(reason) => Some(reason),
494            Self::TransactionRetryRequired(error) => Some(error.as_ref()),
495            Self::UnsupportedStorageFormat(error) => Some(error),
496            Self::BranchReclamationBlocked { cause, .. } => Some(cause.as_ref()),
497            _ => None,
498        }
499    }
500}
501
502impl HawDBError {
503    pub fn read_budget_exceeded(
504        resource: ReadBudgetResource,
505        limit: usize,
506        message: impl Into<String>,
507    ) -> Self {
508        Self::ReadBudgetExceeded(ReadBudgetError {
509            resource,
510            limit,
511            message: message.into(),
512        })
513    }
514
515    /// A relational refusal of `kind`, reported by `surface`.
516    pub fn relational(
517        kind: RelationalErrorKind,
518        surface: RelationalErrorSurface,
519        message: impl Into<String>,
520    ) -> Self {
521        let message = message.into();
522        match kind {
523            RelationalErrorKind::Constraint => Self::Constraint { surface, message },
524            RelationalErrorKind::Schema => Self::Schema { surface, message },
525        }
526    }
527
528    /// The relational refusal kind, for `Constraint` and `Schema` only.
529    pub const fn relational_error_kind(&self) -> Option<RelationalErrorKind> {
530        match self {
531            Self::Constraint { .. } => Some(RelationalErrorKind::Constraint),
532            Self::Schema { .. } => Some(RelationalErrorKind::Schema),
533            _ => None,
534        }
535    }
536
537    /// The layer that reported a `Constraint` or `Schema` refusal.
538    pub const fn relational_error_surface(&self) -> Option<RelationalErrorSurface> {
539        match self {
540            Self::Constraint { surface, .. } | Self::Schema { surface, .. } => Some(*surface),
541            _ => None,
542        }
543    }
544
545    /// Preserve typed storage refusals through nested error wrappers.
546    pub fn from_storage_error(error: impl std::error::Error + 'static) -> Self {
547        if let Some(error) = (&error as &dyn std::error::Error).downcast_ref::<Self>() {
548            return error.clone();
549        }
550        // Storage publishers wrap this public error after their durable
551        // rename. Preserve it before looking for an inner task-stop reason:
552        // a lost response after publication is not a rollback-safe stop.
553        if let Some(error) = find_publish_outcome_unknown(&error) {
554            return error;
555        }
556        // A cancelled or expired runtime task anywhere in the cause chain is
557        // a stop, not a storage failure.
558        if let Some(reason) = find_runtime_task_stop(&error) {
559            return Self::RuntimeTaskStopped(reason);
560        }
561        if let Some(resource) = file_descriptor_error(&error) {
562            Self::FileDescriptors(resource)
563        } else if let Some(resource) = resource::find_resource_budget_error(&error) {
564            Self::from(resource)
565        } else if let Some(error) = storage_format::find_storage_format_error(&error) {
566            Self::UnsupportedStorageFormat(error)
567        } else if let Some(kind) = find_relational_error_kind(&error) {
568            Self::relational(kind, RelationalErrorSurface::Storage, error.to_string())
569        } else {
570            Self::Storage(error.to_string())
571        }
572    }
573
574    /// `from_storage_error`, prefixing a generic `Storage` message with
575    /// `context` and leaving a preserved typed cause (e.g. `FileDescriptors`)
576    /// unprefixed and unchanged.
577    pub fn from_storage_error_with_context(
578        error: impl std::error::Error + 'static,
579        context: &str,
580    ) -> Self {
581        match Self::from_storage_error(error) {
582            Self::Storage(message) => Self::Storage(format!("{context}: {message}")),
583            Self::Constraint {
584                surface: surface @ RelationalErrorSurface::Storage,
585                message,
586            } => Self::Constraint {
587                surface,
588                message: format!("{context}: {message}"),
589            },
590            Self::Schema {
591                surface: surface @ RelationalErrorSurface::Storage,
592                message,
593            } => Self::Schema {
594                surface,
595                message: format!("{context}: {message}"),
596            },
597            error => error,
598        }
599    }
600
601    /// Retry the complete transaction, never only the failed statement.
602    /// Lock timeouts and generic execution/storage failures are not classified here.
603    pub const fn is_retryable_transaction_conflict(&self) -> bool {
604        matches!(
605            self,
606            Self::TransactionConflict { .. } | Self::TransactionRetryRequired(_)
607        )
608    }
609}
610
611pub type Result<T> = std::result::Result<T, HawDBError>;
612
613/// Preserve both I/O-wave outcomes without requiring callers to parse text.
614impl From<crate::RuntimeIoWaveError> for HawDBError {
615    fn from(error: crate::RuntimeIoWaveError) -> Self {
616        match error {
617            crate::RuntimeIoWaveError::Stopped(reason) => Self::RuntimeTaskStopped(reason),
618            crate::RuntimeIoWaveError::ReservationExceeded {
619                requested_slots,
620                reserved_slots,
621            } => Self::RuntimeIoWaveReservationExceeded {
622                requested_slots,
623                reserved_slots,
624            },
625        }
626    }
627}
628
629impl HawDBError {
630    /// Return the typed `RuntimeTaskStopped` when `error` is (or is caused by)
631    /// a cancelled or expired runtime task, otherwise `otherwise()`. Wrap any
632    /// contextual message built from an error that may carry a stop.
633    pub fn or_stop(
634        error: &(dyn std::error::Error + 'static),
635        otherwise: impl FnOnce() -> Self,
636    ) -> Self {
637        match find_runtime_task_stop(error) {
638            Some(reason) => Self::RuntimeTaskStopped(reason),
639            None => otherwise(),
640        }
641    }
642
643    /// Preserve task stops and I/O-wave reservation mismatches through error
644    /// wrappers; all other causes keep their existing execution diagnostic.
645    pub fn from_execution_error(error: impl std::error::Error + 'static) -> Self {
646        if let Some(reason) = find_runtime_task_stop(&error) {
647            return Self::RuntimeTaskStopped(reason);
648        }
649        match find_runtime_io_wave_reservation(&error) {
650            Some((requested_slots, reserved_slots)) => Self::RuntimeIoWaveReservationExceeded {
651                requested_slots,
652                reserved_slots,
653            },
654            None => Self::Execution(error.to_string()),
655        }
656    }
657}
658
659fn find_publish_outcome_unknown(error: &(dyn std::error::Error + 'static)) -> Option<HawDBError> {
660    let mut current = Some(error);
661    while let Some(error) = current {
662        if let Some(error @ HawDBError::PublishOutcomeUnknown { .. }) =
663            error.downcast_ref::<HawDBError>()
664        {
665            return Some(error.clone());
666        }
667        if let Some(error) = error.downcast_ref::<std::io::Error>()
668            && let Some(inner) = error.get_ref()
669            && let Some(error) = find_publish_outcome_unknown(inner)
670        {
671            return Some(error);
672        }
673        current = error.source();
674    }
675    None
676}
677
678fn find_runtime_io_wave_reservation(
679    error: &(dyn std::error::Error + 'static),
680) -> Option<(usize, usize)> {
681    let mut current = Some(error);
682    while let Some(error) = current {
683        if let Some(crate::RuntimeIoWaveError::ReservationExceeded {
684            requested_slots,
685            reserved_slots,
686        }) = error.downcast_ref::<crate::RuntimeIoWaveError>()
687        {
688            return Some((*requested_slots, *reserved_slots));
689        }
690        if let Some(HawDBError::RuntimeIoWaveReservationExceeded {
691            requested_slots,
692            reserved_slots,
693        }) = error.downcast_ref::<HawDBError>()
694        {
695            return Some((*requested_slots, *reserved_slots));
696        }
697        // io::Error hides its boxed cause from Error::source.
698        if let Some(error) = error.downcast_ref::<std::io::Error>()
699            && let Some(inner) = error.get_ref()
700            && let Some(refusal) = find_runtime_io_wave_reservation(inner)
701        {
702            return Some(refusal);
703        }
704        current = error.source();
705    }
706    None
707}
708
709/// The cancellation reason of a stopped runtime task in `error`'s cause chain.
710fn find_runtime_task_stop(
711    error: &(dyn std::error::Error + 'static),
712) -> Option<crate::RuntimeCancellationReason> {
713    let mut current = Some(error);
714    while let Some(error) = current {
715        if let Some(reason) = error.downcast_ref::<crate::RuntimeCancellationReason>() {
716            return Some(*reason);
717        }
718        if let Some(HawDBError::RuntimeTaskStopped(reason)) = error.downcast_ref::<HawDBError>() {
719            return Some(*reason);
720        }
721        // io::Error hides its boxed cause from Error::source.
722        if let Some(error) = error.downcast_ref::<std::io::Error>()
723            && let Some(inner) = error.get_ref()
724            && let Some(reason) = find_runtime_task_stop(inner)
725        {
726            return Some(reason);
727        }
728        current = error.source();
729    }
730    None
731}
732
733/// A stopped runtime task is the typed `HawDBError::RuntimeTaskStopped`.
734impl From<crate::RuntimeCancellationReason> for HawDBError {
735    fn from(reason: crate::RuntimeCancellationReason) -> Self {
736        Self::RuntimeTaskStopped(reason)
737    }
738}
739
740impl From<ResourceBudgetError> for HawDBError {
741    fn from(error: ResourceBudgetError) -> Self {
742        Self::ResourceBudgetExceeded(Box::new(error))
743    }
744}
745
746impl From<std::io::Error> for HawDBError {
747    fn from(error: std::io::Error) -> Self {
748        Self::from_storage_error(error)
749    }
750}
751
752pub fn file_descriptor_error(
753    error: &(dyn std::error::Error + 'static),
754) -> Option<FileDescriptorError> {
755    let mut current = Some(error);
756    while let Some(error) = current {
757        if let Some(resource) = error.downcast_ref::<FileDescriptorError>() {
758            return Some(resource.clone());
759        }
760        if let Some(HawDBError::FileDescriptors(resource)) = error.downcast_ref::<HawDBError>() {
761            return Some(resource.clone());
762        }
763        if let Some(error) = error.downcast_ref::<std::io::Error>() {
764            if let Some(code) = error.raw_os_error()
765                && descriptor_os_limit(code)
766            {
767                return Some(FileDescriptorError::OsLimit {
768                    requested: 1,
769                    os_code: Some(code),
770                    soft: None,
771                    hard: None,
772                });
773            }
774            // io::Error::source can skip its boxed concrete error. Inspect it
775            // explicitly so typed capacity rejections survive each IO layer.
776            if let Some(inner) = error.get_ref()
777                && let Some(resource) = file_descriptor_error(inner)
778            {
779                return Some(resource);
780            }
781        }
782        current = error.source();
783    }
784    None
785}
786
787fn descriptor_os_limit(code: i32) -> bool {
788    #[cfg(unix)]
789    {
790        matches!(code, 23 | 24)
791    }
792    #[cfg(windows)]
793    {
794        code == 4
795    }
796    #[cfg(not(any(unix, windows)))]
797    {
798        let _ = code;
799        false
800    }
801}
802
803#[cfg(test)]
804mod runtime_io_wave_tests {
805    use super::*;
806
807    fn refusal() -> crate::RuntimeIoWaveError {
808        crate::RuntimeIoWaveError::ReservationExceeded {
809            requested_slots: 2,
810            reserved_slots: 1,
811        }
812    }
813
814    #[test]
815    fn reservation_refusal_stays_typed_directly_and_through_io_context() {
816        for error in [
817            HawDBError::from(refusal()),
818            HawDBError::from_execution_error(refusal()),
819            HawDBError::from_execution_error(std::io::Error::other(refusal())),
820        ] {
821            assert!(matches!(
822                error,
823                HawDBError::RuntimeIoWaveReservationExceeded {
824                    requested_slots: 2,
825                    reserved_slots: 1,
826                }
827            ));
828        }
829    }
830
831    #[test]
832    fn stopped_io_wave_stays_a_task_stop() {
833        assert!(matches!(
834            HawDBError::from_execution_error(crate::RuntimeIoWaveError::Stopped(
835                crate::RuntimeCancellationReason::DeadlineExceeded,
836            )),
837            HawDBError::RuntimeTaskStopped(crate::RuntimeCancellationReason::DeadlineExceeded)
838        ));
839    }
840}