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