Skip to main content

hawdb_core/error/
transaction.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 std::fmt::{Display, Formatter};
16
17/// The `key` of the retryable `HawDBError::TransactionConflict` returned when a
18/// transaction that read `graph_change_commit_epoch()` for compare-and-publish
19/// commits after a graph-changing commit was published past its snapshot.
20/// The value is stable; embedded hosts match on it (or use
21/// `HawDBError::is_graph_change_conflict`) instead of a hard-coded string.
22pub const GRAPH_CHANGE_COMMIT_EPOCH_CONFLICT_KEY: &str = "graph_change_commit_epoch";
23
24/// A condition that requires retrying the complete transaction with a fresh snapshot.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum TransactionRetryReason {
27    SnapshotChanged {
28        read_epoch: u64,
29        committed_epoch: u64,
30    },
31    Deadlock {
32        wait_cycle: Vec<u64>,
33    },
34}
35
36/// Preserves the original retry cause on subsequent calls to an aborted transaction.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct TransactionRetryError {
39    pub transaction_id: u64,
40    pub reason: TransactionRetryReason,
41    /// This call encountered a transaction that had already aborted.
42    pub already_aborted: bool,
43}
44
45impl Display for TransactionRetryError {
46    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
47        let transaction_id = self.transaction_id;
48        if self.already_aborted {
49            write!(f, "concurrent transaction {transaction_id} is aborted: ")?;
50        }
51        match &self.reason {
52            TransactionRetryReason::SnapshotChanged { read_epoch, committed_epoch } => write!(
53                f,
54                "pessimistic transaction {transaction_id} cannot acquire a new lock after its snapshot changed from commit epoch {read_epoch} to {committed_epoch}; retry the transaction"
55            ),
56            TransactionRetryReason::Deadlock { wait_cycle } => {
57                write!(f, "deadlock detected; transaction {transaction_id} selected as victim; wait cycle: ")?;
58                for (index, transaction) in wait_cycle.iter().enumerate() {
59                    if index != 0 {
60                        write!(f, " -> ")?;
61                    }
62                    write!(f, "{transaction}")?;
63                }
64                Ok(())
65            }
66        }
67    }
68}
69
70impl std::error::Error for TransactionRetryError {}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use crate::HawDBError;
76
77    #[test]
78    fn transaction_retry_classification_uses_typed_causes_only() {
79        for reason in [
80            TransactionRetryReason::SnapshotChanged {
81                read_epoch: 1,
82                committed_epoch: 2,
83            },
84            TransactionRetryReason::Deadlock {
85                wait_cycle: vec![1, 2, 1],
86            },
87        ] {
88            for already_aborted in [false, true] {
89                let error = HawDBError::TransactionRetryRequired(Box::new(TransactionRetryError {
90                    transaction_id: 1,
91                    reason: reason.clone(),
92                    already_aborted,
93                }));
94                assert!(error.is_retryable_transaction_conflict());
95                assert_eq!(error.to_string().contains("is aborted"), already_aborted);
96            }
97        }
98        assert!(HawDBError::TransactionConflict {
99            read_epoch: 1,
100            committed_epoch: 2,
101            key: "row".into(),
102        }
103        .is_retryable_transaction_conflict());
104        let graph_change = HawDBError::TransactionConflict {
105            read_epoch: 1,
106            committed_epoch: 2,
107            key: GRAPH_CHANGE_COMMIT_EPOCH_CONFLICT_KEY.into(),
108        };
109        assert_eq!(
110            GRAPH_CHANGE_COMMIT_EPOCH_CONFLICT_KEY,
111            "graph_change_commit_epoch"
112        );
113        assert!(graph_change.is_graph_change_conflict());
114        assert!(graph_change.is_retryable_transaction_conflict());
115        assert!(!HawDBError::TransactionConflict {
116            read_epoch: 1,
117            committed_epoch: 2,
118            key: "row".into(),
119        }
120        .is_graph_change_conflict());
121        for error in [
122            HawDBError::Execution("deadlock detected; retry the transaction".into()),
123            HawDBError::Execution("transaction lock wait timed out".into()),
124            HawDBError::Execution("concurrent lock manager is poisoned".into()),
125            HawDBError::Storage("snapshot changed; retry the transaction".into()),
126            HawDBError::Semantic("invalid query".into()),
127        ] {
128            assert!(!error.is_retryable_transaction_conflict());
129        }
130    }
131}