: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
feat(flags): batch evaluation (#62579)
Nick Bestab7bd891d8d9
diff --git a/rust/feature-flags/src/api/batch_flag_evaluation.rs b/rust/feature-flags/src/api/batch_flag_evaluation.rsnew file mode 100644index 000000000000..86583438835f--- /dev/null+++ b/rust/feature-flags/src/api/batch_flag_evaluation.rs@@ -0,0 +1,510 @@+//! Internal batch flag evaluation endpoint for flag-driven static cohort generation.+//!+//! Django's `get_cohort_actors_for_feature_flag` Celery task drives this endpoint with+//! strictly sequential, cursor-paged requests: each page scans a slice of a team's persons+//! and evaluates a single (pinned-version) flag for every person, reusing the exact same+//! `FeatureFlagMatcher` machinery as live `/flags` evaluation. The response carries the+//! matched person UUIDs, which Django inserts into the static cohort.+//!+//! Deliberate differences from the live `/flags` pipeline:+//! - Auth is the `INTERNAL_REQUEST_TOKEN` bearer token only — no SDK token, no team lookup+//! by token.+//! - The handler bypasses the `/flags` request pipeline entirely, so no billing or+//! flag-analytics counters are emitted, and dedicated `flags_batch_eval_*` ops metrics+//! track batch traffic. The per-person matcher still emits its own evaluation metrics+//! (`flags_evaluation_time`, dependency-graph build counters), which share the same+//! series as live `/flags`, so a large cohort run dominates those on its pod.+//! - The matcher always runs with `skip_writes(true)`: experience-continuity hash key+//! overrides are read but never written.+//! - Flags are always read fresh from Postgres (never the hypercache) so the+//! `expected_version` optimistic-lock check is meaningful.+//!+//! 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+//! cursor mid-run are included, persons inserted below it (or deleted) are not. Flag+//! definitions are pinned by `expected_version`, but person membership is eventually+//! consistent with the table at the time each page is scanned. This matches the existing+//! cohort-generation contract (a later refresh reconciles drift).++use std::collections::HashSet;+use std::sync::Arc;++use axum::{+ body::Body,+ extract::State,+ http::{HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ Json,+};+use common_database::PostgresReader;+use common_metrics::inc;+use common_types::PersonId;+use serde::{Deserialize, Serialize};+use sqlx::FromRow;+use tracing::warn;+use uuid::Uuid;++use crate::{+ api::errors::FlagError,+ database::{get_connection_with_metrics, PostgresRouter},+ flags::{+ cache_builder::compute_flag_dependencies,+ feature_flag_list::PreparedFlags,+ flag_matching::FeatureFlagMatcher,+ flag_models::{EvaluationMetadata, FeatureFlag, FeatureFlagList},+ },+ handler::authentication::is_internal_request_inner,+ metrics::consts::{+ FLAG_BATCH_EVAL_PERSONS_COUNTER, FLAG_BATCH_EVAL_REQUESTS_COUNTER, FLAG_BATCH_EVAL_TIME,+ },+ router,+};++#[derive(Debug, Deserialize)]+pub struct BatchFlagEvaluationRequest {+ pub team_id: i32,+ /// The project the flag belongs to. Accepted for contract parity with the Django+ /// caller; flag lookup is team-scoped (matching live Rust evaluation), so this is+ /// currently informational only.+ #[serde(default)]+ pub project_id: Option<i64>,+ pub flag_key: String,+ /// Optimistic-lock pin: the flag `version` Django read before starting the run.+ /// Nullable versions coerce to 0 on both sides, so JSON `null` is accepted and+ /// treated as 0.+ #[serde(default)]+ pub expected_version: Option<i32>,+ /// Exclusive lower bound on `posthog_person.id`; 0 (default) starts from the beginning.+ #[serde(default)]+ pub cursor: i64,+ /// Page size; defaults to `DEFAULT_LIMIT` (1000), capped by `BATCH_FLAG_EVAL_MAX_LIMIT`.+ pub limit: Option<i64>,+}++#[derive(Debug, Serialize, Deserialize)]+pub struct BatchFlagEvaluationResponse {+ pub matched_person_uuids: Vec<Uuid>,+ /// Cursor for the next page, or `None` when this page was the last one.+ pub next_cursor: Option<i64>,+ /// Number of persons in this page whose evaluation failed (they are skipped, not matched).+ pub errors_count: u64,+}++const DEFAULT_LIMIT: i64 = 1_000;++#[derive(Debug)]+pub enum BatchFlagEvaluationError {+ Unauthorized,+ InvalidRequest(String),+ PayloadTooLarge,+ FlagNotFound,+ FlagInactive,+ GroupAggregatedFlag,+ VersionConflict { expected: i32, actual: i32 },+ Upstream(FlagError),+}++impl BatchFlagEvaluationError {+ fn outcome_label(&self) -> &'static str {+ match self {+ Self::Unauthorized => "unauthorized",+ Self::InvalidRequest(_) => "invalid_request",+ Self::PayloadTooLarge => "payload_too_large",+ Self::FlagNotFound => "flag_not_found",+ Self::FlagInactive => "flag_inactive",+ Self::GroupAggregatedFlag => "group_aggregated_flag",+ Self::VersionConflict { .. } => "version_conflict",+ Self::Upstream(_) => "upstream_error",+ }+ }+}++impl IntoResponse for BatchFlagEvaluationError {+ fn into_response(self) -> Response {+ let (status, error, detail, actual_version) = match self {+ Self::Unauthorized => (+ StatusCode::UNAUTHORIZED,+ "unauthorized",+ "Missing or invalid internal request token".to_string(),+ None,+ ),+ Self::InvalidRequest(detail) => {+ (StatusCode::BAD_REQUEST, "invalid_request", detail, None)+ }+ Self::PayloadTooLarge => (+ StatusCode::PAYLOAD_TOO_LARGE,+ "payload_too_large",+ format!("Request body exceeds the {MAX_BATCH_BODY_BYTES}-byte limit"),+ None,+ ),+ Self::FlagNotFound => (+ StatusCode::NOT_FOUND,+ "flag_not_found",+ "No flag with this key exists for this team".to_string(),+ None,+ ),+ Self::FlagInactive => (+ StatusCode::BAD_REQUEST,+ "flag_inactive",+ "Flag is not active".to_string(),+ None,+ ),+ Self::GroupAggregatedFlag => (+ StatusCode::BAD_REQUEST,+ "group_aggregated_flag",+ "Group-aggregated flags are not supported for batch evaluation".to_string(),+ None,+ ),+ Self::VersionConflict { expected, actual } => (+ StatusCode::CONFLICT,+ "version_conflict",+ format!("Flag version is {actual}, expected {expected}; the flag changed during cohort generation"),+ Some(actual),+ ),+ Self::Upstream(e) => {+ // Delegate status selection to FlagError's own mapping, but keep the+ // JSON envelope consistent with the other variants.+ let status = StatusCode::from_u16(e.status_code())+ .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);+ (status, "upstream_error", e.to_string(), None)+ }+ };++ let mut body = serde_json::json!({ "error": error, "detail": detail });+ if let Some(actual) = actual_version {+ body["actual_version"] = serde_json::json!(actual);+ }+ (status, Json(body)).into_response()+ }+}++/// One row from the person page scan: the person plus its deterministic+/// (minimum `posthog_persondistinctid.id`) distinct_id, when one exists.+#[derive(Debug, FromRow)]+struct PersonScanRow {+ id: PersonId,+ uuid: Uuid,+ distinct_id: Option<String>,+}++/// Scans one page of a team's persons in `id` order, attaching the distinct_id with the+/// lowest `posthog_persondistinctid.id` (a deterministic choice). Persons with no+/// distinct_ids come back with `distinct_id = NULL` and still advance the cursor, so a+/// run of distinct_id-less persons cannot stall paging.+async fn scan_persons_page(+ reader: PostgresReader,+ team_id: i32,+ cursor: i64,+ limit: i64,+) -> Result<Vec<PersonScanRow>, FlagError> {+ let mut conn =+ get_connection_with_metrics(&reader, "persons_reader", "batch_eval_person_scan").await?;++ // Sort-free PK range scan on the partitioned persons table; the lateral subquery is+ // covered by the existing person_id index on posthog_persondistinctid.+ let query = r#"+ SELECT p.id, p.uuid, d.distinct_id+ FROM posthog_person p+ LEFT JOIN LATERAL (+ SELECT pd.distinct_id+ FROM posthog_persondistinctid pd+ WHERE pd.person_id = p.id+ AND pd.team_id = p.team_id+ ORDER BY pd.id+ LIMIT 1+ ) d ON true+ WHERE p.team_id = $1+ AND p.id > $2+ ORDER BY p.id+ LIMIT $3+ "#;++ sqlx::query_as::<_, PersonScanRow>(query)+ .bind(team_id)+ .bind(cursor)+ .bind(limit)+ .fetch_all(&mut *conn)+ .await+ .map_err(|e| {+ warn!(team_id, cursor, "Batch eval person scan failed: {e}");+ FlagError::Internal(format!("person scan query failed: {e}"))+ })+}++/// Fetches the team's flags fresh from Postgres and locates the target flag by key.+/// Returns the full flag set (needed for flag-dependency evaluation) and the target's index.+async fn fetch_flags_with_target(+ client: PostgresReader,+ team_id: i32,+ flag_key: &str,+) -> Result<(Vec<FeatureFlag>, usize), BatchFlagEvaluationError> {+ let flags = FeatureFlagList::from_pg(client, team_id)+ .await+ .map_err(BatchFlagEvaluationError::Upstream)?;+ let target_index = flags+ .iter()+ .position(|f| f.key == flag_key)+ .ok_or(BatchFlagEvaluationError::FlagNotFound)?;+ Ok((flags, target_index))+}++/// The request is a small JSON object (~200 bytes typical), so 64 KiB is generous+/// while protecting against oversized payloads.+pub const MAX_BATCH_BODY_BYTES: usize = 64 * 1024;++pub async fn batch_flag_evaluation(+ State(state): State<router::State>,+ headers: HeaderMap,+ body: Body,+) -> Result<Json<BatchFlagEvaluationResponse>, BatchFlagEvaluationError> {+ let timer = common_metrics::timing_guard(FLAG_BATCH_EVAL_TIME, &[]);++ // Authenticate before reading the body so unauthenticated clients cannot+ // tie up resources by streaming large or slow request bodies.+ if !is_internal_request_inner(state.config.internal_request_token.as_deref(), &headers) {+ let outcome = "unauthorized";+ inc(+ FLAG_BATCH_EVAL_REQUESTS_COUNTER,+ &[("outcome".to_string(), outcome.to_string())],+ 1,+ );+ timer.label("outcome", outcome).fin();+ return Err(BatchFlagEvaluationError::Unauthorized);+ }++ let result = match axum::body::to_bytes(body, MAX_BATCH_BODY_BYTES).await {+ Ok(body_bytes) => handle_batch_flag_evaluation(&state, &body_bytes).await,+ // `to_bytes` wraps the underlying http_body_util error; walk the full source+ // chain (not just the first level) to classify an oversized body as 413, the+ // same way `body_read_metrics::record_body_read` does for `/flags`.+ Err(e) => {+ let too_large = std::iter::successors(std::error::Error::source(&e), |s| s.source())+ .any(|s| s.is::<http_body_util::LengthLimitError>());+ Err(if too_large {+ BatchFlagEvaluationError::PayloadTooLarge+ } else {+ BatchFlagEvaluationError::InvalidRequest(format!("body read error: {e}"))+ })+ }+ };++ let outcome = match &result {+ Ok(_) => "success",+ Err(e) => e.outcome_label(),+ };+ inc(+ FLAG_BATCH_EVAL_REQUESTS_COUNTER,+ &[("outcome".to_string(), outcome.to_string())],+ 1,+ );+ timer.label("outcome", outcome).fin();++ result.map(Json)+}++async fn handle_batch_flag_evaluation(+ state: &router::State,+ body: &[u8],+) -> Result<BatchFlagEvaluationResponse, BatchFlagEvaluationError> {+ let request: BatchFlagEvaluationRequest = serde_json::from_slice(body)+ .map_err(|e| BatchFlagEvaluationError::InvalidRequest(format!("invalid JSON body: {e}")))?;++ let max_limit = state.config.batch_flag_eval_max_limit;+ let limit = request.limit.unwrap_or(DEFAULT_LIMIT.min(max_limit));+ if limit < 1 || limit > max_limit {+ return Err(BatchFlagEvaluationError::InvalidRequest(format!(+ "limit must be between 1 and {max_limit}"+ )));+ }+ if request.flag_key.is_empty() {+ return Err(BatchFlagEvaluationError::InvalidRequest(+ "flag_key must not be empty".to_string(),+ ));+ }+ if request.cursor < 0 {+ return Err(BatchFlagEvaluationError::InvalidRequest(+ "cursor must not be negative".to_string(),+ ));+ }++ // Read the flag set from the replica first; on a version mismatch, re-fetch from the+ // primary to rule out replica lag before declaring a conflict. No evaluation happens+ // under the wrong version.+ let (mut flags_vec, mut target_index) = fetch_flags_with_target(+ state.database_pools.non_persons_reader.clone(),+ request.team_id,+ &request.flag_key,+ )+ .await?;++ let expected_version = request.expected_version.unwrap_or(0);+ if flags_vec[target_index].version.unwrap_or(0) != expected_version {+ (flags_vec, target_index) = fetch_flags_with_target(+ state.database_pools.non_persons_writer.clone(),+ request.team_id,+ &request.flag_key,+ )+ .await?;+ let actual = flags_vec[target_index].version.unwrap_or(0);+ if actual != expected_version {+ return Err(BatchFlagEvaluationError::VersionConflict {+ expected: expected_version,+ actual,+ });+ }+ }++ let target = &flags_vec[target_index];+ // The Django caller already returns [] for group-aggregated and inactive flags+ // without calling us; these guards are defensive.+ if target.get_group_type_index().is_some() {+ return Err(BatchFlagEvaluationError::GroupAggregatedFlag);+ }+ if !target.active {+ return Err(BatchFlagEvaluationError::FlagInactive);+ }+ let target_key = target.key.clone();++ // Mirror the live pipeline's exclusion of inactive flags so dependency conditions on+ // them pre-seed as false instead of evaluating.+ let filtered_out_flag_ids: HashSet<i32> = flags_vec+ .iter()+ .filter(|f| !f.active)+ .map(|f| f.id)+ .collect();++ // Real dependency stages (like the hypercache path) rather than the PG fallback's+ // single stage, so flag-dependency conditions on the target flag evaluate correctly.+ let evaluation_metadata = compute_flag_dependencies(&flags_vec).unwrap_or_else(|e| {+ warn!(+ team_id = request.team_id,+ "Batch eval falling back to single-stage flag metadata: {e}"+ );+ EvaluationMetadata::single_stage(&flags_vec)+ });++ let flag_list = FeatureFlagList {+ flags: PreparedFlags::seal(flags_vec),+ filtered_out_flag_ids,+ evaluation_metadata: Arc::new(evaluation_metadata),+ cohorts: None,+ };++ // The service exposes no dedicated non-critical persons pool, so the scan shares the+ // live persons reader.+ let rows = scan_persons_page(+ state.database_pools.persons_reader.clone(),+ request.team_id,+ request.cursor,+ limit,+ )+ .await+ .map_err(BatchFlagEvaluationError::Upstream)?;++ let next_cursor = if rows.len() as i64 == limit {+ rows.last().map(|r| r.id)+ } else {+ None+ };++ let pg_router = PostgresRouter::new(+ state.database_pools.persons_reader.clone(),+ state.database_pools.persons_writer.clone(),+ state.database_pools.non_persons_reader.clone(),+ state.database_pools.non_persons_writer.clone(),+ );+ let enable_realtime_cohort_evaluation = state+ .config+ .realtime_cohort_evaluation_team_ids+ .includes_team(request.team_id);++ let mut matched_person_uuids: Vec<Uuid> = Vec::new();+ let mut errors_count: u64 = 0;++ for row in rows {+ // Persons with zero distinct_ids (almost-deleted) are skipped.+ let Some(distinct_id) = row.distinct_id else {+ record_person_outcome("skipped_no_distinct_id");+ continue;+ };++ // Per-person so each evaluation is independently traceable in canonical logs.+ let request_id = Uuid::new_v4();++ let mut matcher = FeatureFlagMatcher::new(+ distinct_id,+ None,+ request.team_id,+ pg_router.clone(),+ state.cohort_cache_manager.clone(),+ state.group_type_cache_manager.clone(),+ None,+ )+ .with_cohort_membership_provider(state.cohort_membership_provider.clone())+ .with_realtime_cohort_evaluation(enable_realtime_cohort_evaluation)+ .with_rayon_dispatcher(state.rayon_dispatcher.clone())+ .with_parallel_eval_threshold(state.config.parallel_eval_threshold)+ // Read-only: experience-continuity overrides are consulted but never written.+ .with_skip_writes(true);++ let evaluation = matcher+ .evaluate_all_feature_flags(+ flag_list.clone(),+ None,+ None,+ None,+ request_id,+ Some(vec![target_key.clone()]),+ state.config.optimize_experience_continuity_lookups.0,+ )+ .await;++ match evaluation {+ Ok(response) => match response.flags.get(&target_key) {+ Some(details) if details.failed => {+ errors_count += 1;+ record_person_outcome("error");+ }+ Some(details) if details.enabled => {+ matched_person_uuids.push(row.uuid);+ record_person_outcome("matched");+ }+ Some(_) => record_person_outcome("not_matched"),+ None => {+ warn!(+ team_id = request.team_id,+ flag_key = %target_key,+ person_uuid = %row.uuid,+ "Batch eval response missing the target flag"+ );+ errors_count += 1;+ record_person_outcome("error");+ }+ },+ Err(e) => {+ warn!(+ team_id = request.team_id,+ flag_key = %target_key,+ person_uuid = %row.uuid,+ "Batch eval failed for person: {e}"+ );+ errors_count += 1;+ record_person_outcome("error");+ }+ }+ }++ Ok(BatchFlagEvaluationResponse {+ matched_person_uuids,+ next_cursor,+ errors_count,+ })+}++fn record_person_outcome(result: &str) {+ inc(+ FLAG_BATCH_EVAL_PERSONS_COUNTER,+ &[("result".to_string(), result.to_string())],+ 1,+ );+}diff --git a/rust/feature-flags/src/api/mod.rs b/rust/feature-flags/src/api/mod.rsindex 45ca92609fb7..382c79d22fbe 100644--- a/rust/feature-flags/src/api/mod.rs+++ b/rust/feature-flags/src/api/mod.rs@@ -1,4 +1,5 @@pub mod auth;+pub mod batch_flag_evaluation;pub mod body_read_metrics;pub mod concurrency_metrics;pub mod endpoint;diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rsindex 37e13c26c0aa..05f47c9926dc 100644--- a/rust/feature-flags/src/config.rs+++ b/rust/feature-flags/src/config.rs@@ -755,6 +755,19 @@ pub struct Config {#[envconfig(from = "INTERNAL_REQUEST_TOKEN")]pub internal_request_token: Option<String>,+ // Hard ceiling on page size for the internal batch flag evaluation endpoint+ // (static cohort generation); requests above it are rejected with 400. This is a+ // safety cap, not a recommended page size: a page evaluates persons sequentially, so+ // the Django caller should page well below this to stay within the request timeout.+ #[envconfig(from = "BATCH_FLAG_EVAL_MAX_LIMIT", default = "10000")]+ pub batch_flag_eval_max_limit: i64,++ // Request timeout for the internal batch flag evaluation endpoint.+ // Separate from REQUEST_TIMEOUT_MS because a batch page evaluates up to+ // BATCH_FLAG_EVAL_MAX_LIMIT persons sequentially.+ #[envconfig(from = "BATCH_FLAG_EVAL_TIMEOUT_MS", default = "120000")]+ pub batch_flag_eval_timeout_ms: u64,+// Redis compression configuration// When enabled, uses zstd compression for Redis values above threshold// The `default_test_config()` sets this to true for test/development scenarios.@@ -1076,6 +1089,8 @@ impl Config {service_mode: ServiceMode::All,auth_token_cache_ttl_seconds: 300,internal_request_token: None,+ batch_flag_eval_max_limit: 10_000,+ batch_flag_eval_timeout_ms: 120_000,billing_flush_interval_ms: 100,billing_max_pending_entries: 500_000,billing_per_flush_batch_size: 200,diff --git a/rust/feature-flags/src/handler/authentication.rs b/rust/feature-flags/src/handler/authentication.rsindex 4d68b945520a..5d721cb04e55 100644--- a/rust/feature-flags/src/handler/authentication.rs+++ b/rust/feature-flags/src/handler/authentication.rs@@ -46,7 +46,9 @@ pub fn is_internal_request(context: &RequestContext) -> bool {)}-fn is_internal_request_inner(internal_token: Option<&str>, headers: &HeaderMap) -> bool {+/// Shared with the internal batch flag evaluation endpoint, which requires (rather than+/// optionally honors) the internal token.+pub(crate) fn is_internal_request_inner(internal_token: Option<&str>, headers: &HeaderMap) -> bool {use subtle::ConstantTimeEq;let Some(internal_token) = internal_token else {diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex 701cab5f8cd6..048a42881ceb 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -49,6 +49,14 @@ pub const DB_PERSON_AND_GROUP_PROPERTIES_READS_COUNTER: &str ="flags_db_person_and_group_properties_reads_total";pub const FLAG_REQUESTS_COUNTER: &str = "flags_requests_total";pub const FLAG_REQUESTS_LATENCY: &str = "flags_requests_duration_ms";++// Internal batch flag evaluation endpoint (static cohort generation). Dedicated+// `flags_batch_eval_*` names keep batch traffic separable from live `/flags` metrics.+// Not to be confused with the pre-existing `flags_batch_evaluation_*` family below+// (per-request sequential/parallel strategy metrics emitted from flag_matching.rs).+pub const FLAG_BATCH_EVAL_REQUESTS_COUNTER: &str = "flags_batch_eval_requests_total";+pub const FLAG_BATCH_EVAL_PERSONS_COUNTER: &str = "flags_batch_eval_persons_total";+pub const FLAG_BATCH_EVAL_TIME: &str = "flags_batch_eval_duration_ms";pub const FLAG_QUEUE_TIME_MS: &str = "flags_queue_time_ms";pub const FLAG_REQUEST_FAULTS_COUNTER: &str = "flags_request_faults_total";diff --git a/rust/feature-flags/src/router.rs b/rust/feature-flags/src/router.rsindex bf357159ebe8..a55d011352c7 100644--- a/rust/feature-flags/src/router.rs+++ b/rust/feature-flags/src/router.rs@@ -11,7 +11,7 @@ use axum::{error_handling::HandleErrorLayer,extract::DefaultBodyLimit,http::{Method, StatusCode},- routing::{any, get},+ routing::{any, get, post},Router,};use common_cache::{NegativeCache, ReadThroughCacheWithMetrics};@@ -34,6 +34,7 @@ use tower_http::{use crate::{api::{+ batch_flag_evaluation,body_read_metrics::{record_body_read, MAX_FLAGS_BODY_BYTES},concurrency_metrics::{record_concurrency_enter, record_concurrency_wait},endpoint, flag_definitions,@@ -299,6 +300,40 @@ pub fn router(.layer(DefaultBodyLimit::max(MAX_FLAGS_BODY_BYTES));}+ // Internal-only batch flag evaluation for static cohort generation. Kept outside+ // `flags_router` on purpose: it must not share the live path's concurrency limit or+ // request timeout (a page evaluates up to BATCH_FLAG_EVAL_MAX_LIMIT persons), and it+ // bypasses the /flags pipeline (no billing, no flag analytics). Auth is enforced in+ // the handler before the body is read: the handler accepts a raw `Body` (not `Bytes`)+ // so unauthenticated requests are rejected without buffering the payload.+ let mut internal_endpoints: Router<State> = Router::new();+ if matches!(config.service_mode, ServiceMode::All | ServiceMode::Flags) {+ internal_endpoints = internal_endpoints+ .route(+ "/internal/batch_flag_evaluation",+ post(batch_flag_evaluation::batch_flag_evaluation),+ )+ .layer(DefaultBodyLimit::max(+ batch_flag_evaluation::MAX_BATCH_BODY_BYTES,+ ))+ .layer(+ ServiceBuilder::new()+ .layer(HandleErrorLayer::new(|err: tower::BoxError| async move {+ let is_timeout = err.is::<tower::timeout::error::Elapsed>();+ tracing::warn!(error = %err, timeout = is_timeout, "Batch flag evaluation request aborted by tower layer");+ let body = if is_timeout {+ "Request timed out"+ } else {+ "Service unavailable"+ };+ (StatusCode::SERVICE_UNAVAILABLE, body)+ }))+ .layer(TimeoutLayer::new(Duration::from_millis(+ config.batch_flag_eval_timeout_ms,+ ))),+ );+ }+let mut definitions_endpoints: Router<State> = Router::new();if matches!(config.service_mode,@@ -357,6 +392,7 @@ pub fn router(let router = Router::new().merge(status_router).merge(flags_router)+ .merge(internal_endpoints).layer(TraceLayer::new_for_http()).layer(cors).with_state(state);diff --git a/rust/feature-flags/tests/test_batch_flag_evaluation.rs b/rust/feature-flags/tests/test_batch_flag_evaluation.rsnew file mode 100644index 000000000000..be90db1dc27c--- /dev/null+++ b/rust/feature-flags/tests/test_batch_flag_evaluation.rs@@ -0,0 +1,1095 @@+//! Integration tests for the internal batch flag evaluation endpoint+//! (`POST /internal/batch_flag_evaluation`), which backs flag-driven static cohort+//! generation.++use anyhow::Result;+use reqwest::StatusCode;+use serde_json::{json, Value};+use uuid::Uuid;++pub mod common;+use crate::common::ServerHandle;+use feature_flags::config::{Config, DEFAULT_TEST_CONFIG};+use feature_flags::flags::flag_matching_utils::calculate_hash;+use feature_flags::flags::flag_models::FeatureFlagRow;+use feature_flags::utils::test_utils::{random_string, TestContext};++const INTERNAL_TOKEN: &str = "test-internal-request-token";+const ENDPOINT: &str = "/internal/batch_flag_evaluation";++fn batch_eval_config() -> Config {+ let mut config = DEFAULT_TEST_CONFIG.clone();+ config.internal_request_token = Some(INTERNAL_TOKEN.to_string());+ config+}++async fn send_batch_request(+ server: &ServerHandle,+ bearer_token: Option<&str>,+ body: &Value,+) -> reqwest::Response {+ let client = reqwest::Client::new();+ let mut request = client+ .post(format!("http://{}{}", server.addr, ENDPOINT))+ .header("content-type", "application/json")+ .body(body.to_string());+ if let Some(token) = bearer_token {+ request = request.header("authorization", format!("Bearer {token}"));+ }+ request.send().await.expect("Failed to send batch request")+}++fn batch_body(team_id: i32, flag_key: &str, expected_version: i32) -> Value {+ json!({+ "team_id": team_id,+ "project_id": team_id,+ "flag_key": flag_key,+ "expected_version": expected_version,+ })+}++fn flag_row(team_id: i32, key: &str, filters: Value) -> FeatureFlagRow {+ FeatureFlagRow {+ id: 0,+ team_id,+ name: Some(format!("{key} description")),+ key: key.to_string(),+ filters,+ deleted: false,+ active: true,+ ensure_experience_continuity: Some(false),+ version: None,+ evaluation_runtime: None,+ evaluation_tags: None,+ bucketing_identifier: None,+ }+}++/// Matched UUIDs as a sorted Vec for set comparison.+fn matched_uuids(response_json: &Value) -> Vec<Uuid> {+ let mut uuids: Vec<Uuid> = response_json["matched_person_uuids"]+ .as_array()+ .expect("matched_person_uuids should be an array")+ .iter()+ .map(|v| v.as_str().unwrap().parse().unwrap())+ .collect();+ uuids.sort();+ uuids+}++#[tokio::test]+async fn test_rejects_unauthenticated_requests() -> Result<()> {+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ let body = batch_body(team.id, "any-flag", 0);++ // No Authorization header+ let res = send_batch_request(&server, None, &body).await;+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);++ // Wrong bearer token+ let res = send_batch_request(&server, Some("wrong-token"), &body).await;+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);++ Ok(())+}++#[tokio::test]+async fn test_rejects_all_requests_when_no_internal_token_configured() -> Result<()> {+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;++ let mut config = DEFAULT_TEST_CONFIG.clone();+ config.internal_request_token = None;+ let server = ServerHandle::for_config(config).await;++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "any-flag", 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);++ Ok(())+}++#[tokio::test]+async fn test_rejects_invalid_limits() -> Result<()> {+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ for bad_limit in [0, -5, 10_001] {+ let mut body = batch_body(team.id, "any-flag", 0);+ body["limit"] = json!(bad_limit);+ let res = send_batch_request(&server, Some(INTERNAL_TOKEN), &body).await;+ assert_eq!(+ res.status(),+ StatusCode::BAD_REQUEST,+ "limit {bad_limit} should be rejected"+ );+ let json_response = res.json::<Value>().await?;+ assert_eq!(json_response["error"], "invalid_request");+ }++ Ok(())+}++#[tokio::test]+async fn test_missing_and_deleted_flags_return_not_found() -> Result<()> {+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ // Non-existent flag+ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "does-not-exist", 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::NOT_FOUND);++ // Deleted flag — the flag fetch excludes deleted flags, so this is+ // indistinguishable from a missing flag.+ let mut deleted = flag_row(+ team.id,+ "deleted-flag",+ json!({"groups": [{"properties": [{"key": "key", "value": "value", "type": "person"}]}]}),+ );+ deleted.deleted = true;+ context.insert_flag(team.id, Some(deleted)).await?;++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "deleted-flag", 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::NOT_FOUND);++ Ok(())+}++#[tokio::test]+async fn test_inactive_flag_rejected() -> Result<()> {+ // The Django caller returns [] for inactive flags without calling us; this guard+ // is defensive.+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ let mut inactive = flag_row(+ team.id,+ "inactive-flag",+ json!({"groups": [{"rollout_percentage": 100}]}),+ );+ inactive.active = false;+ context.insert_flag(team.id, Some(inactive)).await?;++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "inactive-flag", 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);+ let json_response = res.json::<Value>().await?;+ assert_eq!(json_response["error"], "flag_inactive");++ Ok(())+}++#[tokio::test]+async fn test_group_aggregated_flag_rejected() -> Result<()> {+ // The Django caller returns [] for group-aggregated flags without calling us;+ // this guard is defensive.+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ "group-flag",+ json!({+ "groups": [{"properties": [{"key": "key", "value": "value", "type": "group", "group_type_index": 1}]}],+ "aggregation_group_type_index": 1,+ }),+ )),+ )+ .await?;++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "group-flag", 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);+ let json_response = res.json::<Value>().await?;+ assert_eq!(json_response["error"], "group_aggregated_flag");++ Ok(())+}++#[tokio::test]+async fn test_version_mismatch_returns_conflict_with_actual_version() -> Result<()> {+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ let flag = context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ "versioned-flag",+ json!({"groups": [{"rollout_percentage": 100}]}),+ )),+ )+ .await?;++ let mut conn = context.get_non_persons_connection().await?;+ sqlx::query("UPDATE posthog_featureflag SET version = 3 WHERE id = $1")+ .bind(flag.id)+ .execute(&mut *conn)+ .await?;++ // Stale expected_version → 409 with the actual version, and no evaluation happened.+ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "versioned-flag", 1),+ )+ .await;+ assert_eq!(res.status(), StatusCode::CONFLICT);+ let json_response = res.json::<Value>().await?;+ assert_eq!(json_response["error"], "version_conflict");+ assert_eq!(json_response["actual_version"], json!(3));++ // Matching expected_version → 200.+ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "versioned-flag", 3),+ )+ .await;+ assert_eq!(res.status(), StatusCode::OK);++ Ok(())+}++#[tokio::test]+async fn test_null_expected_version_coerces_to_zero() -> Result<()> {+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ "null-version-flag",+ json!({"groups": [{"rollout_percentage": 100}]}),+ )),+ )+ .await?;++ // JSON null and an omitted field both mean "expect version 0", matching a flag+ // whose version column is NULL.+ let null_body = json!({+ "team_id": team.id,+ "flag_key": "null-version-flag",+ "expected_version": null,+ });+ let res = send_batch_request(&server, Some(INTERNAL_TOKEN), &null_body).await;+ assert_eq!(res.status(), StatusCode::OK);++ let omitted_body = json!({+ "team_id": team.id,+ "flag_key": "null-version-flag",+ });+ let res = send_batch_request(&server, Some(INTERNAL_TOKEN), &omitted_body).await;+ assert_eq!(res.status(), StatusCode::OK);++ Ok(())+}++#[tokio::test]+async fn test_property_filter_selects_matching_persons() -> Result<()> {+ // Port of the core matching behavior in test_creating_static_cohort_iterator: persons+ // matching the property filter are included, others are not.+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ "property-flag",+ json!({+ "groups": [{+ "properties": [{"key": "key", "value": "value", "type": "person"}],+ "rollout_percentage": 100,+ }],+ }),+ )),+ )+ .await?;++ for (distinct_id, properties) in [+ ("prop_person1", json!({"key": "value"})),+ ("prop_person2", json!({"key": "value"})),+ ("prop_person3", json!({"key": "other"})),+ ("prop_person4", json!({})),+ ] {+ context+ .insert_person(team.id, distinct_id.to_string(), Some(properties))+ .await?;+ }++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "property-flag", 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::OK);+ let json_response = res.json::<Value>().await?;++ let mut expected = vec![+ context+ .get_person_uuid_by_distinct_id(team.id, "prop_person1")+ .await?,+ context+ .get_person_uuid_by_distinct_id(team.id, "prop_person2")+ .await?,+ ];+ expected.sort();++ assert_eq!(matched_uuids(&json_response), expected);+ assert_eq!(json_response["errors_count"], json!(0));+ assert_eq!(json_response["next_cursor"], Value::Null);++ Ok(())+}++#[tokio::test]+async fn test_rollout_percentage_bucketing_matches_live_hash() -> Result<()> {+ // Rollout bucketing must use the same `_hash(key, identifier)` as live evaluation.+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ let flag_key = "rollout-flag";+ context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ flag_key,+ json!({"groups": [{"rollout_percentage": 50}]}),+ )),+ )+ .await?;++ let mut expected: Vec<Uuid> = Vec::new();+ let mut expected_out = 0;+ for i in 0..20 {+ let distinct_id = format!("rollout_person_{i}");+ context+ .insert_person(team.id, distinct_id.clone(), Some(json!({})))+ .await?;+ let hash = calculate_hash(&format!("{flag_key}."), &distinct_id, "")?;+ if hash <= 0.5 {+ expected.push(+ context+ .get_person_uuid_by_distinct_id(team.id, &distinct_id)+ .await?,+ );+ } else {+ expected_out += 1;+ }+ }+ expected.sort();+ assert!(+ !expected.is_empty() && expected_out > 0,+ "test should exercise both sides of the rollout boundary"+ );++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, flag_key, 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::OK);+ let json_response = res.json::<Value>().await?;++ assert_eq!(matched_uuids(&json_response), expected);+ assert_eq!(json_response["errors_count"], json!(0));++ Ok(())+}++#[tokio::test]+async fn test_cursor_pagination_covers_all_persons() -> Result<()> {+ // Port of test_creating_static_cohort_iterator's batching behavior, now cursor-paged.+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ "paging-flag",+ json!({"groups": [{"rollout_percentage": 100}]}),+ )),+ )+ .await?;++ let mut expected: Vec<Uuid> = Vec::new();+ for i in 0..5 {+ let distinct_id = format!("paging_person_{i}");+ context+ .insert_person(team.id, distinct_id.clone(), Some(json!({})))+ .await?;+ expected.push(+ context+ .get_person_uuid_by_distinct_id(team.id, &distinct_id)+ .await?,+ );+ }+ expected.sort();++ let mut collected: Vec<Uuid> = Vec::new();+ let mut cursor: i64 = 0;+ let mut pages = 0;+ loop {+ let mut body = batch_body(team.id, "paging-flag", 0);+ body["cursor"] = json!(cursor);+ body["limit"] = json!(2);+ let res = send_batch_request(&server, Some(INTERNAL_TOKEN), &body).await;+ assert_eq!(res.status(), StatusCode::OK);+ let json_response = res.json::<Value>().await?;+ collected.extend(matched_uuids(&json_response));+ pages += 1;+ assert!(pages <= 4, "pagination should terminate");++ match json_response["next_cursor"].as_i64() {+ Some(next) => {+ assert!(next > cursor, "cursor must advance");+ cursor = next;+ }+ None => break,+ }+ }++ // 5 persons with limit 2 → 3 pages (2 + 2 + 1, last page short-circuits next_cursor).+ assert_eq!(pages, 3);+ collected.sort();+ assert_eq!(collected, expected);++ Ok(())+}++#[tokio::test]+async fn test_person_with_no_distinct_ids_is_skipped() -> Result<()> {+ // Almost-deleted persons (no distinct_ids) are skipped without counting as errors.+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ "skip-flag",+ json!({"groups": [{"rollout_percentage": 100}]}),+ )),+ )+ .await?;++ // A person with no posthog_persondistinctid rows at all.+ let orphan_uuid = Uuid::now_v7();+ let mut conn = context.get_persons_connection().await?;+ sqlx::query(+ r#"INSERT INTO posthog_person+ (created_at, properties, properties_last_updated_at, properties_last_operation,+ team_id, is_user_id, is_identified, uuid, version)+ VALUES ('2023-04-05', '{}', '{}', '{}', $1, NULL, true, $2, 0)"#,+ )+ .bind(team.id)+ .bind(orphan_uuid)+ .execute(&mut *conn)+ .await?;+ drop(conn);++ context+ .insert_person(team.id, "normal_person".to_string(), Some(json!({})))+ .await?;++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "skip-flag", 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::OK);+ let json_response = res.json::<Value>().await?;++ let expected = vec![+ context+ .get_person_uuid_by_distinct_id(team.id, "normal_person")+ .await?,+ ];+ assert_eq!(matched_uuids(&json_response), expected);+ assert_eq!(+ json_response["errors_count"],+ json!(0),+ "skipped persons are not errors"+ );++ Ok(())+}++#[tokio::test]+async fn test_distinct_id_choice_is_deterministic_min_id() -> Result<()> {+ // Evaluation uses the distinct_id with the lowest posthog_persondistinctid.id.+ // For a 50% flag, the outcome must follow the FIRST distinct_id's hash, not the+ // second's.+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ let flag_key = "deterministic-flag";+ context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ flag_key,+ json!({"groups": [{"rollout_percentage": 50}]}),+ )),+ )+ .await?;++ // Find a (first, second) distinct_id pair whose hashes land on opposite sides of the+ // rollout boundary, so the test can detect which one was used.+ let salt_prefix = format!("{flag_key}.");+ let (first, second) = (0..10_000)+ .find_map(|i| {+ let first = format!("det_first_{i}");+ let second = format!("det_second_{i}");+ let first_in = calculate_hash(&salt_prefix, &first, "").unwrap() <= 0.5;+ let second_in = calculate_hash(&salt_prefix, &second, "").unwrap() <= 0.5;+ (first_in && !second_in).then_some((first, second))+ })+ .expect("should find a hash pair on opposite sides of the boundary");++ let person_id = context+ .insert_person(team.id, first.clone(), Some(json!({})))+ .await?;+ // Second distinct_id gets a strictly higher posthog_persondistinctid.id.+ let mut conn = context.get_persons_connection().await?;+ sqlx::query(+ "INSERT INTO posthog_persondistinctid (distinct_id, person_id, team_id, version)+ VALUES ($1, $2, $3, 0)",+ )+ .bind(&second)+ .bind(person_id)+ .bind(team.id)+ .execute(&mut *conn)+ .await?;+ drop(conn);++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, flag_key, 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::OK);+ let json_response = res.json::<Value>().await?;++ let person_uuid = context+ .get_person_uuid_by_distinct_id(team.id, &first)+ .await?;+ assert_eq!(+ matched_uuids(&json_response),+ vec![person_uuid],+ "the first (min pd.id) distinct_id hashes inside the rollout, so the person must match"+ );++ Ok(())+}++#[tokio::test]+async fn test_experience_continuity_overrides_read_but_never_written() -> Result<()> {+ // An existing hash key override must be honored (read), and the batch endpoint+ // must never write new overrides (the matcher runs with skip_writes).+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ 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?;++ let salt_prefix = format!("{flag_key}.");+ // A person whose own distinct_id hashes OUT of the rollout, with an override hash key+ // that hashes IN — the override must flip them to matched.+ let overridden = (0..10_000)+ .map(|i| format!("continuity_overridden_{i}"))+ .find(|d| calculate_hash(&salt_prefix, d, "").unwrap() > 0.5)+ .unwrap();+ let override_hash_key = (0..10_000)+ .map(|i| format!("override_key_{i}"))+ .find(|d| calculate_hash(&salt_prefix, d, "").unwrap() <= 0.5)+ .unwrap();+ // A person who'd be out of the rollout with no override — must stay out.+ let plain = (0..10_000)+ .map(|i| format!("continuity_plain_{i}"))+ .find(|d| calculate_hash(&salt_prefix, d, "").unwrap() > 0.5)+ .unwrap();++ let overridden_person_id = context+ .insert_person(team.id, overridden.clone(), Some(json!({})))+ .await?;+ context+ .insert_person(team.id, plain.clone(), Some(json!({})))+ .await?;++ let mut conn = context.get_persons_connection().await?;+ sqlx::query(+ "INSERT INTO posthog_featureflaghashkeyoverride (team_id, person_id, feature_flag_key, hash_key)+ VALUES ($1, $2, $3, $4)",+ )+ .bind(team.id)+ .bind(overridden_person_id)+ .bind(flag_key)+ .bind(&override_hash_key)+ .execute(&mut *conn)+ .await?;+ drop(conn);++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, flag_key, 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::OK);+ let json_response = res.json::<Value>().await?;++ let overridden_uuid = context+ .get_person_uuid_by_distinct_id(team.id, &overridden)+ .await?;+ assert_eq!(+ matched_uuids(&json_response),+ vec![overridden_uuid],+ "the override hash key must flip the overridden person into the rollout"+ );++ // skip_writes: the batch call must not have written any new override rows.+ let mut conn = context.get_persons_connection().await?;+ let override_count: i64 = sqlx::query_scalar(+ "SELECT COUNT(*) FROM posthog_featureflaghashkeyoverride WHERE team_id = $1",+ )+ .bind(team.id)+ .fetch_one(&mut *conn)+ .await?;+ assert_eq!(+ override_count, 1,+ "batch evaluation must never write hash key overrides"+ );++ 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,+ // with live-evaluation semantics: static cohorts resolve via posthog_cohortpeople,+ // dynamic cohorts evaluate in-memory against person properties.+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ let static_cohort = context+ .insert_cohort(team.id, None, json!({}), true)+ .await?;+ let dynamic_cohort = context+ .insert_cohort(+ team.id,+ None,+ json!({"properties": {"type": "OR", "values": [{+ "type": "OR",+ "values": [{"key": "plan", "value": "premium", "type": "person"}],+ }]}}),+ false,+ )+ .await?;++ context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ "cohort-flag",+ json!({+ "groups": [+ {+ "properties": [{"key": "id", "value": static_cohort.id, "type": "cohort"}],+ "rollout_percentage": 100,+ },+ {+ "properties": [{"key": "id", "value": dynamic_cohort.id, "type": "cohort"}],+ "rollout_percentage": 100,+ },+ ],+ }),+ )),+ )+ .await?;++ // in_static: a member of the static cohort.+ let in_static_id = context+ .insert_person(team.id, "cohort_in_static".to_string(), Some(json!({})))+ .await?;+ context+ .add_person_to_cohort(static_cohort.id, in_static_id)+ .await?;+ // in_dynamic: matches the dynamic cohort's property filter.+ context+ .insert_person(+ team.id,+ "cohort_in_dynamic".to_string(),+ Some(json!({"plan": "premium"})),+ )+ .await?;+ // outsider: in neither cohort.+ context+ .insert_person(+ team.id,+ "cohort_outsider".to_string(),+ Some(json!({"plan": "free"})),+ )+ .await?;++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "cohort-flag", 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::OK);+ let json_response = res.json::<Value>().await?;++ let mut expected = vec![+ context+ .get_person_uuid_by_distinct_id(team.id, "cohort_in_static")+ .await?,+ context+ .get_person_uuid_by_distinct_id(team.id, "cohort_in_dynamic")+ .await?,+ ];+ expected.sort();++ assert_eq!(matched_uuids(&json_response), expected);+ assert_eq!(json_response["errors_count"], json!(0));++ Ok(())+}++#[tokio::test]+async fn test_missing_property_negative_operator_uses_live_semantics() -> Result<()> {+ // Live Rust evaluation explicitly treats a missing property as matching `is_not`+ // (see the IsNot arm of `match_property`). The batch endpoint must follow live:+ // a person missing the property still matches `is_not`.+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ "negation-flag",+ json!({+ "groups": [{+ "properties": [{"key": "key", "value": "value", "type": "person", "operator": "is_not"}],+ "rollout_percentage": 100,+ }],+ }),+ )),+ )+ .await?;++ context+ .insert_person(+ team.id,+ "neg_has_other_value".to_string(),+ Some(json!({"key": "other"})),+ )+ .await?;+ context+ .insert_person(team.id, "neg_missing_property".to_string(), Some(json!({})))+ .await?;++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "negation-flag", 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::OK);+ let json_response = res.json::<Value>().await?;++ let mut expected = vec![+ context+ .get_person_uuid_by_distinct_id(team.id, "neg_has_other_value")+ .await?,+ context+ .get_person_uuid_by_distinct_id(team.id, "neg_missing_property")+ .await?,+ ];+ expected.sort();+ assert_eq!(+ matched_uuids(&json_response),+ expected,+ "a person missing the property must match is_not, like live evaluation does"+ );++ Ok(())+}++#[tokio::test]+async fn test_multivariate_flag_variants_count_as_matched() -> Result<()> {+ // Cohort membership is "does the live flag match", regardless of which variant.+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ "multivariate-flag",+ json!({+ "groups": [{"rollout_percentage": 100}],+ "multivariate": {+ "variants": [+ {"key": "control", "rollout_percentage": 50},+ {"key": "test", "rollout_percentage": 50},+ ],+ },+ }),+ )),+ )+ .await?;++ let mut expected = Vec::new();+ for i in 0..4 {+ let distinct_id = format!("variant_person_{i}");+ context+ .insert_person(team.id, distinct_id.clone(), Some(json!({})))+ .await?;+ expected.push(+ context+ .get_person_uuid_by_distinct_id(team.id, &distinct_id)+ .await?,+ );+ }+ expected.sort();++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "multivariate-flag", 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::OK);+ let json_response = res.json::<Value>().await?;++ assert_eq!(matched_uuids(&json_response), expected);++ Ok(())+}++#[tokio::test]+async fn test_no_flag_analytics_emitted_for_batch_requests() -> Result<()> {+ // The batch handler bypasses the /flags pipeline by construction (no billing, no+ // flag analytics); this test pins that so a refactor can't silently reintroduce it.+ use feature_flags::flags::flag_analytics::{current_bucket, get_team_request_key};+ use feature_flags::flags::flag_request::FlagRequestType;+ use feature_flags::utils::test_utils::setup_redis_client;++ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ let server = ServerHandle::for_config(batch_eval_config()).await;++ context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ "analytics-flag",+ json!({"groups": [{"rollout_percentage": 100}]}),+ )),+ )+ .await?;+ context+ .insert_person(+ team.id,+ random_string("analytics_person", 8),+ Some(json!({})),+ )+ .await?;++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, "analytics-flag", 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::OK);++ let redis_client = setup_redis_client(None).await;+ for request_type in [FlagRequestType::Decide, FlagRequestType::FlagDefinitions] {+ let key = get_team_request_key(team.id, request_type);+ let bucket = current_bucket();+ // Billing aggregator keys are `<team_key>:<bucket>`; analytics counters use the+ // same keyspace. Neither must exist after a batch-only workload.+ for candidate in [key.clone(), format!("{key}:{bucket}")] {+ let value = redis_client.get(candidate.clone()).await;+ assert!(+ value.is_err(),+ "no analytics/billing key should exist for batch requests, found {candidate}"+ );+ }+ }++ Ok(())+}++#[tokio::test]+async fn test_batch_results_match_live_flags_evaluation() -> Result<()> {+ // The contract for static cohort generation is "cohort membership = who the live+ // flag matches". Evaluate the same flag for the same persons via the live /flags+ // endpoint and via the batch endpoint, and require identical outcomes.+ let context = TestContext::new(None).await;+ let team = context.insert_new_team(None).await?;+ // Mock redis validates the team token for the live path; flags are only in PG, so+ // both the live path (PG fallback) and the batch path read the same definitions.+ let server = ServerHandle::for_config_with_mock_redis(+ batch_eval_config(),+ vec![],+ vec![(team.api_token.clone(), team.id)],+ )+ .await;++ let flag_key = "parity-flag";+ context+ .insert_flag(+ team.id,+ Some(flag_row(+ team.id,+ flag_key,+ json!({+ "groups": [{+ "properties": [{"key": "plan", "value": "premium", "type": "person"}],+ "rollout_percentage": 50,+ }],+ }),+ )),+ )+ .await?;++ // Pick distinct_ids whose rollout hashes are known to land on both sides of the 50%+ // boundary, so the test deterministically exercises matched and unmatched persons.+ let salt_prefix = format!("{flag_key}.");+ let mut in_rollout_ids = (0..10_000)+ .map(|i| format!("parity_in_{i}"))+ .filter(|d| calculate_hash(&salt_prefix, d, "").unwrap() <= 0.5);+ let mut out_of_rollout_ids = (0..10_000)+ .map(|i| format!("parity_out_{i}"))+ .filter(|d| calculate_hash(&salt_prefix, d, "").unwrap() > 0.5);+ let persons = [+ (in_rollout_ids.next().unwrap(), json!({"plan": "premium"})),+ (in_rollout_ids.next().unwrap(), json!({"plan": "premium"})),+ (+ out_of_rollout_ids.next().unwrap(),+ json!({"plan": "premium"}),+ ),+ (in_rollout_ids.next().unwrap(), json!({"plan": "free"})),+ (out_of_rollout_ids.next().unwrap(), json!({"plan": "free"})),+ ];++ let mut live_matched: Vec<Uuid> = Vec::new();+ for (distinct_id, properties) in persons {+ context+ .insert_person(team.id, distinct_id.clone(), Some(properties))+ .await?;++ let live_response = server+ .send_flags_request(+ json!({"token": team.api_token, "distinct_id": distinct_id}).to_string(),+ Some("2"),+ None,+ )+ .await;+ assert_eq!(live_response.status(), StatusCode::OK);+ let live_json = live_response.json::<Value>().await?;+ if live_json["flags"][flag_key]["enabled"] == json!(true) {+ live_matched.push(+ context+ .get_person_uuid_by_distinct_id(team.id, &distinct_id)+ .await?,+ );+ }+ }+ live_matched.sort();+ assert_eq!(+ live_matched.len(),+ 2,+ "exactly the two premium persons inside the rollout should match live"+ );++ let res = send_batch_request(+ &server,+ Some(INTERNAL_TOKEN),+ &batch_body(team.id, flag_key, 0),+ )+ .await;+ assert_eq!(res.status(), StatusCode::OK);+ let json_response = res.json::<Value>().await?;++ assert_eq!(+ matched_uuids(&json_response),+ live_matched,+ "batch evaluation must match live /flags evaluation exactly"+ );+ assert_eq!(json_response["errors_count"], json!(0));++ Ok(())+}