1use crate::RuntimeCapability;
16use std::fmt::{Display, Formatter};
17
18mod resource;
19pub use resource::{ResourceBudgetError, ResourceBudgetKind, ResourceBudgetScope};
20mod transaction;
21pub use transaction::{TransactionRetryError, TransactionRetryReason};
22mod storage_format;
23pub use storage_format::{
24 StorageFormatError, APPEND_WAL_FORMAT, LOGICAL_DUMP_FORMAT,
25 RELATIONAL_CHECKPOINT_LAYOUT_FORMAT, RELATIONAL_DURABLE_CODEC_FORMAT,
26 RELATIONAL_ROW_PAGE_FORMAT, RELATIONAL_SCHEMA_FORMAT, SEARCH_PROJECTION_MANIFEST_FORMAT,
27 STORAGE_MANIFEST_FORMAT,
28};
29mod relational;
30mod wal_record;
31pub use relational::{find_relational_error_kind, RelationalErrorKind, RelationalErrorSurface};
32pub use wal_record::{WalRecordLimit, WalRecordLimitError};
33
34#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum FileDescriptorError {
39 InvalidBudget {
40 limit: usize,
41 },
42 ConfigurationConflict {
43 configured: usize,
44 requested: usize,
45 },
46 CapacityPolicyConflict {
47 configured: bool,
48 requested: bool,
49 },
50 BudgetExceeded {
51 requested: usize,
52 available: usize,
53 limit: usize,
54 },
55 OsLimit {
56 requested: usize,
57 os_code: Option<i32>,
58 soft: Option<u64>,
59 hard: Option<u64>,
60 },
61}
62
63impl Display for FileDescriptorError {
64 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
65 match self {
66 Self::InvalidBudget { limit } => write!(formatter, "invalid file descriptor budget: {limit}"),
67 Self::ConfigurationConflict { configured, requested } => write!(formatter,
68 "project file descriptor budget conflict: configured {configured}, requested {requested}"),
69 Self::CapacityPolicyConflict { configured, requested } => write!(formatter,
70 "project strict_capacity_limit conflict: configured {configured}, requested {requested}"),
71 Self::BudgetExceeded { requested, available, limit } => write!(formatter,
72 "project file descriptor budget exceeded: requested {requested}, available {available}, limit {limit}"),
73 Self::OsLimit { requested, os_code, soft, hard } => write!(formatter,
74 "operating system file descriptor limit: requested {requested}, soft {soft:?}, hard {hard:?}, OS code {os_code:?}"),
75 }
76 }
77}
78
79impl std::error::Error for FileDescriptorError {}
80
81#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum ReadBudgetResource {
84 Rows,
85 PayloadBytes,
86}
87
88impl ReadBudgetResource {
89 pub const fn as_str(self) -> &'static str {
90 match self {
91 Self::Rows => "result_rows",
92 Self::PayloadBytes => "result_payload_bytes",
93 }
94 }
95
96 pub const fn budget_option(self) -> &'static str {
100 match self {
101 Self::Rows => "max_read_result_rows",
102 Self::PayloadBytes => "max_read_result_payload_bytes",
103 }
104 }
105}
106
107#[derive(Debug, Clone, PartialEq, Eq)]
109pub struct ReadBudgetError {
110 pub resource: ReadBudgetResource,
111 pub limit: usize,
112 pub message: String,
113}
114
115impl Display for ReadBudgetError {
116 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
117 formatter.write_str(&self.message)
118 }
119}
120
121impl std::error::Error for ReadBudgetError {}
122
123#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum SearchProjectionRebuildRefusal {
126 TargetExists,
128 TargetParentMissing,
130 TargetInvalid,
132 TargetAppeared,
134 VerificationMismatch,
136}
137
138impl SearchProjectionRebuildRefusal {
139 pub const fn as_str(self) -> &'static str {
140 match self {
141 Self::TargetExists => "target_exists",
142 Self::TargetParentMissing => "target_parent_missing",
143 Self::TargetInvalid => "target_invalid",
144 Self::TargetAppeared => "target_appeared",
145 Self::VerificationMismatch => "verification_mismatch",
146 }
147 }
148}
149
150#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum SearchProjectionEpochAdvanceRefusal {
155 ProjectionChanged,
158 ChangeLogGap,
161 RangeUnavailable,
164 UncheckpointedChanges,
167}
168
169impl SearchProjectionEpochAdvanceRefusal {
170 pub const fn as_str(self) -> &'static str {
171 match self {
172 Self::ProjectionChanged => "projection_changed",
173 Self::ChangeLogGap => "change_log_gap",
174 Self::RangeUnavailable => "range_unavailable",
175 Self::UncheckpointedChanges => "uncheckpointed_changes",
176 }
177 }
178}
179
180#[derive(Debug, Clone, PartialEq, Eq)]
181pub enum HawDBError {
182 Parse(String),
183 Semantic(String),
184 Storage(String),
185 Constraint {
189 surface: RelationalErrorSurface,
190 message: String,
191 },
192 Schema {
195 surface: RelationalErrorSurface,
196 message: String,
197 },
198 FileDescriptors(FileDescriptorError),
199 StorageIntegrity(String),
200 WalRecoveryIo {
202 operation: &'static str,
203 kind: std::io::ErrorKind,
204 os_code: Option<i32>,
205 message: String,
206 },
207 UnsupportedStorageFormat(StorageFormatError),
208 PublishOutcomeUnknown {
214 destination: std::path::PathBuf,
215 message: String,
216 },
217 ProjectionBusy,
219 SearchProjectionMismatch {
228 projection: Option<std::path::PathBuf>,
229 message: String,
230 },
231 SearchProjectionRebuildRefused {
237 reason: SearchProjectionRebuildRefusal,
238 target: std::path::PathBuf,
239 message: String,
240 },
241 SearchProjectionEpochAdvanceRefused {
246 reason: SearchProjectionEpochAdvanceRefusal,
247 source_graph_commit_epoch: Option<u64>,
248 target_graph_commit_epoch: u64,
249 message: String,
250 },
251 SearchProjectionOwnershipMismatch {
257 projection: std::path::PathBuf,
258 recorded: Vec<String>,
259 requested: Vec<String>,
260 },
261 SearchProjectionOwnershipMarkerCorrupt {
268 projection: std::path::PathBuf,
269 marker: String,
270 message: String,
271 },
272 Execution(String),
273 ResourceBudgetExceeded(Box<ResourceBudgetError>),
275 ReadBudgetExceeded(ReadBudgetError),
276 WalRecordLimitExceeded(Box<WalRecordLimitError>),
280 GraphExpansionCandidateLimitExceeded {
281 requested: usize,
282 limit: usize,
283 },
284 GraphExpansionPayloadLimitExceeded {
285 requested: usize,
286 limit: usize,
287 },
288 TransactionConflict {
289 read_epoch: u64,
290 committed_epoch: u64,
291 key: String,
292 },
293 TransactionRetryRequired(Box<TransactionRetryError>),
295 TransactionReadDependencyRefused {
297 reason: String,
298 },
299 AppendSequenceExhausted {
300 table: String,
301 watermark: i64,
302 requested: usize,
303 },
304 CapabilityUnavailable {
305 capability: RuntimeCapability,
306 },
307 ReadOnly {
312 operation: &'static str,
313 },
314 BranchCommandUnsupported {
315 command: &'static str,
316 context: &'static str,
317 },
318 BranchBusy {
319 resource: &'static str,
320 },
321 BranchEvidenceBudgetExceeded {
322 resource: &'static str,
323 requested: u64,
324 limit: u64,
325 },
326 BranchReclamationBlocked {
329 branch_id: crate::Uuid,
330 catalog_revision: u64,
331 metadata_revision: u64,
332 cause: Box<HawDBError>,
333 },
334}
335
336impl Display for HawDBError {
337 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
338 match self {
339 HawDBError::Parse(message) => write!(f, "parse error: {message}"),
340 HawDBError::Semantic(message) => write!(f, "semantic error: {message}"),
341 HawDBError::Storage(message) => write!(f, "storage error: {message}"),
342 HawDBError::Constraint { surface, message }
343 | HawDBError::Schema { surface, message } => {
344 write!(f, "{}: {message}", surface.prefix())
345 }
346 HawDBError::FileDescriptors(error) => Display::fmt(error, f),
347 HawDBError::WalRecoveryIo { operation, message, .. } => write!(f, "WAL recovery {operation} failed; retain evidence and retry open: {message}"),
348 HawDBError::StorageIntegrity(message) => {
349 write!(f, "storage integrity error: {message}")
350 }
351 HawDBError::UnsupportedStorageFormat(error) => Display::fmt(error, f),
352 HawDBError::PublishOutcomeUnknown { destination, message } => write!(
353 f,
354 "publication of {} has an unknown outcome; keep the destination and reconcile it before retrying: {message}",
355 destination.display()
356 ),
357 HawDBError::ProjectionBusy => f.write_str("search projection operation is busy"),
358 HawDBError::SearchProjectionMismatch { message, .. } => {
359 write!(f, "storage error: {message}")
360 }
361 HawDBError::SearchProjectionRebuildRefused {
362 reason, message, ..
363 } => write!(
364 f,
365 "search projection rebuild refused ({}): {message}",
366 reason.as_str()
367 ),
368 HawDBError::SearchProjectionEpochAdvanceRefused {
369 reason, message, ..
370 } => write!(
371 f,
372 "search projection epoch advance refused ({}): {message}",
373 reason.as_str()
374 ),
375 HawDBError::SearchProjectionOwnershipMismatch {
376 projection,
377 recorded,
378 requested,
379 } => write!(
380 f,
381 "search projection ownership mismatch: {} records externally owned kinds [{}], open requested [{}]; pass the recorded set or rebuild the projection into a new directory",
382 projection.display(),
383 recorded.join(", "),
384 requested.join(", ")
385 ),
386 HawDBError::SearchProjectionOwnershipMarkerCorrupt {
387 projection,
388 marker,
389 message,
390 } => write!(
391 f,
392 "search projection ownership record {marker} in {} is unreadable ({message}); reopen with the externally owned search kinds reset to rewrite it",
393 projection.display()
394 ),
395 HawDBError::Execution(message) => write!(f, "execution error: {message}"),
396 HawDBError::ResourceBudgetExceeded(error) => write!(f, "execution error: {error}"),
397 HawDBError::ReadBudgetExceeded(error) => write!(f, "execution error: {error}"),
398 HawDBError::GraphExpansionCandidateLimitExceeded { requested, limit } => write!(
399 f,
400 "graph expansion candidate_limit exceeded: requested {requested} rows, limit {limit} rows; configure ExecutionMemoryConfig.graph_expansion_budget.candidate_limit"
401 ),
402 HawDBError::WalRecordLimitExceeded(error) => write!(f, "execution error: {error}"),
403 HawDBError::GraphExpansionPayloadLimitExceeded { requested, limit } => write!(
404 f,
405 "graph expansion payload_byte_limit exceeded: requested {requested} bytes, limit {limit} bytes; configure ExecutionMemoryConfig.graph_expansion_budget.payload_byte_limit"
406 ),
407 HawDBError::TransactionConflict {
408 read_epoch,
409 committed_epoch,
410 key,
411 } => write!(
412 f,
413 "transaction conflict on {key}: transaction read epoch {read_epoch}, conflicting commit epoch {committed_epoch}"
414 ),
415 HawDBError::TransactionRetryRequired(error) => Display::fmt(error, f),
416 HawDBError::AppendSequenceExhausted {
417 table,
418 watermark,
419 requested,
420 } => write!(
421 f,
422 "append commit sequence exhausted for table {table}: watermark={watermark}, requested={requested}"
423 ),
424 HawDBError::TransactionReadDependencyRefused { reason } => {
425 write!(f, "transaction read dependency capture refused: {reason}")
426 }
427 HawDBError::CapabilityUnavailable { capability } => {
428 write!(f, "capability unavailable: {}", capability.as_str())
429 }
430 HawDBError::ReadOnly { operation } => {
431 write!(f, "execution error: {operation} requires a writable handle; this handle is read-only")
432 }
433 HawDBError::BranchCommandUnsupported { command, context } => {
434 write!(f, "{command} is unavailable in {context}")
435 }
436 HawDBError::BranchBusy { resource } => write!(f, "branch is busy: {resource}"),
437 HawDBError::BranchEvidenceBudgetExceeded { resource, requested, limit } => write!(
438 f,
439 "branch quarantine evidence {resource} budget exceeded: requested {requested}, limit {limit}"
440 ),
441 HawDBError::BranchReclamationBlocked {
442 branch_id,
443 catalog_revision,
444 metadata_revision,
445 cause,
446 } => write!(
447 f,
448 "pending branch {branch_id} blocks reclamation at catalog revision {catalog_revision}, branch revision {metadata_revision}: {cause}"
449 ),
450 }
451 }
452}
453
454impl std::error::Error for HawDBError {
455 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
456 match self {
457 Self::FileDescriptors(error) => Some(error),
458 Self::ResourceBudgetExceeded(error) => Some(error.as_ref()),
459 Self::ReadBudgetExceeded(error) => Some(error),
460 Self::WalRecordLimitExceeded(error) => Some(error.as_ref()),
461 Self::TransactionRetryRequired(error) => Some(error.as_ref()),
462 Self::UnsupportedStorageFormat(error) => Some(error),
463 Self::BranchReclamationBlocked { cause, .. } => Some(cause.as_ref()),
464 _ => None,
465 }
466 }
467}
468
469impl HawDBError {
470 pub fn read_budget_exceeded(
471 resource: ReadBudgetResource,
472 limit: usize,
473 message: impl Into<String>,
474 ) -> Self {
475 Self::ReadBudgetExceeded(ReadBudgetError {
476 resource,
477 limit,
478 message: message.into(),
479 })
480 }
481
482 pub fn relational(
484 kind: RelationalErrorKind,
485 surface: RelationalErrorSurface,
486 message: impl Into<String>,
487 ) -> Self {
488 let message = message.into();
489 match kind {
490 RelationalErrorKind::Constraint => Self::Constraint { surface, message },
491 RelationalErrorKind::Schema => Self::Schema { surface, message },
492 }
493 }
494
495 pub const fn relational_error_kind(&self) -> Option<RelationalErrorKind> {
497 match self {
498 Self::Constraint { .. } => Some(RelationalErrorKind::Constraint),
499 Self::Schema { .. } => Some(RelationalErrorKind::Schema),
500 _ => None,
501 }
502 }
503
504 pub const fn relational_error_surface(&self) -> Option<RelationalErrorSurface> {
506 match self {
507 Self::Constraint { surface, .. } | Self::Schema { surface, .. } => Some(*surface),
508 _ => None,
509 }
510 }
511
512 pub fn from_storage_error(error: impl std::error::Error + 'static) -> Self {
514 if let Some(error) = (&error as &dyn std::error::Error).downcast_ref::<Self>() {
515 return error.clone();
516 }
517 if let Some(resource) = file_descriptor_error(&error) {
518 Self::FileDescriptors(resource)
519 } else if let Some(resource) = resource::find_resource_budget_error(&error) {
520 Self::from(resource)
521 } else if let Some(error) = storage_format::find_storage_format_error(&error) {
522 Self::UnsupportedStorageFormat(error)
523 } else if let Some(kind) = find_relational_error_kind(&error) {
524 Self::relational(kind, RelationalErrorSurface::Storage, error.to_string())
525 } else {
526 Self::Storage(error.to_string())
527 }
528 }
529
530 pub fn from_storage_error_with_context(
534 error: impl std::error::Error + 'static,
535 context: &str,
536 ) -> Self {
537 match Self::from_storage_error(error) {
538 Self::Storage(message) => Self::Storage(format!("{context}: {message}")),
539 Self::Constraint {
540 surface: surface @ RelationalErrorSurface::Storage,
541 message,
542 } => Self::Constraint {
543 surface,
544 message: format!("{context}: {message}"),
545 },
546 Self::Schema {
547 surface: surface @ RelationalErrorSurface::Storage,
548 message,
549 } => Self::Schema {
550 surface,
551 message: format!("{context}: {message}"),
552 },
553 error => error,
554 }
555 }
556
557 pub const fn is_retryable_transaction_conflict(&self) -> bool {
560 matches!(
561 self,
562 Self::TransactionConflict { .. } | Self::TransactionRetryRequired(_)
563 )
564 }
565}
566
567pub type Result<T> = std::result::Result<T, HawDBError>;
568
569impl From<ResourceBudgetError> for HawDBError {
570 fn from(error: ResourceBudgetError) -> Self {
571 Self::ResourceBudgetExceeded(Box::new(error))
572 }
573}
574
575impl From<std::io::Error> for HawDBError {
576 fn from(error: std::io::Error) -> Self {
577 Self::from_storage_error(error)
578 }
579}
580
581pub fn file_descriptor_error(
582 error: &(dyn std::error::Error + 'static),
583) -> Option<FileDescriptorError> {
584 let mut current = Some(error);
585 while let Some(error) = current {
586 if let Some(resource) = error.downcast_ref::<FileDescriptorError>() {
587 return Some(resource.clone());
588 }
589 if let Some(HawDBError::FileDescriptors(resource)) = error.downcast_ref::<HawDBError>() {
590 return Some(resource.clone());
591 }
592 if let Some(error) = error.downcast_ref::<std::io::Error>() {
593 if let Some(code) = error.raw_os_error()
594 && descriptor_os_limit(code)
595 {
596 return Some(FileDescriptorError::OsLimit {
597 requested: 1,
598 os_code: Some(code),
599 soft: None,
600 hard: None,
601 });
602 }
603 if let Some(inner) = error.get_ref()
606 && let Some(resource) = file_descriptor_error(inner)
607 {
608 return Some(resource);
609 }
610 }
611 current = error.source();
612 }
613 None
614}
615
616fn descriptor_os_limit(code: i32) -> bool {
617 #[cfg(unix)]
618 {
619 matches!(code, 23 | 24)
620 }
621 #[cfg(windows)]
622 {
623 code == 4
624 }
625 #[cfg(not(any(unix, windows)))]
626 {
627 let _ = code;
628 false
629 }
630}