Skip to main content

systemprompt_database/lifecycle/installation/
lock_conflict.rs

1//! Which schema-phase failures are a transient lock conflict with live
2//! traffic, so the phase is rolled back and retried rather than failing the
3//! install.
4//!
5//! The decision reads the Postgres SQLSTATE wherever the error chain carries
6//! one: `55P03` `lock_not_available` (the phase's `lock_timeout`), `40P01`
7//! `deadlock_detected` (re-creating a trigger while writers hold row locks on
8//! the tables it touches) and `40001` `serialization_failure`. Any other
9//! SQLSTATE is not retried, whatever its message says. Only a chain that
10//! carries no SQLSTATE at all falls back to the server's message text.
11//!
12//! A read-only catalog scan has one further transient failure: an object the
13//! scan listed is dropped by another session before the scan opens it, and
14//! Postgres reports `XX000` with "could not open relation with OID" or
15//! "cache lookup failed for"; or the scan's `ACCESS SHARE` locks meet a
16//! `DROP … CASCADE` taking `ACCESS EXCLUSIVE` in the other order and one
17//! side is the `40P01` victim. Either way [`read_catalog`] reads the scan
18//! again, at most ten times within a second, rather than failing.
19//!
20//! Copyright (c) systemprompt.io — Business Source License 1.1.
21//! See <https://systemprompt.io> for licensing details.
22
23use std::error::Error;
24use std::future::Future;
25use std::time::Duration;
26
27use systemprompt_traits::RepositoryError;
28
29pub const RETRYABLE_SQLSTATES: [&str; 3] = ["55P03", "40P01", "40001"];
30
31const RETRYABLE_MESSAGES: [&str; 3] = [
32    "lock timeout",
33    "deadlock detected",
34    "could not serialize access",
35];
36
37#[must_use]
38pub fn is_retryable_sqlstate(code: &str) -> bool {
39    RETRYABLE_SQLSTATES.contains(&code)
40}
41
42#[must_use]
43pub fn is_retryable_lock_conflict(error: &(dyn Error + 'static)) -> bool {
44    sqlstate_in_chain(error).map_or_else(
45        || message_in_chain(error),
46        |code| is_retryable_sqlstate(&code),
47    )
48}
49
50fn sqlstate_in_chain(error: &(dyn Error + 'static)) -> Option<String> {
51    let mut source: Option<&(dyn Error + 'static)> = Some(error);
52    while let Some(current) = source {
53        if let Some(RepositoryError::Database {
54            sqlstate: Some(code),
55            ..
56        }) = current.downcast_ref::<RepositoryError>()
57        {
58            return Some(code.clone());
59        }
60        if let Some(code) = current
61            .downcast_ref::<sqlx::Error>()
62            .and_then(sqlx::Error::as_database_error)
63            .and_then(sqlx::error::DatabaseError::code)
64        {
65            return Some(code.into_owned());
66        }
67        source = current.source();
68    }
69    None
70}
71
72const CONCURRENT_DROP_MESSAGES: [&str; 2] = [
73    "could not open relation with OID",
74    "cache lookup failed for",
75];
76
77const CATALOG_READ_ATTEMPTS: u32 = 10;
78
79#[must_use]
80pub(crate) fn is_retryable_catalog_read(error: &(dyn Error + 'static)) -> bool {
81    let mut source: Option<&(dyn Error + 'static)> = Some(error);
82    while let Some(current) = source {
83        if let Some(db) = current
84            .downcast_ref::<sqlx::Error>()
85            .and_then(sqlx::Error::as_database_error)
86        {
87            return match db.code().as_deref() {
88                Some("XX000") => CONCURRENT_DROP_MESSAGES
89                    .iter()
90                    .any(|needle| db.message().starts_with(needle)),
91                Some(code) => is_retryable_sqlstate(code),
92                None => false,
93            };
94        }
95        source = current.source();
96    }
97    false
98}
99
100pub(crate) async fn read_catalog<T, E, F, Fut>(what: &'static str, mut read: F) -> Result<T, E>
101where
102    E: Error + 'static,
103    F: FnMut() -> Fut,
104    Fut: Future<Output = Result<T, E>>,
105{
106    let mut attempt = 1;
107    loop {
108        match read().await {
109            Err(error) if attempt < CATALOG_READ_ATTEMPTS && is_retryable_catalog_read(&error) => {
110                tracing::debug!(
111                    attempt,
112                    read = what,
113                    error = %error,
114                    "Catalog read raced concurrent DDL; reading again",
115                );
116                tokio::time::sleep(Duration::from_millis(u64::from(attempt) * 20)).await;
117                attempt += 1;
118            },
119            result => return result,
120        }
121    }
122}
123
124fn message_in_chain(error: &(dyn Error + 'static)) -> bool {
125    let mut source: Option<&(dyn Error + 'static)> = Some(error);
126    while let Some(current) = source {
127        let text = current.to_string();
128        if RETRYABLE_MESSAGES
129            .iter()
130            .any(|needle| text.contains(needle))
131        {
132            return true;
133        }
134        source = current.source();
135    }
136    false
137}