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 write was refused because the handle is read-only (for example an
414    /// embedded store opened in `GraphMode::ShadowReadOnly`). Nothing was
415    /// written. This is a caller error, not a storage failure: reopen the
416    /// store writable to perform `operation`.
417    ReadOnly {
418        operation: &'static str,
419    },
420    BranchCommandUnsupported {
421        command: &'static str,
422        context: &'static str,
423    },
424    BranchBusy {
425        resource: &'static str,
426    },
427    BranchEvidenceBudgetExceeded {
428        resource: &'static str,
429        requested: u64,
430        limit: u64,
431    },
432    /// An unleased pending create prevents a complete reclamation mark.
433    /// This identifies retained evidence, not authorization to discard it.
434    BranchReclamationBlocked {
435        branch_id: crate::Uuid,
436        catalog_revision: u64,
437        metadata_revision: u64,
438        cause: Box<HawDBError>,
439    },
440}
441
442impl Display for HawDBError {
443    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
444        match self {
445            HawDBError::Parse(message) => write!(f, "parse error: {message}"),
446            HawDBError::Semantic(message) => write!(f, "semantic error: {message}"),
447            HawDBError::Storage(message) => write!(f, "storage error: {message}"),
448            HawDBError::Constraint { surface, message }
449            | HawDBError::Schema { surface, message } => {
450                write!(f, "{}: {message}", surface.prefix())
451            }
452            HawDBError::FileDescriptors(error) => Display::fmt(error, f),
453            HawDBError::WalRecoveryIo { operation, message, .. } => write!(f, "WAL recovery {operation} failed; retain evidence and retry open: {message}"),
454            HawDBError::StorageIntegrity(message) => {
455                write!(f, "storage integrity error: {message}")
456            }
457            HawDBError::UnsupportedStorageFormat(error) => Display::fmt(error, f),
458            HawDBError::PublishOutcomeUnknown { destination, message } => write!(
459                f,
460                "publication of {} has an unknown outcome; keep the destination and reconcile it before retrying: {message}",
461                destination.display()
462            ),
463            HawDBError::ProjectionBusy => f.write_str("search projection operation is busy"),
464            HawDBError::SearchProjectionMismatch { message, .. } => {
465                write!(f, "storage error: {message}")
466            }
467            HawDBError::SearchProjectionRebuildRefused {
468                reason, message, ..
469            } => write!(
470                f,
471                "search projection rebuild refused ({}): {message}",
472                reason.as_str()
473            ),
474            HawDBError::SearchProjectionEpochAdvanceRefused {
475                reason, message, ..
476            } => write!(
477                f,
478                "search projection epoch advance refused ({}): {message}",
479                reason.as_str()
480            ),
481            HawDBError::SearchProjectionPrefixBehindSource {
482                complete_through_commit_epoch,
483                source_commit_epoch,
484            } => write!(
485                f,
486                "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"
487            ),
488            HawDBError::SearchProjectionBatchBudgetExceeded {
489                budget,
490                commit_epoch,
491                required_operations,
492                limit,
493            } => match (budget, commit_epoch) {
494                (SearchProjectionBatchBudget::ChangeBatch, Some(commit_epoch)) => write!(
495                    f,
496                    "storage error: search projection change at commit epoch {commit_epoch} requires {required_operations} operations, exceeding configured per-batch limit {limit}"
497                ),
498                (SearchProjectionBatchBudget::ChangeBatch, None) => write!(
499                    f,
500                    "storage error: search projection change requires {required_operations} operations, exceeding configured per-batch limit {limit}"
501                ),
502                (SearchProjectionBatchBudget::GraphDelta, _) => write!(
503                    f,
504                    "storage error: search projection graph delta operation count {required_operations} exceeded configured limit {limit}"
505                ),
506                (SearchProjectionBatchBudget::ProjectionDelta, _) => write!(
507                    f,
508                    "storage error: incremental projection update operation count {required_operations} exceeded configured limit {limit}"
509                ),
510            },
511            HawDBError::SearchProductionQualificationGraphEpochMismatch {
512                expected_canonical_graph_commit_epoch,
513                opened_graph_commit_epoch,
514            } => write!(
515                f,
516                "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}"
517            ),
518            HawDBError::SearchProductionQualificationRefused { blocker_codes } => write!(
519                f,
520                "storage error: segmented lexical projection is not qualified for the current production release: {}",
521                blocker_codes.join(",")
522            ),
523            HawDBError::SearchProjectionOwnershipMismatch {
524                projection,
525                recorded,
526                requested,
527            } => write!(
528                f,
529                "search projection ownership mismatch: {} records externally owned kinds [{}], open requested [{}]; pass the recorded set or rebuild the projection into a new directory",
530                projection.display(),
531                recorded.join(", "),
532                requested.join(", ")
533            ),
534            HawDBError::SearchProjectionOwnershipMarkerCorrupt {
535                projection,
536                marker,
537                message,
538            } => write!(
539                f,
540                "search projection ownership record {marker} in {} is unreadable ({message}); reopen with the externally owned search kinds reset to rewrite it",
541                projection.display()
542            ),
543            HawDBError::Execution(message) => write!(f, "execution error: {message}"),
544            HawDBError::ResourceBudgetExceeded(error) => write!(f, "execution error: {error}"),
545            HawDBError::ReadBudgetExceeded(error) => write!(f, "execution error: {error}"),
546            HawDBError::GraphExpansionCandidateLimitExceeded { requested, limit } => write!(
547                f,
548                "graph expansion candidate_limit exceeded: requested {requested} rows, limit {limit} rows; configure ExecutionMemoryConfig.graph_expansion_budget.candidate_limit"
549            ),
550            HawDBError::WalRecordLimitExceeded(error) => write!(f, "execution error: {error}"),
551            HawDBError::RuntimeAdmissionRefused(error) => write!(f, "execution error: {error}"),
552            HawDBError::RuntimeIoWaveReservationExceeded {
553                requested_slots,
554                reserved_slots,
555            } => write!(
556                f,
557                "execution error: runtime I/O wave requested {requested_slots} slots, exceeding the {reserved_slots}-slot reservation"
558            ),
559            HawDBError::RuntimeTaskStopped(reason) => {
560                write!(f, "execution error: runtime task stopped: {reason}")
561            }
562            HawDBError::GraphExpansionPayloadLimitExceeded { requested, limit } => write!(
563                f,
564                "graph expansion payload_byte_limit exceeded: requested {requested} bytes, limit {limit} bytes; configure ExecutionMemoryConfig.graph_expansion_budget.payload_byte_limit"
565            ),
566            HawDBError::TransactionConflict {
567                read_epoch,
568                committed_epoch,
569                key,
570            } => write!(
571                f,
572                "transaction conflict on {key}: transaction read epoch {read_epoch}, conflicting commit epoch {committed_epoch}"
573            ),
574            HawDBError::TransactionRetryRequired(error) => Display::fmt(error, f),
575            HawDBError::AppendSequenceExhausted {
576                table,
577                watermark,
578                requested,
579            } => write!(
580                f,
581                "append commit sequence exhausted for table {table}: watermark={watermark}, requested={requested}"
582            ),
583            HawDBError::TransactionReadDependencyRefused { reason } => {
584                write!(f, "transaction read dependency capture refused: {reason}")
585            }
586            HawDBError::CapabilityUnavailable { capability } => {
587                write!(f, "capability unavailable: {}", capability.as_str())
588            }
589            HawDBError::ReadOnly { operation } => {
590                write!(f, "execution error: {operation} requires a writable handle; this handle is read-only")
591            }
592            HawDBError::BranchCommandUnsupported { command, context } => {
593                write!(f, "{command} is unavailable in {context}")
594            }
595            HawDBError::BranchBusy { resource } => write!(f, "branch is busy: {resource}"),
596            HawDBError::BranchEvidenceBudgetExceeded { resource, requested, limit } => write!(
597                f,
598                "branch quarantine evidence {resource} budget exceeded: requested {requested}, limit {limit}"
599            ),
600            HawDBError::BranchReclamationBlocked {
601                branch_id,
602                catalog_revision,
603                metadata_revision,
604                cause,
605            } => write!(
606                f,
607                "pending branch {branch_id} blocks reclamation at catalog revision {catalog_revision}, branch revision {metadata_revision}: {cause}"
608            ),
609        }
610    }
611}
612
613impl std::error::Error for HawDBError {
614    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
615        match self {
616            Self::FileDescriptors(error) => Some(error),
617            Self::ResourceBudgetExceeded(error) => Some(error.as_ref()),
618            Self::ReadBudgetExceeded(error) => Some(error),
619            Self::WalRecordLimitExceeded(error) => Some(error.as_ref()),
620            Self::RuntimeAdmissionRefused(error) => Some(error),
621            Self::RuntimeTaskStopped(reason) => Some(reason),
622            Self::TransactionRetryRequired(error) => Some(error.as_ref()),
623            Self::UnsupportedStorageFormat(error) => Some(error),
624            Self::BranchReclamationBlocked { cause, .. } => Some(cause.as_ref()),
625            _ => None,
626        }
627    }
628}
629
630impl HawDBError {
631    pub fn read_budget_exceeded(
632        resource: ReadBudgetResource,
633        limit: usize,
634        message: impl Into<String>,
635    ) -> Self {
636        Self::ReadBudgetExceeded(ReadBudgetError {
637            resource,
638            limit,
639            message: message.into(),
640        })
641    }
642
643    /// A relational refusal of `kind`, reported by `surface`.
644    pub fn relational(
645        kind: RelationalErrorKind,
646        surface: RelationalErrorSurface,
647        message: impl Into<String>,
648    ) -> Self {
649        let message = message.into();
650        match kind {
651            RelationalErrorKind::Constraint => Self::Constraint { surface, message },
652            RelationalErrorKind::Schema => Self::Schema { surface, message },
653        }
654    }
655
656    /// The relational refusal kind, for `Constraint` and `Schema` only.
657    pub const fn relational_error_kind(&self) -> Option<RelationalErrorKind> {
658        match self {
659            Self::Constraint { .. } => Some(RelationalErrorKind::Constraint),
660            Self::Schema { .. } => Some(RelationalErrorKind::Schema),
661            _ => None,
662        }
663    }
664
665    /// The layer that reported a `Constraint` or `Schema` refusal.
666    pub const fn relational_error_surface(&self) -> Option<RelationalErrorSurface> {
667        match self {
668            Self::Constraint { surface, .. } | Self::Schema { surface, .. } => Some(*surface),
669            _ => None,
670        }
671    }
672
673    /// Preserve typed storage refusals through nested error wrappers.
674    pub fn from_storage_error(error: impl std::error::Error + 'static) -> Self {
675        if let Some(error) = (&error as &dyn std::error::Error).downcast_ref::<Self>() {
676            return error.clone();
677        }
678        // Storage publishers wrap this public error after their durable
679        // rename. Preserve it before looking for an inner task-stop reason:
680        // a lost response after publication is not a rollback-safe stop.
681        if let Some(error) = find_publish_outcome_unknown(&error) {
682            return error;
683        }
684        // A cancelled or expired runtime task anywhere in the cause chain is
685        // a stop, not a storage failure.
686        if let Some(reason) = find_runtime_task_stop(&error) {
687            return Self::RuntimeTaskStopped(reason);
688        }
689        if let Some(resource) = file_descriptor_error(&error) {
690            Self::FileDescriptors(resource)
691        } else if let Some(resource) = resource::find_resource_budget_error(&error) {
692            Self::from(resource)
693        } else if let Some(error) = storage_format::find_storage_format_error(&error) {
694            Self::UnsupportedStorageFormat(error)
695        } else if let Some(kind) = find_relational_error_kind(&error) {
696            Self::relational(kind, RelationalErrorSurface::Storage, error.to_string())
697        } else {
698            Self::Storage(error.to_string())
699        }
700    }
701
702    /// `from_storage_error`, prefixing a generic `Storage` message with
703    /// `context` and leaving a preserved typed cause (e.g. `FileDescriptors`)
704    /// unprefixed and unchanged.
705    pub fn from_storage_error_with_context(
706        error: impl std::error::Error + 'static,
707        context: &str,
708    ) -> Self {
709        match Self::from_storage_error(error) {
710            Self::Storage(message) => Self::Storage(format!("{context}: {message}")),
711            Self::Constraint {
712                surface: surface @ RelationalErrorSurface::Storage,
713                message,
714            } => Self::Constraint {
715                surface,
716                message: format!("{context}: {message}"),
717            },
718            Self::Schema {
719                surface: surface @ RelationalErrorSurface::Storage,
720                message,
721            } => Self::Schema {
722                surface,
723                message: format!("{context}: {message}"),
724            },
725            error => error,
726        }
727    }
728
729    /// Retry the complete transaction, never only the failed statement.
730    /// Lock timeouts and generic execution/storage failures are not classified here.
731    pub const fn is_retryable_transaction_conflict(&self) -> bool {
732        matches!(
733            self,
734            Self::TransactionConflict { .. } | Self::TransactionRetryRequired(_)
735        )
736    }
737
738    /// A graph-changing commit was published after the snapshot of a
739    /// transaction that read `graph_change_commit_epoch()` for
740    /// compare-and-publish. Implies `is_retryable_transaction_conflict`.
741    pub fn is_graph_change_conflict(&self) -> bool {
742        matches!(
743            self,
744            Self::TransactionConflict { key, .. } if key == GRAPH_CHANGE_COMMIT_EPOCH_CONFLICT_KEY
745        )
746    }
747}
748
749pub type Result<T> = std::result::Result<T, HawDBError>;
750
751/// Preserve both I/O-wave outcomes without requiring callers to parse text.
752impl From<crate::RuntimeIoWaveError> for HawDBError {
753    fn from(error: crate::RuntimeIoWaveError) -> Self {
754        match error {
755            crate::RuntimeIoWaveError::Stopped(reason) => Self::RuntimeTaskStopped(reason),
756            crate::RuntimeIoWaveError::ReservationExceeded {
757                requested_slots,
758                reserved_slots,
759            } => Self::RuntimeIoWaveReservationExceeded {
760                requested_slots,
761                reserved_slots,
762            },
763        }
764    }
765}
766
767impl HawDBError {
768    /// Return the typed `RuntimeTaskStopped` when `error` is (or is caused by)
769    /// a cancelled or expired runtime task, otherwise `otherwise()`. Wrap any
770    /// contextual message built from an error that may carry a stop.
771    pub fn or_stop(
772        error: &(dyn std::error::Error + 'static),
773        otherwise: impl FnOnce() -> Self,
774    ) -> Self {
775        match find_runtime_task_stop(error) {
776            Some(reason) => Self::RuntimeTaskStopped(reason),
777            None => otherwise(),
778        }
779    }
780
781    /// Preserve task stops and I/O-wave reservation mismatches through error
782    /// wrappers; all other causes keep their existing execution diagnostic.
783    pub fn from_execution_error(error: impl std::error::Error + 'static) -> Self {
784        if let Some(reason) = find_runtime_task_stop(&error) {
785            return Self::RuntimeTaskStopped(reason);
786        }
787        match find_runtime_io_wave_reservation(&error) {
788            Some((requested_slots, reserved_slots)) => Self::RuntimeIoWaveReservationExceeded {
789                requested_slots,
790                reserved_slots,
791            },
792            None => Self::Execution(error.to_string()),
793        }
794    }
795}
796
797fn find_publish_outcome_unknown(error: &(dyn std::error::Error + 'static)) -> Option<HawDBError> {
798    let mut current = Some(error);
799    while let Some(error) = current {
800        if let Some(error @ HawDBError::PublishOutcomeUnknown { .. }) =
801            error.downcast_ref::<HawDBError>()
802        {
803            return Some(error.clone());
804        }
805        if let Some(error) = error.downcast_ref::<std::io::Error>()
806            && let Some(inner) = error.get_ref()
807            && let Some(error) = find_publish_outcome_unknown(inner)
808        {
809            return Some(error);
810        }
811        current = error.source();
812    }
813    None
814}
815
816fn find_runtime_io_wave_reservation(
817    error: &(dyn std::error::Error + 'static),
818) -> Option<(usize, usize)> {
819    let mut current = Some(error);
820    while let Some(error) = current {
821        if let Some(crate::RuntimeIoWaveError::ReservationExceeded {
822            requested_slots,
823            reserved_slots,
824        }) = error.downcast_ref::<crate::RuntimeIoWaveError>()
825        {
826            return Some((*requested_slots, *reserved_slots));
827        }
828        if let Some(HawDBError::RuntimeIoWaveReservationExceeded {
829            requested_slots,
830            reserved_slots,
831        }) = error.downcast_ref::<HawDBError>()
832        {
833            return Some((*requested_slots, *reserved_slots));
834        }
835        // io::Error hides its boxed cause from Error::source.
836        if let Some(error) = error.downcast_ref::<std::io::Error>()
837            && let Some(inner) = error.get_ref()
838            && let Some(refusal) = find_runtime_io_wave_reservation(inner)
839        {
840            return Some(refusal);
841        }
842        current = error.source();
843    }
844    None
845}
846
847/// The cancellation reason of a stopped runtime task in `error`'s cause chain.
848fn find_runtime_task_stop(
849    error: &(dyn std::error::Error + 'static),
850) -> Option<crate::RuntimeCancellationReason> {
851    let mut current = Some(error);
852    while let Some(error) = current {
853        if let Some(reason) = error.downcast_ref::<crate::RuntimeCancellationReason>() {
854            return Some(*reason);
855        }
856        if let Some(HawDBError::RuntimeTaskStopped(reason)) = error.downcast_ref::<HawDBError>() {
857            return Some(*reason);
858        }
859        // io::Error hides its boxed cause from Error::source.
860        if let Some(error) = error.downcast_ref::<std::io::Error>()
861            && let Some(inner) = error.get_ref()
862            && let Some(reason) = find_runtime_task_stop(inner)
863        {
864            return Some(reason);
865        }
866        current = error.source();
867    }
868    None
869}
870
871/// A stopped runtime task is the typed `HawDBError::RuntimeTaskStopped`.
872impl From<crate::RuntimeCancellationReason> for HawDBError {
873    fn from(reason: crate::RuntimeCancellationReason) -> Self {
874        Self::RuntimeTaskStopped(reason)
875    }
876}
877
878impl From<ResourceBudgetError> for HawDBError {
879    fn from(error: ResourceBudgetError) -> Self {
880        Self::ResourceBudgetExceeded(Box::new(error))
881    }
882}
883
884impl From<std::io::Error> for HawDBError {
885    fn from(error: std::io::Error) -> Self {
886        Self::from_storage_error(error)
887    }
888}
889
890pub fn file_descriptor_error(
891    error: &(dyn std::error::Error + 'static),
892) -> Option<FileDescriptorError> {
893    let mut current = Some(error);
894    while let Some(error) = current {
895        if let Some(resource) = error.downcast_ref::<FileDescriptorError>() {
896            return Some(resource.clone());
897        }
898        if let Some(HawDBError::FileDescriptors(resource)) = error.downcast_ref::<HawDBError>() {
899            return Some(resource.clone());
900        }
901        if let Some(error) = error.downcast_ref::<std::io::Error>() {
902            if let Some(code) = error.raw_os_error()
903                && descriptor_os_limit(code)
904            {
905                return Some(FileDescriptorError::OsLimit {
906                    requested: 1,
907                    os_code: Some(code),
908                    soft: None,
909                    hard: None,
910                });
911            }
912            // io::Error::source can skip its boxed concrete error. Inspect it
913            // explicitly so typed capacity rejections survive each IO layer.
914            if let Some(inner) = error.get_ref()
915                && let Some(resource) = file_descriptor_error(inner)
916            {
917                return Some(resource);
918            }
919        }
920        current = error.source();
921    }
922    None
923}
924
925fn descriptor_os_limit(code: i32) -> bool {
926    #[cfg(unix)]
927    {
928        matches!(code, 23 | 24)
929    }
930    #[cfg(windows)]
931    {
932        code == 4
933    }
934    #[cfg(not(any(unix, windows)))]
935    {
936        let _ = code;
937        false
938    }
939}
940
941#[cfg(test)]
942mod runtime_io_wave_tests {
943    use super::*;
944
945    fn refusal() -> crate::RuntimeIoWaveError {
946        crate::RuntimeIoWaveError::ReservationExceeded {
947            requested_slots: 2,
948            reserved_slots: 1,
949        }
950    }
951
952    #[test]
953    fn reservation_refusal_stays_typed_directly_and_through_io_context() {
954        for error in [
955            HawDBError::from(refusal()),
956            HawDBError::from_execution_error(refusal()),
957            HawDBError::from_execution_error(std::io::Error::other(refusal())),
958        ] {
959            assert!(matches!(
960                error,
961                HawDBError::RuntimeIoWaveReservationExceeded {
962                    requested_slots: 2,
963                    reserved_slots: 1,
964                }
965            ));
966        }
967    }
968
969    #[test]
970    fn stopped_io_wave_stays_a_task_stop() {
971        assert!(matches!(
972            HawDBError::from_execution_error(crate::RuntimeIoWaveError::Stopped(
973                crate::RuntimeCancellationReason::DeadlineExceeded,
974            )),
975            HawDBError::RuntimeTaskStopped(crate::RuntimeCancellationReason::DeadlineExceeded)
976        ));
977    }
978}