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.

fix(flags): limit how long the replica override upsert waits on a lock (#113497)

Phil Haack2304e4e42e0d
diff --git a/rust/personhog-replica/src/storage/postgres/feature_flag.rs b/rust/personhog-replica/src/storage/postgres/feature_flag.rs
index bd18b6167aa3..d01644d62130 100644
--- a/rust/personhog-replica/src/storage/postgres/feature_flag.rs
+++ b/rust/personhog-replica/src/storage/postgres/feature_flag.rs
@@ -175,6 +175,19 @@ impl FeatureFlagStorage for PostgresStorage {
let _timer = common_metrics::timing_guard(DB_QUERY_DURATION, &labels);
let mut conn = PostgresStorage::acquire_timed(&self.primary_pool, "primary").await?;
+ let mut tx = sqlx::Connection::begin(&mut *conn).await?;
+ // The foreign key from posthog_featureflaghashkeyoverride to posthog_person is deferred.
+ // Postgres checks deferred keys at COMMIT. statement_timeout does not cover COMMIT. A
+ // person delete or merge holds FOR UPDATE on the person row until its transaction ends.
+ // Until then, the commit waits. This statement moves the check into the INSERT, where
+ // statement_timeout applies.
+ sqlx::query("SET CONSTRAINTS ALL IMMEDIATE")
+ .execute(&mut *tx)
+ .await?;
+ // Kept under the router's 5 s backend deadline so the caller sees an error, not a timeout.
+ sqlx::query("SET LOCAL lock_timeout = '2s'")
+ .execute(&mut *tx)
+ .await?;
// DO UPDATE locks each conflicting row even when its WHERE is false, so NOT EXISTS
// skips the pairs that already hold a real key. The WHERE still keeps a real key that a
@@ -205,8 +218,9 @@ impl FeatureFlagStorage for PostgresStorage {
feature_flag_keys,
COOKIELESS_SENTINEL_VALUE
)
- .execute(&mut *conn)
+ .execute(&mut *tx)
.await?;
+ tx.commit().await?;
Ok(result.rows_affected() as i64)
}
diff --git a/rust/personhog-replica/tests/common/mod.rs b/rust/personhog-replica/tests/common/mod.rs
index 42d9cff7079d..ab8b1f230af3 100644
--- a/rust/personhog-replica/tests/common/mod.rs
+++ b/rust/personhog-replica/tests/common/mod.rs
@@ -1,6 +1,8 @@
+use common_database::{get_pool_with_config, PoolConfig};
use personhog_replica::storage::{postgres::PostgresStorage, FullStorage};
use rand::Rng;
use sqlx::postgres::PgPool;
+use sqlx::{Postgres, Transaction};
use std::sync::Arc;
use uuid::Uuid;
@@ -12,6 +14,24 @@ fn random_person_id() -> i64 {
rand::thread_rng().gen_range(1_000_000..100_000_000)
}
+fn database_url() -> String {
+ std::env::var("DATABASE_URL")
+ .unwrap_or_else(|_| "postgres://posthog:posthog@localhost:5432/posthog_persons".to_string())
+}
+
+fn storage_over(pool: PgPool) -> Arc<dyn FullStorage> {
+ // In tests, use the same pool for everything
+ Arc::new(PostgresStorage::new(
+ pool.clone(),
+ pool.clone(),
+ pool.clone(),
+ pool,
+ 50, // bulk_chunk_size — small so parallel path is exercised with fewer test rows
+ 5, // bulk_max_concurrent_chunks
+ 12, // tombstoned_delete_max_rows, small enough that the clamp is observable
+ ))
+}
+
/// Test context that manages database connections and provides test data helpers.
pub struct TestContext {
pub pool: PgPool,
@@ -21,23 +41,10 @@ pub struct TestContext {
impl TestContext {
pub async fn new() -> Self {
- let database_url = std::env::var("DATABASE_URL").unwrap_or_else(|_| {
- "postgres://posthog:posthog@localhost:5432/posthog_persons".to_string()
- });
-
- let pool = PgPool::connect(&database_url)
+ let pool = PgPool::connect(&database_url())
.await
.expect("Failed to connect to test database");
- // In tests, use the same pool for everything
- let storage = Arc::new(PostgresStorage::new(
- pool.clone(),
- pool.clone(),
- pool.clone(),
- pool.clone(),
- 50, // bulk_chunk_size — small so parallel path is exercised with fewer test rows
- 5, // bulk_max_concurrent_chunks
- 12, // tombstoned_delete_max_rows, small enough that the clamp is observable
- ));
+ let storage = storage_over(pool.clone());
let team_id = random_team_id();
Self {
@@ -47,6 +54,18 @@ impl TestContext {
}
}
+ pub fn storage_with_statement_timeout(statement_timeout_ms: u64) -> Arc<dyn FullStorage> {
+ let pool = get_pool_with_config(
+ &database_url(),
+ PoolConfig {
+ statement_timeout_ms: Some(statement_timeout_ms),
+ ..PoolConfig::default()
+ },
+ )
+ .expect("Failed to create test database pool");
+ storage_over(pool)
+ }
+
pub async fn insert_person(
&self,
distinct_id: &str,
@@ -269,6 +288,19 @@ impl TestContext {
Ok(())
}
+ pub async fn lock_person_row(
+ &self,
+ person_id: i64,
+ ) -> Result<Transaction<'static, Postgres>, sqlx::Error> {
+ let mut tx = self.pool.begin().await?;
+ sqlx::query("SELECT id FROM posthog_person WHERE team_id = $1 AND id = $2 FOR UPDATE")
+ .bind(self.team_id)
+ .bind(person_id)
+ .execute(&mut *tx)
+ .await?;
+ Ok(tx)
+ }
+
/// True while the row exists in any state; the storage reads hide tombstoned rows.
pub async fn person_row_exists(&self, person_id: i64) -> Result<bool, sqlx::Error> {
let id: Option<i64> =
diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rs
index 4cf5831da5c5..7da6f6f9fdfc 100644
--- a/rust/personhog-replica/tests/storage_tests.rs
+++ b/rust/personhog-replica/tests/storage_tests.rs
@@ -1599,6 +1599,53 @@ async fn test_upsert_hash_key_overrides_replaces_only_a_stored_cookieless_sentin
ctx.cleanup().await.ok();
}
+#[rstest]
+#[case::statement_timeout(Some(200), "statement timeout")]
+#[case::lock_timeout(None, "lock timeout")]
+#[tokio::test]
+async fn test_upsert_hash_key_overrides_fails_fast_behind_a_locked_person_row(
+ #[case] statement_timeout_ms: Option<u64>,
+ #[case] expected_error: &str,
+) {
+ let ctx = TestContext::new().await;
+ let person = ctx
+ .insert_person("upsert_locked_user", None)
+ .await
+ .expect("Failed to insert person");
+ let storage = match statement_timeout_ms {
+ Some(ms) => TestContext::storage_with_statement_timeout(ms),
+ None => ctx.storage.clone(),
+ };
+
+ // FOR UPDATE conflicts with the KEY SHARE lock that the foreign key check takes on the
+ // person row.
+ let holder = ctx.lock_person_row(person.id).await.unwrap();
+
+ let result = tokio::time::timeout(
+ Duration::from_secs(10),
+ storage.upsert_hash_key_overrides(
+ ctx.team_id,
+ &["upsert_locked_user".to_string()],
+ &["test-flag".to_string()],
+ "my_hash_key",
+ ),
+ )
+ .await
+ .expect("the upsert waited for the person row lock instead of timing out");
+ holder.rollback().await.unwrap();
+
+ assert!(
+ matches!(
+ &result,
+ Err(personhog_replica::storage::StorageError::Query(msg)) if msg.contains(expected_error)
+ ),
+ "expected a {expected_error}, got {result:?}"
+ );
+ assert_eq!(ctx.hash_key_override_count(person.id).await.unwrap(), 0);
+
+ ctx.cleanup().await.ok();
+}
+
// ============================================================
// Delete hash key overrides by teams tests
// ============================================================
@@ -4220,13 +4267,7 @@ async fn test_primary_writes_give_up_when_a_writer_holds_the_row(#[case] write:
}
let person_before = person_state(&ctx, person.uuid).await;
let distinct_id_before = distinct_id_state(&ctx, "held_row").await;
- let mut holder = ctx.pool.begin().await.unwrap();
- sqlx::query("SELECT id FROM posthog_person WHERE team_id = $1 AND id = $2 FOR UPDATE")
- .bind(ctx.team_id)
- .bind(person.id)
- .execute(&mut *holder)
- .await
- .unwrap();
+ let holder = ctx.lock_person_row(person.id).await.unwrap();
let started = Instant::now();
let result = match write {