hyprstream_ledger/errors.rs
1//! The ledger error vocabulary.
2//!
3//! Errors are **data** (no wrapped source types) so an [`crate::Outcome`] is
4//! `Clone + PartialEq + Eq` and a replay can be asserted byte-identical to the
5//! original — the property the idempotency proptests lean on.
6
7use serde::{Deserialize, Serialize};
8use thiserror::Error;
9
10use crate::types::{AccountId, TransferId, UnitId};
11
12/// Every way a ledger operation can fail. All variants are deterministic
13/// functions of `(current state, op)` so a replay reproduces them exactly.
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Error)]
15pub enum LedgerError {
16 /// A referenced account does not exist.
17 #[error("unknown account {0:?}")]
18 UnknownAccount(AccountId),
19
20 /// The transfer's unit does not match a touched account's unit (INV-1(b)).
21 #[error("unit mismatch: transfer unit {transfer:?} != account unit {account:?}")]
22 UnitMismatch {
23 /// The unit named on the transfer.
24 transfer: UnitId,
25 /// The unit denormalized on the account.
26 account: UnitId,
27 },
28
29 /// `open_account` was called for an existing id but with a different unit.
30 #[error("account {id:?} already exists with a different unit")]
31 AccountUnitConflict {
32 /// The account id whose unit conflicts.
33 id: AccountId,
34 },
35
36 /// The debit account cannot cover the amount once pending holds are counted
37 /// (overdraft floor, plan §2b.1).
38 #[error("insufficient balance on {account:?}: need {needed}, available {available}")]
39 InsufficientBalance {
40 /// The debit account.
41 account: AccountId,
42 /// Amount requested.
43 needed: u128,
44 /// Amount actually available.
45 available: u128,
46 },
47
48 /// Amount was zero (transfers must move a positive amount).
49 #[error("amount must be greater than zero")]
50 ZeroAmount,
51
52 /// A transfer named the same account on both sides. Double-entry requires two
53 /// distinct accounts (the TigerBeetle `accounts_must_be_different` rule) — a
54 /// self-transfer is meaningless and would collapse two deltas onto one row.
55 #[error("debit and credit accounts must differ ({0:?})")]
56 AccountsMustDiffer(AccountId),
57
58 /// A partial post named an amount larger than the reservation.
59 #[error("post amount {requested} exceeds reserved {reserved}")]
60 PostExceedsReservation {
61 /// Requested post amount.
62 requested: u128,
63 /// The reserved amount.
64 reserved: u128,
65 },
66
67 /// `credit` was called with a debit side that is not an issuer-liability
68 /// account (INV-1: issuance must debit the issuer's own liability).
69 #[error("issuance debit account {0:?} is not an issuer-liability account")]
70 NotIssuerLiability(AccountId),
71
72 /// A second-phase op named a pending id that does not exist.
73 #[error("unknown pending transfer {0:?}")]
74 UnknownPendingTransfer(TransferId),
75
76 /// The reservation's deadline passed before this second phase committed
77 /// (plan §2b.5 — the loser of the expiry-vs-post race).
78 #[error("pending transfer {0:?} expired")]
79 PendingTransferExpired(TransferId),
80
81 /// The reservation was already posted by an earlier second phase.
82 #[error("pending transfer {0:?} already posted")]
83 PendingTransferAlreadyPosted(TransferId),
84
85 /// The reservation was already voided by an earlier second phase.
86 #[error("pending transfer {0:?} already voided")]
87 PendingTransferAlreadyVoided(TransferId),
88
89 /// A reservation timeout was outside the permitted `[1s, 24h]` band.
90 #[error("reservation timeout {0}s out of bounds")]
91 TimeoutOutOfBounds(u32),
92
93 /// A replay arrived for a `TransferId` whose outcome row was already pruned
94 /// past the retention horizon (plan §2c). Distinguishable from "never seen"
95 /// so a caller escalates rather than blindly re-executing. (MemLedger never
96 /// prunes, so it never returns this; retention lands with a later work item.)
97 #[error("transfer id {0:?} is older than the outcome-retention horizon")]
98 IdTooOld(TransferId),
99
100 /// A replay was detected. The reference contract is **transparent replay**
101 /// (the stored [`crate::Outcome`] is returned verbatim), so MemLedger does
102 /// not surface this; it exists for backends that prefer an explicit signal,
103 /// carrying the original outcome.
104 #[error("duplicate transfer id {id:?}")]
105 DuplicateTransferId {
106 /// The replayed id.
107 id: TransferId,
108 /// The original recorded outcome, boxed to keep the enum small.
109 original: Box<crate::types::Outcome>,
110 },
111
112 /// An internal invariant/encoding failure. Fail-closed: the op is rejected
113 /// without mutating state, and is retryable.
114 #[error("internal ledger error: {0}")]
115 Internal(String),
116
117 /// Another process already holds the single-writer lease for this cell.
118 ///
119 /// A durable backend admits **exactly one** writer per cell for the whole
120 /// instance lifetime (the premise [`crate::engine`] is written against).
121 /// A second instance is rejected at construction rather than allowed to
122 /// stage from its own mirror.
123 #[error("writer lease for this cell is held by another instance (epoch {epoch})")]
124 WriterLeaseHeld {
125 /// The epoch of the lease currently recorded in the database.
126 epoch: u64,
127 },
128
129 /// This instance's writer lease was taken over by another instance.
130 ///
131 /// The fencing epoch recorded in the database no longer matches the epoch
132 /// this instance acquired, so its mirror may be arbitrarily stale. The op
133 /// is refused and the instance poisons itself — it never writes again.
134 #[error("writer lease lost: acquired epoch {expected}, database now at {found}")]
135 WriterLeaseLost {
136 /// The epoch this instance acquired at startup.
137 expected: u64,
138 /// The epoch currently recorded in the database.
139 found: u64,
140 },
141
142 /// The in-memory mirror did not describe the state that produced the
143 /// committed head, so the staged deltas cannot be persisted.
144 ///
145 /// Absolute account counters are only meaningful relative to the state
146 /// they were computed from. Committing deltas staged against a stale
147 /// mirror is exactly the lost-update bug, so the commit is refused inside
148 /// the ordering boundary instead.
149 #[error("mirror stale: staged against seq {mirror_seq}, database head is seq {db_seq}")]
150 MirrorStale {
151 /// The head sequence the mirror staged against.
152 mirror_seq: u64,
153 /// The head sequence actually found in the database.
154 db_seq: u64,
155 },
156
157 /// The backend refused the op because a prior integrity failure poisoned
158 /// this instance. Fail-closed and terminal: the process must restart (and
159 /// rebuild from the journal) to write again.
160 #[error("ledger instance poisoned, refusing all writes: {0}")]
161 Poisoned(String),
162
163 /// A persisted row could not be decoded under the strict representation.
164 ///
165 /// 128-bit ids and amounts are exactly 16 bytes; anything else is a
166 /// legacy or corrupt row. Decoding fails closed rather than truncating or
167 /// substituting zero, which would silently alias distinct ids.
168 #[error("corrupt persisted row: {0}")]
169 CorruptRow(String),
170
171 /// The database schema version is not one this build can serve.
172 #[error("incompatible ledger schema: {0}")]
173 SchemaIncompatible(String),
174
175 /// An issuance was attempted without a valid authorization.
176 ///
177 /// Minting is the only supply-growing operation (INV-1), so it is gated on
178 /// a verified, transfer-bound capability rather than on the caller merely
179 /// holding a backend. See [`crate::mint`].
180 #[error("issuance not authorized: {0}")]
181 MintNotAuthorized(String),
182}