Skip to main content

uqa_execution/
storage_errors.rs

1//
2// Unified Query Algebra
3//
4// Copyright (c) 2023-2026 Cognica, Inc.
5//
6
7//! Typed transaction and resource diagnostics across execution storage capabilities.
8
9use uqa_core::{JsonbKeyError, ValueRetentionError};
10use uqa_sql::SQLError;
11
12/// Keep cancellation, memory limits and serialization conflicts typed across storage reads, observations and mutations.
13pub fn storage_error(action: &str, error: &uqa_storage::StorageBackendError) -> SQLError {
14    use uqa_storage::mvcc::TransactionOutcome;
15    match error.transaction_outcome() {
16        Some(TransactionOutcome::Aborted(transaction)) => {
17            return SQLError::Routine {
18                sqlstate: "25000".into(),
19                message: format!(
20                    "{action} cannot commit transaction {transaction:?}: it was already aborted"
21                ),
22            };
23        }
24        Some(TransactionOutcome::Indeterminate(transaction)) => {
25            return SQLError::Routine {
26                sqlstate: "08007".into(),
27                message: format!("transaction {transaction:?} requires commit resolution: {error}"),
28            };
29        }
30        Some(TransactionOutcome::Committed(_)) => {
31            return SQLError::Internal(format!("{action} failed after storage committed: {error}"));
32        }
33        None => {}
34    }
35    let mut cause: Option<&(dyn std::error::Error + 'static)> = Some(error);
36    while let Some(source) = cause {
37        if matches!(
38            source.downcast_ref::<uqa_storage::mvcc::VersionError>(),
39            Some(uqa_storage::mvcc::VersionError::ReceiptRetentionExhausted { .. })
40        ) {
41            return SQLError::Routine {
42                sqlstate: "53400".into(),
43                message: format!("{action}: {error}"),
44            };
45        }
46        // Transparent Core wrappers forward their inner source and may terminate the error chain themselves.
47        let cancelled = match source.downcast_ref::<uqa_storage::StorageBackendError>() {
48            Some(uqa_storage::StorageBackendError::Cancelled(cancelled)) => Some(cancelled),
49            _ => source.downcast_ref::<uqa_core::QueryCancelled>(),
50        }
51        .or_else(|| match source.downcast_ref::<ValueRetentionError>() {
52            Some(ValueRetentionError::Cancelled(cancelled)) => Some(cancelled),
53            _ => None,
54        })
55        .or_else(|| match source.downcast_ref::<JsonbKeyError>() {
56            Some(JsonbKeyError::Cancelled(cancelled)) => Some(cancelled),
57            _ => None,
58        });
59        if let Some(cancelled) = cancelled {
60            return SQLError::Cancelled(*cancelled);
61        }
62        if matches!(
63            source.downcast_ref::<uqa_storage::StorageBackendError>(),
64            Some(uqa_storage::StorageBackendError::Memory(_))
65        ) || source.is::<uqa_core::memory::MemoryError>()
66            || matches!(
67                source.downcast_ref::<ValueRetentionError>(),
68                Some(ValueRetentionError::Memory(_))
69            )
70            || matches!(
71                source.downcast_ref::<JsonbKeyError>(),
72                Some(JsonbKeyError::Memory(_))
73            )
74        {
75            return SQLError::Routine {
76                sqlstate: "53200".into(),
77                message: format!("{action}: {error}"),
78            };
79        }
80        if matches!(
81            source.downcast_ref::<uqa_storage::mvcc::VersionError>(),
82            Some(
83                uqa_storage::mvcc::VersionError::WriteConflict { .. }
84                    | uqa_storage::mvcc::VersionError::ReadConflict { .. }
85                    | uqa_storage::mvcc::VersionError::SerializationConflict { .. }
86            )
87        ) {
88            return SQLError::Routine {
89                sqlstate: "40001".into(),
90                message: format!("{action} could not serialize storage changes: {error}"),
91            };
92        }
93        if matches!(
94            source.downcast_ref::<uqa_graph::GraphStoreError>(),
95            Some(uqa_graph::GraphStoreError::SerializationFailure(_))
96        ) || matches!(
97            source.downcast_ref::<uqa_graph::cypher::CypherError>(),
98            Some(uqa_graph::cypher::CypherError::SerializationFailure(_))
99        ) {
100            return SQLError::Routine {
101                sqlstate: "40001".into(),
102                message: format!("{action}: {error}"),
103            };
104        }
105        cause = source.source();
106    }
107    uqa_sql::catalog::errors::storage_error(action, error)
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    use uqa_storage::{mvcc::VersionError, StorageBackendError};
114
115    #[test]
116    fn durable_receipt_capacity_preserves_its_configuration_limit_diagnostic() {
117        let error = StorageBackendError::backend(
118            "provider",
119            VersionError::ReceiptRetentionExhausted { limit: 7 },
120        );
121        let sql = storage_error("allocate transaction", &error);
122        assert_eq!(sql.sqlstate(), Some("53400"));
123        assert!(sql.to_string().contains("7 entries"));
124    }
125
126    #[test]
127    fn core_normalization_diagnostics_survive_provider_error_wrappers() {
128        use uqa_core::{memory::MemoryError, QueryCancelled};
129
130        for wrapped in [false, true] {
131            for (error, state) in [
132                (
133                    StorageBackendError::backend(
134                        "decimal",
135                        ValueRetentionError::Memory(MemoryError::SizeOverflow),
136                    ),
137                    "53200",
138                ),
139                (
140                    StorageBackendError::backend(
141                        "decimal",
142                        ValueRetentionError::Cancelled(QueryCancelled::USER_REQUEST),
143                    ),
144                    "57014",
145                ),
146                (
147                    StorageBackendError::backend(
148                        "jsonb",
149                        JsonbKeyError::Memory(MemoryError::SizeOverflow),
150                    ),
151                    "53200",
152                ),
153                (
154                    StorageBackendError::backend(
155                        "jsonb",
156                        JsonbKeyError::Cancelled(QueryCancelled::USER_REQUEST),
157                    ),
158                    "57014",
159                ),
160                (
161                    StorageBackendError::backend("jsonb", JsonbKeyError::InvalidJson),
162                    "XX000",
163                ),
164            ] {
165                let error = if wrapped {
166                    StorageBackendError::backend("provider", error)
167                } else {
168                    error
169                };
170                let actual = storage_error("normalize key", &error);
171                assert_eq!(actual.sqlstate(), Some(state), "{actual}");
172                if state == "57014" {
173                    assert!(matches!(actual, SQLError::Cancelled(_)));
174                }
175            }
176        }
177    }
178
179    #[test]
180    fn completion_evidence_precedes_core_normalization_failures() {
181        use uqa_core::{memory::MemoryError, QueryCancelled};
182        use uqa_storage::mvcc::{CommitFailure, DatabaseId, StorageTransactionId};
183
184        let transaction = StorageTransactionId::new(DatabaseId::from_bytes([1; 16]), 7).unwrap();
185        for source in [
186            StorageBackendError::backend(
187                "decimal",
188                ValueRetentionError::Memory(MemoryError::SizeOverflow),
189            ),
190            StorageBackendError::backend(
191                "jsonb",
192                JsonbKeyError::Cancelled(QueryCancelled::USER_REQUEST),
193            ),
194        ] {
195            let error = StorageBackendError::backend(
196                "receipt",
197                CommitFailure::Indeterminate {
198                    transaction,
199                    source,
200                },
201            );
202            assert_eq!(
203                storage_error("complete transaction", &error).sqlstate(),
204                Some("08007")
205            );
206        }
207    }
208
209    #[test]
210    fn graph_diagnostics_keep_completion_evidence_ahead_of_nested_conflicts() {
211        use uqa_storage::mvcc::{CommitFailure, DatabaseId, StorageTransactionId};
212        let transaction = StorageTransactionId::new(DatabaseId::from_bytes([1; 16]), 7).unwrap();
213        for (error, state) in [
214            (
215                StorageBackendError::backend(
216                    "receipt",
217                    CommitFailure::Indeterminate {
218                        transaction,
219                        source: VersionError::WriteConflict {
220                            mutation: 0,
221                            expected: None,
222                            actual: None,
223                        }
224                        .into_storage_error(),
225                    },
226                ),
227                "08007",
228            ),
229            (
230                VersionError::AlreadyAborted(transaction).into_storage_error(),
231                "25000",
232            ),
233        ] {
234            let cypher =
235                uqa_graph::cypher::CypherError::from(uqa_graph::GraphStoreError::from(error));
236            let error = StorageBackendError::backend("graph", cypher);
237            assert_eq!(
238                storage_error("complete graph", &error).sqlstate(),
239                Some(state)
240            );
241        }
242    }
243
244    #[test]
245    fn graph_and_cypher_keep_transaction_and_resource_diagnostics() {
246        for cypher in [false, true] {
247            for (error, state) in [
248                (
249                    StorageBackendError::from(uqa_core::QueryCancelled::USER_REQUEST),
250                    "57014",
251                ),
252                (
253                    StorageBackendError::backend("fixture", uqa_core::QueryCancelled::USER_REQUEST),
254                    "57014",
255                ),
256                (
257                    StorageBackendError::from(uqa_core::memory::MemoryError::SizeOverflow),
258                    "53200",
259                ),
260                (
261                    StorageBackendError::backend(
262                        "fixture",
263                        uqa_core::memory::MemoryError::SizeOverflow,
264                    ),
265                    "53200",
266                ),
267                (
268                    VersionError::WriteConflict {
269                        mutation: 1,
270                        expected: None,
271                        actual: None,
272                    }
273                    .into_storage_error(),
274                    "40001",
275                ),
276            ] {
277                let graph = uqa_graph::GraphStoreError::from(StorageBackendError::backend(
278                    "fixture", error,
279                ));
280                let error = if cypher {
281                    StorageBackendError::backend(
282                        "cypher",
283                        uqa_graph::cypher::CypherError::from(graph),
284                    )
285                } else {
286                    StorageBackendError::backend("graph", graph)
287                };
288                let actual = storage_error("execute graph", &error);
289                assert_eq!(actual.sqlstate(), Some(state), "{actual}");
290                if state == "57014" {
291                    assert!(matches!(actual, SQLError::Cancelled(_)));
292                }
293            }
294        }
295        for error in [
296            StorageBackendError::backend(
297                "graph",
298                uqa_graph::GraphStoreError::SerializationFailure("stale entity".into()),
299            ),
300            StorageBackendError::backend(
301                "cypher",
302                uqa_graph::cypher::CypherError::SerializationFailure("stale entity".into()),
303            ),
304        ] {
305            assert_eq!(
306                storage_error("graph mutation", &error).sqlstate(),
307                Some("40001")
308            );
309        }
310    }
311
312    #[test]
313    fn transaction_diagnostics_survive_provider_error_wrappers() {
314        for wrapped in [false, true] {
315            let errors = [
316                (
317                    StorageBackendError::from(uqa_core::QueryCancelled::USER_REQUEST),
318                    "57014",
319                ),
320                (
321                    StorageBackendError::from(uqa_core::memory::MemoryError::SizeOverflow),
322                    "53200",
323                ),
324                (
325                    VersionError::WriteConflict {
326                        mutation: 0,
327                        expected: None,
328                        actual: None,
329                    }
330                    .into_storage_error(),
331                    "40001",
332                ),
333                (
334                    VersionError::ReadConflict {
335                        dependency: 0,
336                        expected: None,
337                        actual: None,
338                    }
339                    .into_storage_error(),
340                    "40001",
341                ),
342                (
343                    VersionError::SerializationConflict {
344                        transaction: uqa_storage::mvcc::SerializableTransactionId::new(
345                            uqa_storage::mvcc::DatabaseId::from_bytes([1; 16]),
346                            [2; 16],
347                            1,
348                        )
349                        .unwrap(),
350                    }
351                    .into_storage_error(),
352                    "40001",
353                ),
354                (
355                    StorageBackendError::backend(
356                        "fixture",
357                        SQLError::Routine {
358                            sqlstate: "22003".into(),
359                            message: "identity out of range".into(),
360                        },
361                    ),
362                    "22003",
363                ),
364            ];
365            for (error, state) in errors {
366                let error = if wrapped {
367                    StorageBackendError::backend("wrapped", error)
368                } else {
369                    error
370                };
371                let result = storage_error("reserve identity", &error);
372                assert_eq!(result.sqlstate(), Some(state), "{result}");
373                if state == "57014" {
374                    assert!(matches!(result, SQLError::Cancelled(_)));
375                }
376            }
377        }
378        let error = storage_error(
379            "observe identity",
380            &StorageBackendError::Other("unavailable".into()),
381        );
382        assert_eq!(error.sqlstate(), Some("XX000"));
383        assert!(error.to_string().contains("observe identity"));
384    }
385}