: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): run batch flag evaluation under the persons db deadline (#114082)
Phil Haack3dc635221aa5
diff --git a/docs/internal/feature-flags/database-interaction-patterns.md b/docs/internal/feature-flags/database-interaction-patterns.mdindex 29b83911bb15..ce9a4e5b7c04 100644--- a/docs/internal/feature-flags/database-interaction-patterns.md+++ b/docs/internal/feature-flags/database-interaction-patterns.md@@ -103,9 +103,11 @@ That includes a flag that skips DB preparation because its only group filter hasSee [Unfetched properties fail closed](flag-evaluation-engine.md#unfetched-properties-fail-closed).Each stopped call increments `flags_database_error_total` with `timeout_type="persons_db_deadline"` and the call's `operation`.The canonical log line records the first stopped call in `persons_db_deadline_exceeded`.-The internal batch evaluation endpoint does not apply the deadline.-When a person's evaluation returns an error, Django leaves that person out of the static cohort, keeps the persons that matched, and records the run as failed.-The batch endpoint shares the group type mapping cache with `/flags`, so its group type lookup still stops at the 5s shared fetch cap.+The internal batch evaluation endpoint applies the deadline to each person's evaluation.+A person that fails at the deadline is evaluated once more with a fresh deadline, up to `MAX_PERSON_RETRIES_PER_PAGE` retries per page.+The deadline bounds each person, not the page.+A persons database that stays unresponsive still ends the page at `BATCH_FLAG_EVAL_TIMEOUT_MS`.+When a person's evaluation still returns an error, Django leaves that person out of the static cohort, keeps the persons that matched, and records the run as failed.Set `PERSONS_DB_DEADLINE_MS=0` to disable the deadline.A query that the deadline drops mid-flight keeps its connection until sqlx's on-release ping finishes.diff --git a/rust/feature-flags/src/api/batch_flag_evaluation.rs b/rust/feature-flags/src/api/batch_flag_evaluation.rsindex 1432d8f60028..036cc663aed5 100644--- a/rust/feature-flags/src/api/batch_flag_evaluation.rs+++ b/rust/feature-flags/src/api/batch_flag_evaluation.rs@@ -22,12 +22,6 @@//! caller reads only the target's `enabled`.//! - Flags are always read fresh from Postgres (never the hypercache) so the//! `expected_version` optimistic-lock check is meaningful.-//! - The matcher runs without the persons DB deadline (`PERSONS_DB_DEADLINE_MS`). When a-//! person's evaluation returns an error, Django leaves that person out of the cohort and-//! still reports the run as a success. A slow persons query must therefore finish rather-//! than time out. The group type mapping lookup is the exception. This endpoint shares-//! `GroupTypeCacheManager` with live `/flags`, so that lookup still fails with-//! `client_timeout` at the cache's 5s shared fetch cap.//!//! The paged scan walks `posthog_person.id` ascending across a live table, so the run sees//! a moving snapshot rather than a point-in-time one: persons inserted above the current@@ -113,8 +107,8 @@ pub struct BatchFlagEvaluationResponse {const DEFAULT_LIMIT: i64 = 1_000;/// A page evaluates its persons one at a time under `BATCH_FLAG_EVAL_TIMEOUT_MS`. A retry of a-/// person that timed out waits the persons pool timeouts a second time. The cap keeps a-/// sustained stall from spending the page timeout on retries.+/// person that timed out waits on the persons DB a second time. The cap keeps a sustained stall+/// from spending the page timeout on retries.const MAX_PERSON_RETRIES_PER_PAGE: u32 = 20;#[derive(Debug)]@@ -662,7 +656,10 @@ async fn handle_batch_flag_evaluation(// Read-only: experience-continuity overrides are consulted but never written..with_skip_writes(true).with_enabled_only_flag_keys(enabled_only_flag_keys.clone())- .with_timezone(team_timezone);+ .with_timezone(team_timezone)+ // The deadline starts when the matcher is built. Building the matcher in this+ // closure gives the retry in `evaluate_with_one_retry` its own deadline.+ .with_persons_db_deadline(state.config.persons_db_deadline());let flag_list = flag_list.clone();let target_key = target_key.clone();diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rsindex c43676e68df9..259b951859c9 100644--- a/rust/feature-flags/src/config.rs+++ b/rust/feature-flags/src/config.rs@@ -435,12 +435,12 @@ pub struct Config {#[envconfig(from = "REALTIME_COHORT_LOOKUP_TIMEOUT_MS", default = "1000")]pub realtime_cohort_lookup_timeout_ms: u64,- // Deadline shared by all persons DB calls in one /flags evaluation: the hash key override+ // Deadline shared by all persons DB calls in one flag evaluation: the hash key override// check, write, and read, the group type mapping lookup, and the properties fetch.// statement_timeout cannot cancel a query on a database that has stopped answering.- // Only this timer bounds the request then. On expiry, the flags that need persons data+ // Only this timer bounds those calls then. On expiry, the flags that need persons data// return an error and the other flags evaluate normally. The default leaves 2s of the- // 4.5s REQUEST_TIMEOUT_MS for the rest of the request. 0 disables the deadline.+ // 4.5s REQUEST_TIMEOUT_MS for the rest of a /flags request. 0 disables the deadline.#[envconfig(from = "PERSONS_DB_DEADLINE_MS", default = "2500")]pub persons_db_deadline_ms: u64,diff --git a/rust/feature-flags/tests/test_batch_flag_evaluation.rs b/rust/feature-flags/tests/test_batch_flag_evaluation.rsindex 9317731c3674..ef2da80f2302 100644--- a/rust/feature-flags/tests/test_batch_flag_evaluation.rs+++ b/rust/feature-flags/tests/test_batch_flag_evaluation.rs@@ -2,9 +2,16 @@//! (`POST /internal/batch_flag_evaluation`), which backs flag-driven static cohort//! generation.+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::Arc;+use anyhow::Result;use reqwest::StatusCode;use serde_json::{json, Value};+use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};+use tokio::net::{TcpListener, TcpStream};+use url::Url;use uuid::Uuid;pub mod common;@@ -942,6 +949,123 @@ async fn test_experience_continuity_overrides_read_but_never_written() -> ResultOk(())}+/// Returns a persons database URL that goes through a proxy. The proxy forwards traffic until a+/// client sends bytes that contain `needle`. From then on it sends nothing more to Postgres on any+/// connection and keeps every socket open. Postgres never receives the frozen query. Its statement+/// timeout therefore cannot end the query. A database that has stopped answering behaves the same+/// way.+async fn persons_db_url_frozen_by_query_containing(needle: &'static [u8]) -> Result<String> {+ let mut url = Url::parse(&DEFAULT_TEST_CONFIG.persons_read_database_url)?;+ let upstream = format!(+ "{}:{}",+ url.host_str().expect("the persons database URL has a host"),+ url.port().unwrap_or(5432)+ );+ let listener = TcpListener::bind("127.0.0.1:0").await?;+ let proxy_port = listener.local_addr()?.port();+ let frozen = Arc::new(AtomicBool::new(false));++ tokio::spawn(async move {+ while let Ok((client, _)) = listener.accept().await {+ let upstream = upstream.clone();+ let frozen = frozen.clone();+ tokio::spawn(async move {+ let Ok(server) = TcpStream::connect(&upstream).await else {+ return;+ };+ let (client_reader, mut client_writer) = client.into_split();+ let (mut server_reader, server_writer) = server.into_split();+ tokio::spawn(async move {+ tokio::io::copy(&mut server_reader, &mut client_writer).await+ });+ forward_to_postgres_until_frozen(client_reader, server_writer, &frozen, needle)+ .await;+ });+ }+ });++ url.set_host(Some("127.0.0.1"))?;+ url.set_port(Some(proxy_port))+ .expect("a postgres URL accepts a port");+ // The proxy matches `needle` in plaintext, so the connection must not use TLS.+ url.query_pairs_mut().append_pair("sslmode", "disable");+ Ok(url.to_string())+}++async fn forward_to_postgres_until_frozen(+ mut from: OwnedReadHalf,+ mut to: OwnedWriteHalf,+ frozen: &AtomicBool,+ needle: &[u8],+) {+ let mut buf = vec![0; 16 * 1024];+ // Keeps the end of the previous read so that a needle split across two reads still matches.+ let mut window = Vec::new();+ loop {+ let n = match from.read(&mut buf).await {+ Ok(0) | Err(_) => return,+ Ok(n) => n,+ };+ window.extend_from_slice(&buf[..n]);+ if window.windows(needle.len()).any(|w| w == needle) {+ frozen.store(true, Ordering::SeqCst);+ }+ window.drain(..window.len().saturating_sub(needle.len() - 1));+ if frozen.load(Ordering::SeqCst) {+ std::future::pending::<()>().await;+ }+ if to.write_all(&buf[..n]).await.is_err() {+ return;+ }+ }+}++#[tokio::test]+async fn test_unanswered_persons_query_fails_the_person_at_the_deadline() -> Result<()> {+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;++ // A continuity flag at 100% rollout skips the hash key override lookup. This flag uses 50% so+ // that the lookup runs.+ let flag_key = "continuity-flag";+ let mut flag = flag_row(+ team.id,+ flag_key,+ json!({"groups": [{"rollout_percentage": 50}]}),+ );+ flag.ensure_experience_continuity = Some(true);+ context.insert_flag(team.id, Some(flag)).await?;+ context+ .insert_person(team.id, "unanswered_user".to_string(), Some(json!({})))+ .await?;++ let mut config = batch_eval_config();+ // Only the per-person evaluation reads the override table. The page scan runs before it+ // through the same proxy and gets its answer.+ config.persons_read_database_url =+ persons_db_url_frozen_by_query_containing(b"posthog_featureflaghashkeyoverride").await?;+ config.persons_db_deadline_ms = 200;+ // Without the deadline, the page does not finish before this timeout. The endpoint then+ // returns 503.+ config.batch_flag_eval_timeout_ms = 30_000;+ let server = ServerHandle::for_config(config).await;++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, flag_key, 0),+ )+ .await;+ let status = res.status();+ let body = res.text().await?;+ assert_eq!(status, StatusCode::OK, "{body}");+ let json_response: Value = serde_json::from_str(&body)?;+ assert_eq!(json_response["errors_count"], json!(1));+ assert_eq!(json_response["matched_person_uuids"], json!([]));++ Ok(())+}+#[tokio::test]async fn test_static_and_dynamic_cohort_conditions() -> Result<()> {// Port of test_creating_static_cohort_with_cohort_flag_adds_cohort_props_as_default_too,