hawdb_core/error/
transaction.rs1use std::fmt::{Display, Formatter};
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum TransactionRetryReason {
20 SnapshotChanged {
21 read_epoch: u64,
22 committed_epoch: u64,
23 },
24 Deadlock {
25 wait_cycle: Vec<u64>,
26 },
27}
28
29#[derive(Debug, Clone, PartialEq, Eq)]
31pub struct TransactionRetryError {
32 pub transaction_id: u64,
33 pub reason: TransactionRetryReason,
34 pub already_aborted: bool,
36}
37
38impl Display for TransactionRetryError {
39 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
40 let transaction_id = self.transaction_id;
41 if self.already_aborted {
42 write!(f, "concurrent transaction {transaction_id} is aborted: ")?;
43 }
44 match &self.reason {
45 TransactionRetryReason::SnapshotChanged { read_epoch, committed_epoch } => write!(
46 f,
47 "pessimistic transaction {transaction_id} cannot acquire a new lock after its snapshot changed from commit epoch {read_epoch} to {committed_epoch}; retry the transaction"
48 ),
49 TransactionRetryReason::Deadlock { wait_cycle } => {
50 write!(f, "deadlock detected; transaction {transaction_id} selected as victim; wait cycle: ")?;
51 for (index, transaction) in wait_cycle.iter().enumerate() {
52 if index != 0 {
53 write!(f, " -> ")?;
54 }
55 write!(f, "{transaction}")?;
56 }
57 Ok(())
58 }
59 }
60 }
61}
62
63impl std::error::Error for TransactionRetryError {}
64
65#[cfg(test)]
66mod tests {
67 use super::*;
68 use crate::HawDBError;
69
70 #[test]
71 fn transaction_retry_classification_uses_typed_causes_only() {
72 for reason in [
73 TransactionRetryReason::SnapshotChanged {
74 read_epoch: 1,
75 committed_epoch: 2,
76 },
77 TransactionRetryReason::Deadlock {
78 wait_cycle: vec![1, 2, 1],
79 },
80 ] {
81 for already_aborted in [false, true] {
82 let error = HawDBError::TransactionRetryRequired(Box::new(TransactionRetryError {
83 transaction_id: 1,
84 reason: reason.clone(),
85 already_aborted,
86 }));
87 assert!(error.is_retryable_transaction_conflict());
88 assert_eq!(error.to_string().contains("is aborted"), already_aborted);
89 }
90 }
91 assert!(HawDBError::TransactionConflict {
92 read_epoch: 1,
93 committed_epoch: 2,
94 key: "row".into(),
95 }
96 .is_retryable_transaction_conflict());
97 for error in [
98 HawDBError::Execution("deadlock detected; retry the transaction".into()),
99 HawDBError::Execution("transaction lock wait timed out".into()),
100 HawDBError::Execution("concurrent lock manager is poisoned".into()),
101 HawDBError::Storage("snapshot changed; retry the transaction".into()),
102 HawDBError::Semantic("invalid query".into()),
103 ] {
104 assert!(!error.is_retryable_transaction_conflict());
105 }
106 }
107}