Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(personhog): give database timeouts their own status and label (#116549)

Phil Haackd39bb341f525
diff --git a/rust/personhog-common/src/grpc.rs b/rust/personhog-common/src/grpc.rs
index e31fce12313a..e29aba9e1ca1 100644
--- a/rust/personhog-common/src/grpc.rs
+++ b/rust/personhog-common/src/grpc.rs
@@ -13,9 +13,12 @@ use pin_project::{pin_project, pinned_drop};
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
use tokio::net::{TcpListener, TcpStream};
use tokio::task::futures::TaskLocalFuture;
+use tonic::metadata::MetadataValue;
use tonic::transport::server::Connected;
use tower::{Layer, Service};
+use crate::storage_error::TimeoutKind;
+
// ============================================================
// Client name extraction
// ============================================================
@@ -37,6 +40,20 @@ pub const SEMANTIC_REFUSAL_METADATA_KEY: &str = "x-semantic-refusal";
/// Never set where the request may have been applied.
pub const NOT_APPLIED_HEADER: &str = "x-not-applied";
+/// Marks a DEADLINE_EXCEEDED that a Postgres timeout caused, rather than an
+/// expired gRPC deadline. The value names the setting that fired:
+/// `statement_timeout` or `lock_timeout`.
+pub const DB_TIMEOUT_METADATA_KEY: &str = "x-db-timeout";
+
+pub fn db_timeout_status(message: impl Into<String>, kind: TimeoutKind) -> tonic::Status {
+ let mut status = tonic::Status::deadline_exceeded(message.into());
+ status.metadata_mut().insert(
+ DB_TIMEOUT_METADATA_KEY,
+ MetadataValue::from_static(kind.as_str()),
+ );
+ status
+}
+
/// Build a semantic refusal. The reason is a short slug used as a metric
/// label.
pub fn semantic_refusal(message: impl Into<String>, reason: &'static str) -> tonic::Status {
diff --git a/rust/personhog-common/src/storage_error.rs b/rust/personhog-common/src/storage_error.rs
index 4fc9fe747365..09cafc0aa0c4 100644
--- a/rust/personhog-common/src/storage_error.rs
+++ b/rust/personhog-common/src/storage_error.rs
@@ -5,7 +5,7 @@
use thiserror::Error;
-#[derive(Error, Debug)]
+#[derive(Error, Debug, Clone)]
pub enum StorageError {
/// Connection-level errors (network, TLS, authentication)
#[error("Database connection error: {0}")]
@@ -15,6 +15,11 @@ pub enum StorageError {
#[error("Database query error: {0}")]
Query(String),
+ /// Postgres cancelled a statement because a timeout fired. That
+ /// statement's transaction rolled back.
+ #[error("Database {}: {message}", .kind.as_str())]
+ Timeout { kind: TimeoutKind, message: String },
+
/// Connection pool exhausted or closed
#[error("Database pool exhausted")]
PoolExhausted,
@@ -28,14 +33,41 @@ pub enum StorageError {
FailedPrecondition(String),
}
-impl Clone for StorageError {
- fn clone(&self) -> Self {
+impl StorageError {
+ /// The `error_type` metric label.
+ pub fn error_type(&self) -> &'static str {
match self {
- Self::Connection(msg) => Self::Connection(msg.clone()),
- Self::Query(msg) => Self::Query(msg.clone()),
- Self::PoolExhausted => Self::PoolExhausted,
- Self::NotFound(msg) => Self::NotFound(msg.clone()),
- Self::FailedPrecondition(msg) => Self::FailedPrecondition(msg.clone()),
+ Self::Connection(_) => "connection",
+ Self::Query(_) => "query",
+ Self::Timeout { kind, .. } => kind.as_str(),
+ Self::PoolExhausted => "pool_exhausted",
+ Self::NotFound(_) => "not_found",
+ Self::FailedPrecondition(_) => "failed_precondition",
+ }
+ }
+}
+
+#[derive(Clone, Copy, Debug)]
+pub enum TimeoutKind {
+ Statement,
+ Lock,
+}
+
+impl TimeoutKind {
+ /// SQLSTATE 57014 also covers a `pg_cancel_backend` call, which this
+ /// reports as a statement timeout.
+ fn from_sqlstate(code: Option<&str>) -> Option<Self> {
+ match code {
+ Some("57014") => Some(Self::Statement),
+ Some("55P03") => Some(Self::Lock),
+ _ => None,
+ }
+ }
+
+ pub(crate) fn as_str(self) -> &'static str {
+ match self {
+ Self::Statement => "statement_timeout",
+ Self::Lock => "lock_timeout",
}
}
}
@@ -47,9 +79,78 @@ impl From<sqlx::Error> for StorageError {
sqlx::Error::Io(_) | sqlx::Error::Tls(_) => StorageError::Connection(err.to_string()),
+ sqlx::Error::Database(db) => match TimeoutKind::from_sqlstate(db.code().as_deref()) {
+ Some(kind) => StorageError::Timeout {
+ kind,
+ message: err.to_string(),
+ },
+ None => StorageError::Query(err.to_string()),
+ },
+
_ => StorageError::Query(err.to_string()),
}
}
}
pub type StorageResult<T> = Result<T, StorageError>;
+
+#[cfg(test)]
+mod tests {
+ use std::borrow::Cow;
+ use std::fmt;
+
+ use rstest::rstest;
+
+ use super::*;
+
+ #[derive(Debug)]
+ struct FakePgError(&'static str);
+
+ impl fmt::Display for FakePgError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "fake database error ({})", self.0)
+ }
+ }
+
+ impl std::error::Error for FakePgError {}
+
+ impl sqlx::error::DatabaseError for FakePgError {
+ fn message(&self) -> &str {
+ "fake database error"
+ }
+
+ fn code(&self) -> Option<Cow<'_, str>> {
+ Some(Cow::Borrowed(self.0))
+ }
+
+ fn as_error(&self) -> &(dyn std::error::Error + Send + Sync + 'static) {
+ self
+ }
+
+ fn as_error_mut(&mut self) -> &mut (dyn std::error::Error + Send + Sync + 'static) {
+ self
+ }
+
+ fn into_error(self: Box<Self>) -> Box<dyn std::error::Error + Send + Sync + 'static> {
+ self
+ }
+
+ fn kind(&self) -> sqlx::error::ErrorKind {
+ sqlx::error::ErrorKind::Other
+ }
+ }
+
+ #[rstest]
+ #[case::statement_timeout("57014", "statement_timeout")]
+ #[case::lock_timeout("55P03", "lock_timeout")]
+ #[case::unique_violation("23505", "query")]
+ #[case::deadlock("40P01", "query")]
+ fn database_error_is_classified_by_sqlstate(
+ #[case] sqlstate: &'static str,
+ #[case] expected_error_type: &str,
+ ) {
+ let err = StorageError::from(sqlx::Error::Database(Box::new(FakePgError(sqlstate))));
+
+ assert_eq!(err.error_type(), expected_error_type);
+ }
+}
diff --git a/rust/personhog-identity/src/service/error.rs b/rust/personhog-identity/src/service/error.rs
index 2945543b4928..bc94f475f2c6 100644
--- a/rust/personhog-identity/src/service/error.rs
+++ b/rust/personhog-identity/src/service/error.rs
@@ -1,4 +1,4 @@
-use personhog_common::grpc::current_client_name;
+use personhog_common::grpc::{current_client_name, db_timeout_status};
use tonic::Status;
use tracing::error;
@@ -8,17 +8,10 @@ const STORAGE_ERRORS_TOTAL: &str = "personhog_identity_storage_errors_total";
pub fn log_and_convert_error(err: storage::StorageError, operation: &str) -> Status {
let client = current_client_name();
- let error_type = match &err {
- storage::StorageError::Connection(_) => "connection",
- storage::StorageError::PoolExhausted => "pool_exhausted",
- storage::StorageError::Query(_) => "query",
- storage::StorageError::NotFound(_) => "not_found",
- storage::StorageError::FailedPrecondition(_) => "failed_precondition",
- };
common_metrics::inc(
STORAGE_ERRORS_TOTAL,
&[
- ("error_type".to_string(), error_type.to_string()),
+ ("error_type".to_string(), err.error_type().to_string()),
("operation".to_string(), operation.to_string()),
("client".to_string(), client.to_string()),
],
@@ -37,6 +30,10 @@ pub fn log_and_convert_error(err: storage::StorageError, operation: &str) -> Sta
error!(operation, error = %msg, "Database query error");
Status::internal(format!("Database error: {msg}"))
}
+ storage::StorageError::Timeout { kind, .. } => {
+ error!(operation, error = %err, "Database timeout");
+ db_timeout_status(err.to_string(), kind)
+ }
storage::StorageError::NotFound(msg) => Status::not_found(msg),
storage::StorageError::FailedPrecondition(msg) => Status::failed_precondition(msg),
}
diff --git a/rust/personhog-replica/src/service/error.rs b/rust/personhog-replica/src/service/error.rs
index 0b41a1153f57..2b654e6da0dc 100644
--- a/rust/personhog-replica/src/service/error.rs
+++ b/rust/personhog-replica/src/service/error.rs
@@ -1,4 +1,4 @@
-use personhog_common::grpc::current_client_name;
+use personhog_common::grpc::{current_client_name, db_timeout_status};
use tonic::Status;
use tracing::{error, warn};
@@ -7,60 +7,38 @@ use crate::storage;
const STORAGE_ERRORS_TOTAL: &str = "personhog_replica_storage_errors_total";
pub fn log_and_convert_error(err: storage::StorageError, operation: &str) -> Status {
- let client = current_client_name();
- match &err {
+ if !matches!(err, storage::StorageError::NotFound(_)) {
+ common_metrics::inc(
+ STORAGE_ERRORS_TOTAL,
+ &[
+ ("error_type".to_string(), err.error_type().to_string()),
+ ("operation".to_string(), operation.to_string()),
+ ("client".to_string(), current_client_name().to_string()),
+ ],
+ 1,
+ );
+ }
+ match err {
storage::StorageError::Connection(msg) => {
error!(operation, error = %msg, "Database connection error");
- common_metrics::inc(
- STORAGE_ERRORS_TOTAL,
- &[
- ("error_type".to_string(), "connection".to_string()),
- ("operation".to_string(), operation.to_string()),
- ("client".to_string(), client.to_string()),
- ],
- 1,
- );
Status::unavailable(format!("Database unavailable: {msg}"))
}
storage::StorageError::PoolExhausted => {
error!(operation, "Database pool exhausted");
- common_metrics::inc(
- STORAGE_ERRORS_TOTAL,
- &[
- ("error_type".to_string(), "pool_exhausted".to_string()),
- ("operation".to_string(), operation.to_string()),
- ("client".to_string(), client.to_string()),
- ],
- 1,
- );
Status::unavailable("Database pool exhausted")
}
storage::StorageError::Query(msg) => {
error!(operation, error = %msg, "Database query error");
- common_metrics::inc(
- STORAGE_ERRORS_TOTAL,
- &[
- ("error_type".to_string(), "query".to_string()),
- ("operation".to_string(), operation.to_string()),
- ("client".to_string(), client.to_string()),
- ],
- 1,
- );
Status::internal(format!("Database error: {msg}"))
}
- storage::StorageError::NotFound(msg) => Status::not_found(msg.clone()),
+ storage::StorageError::Timeout { kind, .. } => {
+ error!(operation, error = %err, "Database timeout");
+ db_timeout_status(err.to_string(), kind)
+ }
+ storage::StorageError::NotFound(msg) => Status::not_found(msg),
storage::StorageError::FailedPrecondition(msg) => {
warn!(operation, error = %msg, "Failed precondition");
- common_metrics::inc(
- STORAGE_ERRORS_TOTAL,
- &[
- ("error_type".to_string(), "failed_precondition".to_string()),
- ("operation".to_string(), operation.to_string()),
- ("client".to_string(), client.to_string()),
- ],
- 1,
- );
- Status::failed_precondition(msg.clone())
+ Status::failed_precondition(msg)
}
}
}
@@ -68,22 +46,54 @@ pub fn log_and_convert_error(err: storage::StorageError, operation: &str) -> Sta
#[cfg(test)]
mod tests {
use metrics_util::debugging::{DebugValue, DebuggingRecorder};
+ use personhog_common::grpc::DB_TIMEOUT_METADATA_KEY;
+ use rstest::rstest;
use tonic::Code;
use super::*;
- #[test]
- fn failed_precondition_is_counted() {
+ fn timeout(kind: storage::TimeoutKind) -> storage::StorageError {
+ storage::StorageError::Timeout {
+ kind,
+ message: "canceling statement".to_string(),
+ }
+ }
+
+ #[rstest]
+ #[case::failed_precondition(
+ storage::StorageError::FailedPrecondition("persons are claimed".to_string()),
+ Code::FailedPrecondition,
+ "failed_precondition"
+ )]
+ #[case::statement_timeout(
+ timeout(storage::TimeoutKind::Statement),
+ Code::DeadlineExceeded,
+ "statement_timeout"
+ )]
+ #[case::lock_timeout(
+ timeout(storage::TimeoutKind::Lock),
+ Code::DeadlineExceeded,
+ "lock_timeout"
+ )]
+ fn storage_error_is_counted_by_type(
+ #[case] err: storage::StorageError,
+ #[case] expected_code: Code,
+ #[case] expected_error_type: &str,
+ ) {
let recorder = DebuggingRecorder::new();
let snapshotter = recorder.snapshotter();
let _guard = metrics::set_default_local_recorder(&recorder);
- let status = log_and_convert_error(
- storage::StorageError::FailedPrecondition("persons are claimed".to_string()),
- "delete_persons",
- );
+ let status = log_and_convert_error(err, "delete_persons");
- assert_eq!(status.code(), Code::FailedPrecondition);
+ assert_eq!(status.code(), expected_code);
+ assert_eq!(
+ status
+ .metadata()
+ .get(DB_TIMEOUT_METADATA_KEY)
+ .and_then(|v| v.to_str().ok()),
+ (expected_code == Code::DeadlineExceeded).then_some(expected_error_type)
+ );
let counted: u64 = snapshotter
.snapshot()
.into_vec()
@@ -93,7 +103,7 @@ mod tests {
&& key
.key()
.labels()
- .any(|l| l.key() == "error_type" && l.value() == "failed_precondition")
+ .any(|l| l.key() == "error_type" && l.value() == expected_error_type)
})
.map(|(_, _, _, value)| match value {
DebugValue::Counter(n) => n,
diff --git a/rust/personhog-replica/src/storage/error.rs b/rust/personhog-replica/src/storage/error.rs
index b4aa008dbc11..c2aa2cb61fdc 100644
--- a/rust/personhog-replica/src/storage/error.rs
+++ b/rust/personhog-replica/src/storage/error.rs
@@ -1 +1 @@
-pub use personhog_common::storage_error::{StorageError, StorageResult};
+pub use personhog_common::storage_error::{StorageError, StorageResult, TimeoutKind};
diff --git a/rust/personhog-replica/src/storage/mod.rs b/rust/personhog-replica/src/storage/mod.rs
index dc14220ea2c3..11eb194c8efd 100644
--- a/rust/personhog-replica/src/storage/mod.rs
+++ b/rust/personhog-replica/src/storage/mod.rs
@@ -3,7 +3,7 @@ pub mod postgres;
pub mod traits;
pub mod types;
-pub use error::{StorageError, StorageResult};
+pub use error::{StorageError, StorageResult, TimeoutKind};
pub use types::{
CohortMembership, DeletePersonsOutcome, DistinctIdMapping, DistinctIdWithVersion, Group,
diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rs
index e23af344ec12..45205de5abbf 100644
--- a/rust/personhog-replica/tests/storage_tests.rs
+++ b/rust/personhog-replica/tests/storage_tests.rs
@@ -4,8 +4,8 @@ use common::TestContext;
use metrics_util::debugging::{DebugValue, DebuggingRecorder, Snapshotter};
use personhog_replica::storage::postgres::ConsistencyLevel;
use personhog_replica::storage::{
- GroupKey, PersonVersionFloorResult, StorageError, TombstoneTarget, TombstonedDeleteOutcome,
- TombstonedDistinctId, TombstonedPerson, VersionFloorOutcome,
+ GroupKey, PersonVersionFloorResult, StorageError, TimeoutKind, TombstoneTarget,
+ TombstonedDeleteOutcome, TombstonedDistinctId, TombstonedPerson, VersionFloorOutcome,
};
use rand::Rng;
use rstest::rstest;
@@ -1628,7 +1628,10 @@ async fn test_upsert_hash_key_overrides_fails_fast_behind_a_locked_person_row()
assert!(
matches!(
&result,
- Err(personhog_replica::storage::StorageError::Query(msg)) if msg.contains("statement timeout")
+ Err(StorageError::Timeout {
+ kind: TimeoutKind::Statement,
+ ..
+ })
),
"expected a statement timeout, got {result:?}"
);
@@ -4275,7 +4278,13 @@ async fn test_primary_writes_give_up_when_a_writer_holds_the_row(#[case] write:
};
assert!(
- matches!(result, Err(StorageError::Query(_))),
+ matches!(
+ result,
+ Err(StorageError::Timeout {
+ kind: TimeoutKind::Lock,
+ ..
+ })
+ ),
"expected the lock_timeout to fail the request, got {result:?}"
);
assert!(started.elapsed() < Duration::from_secs(20));