: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(flags): bound the replica hash key override insert with a timeout (#113666)
Phil Haack692919b4f832
diff --git a/rust/personhog-replica/src/config.rs b/rust/personhog-replica/src/config.rsindex 7b8e05142e41..356bbef9136c 100644--- a/rust/personhog-replica/src/config.rs+++ b/rust/personhog-replica/src/config.rs@@ -36,6 +36,13 @@ pub struct Config {#[envconfig(default = "5000")]pub statement_timeout_ms: u64,+ /// Statement timeout (ms) for the INSERT in UpsertHashKeyOverrides. Keep it+ /// below the shortest caller deadline, with room for pool acquire and round+ /// trips. The feature-flags service gives this write 2.5 s by default+ /// (PERSONS_DB_DEADLINE_MS).+ #[envconfig(default = "2000")]+ pub hash_key_override_statement_timeout_ms: u64,+/// Max connections for the bulk pool (large batch reads, deletes)./// Kept small so bulk queries can't starve the fast pool.#[envconfig(default = "5")]diff --git a/rust/personhog-replica/src/main.rs b/rust/personhog-replica/src/main.rsindex f6ac6cb02bea..c4fdf8e2e41b 100644--- a/rust/personhog-replica/src/main.rs+++ b/rust/personhog-replica/src/main.rs@@ -102,6 +102,11 @@ async fn create_storage(config: &Config) -> Arc<PostgresStorage> {config.tombstoned_delete_max_rows >= 1,"TOMBSTONED_DELETE_MAX_ROWS must be at least 1");+ assert!(+ (1..=i32::MAX as u64).contains(&config.hash_key_override_statement_timeout_ms),+ "HASH_KEY_OVERRIDE_STATEMENT_TIMEOUT_MS must be between 1 and {}",+ i32::MAX+ );assert!(config.bulk_max_concurrent_chunks >= 1,"BULK_MAX_CONCURRENT_CHUNKS must be at least 1"@@ -121,6 +126,7 @@ async fn create_storage(config: &Config) -> Arc<PostgresStorage> {config.bulk_chunk_size,config.bulk_max_concurrent_chunks,config.tombstoned_delete_max_rows,+ config.hash_key_override_statement_timeout_ms,))}other => {diff --git a/rust/personhog-replica/src/storage/postgres/feature_flag.rs b/rust/personhog-replica/src/storage/postgres/feature_flag.rsindex 8b58bab07668..e7966564b41e 100644--- a/rust/personhog-replica/src/storage/postgres/feature_flag.rs+++ b/rust/personhog-replica/src/storage/postgres/feature_flag.rs@@ -185,8 +185,14 @@ impl FeatureFlagStorage for PostgresStorage {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'")+ // statement_timeout includes time spent waiting on row locks, so it bounds the whole+ // INSERT, including several held rows in turn. It stays under the caller's deadline, so+ // the INSERT can fail with its own error before the caller gives up. The limit covers+ // only the INSERT. The pool acquire above runs before it and can still use up the+ // caller's deadline. The setting is local to the transaction, so PgBouncer does not pass+ // it to the next client of the server connection.+ sqlx::query("SELECT set_config('statement_timeout', $1, true)")+ .bind(self.hash_key_override_statement_timeout_ms.to_string()).execute(&mut *tx).await?;diff --git a/rust/personhog-replica/src/storage/postgres/mod.rs b/rust/personhog-replica/src/storage/postgres/mod.rsindex e6ab51353075..452b763cbcc4 100644--- a/rust/personhog-replica/src/storage/postgres/mod.rs+++ b/rust/personhog-replica/src/storage/postgres/mod.rs@@ -42,10 +42,12 @@ pub struct PostgresStorage {pub(crate) bulk_chunk_size: usize,pub(crate) bulk_max_concurrent_chunks: usize,pub(crate) tombstoned_delete_max_rows: usize,+ pub(crate) hash_key_override_statement_timeout_ms: u64,}impl PostgresStorage {/// Create a new PostgresStorage with separate primary, replica, and bulk pools.+ #[allow(clippy::too_many_arguments)]pub fn new(primary_pool: PgPool,replica_pool: PgPool,@@ -54,6 +56,7 @@ impl PostgresStorage {bulk_chunk_size: usize,bulk_max_concurrent_chunks: usize,tombstoned_delete_max_rows: usize,+ hash_key_override_statement_timeout_ms: u64,) -> Self {Self {primary_pool,@@ -63,6 +66,7 @@ impl PostgresStorage {bulk_chunk_size,bulk_max_concurrent_chunks,tombstoned_delete_max_rows,+ hash_key_override_statement_timeout_ms,}}diff --git a/rust/personhog-replica/tests/common/mod.rs b/rust/personhog-replica/tests/common/mod.rsindex ab8b1f230af3..ad75902f5283 100644--- a/rust/personhog-replica/tests/common/mod.rs+++ b/rust/personhog-replica/tests/common/mod.rs@@ -1,4 +1,3 @@-use common_database::{get_pool_with_config, PoolConfig};use personhog_replica::storage::{postgres::PostgresStorage, FullStorage};use rand::Rng;use sqlx::postgres::PgPool;@@ -19,7 +18,7 @@ fn database_url() -> String {.unwrap_or_else(|_| "postgres://posthog:posthog@localhost:5432/posthog_persons".to_string())}-fn storage_over(pool: PgPool) -> Arc<dyn FullStorage> {+fn storage_over(pool: PgPool, hash_key_override_statement_timeout_ms: u64) -> Arc<dyn FullStorage> {// In tests, use the same pool for everythingArc::new(PostgresStorage::new(pool.clone(),@@ -29,6 +28,7 @@ fn storage_over(pool: PgPool) -> Arc<dyn FullStorage> {50, // bulk_chunk_size — small so parallel path is exercised with fewer test rows5, // bulk_max_concurrent_chunks12, // tombstoned_delete_max_rows, small enough that the clamp is observable+ hash_key_override_statement_timeout_ms,))}@@ -44,7 +44,7 @@ impl TestContext {let pool = PgPool::connect(&database_url()).await.expect("Failed to connect to test database");- let storage = storage_over(pool.clone());+ let storage = storage_over(pool.clone(), 4000);let team_id = random_team_id();Self {@@ -54,16 +54,11 @@ 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 fn storage_with_hash_key_override_statement_timeout(+ &self,+ statement_timeout_ms: u64,+ ) -> Arc<dyn FullStorage> {+ storage_over(self.pool.clone(), statement_timeout_ms)}pub async fn insert_person(diff --git a/rust/personhog-replica/tests/storage_tests.rs b/rust/personhog-replica/tests/storage_tests.rsindex 7da6f6f9fdfc..e23af344ec12 100644--- a/rust/personhog-replica/tests/storage_tests.rs+++ b/rust/personhog-replica/tests/storage_tests.rs@@ -1599,23 +1599,14 @@ async fn test_upsert_hash_key_overrides_replaces_only_a_stored_cookieless_sentinctx.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,-) {+async fn test_upsert_hash_key_overrides_fails_fast_behind_a_locked_person_row() {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(),- };+ let storage = ctx.storage_with_hash_key_override_statement_timeout(200);// FOR UPDATE conflicts with the KEY SHARE lock that the foreign key check takes on the// person row.@@ -1637,9 +1628,9 @@ 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(expected_error)+ Err(personhog_replica::storage::StorageError::Query(msg)) if msg.contains("statement timeout")),- "expected a {expected_error}, got {result:?}"+ "expected a statement timeout, got {result:?}");assert_eq!(ctx.hash_key_override_count(person.id).await.unwrap(), 0);