: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
chore(flags): remove billing aggregator shadow mode (#59548)
Phil Haacka06806562cc8
diff --git a/rust/feature-flags/src/api/flag_definitions.rs b/rust/feature-flags/src/api/flag_definitions.rsindex e0d2094a867d..9dacfa479498 100644--- a/rust/feature-flags/src/api/flag_definitions.rs+++ b/rust/feature-flags/src/api/flag_definitions.rs@@ -8,7 +8,7 @@ use crate::{flag_analytics::is_billable_flag_key, flag_request::FlagRequestType,flag_service::FlagService,},- handler::{billing::record_billing_increment, types::Library},+ handler::types::Library,metrics::consts::{FLAG_DEFINITIONS_AUTH_COUNTER, FLAG_DEFINITIONS_CACHE_HIT_COUNTER,FLAG_DEFINITIONS_CACHE_MISS_COUNTER, FLAG_DEFINITIONS_ETAG_COUNTER,@@ -222,14 +222,9 @@ pub async fn flags_definitions(// matching Django's /local_evaluation behavior.if !*state.config.skip_writes && has_billable_flags(&cached_response) {let library = Library::from_headers(&headers);- record_billing_increment(- state.redis_client.clone(),- state.billing_aggregator.as_ref(),- team.id,- FlagRequestType::FlagDefinitions,- library,- )- .await;+ state+ .billing_aggregator+ .record(team.id, FlagRequestType::FlagDefinitions, Some(library));}Ok(ok_response_with_etag(diff --git a/rust/feature-flags/src/billing/aggregator.rs b/rust/feature-flags/src/billing/aggregator.rsindex e9e2eef6bf69..9d7dc9d1da04 100644--- a/rust/feature-flags/src/billing/aggregator.rs+++ b/rust/feature-flags/src/billing/aggregator.rs@@ -5,15 +5,10 @@//! map, and issues pipelined `HINCRBY`s to Redis. On graceful shutdown a//! final flush runs before the service exits.//!-//! # Mode-//!-//! `AggregatorMode::Shadow` writes `…:shadow`-suffixed keys for offline-//! reconciliation against the per-request synchronous HINCRBY path; both-//! writes happen on every billable request. `AggregatorMode::Authoritative`-//! writes the production billing keys directly and the per-request path is-//! skipped — at this point `flags_billing_pending_records` and-//! `flags_billing_seconds_since_successful_flush` are billing-critical-//! signals, not just reconciliation hygiene.+//! The aggregator is the authoritative writer for the production billing+//! keyspace — there is no per-request synchronous HINCRBY. That makes+//! `flags_billing_pending_records` and+//! `flags_billing_seconds_since_successful_flush` billing-critical signals.//!//! # Durability trade-off//!@@ -88,7 +83,6 @@ use tokio::task::JoinHandle;use crate::flags::flag_analytics::{current_bucket, get_team_request_key, get_team_request_library_key,- get_team_request_library_shadow_key, get_team_request_shadow_key,};use crate::flags::flag_request::FlagRequestType;use crate::handler::types::Library;@@ -229,39 +223,6 @@ pub struct AggregationKey {pub bucket: u64,}-/// Which Redis keyspace the aggregator writes to.-///-/// `Shadow` writes `…:shadow`-suffixed keys that run in parallel with the-/// authoritative per-request HINCRBY in `flag_analytics::increment_request_count`,-/// so its counts can be reconciled before cutover. `Authoritative` writes the-/// production billing keys directly — at that point the per-request HINCRBY is-/// skipped (see `handler::billing::record_billing_increment`).-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum AggregatorMode {- Shadow,- Authoritative,-}--impl AggregatorMode {- fn team_key(self, team_id: i32, request_type: FlagRequestType) -> String {- match self {- AggregatorMode::Shadow => get_team_request_shadow_key(team_id, request_type),- AggregatorMode::Authoritative => get_team_request_key(team_id, request_type),- }- }-- fn library_key(self, team_id: i32, request_type: FlagRequestType, library: Library) -> String {- match self {- AggregatorMode::Shadow => {- get_team_request_library_shadow_key(team_id, request_type, library)- }- AggregatorMode::Authoritative => {- get_team_request_library_key(team_id, request_type, library)- }- }- }-}-/// Policy for handling a chunk error during a flush. The flusher's normal/// tick uses `BailOnError` (if Redis is rejecting, save RTTs and retry next/// interval). The shutdown path uses `BestEffort` — it's our last chance to@@ -335,7 +296,6 @@ pub struct BillingAggregator {struct Inner {config: BillingAggregatorConfig,- mode: AggregatorMode,redis: Arc<dyn RedisClient + Send + Sync>,pending: Mutex<HashMap<AggregationKey, u64>>,/// Running sum of `pending.values()`. Updated under the `pending` lock so@@ -369,11 +329,9 @@ impl Inner {fn new(redis: Arc<dyn RedisClient + Send + Sync>,config: BillingAggregatorConfig,- mode: AggregatorMode,) -> Arc<Self> {Arc::new(Self {config,- mode,redis,pending: Mutex::new(HashMap::new()),pending_total: AtomicU64::new(0),@@ -408,7 +366,6 @@ impl BillingAggregator {pub fn start(redis: Arc<dyn RedisClient + Send + Sync>,config: BillingAggregatorConfig,- mode: AggregatorMode,) -> Arc<Self> {// Fail fast on misconfiguration. A misconfigured FLAGS_BILLING_*// env var would otherwise panic the flusher task silently, or silently@@ -421,7 +378,7 @@ impl BillingAggregator {let max_pending_entries = config.max_pending_entries;let per_flush_batch_size = config.per_flush_batch_size;- let inner = Inner::new(redis, config, mode);+ let inner = Inner::new(redis, config);let flusher = tokio::spawn(run_flusher(inner.clone()));let metrics_sampler = tokio::spawn(run_metrics_sampler(inner.clone()));@@ -429,7 +386,6 @@ impl BillingAggregator {flush_interval_ms,max_pending_entries,per_flush_batch_size,- mode = ?mode,"BillingAggregator started");@@ -600,29 +556,13 @@ impl BillingAggregator {pub fn for_tests(redis: Arc<dyn RedisClient + Send + Sync>,config: BillingAggregatorConfig,- ) -> Arc<Self> {- Self::for_tests_with_mode(redis, config, AggregatorMode::Shadow)- }-- #[doc(hidden)]- pub fn for_tests_with_mode(- redis: Arc<dyn RedisClient + Send + Sync>,- config: BillingAggregatorConfig,- mode: AggregatorMode,) -> Arc<Self> {Arc::new(Self {- inner: Inner::new(redis, config, mode),+ inner: Inner::new(redis, config),flusher: Mutex::new(None),metrics_sampler: Mutex::new(None),})}-- /// Read-only accessor used by `record_billing_increment` to decide whether- /// to skip the per-request HINCRBY (`Authoritative` mode) or run today's- /// dual-write coupling (`Shadow` mode).- pub fn mode(&self) -> AggregatorMode {- self.inner.mode- }}/// Spawned task: tick → drain → flush, until the shutdown signal fires.@@ -858,15 +798,13 @@ async fn flush_once(inner: &Arc<Inner>, policy: FlushPolicy) {// into the team command without an extra clone.if let Some(library) = key.library {buffer.push(PipelineCommand::HIncrBy {- key: inner- .mode- .library_key(key.team_id, key.request_type, library),+ key: get_team_request_library_key(key.team_id, key.request_type, library),field: field.clone(),count: count_i64,});}buffer.push(PipelineCommand::HIncrBy {- key: inner.mode.team_key(key.team_id, key.request_type),+ key: get_team_request_key(key.team_id, key.request_type),field,count: count_i64,});@@ -1213,9 +1151,6 @@ fn pick_jitter(flush_interval: Duration) -> Duration {#[cfg(test)]mod tests {use super::*;- use crate::flags::flag_analytics::{- get_team_request_library_shadow_key, get_team_request_shadow_key,- };use common_redis::{MockRedisClient, MockRedisValue};use rstest::rstest;@@ -1242,7 +1177,7 @@ mod tests {) -> (Arc<MockRedisClient>, Arc<BillingAggregator>) {let redis = Arc::new(redis);let agg = Arc::new(BillingAggregator {- inner: Inner::new(redis.clone(), config, AggregatorMode::Shadow),+ inner: Inner::new(redis.clone(), config),flusher: Mutex::new(None),metrics_sampler: Mutex::new(None),});@@ -1278,6 +1213,21 @@ mod tests {panic!("wait_until: condition not satisfied within 1s");}+ /// Paused-time counterpart of `wait_until`. `tokio::time::advance` wakes+ /// timer-blocked tasks but does not poll them; each `yield_now` lets the+ /// runtime schedule a ready task. `wait_until`'s 1ms sleep would itself+ /// block forever under paused time. Bounded so a stuck condition fails+ /// loudly rather than hanging the test.+ async fn yield_until(mut cond: impl FnMut() -> bool) {+ for _ in 0..1000 {+ if cond() {+ return;+ }+ tokio::task::yield_now().await;+ }+ panic!("yield_until: condition not satisfied after 1000 yields");+ }+/// Record `n` Decide requests for teams `1..=n` with the PosthogJs library./// Each call generates one team-level + one library-level entry under the/// same bucket. Used by the flush-policy tests to set up a known shape.@@ -1425,15 +1375,15 @@ mod tests {let expected_team_42_team = format!("{}:{bucket}",- get_team_request_shadow_key(42, FlagRequestType::Decide)+ get_team_request_key(42, FlagRequestType::Decide));let expected_team_42_sdk = format!("{}:{bucket}",- get_team_request_library_shadow_key(42, FlagRequestType::Decide, Library::PosthogJs)+ get_team_request_library_key(42, FlagRequestType::Decide, Library::PosthogJs));let expected_team_7_team = format!("{}:{bucket}",- get_team_request_shadow_key(7, FlagRequestType::Decide)+ get_team_request_key(7, FlagRequestType::Decide));assert!(@@ -1457,37 +1407,6 @@ mod tests {async fn test_flush_once_writes_flag_definitions_keys() {let (redis, agg) = new_test_aggregator(test_config());- agg.record(- 42,- FlagRequestType::FlagDefinitions,- Some(Library::PosthogJs),- );-- let bucket = current_bucket();- flush_once(&agg.inner, FlushPolicy::BailOnError).await;-- let calls = hincrby_calls(&redis);- let expected_team = format!("posthog:local_evaluation_requests:42:shadow:{bucket}");- let expected_sdk =- format!("posthog:local_evaluation_requests:sdk:42:posthog-js:shadow:{bucket}");- assert_eq!(calls.len(), 2);- assert!(calls.contains(&(expected_team, 1)));- assert!(calls.contains(&(expected_sdk, 1)));- }-- /// Cutover-mode counterpart to `test_flush_once_writes_flag_definitions_keys`:- /// in `Authoritative` mode the aggregator writes the production billing- /// keys without the `:shadow` suffix, so the existing- /// `calculate_decide_usage` reader picks them up unchanged.- #[tokio::test]- async fn test_flush_once_authoritative_writes_non_shadow_keys() {- let redis = Arc::new(MockRedisClient::new());- let agg = BillingAggregator::for_tests_with_mode(- redis.clone(),- test_config(),- AggregatorMode::Authoritative,- );-agg.record(42,FlagRequestType::FlagDefinitions,@@ -1508,13 +1427,13 @@ mod tests {assert!(calls.contains(&(expected_sdk_42_def, 1)));assert!(calls.contains(&(expected_team_7_decide, 1)));- // Belt-and-braces: no key the aggregator writes in authoritative mode- // should ever carry the `:shadow` suffix. A regression here would- // double-count once the per-request HINCRBY is removed.+ // Belt-and-braces: the aggregator must never write `:shadow`-suffixed+ // keys. A regression here would mean we're writing into the+ // reconciliation keyspace that has no reader.for (key, _) in &calls {assert!(!key.contains(":shadow"),- "authoritative mode wrote a shadow-suffixed key: {key}"+ "aggregator wrote a shadow-suffixed key: {key}");}}@@ -1593,6 +1512,87 @@ mod tests {}}+ #[tokio::test(start_paused = true)]+ async fn test_flusher_swallows_initial_tick_then_flushes_on_interval() {+ // The only test exercising `run_flusher`'s timing path — every other+ // test calls `flush_once` directly. Pins two invariants that the+ // direct-flush tests can't reach:+ //+ // 1. The first immediate tick from `tokio::time::interval` is+ // swallowed deliberately; no flush fires within the jitter+ // window or at interval creation.+ // 2. Subsequent ticks drive flushes on the configured cadence.+ //+ // Paused-time timing model. Jitter is in [0, 100ms] for+ // flush_interval = 1s. We yield *before* advancing so the flusher+ // parks on its `sleep(jitter)` at virtual t=0 — otherwise the+ // sleep deadline would be set relative to whatever virtual time+ // we'd already advanced to. Advancing past max_jitter wakes the+ // sleep; after the flusher resumes (via yield), it creates its+ // interval at virtual time ≈ 101ms, so the first *real* tick+ // fires at ≈ 1101ms.+ let flush_interval = Duration::from_secs(1);+ let redis = Arc::new(MockRedisClient::new());+ let agg = BillingAggregator::start(+ redis.clone(),+ BillingAggregatorConfig {+ flush_interval,+ ..test_config()+ },+ );++ agg.record(1, FlagRequestType::Decide, None);++ // Park the flusher on its jitter sleep before any advance.+ tokio::task::yield_now().await;++ // Advance past max jitter so the sleep wakes; the flusher then+ // installs its interval and swallows the immediate first tick.+ tokio::time::advance(Duration::from_millis(101)).await;+ for _ in 0..16 {+ tokio::task::yield_now().await;+ }+ assert_eq!(+ hincrby_calls(&redis).len(),+ 0,+ "the first immediate interval tick must be swallowed — a flush \+ here would mean the flusher fired at t ≈ jitter, before any \+ real tick had a chance to elapse"+ );++ // Just before the first real tick (at ≈ 1101ms).+ tokio::time::advance(Duration::from_millis(998)).await;+ for _ in 0..16 {+ tokio::task::yield_now().await;+ }+ assert_eq!(+ hincrby_calls(&redis).len(),+ 0,+ "no flush before flush_interval elapses from interval creation"+ );++ // Cross the first real tick.+ tokio::time::advance(Duration::from_millis(10)).await;+ yield_until(|| !hincrby_calls(&redis).is_empty()).await;+ assert_eq!(+ hincrby_calls(&redis).len(),+ 1,+ "first real interval tick should drive exactly one flush"+ );++ // Pin the cadence: a second record + another full interval should+ // produce a second flush. Catches a regression that fired once and+ // then stopped, or lost its interval state between ticks.+ agg.record(2, FlagRequestType::Decide, None);+ tokio::time::advance(flush_interval).await;+ yield_until(|| hincrby_calls(&redis).len() >= 2).await;+ assert_eq!(+ hincrby_calls(&redis).len(),+ 2,+ "a second flush should fire on the next interval tick"+ );+ }+#[tokio::test]async fn test_shutdown_flushes_then_stops() {let redis = Arc::new(MockRedisClient::new());@@ -1603,7 +1603,6 @@ mod tests {flush_interval: Duration::from_secs(60),..test_config()},- AggregatorMode::Shadow,);agg.record(1, FlagRequestType::Decide, None);@@ -1616,7 +1615,7 @@ mod tests {assert_eq!(calls.len(), 1, "shutdown should trigger one HIncrBy");let expected_key = format!("{}:{bucket}",- get_team_request_shadow_key(1, FlagRequestType::Decide)+ get_team_request_key(1, FlagRequestType::Decide));assert_eq!(calls[0], (expected_key, 2));}@@ -1630,7 +1629,6 @@ mod tests {flush_interval: Duration::from_secs(60),..test_config()},- AggregatorMode::Shadow,);agg.record(1, FlagRequestType::Decide, None);@@ -1658,7 +1656,6 @@ mod tests {shutdown_flush_timeout: Duration::from_millis(100),..test_config()},- AggregatorMode::Shadow,);agg.record(1, FlagRequestType::Decide, None);@@ -2064,7 +2061,6 @@ mod tests {per_flush_batch_size: 2,..test_config()},- AggregatorMode::Shadow,);record_n_decide_with_library(&agg, 5);@@ -2145,7 +2141,7 @@ mod tests {// The mock records calls as "{key}:{field}", so a per-bucket HINCRBY// shows up under "{team_key}:{bucket}".- let team_key = get_team_request_shadow_key(1, FlagRequestType::Decide);+ let team_key = get_team_request_key(1, FlagRequestType::Decide);let calls = hincrby_calls(&redis);let bucket_100_key = format!("{team_key}:100");let bucket_101_key = format!("{team_key}:101");@@ -2208,7 +2204,7 @@ mod tests {shutdown_flush_timeout: Duration::from_millis(50),..test_config()};- let agg = BillingAggregator::start(redis, config, AggregatorMode::Shadow);+ let agg = BillingAggregator::start(redis, config);for _ in 0..7 {agg.record(1, FlagRequestType::Decide, None);@@ -2538,7 +2534,6 @@ mod tests {flush_interval: Duration::ZERO,..test_config()},- AggregatorMode::Shadow,);}}diff --git a/rust/feature-flags/src/billing/mod.rs b/rust/feature-flags/src/billing/mod.rsindex 48dd2335daed..dd7bf16a409b 100644--- a/rust/feature-flags/src/billing/mod.rs+++ b/rust/feature-flags/src/billing/mod.rs@@ -1,19 +1,12 @@//! Billing counters for the feature-flags service.//!-//! - In `AggregatorMode::Shadow`, the authoritative billing write is the-//! synchronous per-request-//! [`crate::flags::flag_analytics::increment_request_count`], and-//! [`aggregator`] tees a parallel write to `…:shadow`-suffixed keys via-//! [`crate::flags::flag_analytics::get_team_request_shadow_key`] for-//! offline reconciliation.-//! - In `AggregatorMode::Authoritative`, [`aggregator`] *is* the-//! authoritative writer — it writes the production billing keys and the-//! per-request synchronous HINCRBY is skipped.-//! - [`limiters`] reads the production counters to enforce per-tenant-//! quotas; the same keys are read regardless of mode.+//! - [`aggregator`] is the authoritative writer for the production billing+//! keyspace. Each pod aggregates billable requests in memory and flushes+//! them to Redis on a periodic tick (and on graceful shutdown).+//! - [`limiters`] reads the same counters to enforce per-tenant quotas.pub mod aggregator;pub mod limiters;-pub use aggregator::{AggregationKey, AggregatorMode, BillingAggregator, BillingAggregatorConfig};+pub use aggregator::{AggregationKey, BillingAggregator, BillingAggregatorConfig};pub use limiters::{FeatureFlagsLimiter, SessionReplayLimiter};diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rsindex 8a8f8bd0379a..37e13c26c0aa 100644--- a/rust/feature-flags/src/config.rs+++ b/rust/feature-flags/src/config.rs@@ -11,8 +11,6 @@ use std::path::{Path, PathBuf};use std::str::FromStr;use tracing::Level;-use crate::billing::AggregatorMode;-#[derive(Debug, Clone, PartialEq, Eq)]pub struct FlexBool(pub bool);@@ -99,42 +97,6 @@ impl FromStr for BotFilterMode {}}-/// Tristate selector for the in-process billing aggregator. Encoded as one-/// enum so `(authoritative=true, enabled=false)` is unrepresentable — the-/// previous two-boolean form allowed it and `server.rs` had to panic on it.-/// See `AggregatorMode` for what each non-`Off` variant does at runtime.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum AggregatorModeConfig {- Off,- Shadow,- Authoritative,-}--impl FromStr for AggregatorModeConfig {- type Err = String;-- fn from_str(s: &str) -> Result<Self, Self::Err> {- match s.trim().to_lowercase().as_str() {- "off" => Ok(AggregatorModeConfig::Off),- "shadow" => Ok(AggregatorModeConfig::Shadow),- "authoritative" => Ok(AggregatorModeConfig::Authoritative),- _ => Err(format!(- "Invalid FLAGS_BILLING_AGGREGATOR_MODE: '{s}'. Expected 'off', 'shadow', or 'authoritative'"- )),- }- }-}--impl AggregatorModeConfig {- pub fn into_runtime(self) -> Option<AggregatorMode> {- match self {- AggregatorModeConfig::Off => None,- AggregatorModeConfig::Shadow => Some(AggregatorMode::Shadow),- AggregatorModeConfig::Authoritative => Some(AggregatorMode::Authoritative),- }- }-}-#[derive(Debug, Clone, PartialEq, Eq)]pub enum TeamIdCollection {All,@@ -863,14 +825,6 @@ pub struct Config {#[envconfig(from = "SERVICE_MODE", default = "all")]pub service_mode: ServiceMode,- // Selects the in-process billing aggregator mode. See `AggregatorModeConfig`.- // Defaults to `shadow` to match what's deployed in dev/prod-eu/prod-us today,- // so swapping the old `FLAGS_BILLING_AGGREGATOR_ENABLED=true` env var for- // unsetting it leaves runtime behavior unchanged. `default_test_config` keeps- // `Off` so tests that don't opt in don't start the aggregator.- #[envconfig(from = "FLAGS_BILLING_AGGREGATOR_MODE", default = "shadow")]- pub billing_aggregator_mode: AggregatorModeConfig,-// BillingAggregator tuning knobs. `BillingAggregatorConfig::validate`// rejects zero values at boot — see the module docs on// `src/billing/aggregator.rs` for the durability trade-offs that hang@@ -1010,6 +964,16 @@ impl Config {}}+ /// Baseline config for the integration test harness.+ ///+ /// Diverges from production defaults in one billing-critical way:+ /// `billing_flush_interval_ms` is 100 (vs 10_000 in production). Tests+ /// that poll Redis for an aggregator write expect a flush inside their+ /// ~1s budget; tests that assert *absence* of a write sleep ≥ 500ms+ /// (several flush windows) before reading. If you raise this default,+ /// audit `test_skip_writes_suppresses_billing_redis_counter` and+ /// `test_flag_definitions_billing_counter` — their negative-case sleeps+ /// must cover at least one full flush window.pub fn default_test_config() -> Self {Self {continuous_profiling: ContinuousProfilingConfig::default(),@@ -1112,8 +1076,7 @@ impl Config {service_mode: ServiceMode::All,auth_token_cache_ttl_seconds: 300,internal_request_token: None,- billing_aggregator_mode: AggregatorModeConfig::Off,- billing_flush_interval_ms: 10_000,+ billing_flush_interval_ms: 100,billing_max_pending_entries: 500_000,billing_per_flush_batch_size: 200,billing_shutdown_flush_timeout_ms: 15_000,@@ -1184,6 +1147,17 @@ impl Config {}}+ pub fn get_billing_aggregator_config(&self) -> crate::billing::BillingAggregatorConfig {+ crate::billing::BillingAggregatorConfig {+ flush_interval: std::time::Duration::from_millis(self.billing_flush_interval_ms),+ max_pending_entries: self.billing_max_pending_entries,+ per_flush_batch_size: self.billing_per_flush_batch_size,+ shutdown_flush_timeout: std::time::Duration::from_millis(+ self.billing_shutdown_flush_timeout_ms,+ ),+ }+ }+/// Check if persons database routing is enabledpub fn is_persons_db_routing_enabled(&self) -> bool {!self.persons_read_database_url.is_empty() && !self.persons_write_database_url.is_empty()@@ -1217,7 +1191,6 @@ pub static DEFAULT_TEST_CONFIG: Lazy<Config> = Lazy::new(Config::default_test_co#[cfg(test)]mod tests {use super::*;- use rstest::rstest;#[test]fn test_default_config() {@@ -1259,7 +1232,6 @@ mod tests {// posture so a future env-var rename / refactor can't silently// flip it back to Enforced.assert_eq!(config.bot_filter_mode, BotFilterMode::LogOnly);- assert_eq!(config.billing_aggregator_mode, AggregatorModeConfig::Shadow);}#[test]@@ -1322,40 +1294,6 @@ mod tests {);}- #[rstest]- #[case::off("off", AggregatorModeConfig::Off)]- #[case::shadow("shadow", AggregatorModeConfig::Shadow)]- #[case::authoritative("authoritative", AggregatorModeConfig::Authoritative)]- #[case::trim_and_lowercase(" SHADOW ", AggregatorModeConfig::Shadow)]- fn aggregator_mode_config_parses_valid_values(- #[case] input: &str,- #[case] expected: AggregatorModeConfig,- ) {- assert_eq!(input.parse::<AggregatorModeConfig>().unwrap(), expected);- }-- #[test]- fn aggregator_mode_config_rejects_invalid_value() {- let err = "yes".parse::<AggregatorModeConfig>().unwrap_err();- assert!(- err.contains("Invalid FLAGS_BILLING_AGGREGATOR_MODE"),- "unexpected error message: {err}"- );- }-- #[test]- fn aggregator_mode_config_into_runtime_maps_correctly() {- assert_eq!(AggregatorModeConfig::Off.into_runtime(), None);- assert_eq!(- AggregatorModeConfig::Shadow.into_runtime(),- Some(AggregatorMode::Shadow)- );- assert_eq!(- AggregatorModeConfig::Authoritative.into_runtime(),- Some(AggregatorMode::Authoritative)- );- }-#[test]fn test_team_ids_to_track_all() {let team_ids: TeamIdCollection = "all".parse().unwrap();@@ -1682,6 +1620,27 @@ mod service_mode_tests {assert!("off".parse::<BotFilterMode>().is_err());assert!("true".parse::<BotFilterMode>().is_err());}++ /// Pin the `Config → BillingAggregatorConfig` field mapping. A swap of+ /// `from_millis`/`from_secs`, or a transposition of `flush_interval` and+ /// `shutdown_flush_timeout`, would silently change the production+ /// flush cadence by 1000×.+ #[test]+ fn get_billing_aggregator_config_maps_fields_correctly() {+ use std::time::Duration;+ let mut config = Config::default_test_config();+ config.billing_flush_interval_ms = 250;+ config.billing_max_pending_entries = 99;+ config.billing_per_flush_batch_size = 7;+ config.billing_shutdown_flush_timeout_ms = 5_000;++ let bcfg = config.get_billing_aggregator_config();++ assert_eq!(bcfg.flush_interval, Duration::from_millis(250));+ assert_eq!(bcfg.max_pending_entries, 99);+ assert_eq!(bcfg.per_flush_batch_size, 7);+ assert_eq!(bcfg.shutdown_flush_timeout, Duration::from_millis(5_000));+ }}#[cfg(test)]diff --git a/rust/feature-flags/src/flags/flag_analytics.rs b/rust/feature-flags/src/flags/flag_analytics.rsindex b5f801bbe356..fc8ccb31063d 100644--- a/rust/feature-flags/src/flags/flag_analytics.rs+++ b/rust/feature-flags/src/flags/flag_analytics.rs@@ -1,8 +1,5 @@use crate::flags::flag_request::FlagRequestType;use crate::handler::types::Library;-use anyhow::Result;-use common_redis::{Client as RedisClient, CustomRedisError, PipelineCommand};-use std::sync::Arc;use std::time::{SystemTime, UNIX_EPOCH};pub const SURVEY_TARGETING_FLAG_PREFIX: &str = "survey-targeting-";@@ -43,69 +40,9 @@ pub fn get_team_request_library_key(}}-/// Suffix appended to a production key to obtain its shadow-keyspace mirror.-/// The `BillingAggregator` writes to shadow keys so its counts can be-/// reconciled against the authoritative synchronous path without affecting-/// billing.-pub const SHADOW_KEY_SUFFIX: &str = ":shadow";--pub fn get_team_request_shadow_key(team_id: i32, request_type: FlagRequestType) -> String {- format!(- "{}{SHADOW_KEY_SUFFIX}",- get_team_request_key(team_id, request_type)- )-}--pub fn get_team_request_library_shadow_key(- team_id: i32,- request_type: FlagRequestType,- library: Library,-) -> String {- format!(- "{}{SHADOW_KEY_SUFFIX}",- get_team_request_library_key(team_id, request_type, library)- )-}--/// Synchronous, per-request HINCRBY into the production billing keyspace.-/// This is the authoritative billing write — see `crate::billing` for the-/// dual-write contract.-pub async fn increment_request_count(- redis_client: Arc<dyn RedisClient + Send + Sync>,- team_id: i32,- count: i64,- request_type: FlagRequestType,- library: Option<Library>,-) -> Result<(), CustomRedisError> {- let time_bucket_str = current_bucket().to_string();- let key_name = get_team_request_key(team_id, request_type);-- // Build pipeline commands for a single Redis round-trip- let mut commands = vec![PipelineCommand::HIncrBy {- key: key_name,- field: time_bucket_str.clone(),- count,- }];-- if let Some(lib) = library {- let library_key = get_team_request_library_key(team_id, request_type, lib);- commands.push(PipelineCommand::HIncrBy {- key: library_key,- field: time_bucket_str,- count,- });- }-- // Execute all commands in a single round-trip- redis_client.execute_pipeline(commands).await?;-- Ok(())-}-#[cfg(test)]mod tests {use super::*;- use crate::utils::test_utils::setup_redis_client;#[tokio::test]async fn test_get_team_request_key() {@@ -152,295 +89,4 @@ mod tests {"posthog:decide_requests:sdk:102:other");}-- #[test]- fn test_get_team_request_shadow_key() {- assert_eq!(- get_team_request_shadow_key(123, FlagRequestType::Decide),- "posthog:decide_requests:123:shadow"- );- assert_eq!(- get_team_request_shadow_key(456, FlagRequestType::FlagDefinitions),- "posthog:local_evaluation_requests:456:shadow"- );- }-- #[test]- fn test_get_team_request_library_shadow_key() {- assert_eq!(- get_team_request_library_shadow_key(123, FlagRequestType::Decide, Library::PosthogNode),- "posthog:decide_requests:sdk:123:posthog-node:shadow"- );- assert_eq!(- get_team_request_library_shadow_key(- 456,- FlagRequestType::FlagDefinitions,- Library::PosthogJs- ),- "posthog:local_evaluation_requests:sdk:456:posthog-js:shadow"- );- }-- #[test]- fn test_shadow_keys_never_collide_with_production_keys() {- // The reconciliation strategy depends on the two keyspaces being- // disjoint — a shared key would corrupt the production count.- for team_id in [1, 100_000, i32::MAX] {- for rt in [FlagRequestType::Decide, FlagRequestType::FlagDefinitions] {- assert_ne!(- get_team_request_key(team_id, rt),- get_team_request_shadow_key(team_id, rt)- );- for lib in [Library::PosthogNode, Library::PosthogJs, Library::Other] {- assert_ne!(- get_team_request_library_key(team_id, rt, lib),- get_team_request_library_shadow_key(team_id, rt, lib)- );- }- }- }- }-- #[tokio::test]- async fn test_increment_request_count() {- let redis_client = setup_redis_client(None).await;-- let team_id = 789;- let count = 5;-- let decide_key = get_team_request_key(team_id, FlagRequestType::Decide);- let flag_definitions_key = get_team_request_key(team_id, FlagRequestType::FlagDefinitions);-- // Clean up Redis before the test to ensure no leftover data- redis_client.del(decide_key.clone()).await.unwrap();- redis_client- .del(flag_definitions_key.clone())- .await- .unwrap();-- // Test for Decide request type- increment_request_count(- redis_client.clone(),- team_id,- count,- FlagRequestType::Decide,- None,- )- .await- .unwrap();-- // Test for FlagDefinitions request type- increment_request_count(- redis_client.clone(),- team_id,- count,- FlagRequestType::FlagDefinitions,- None,- )- .await- .unwrap();-- // Get the current time bucket- let time_bucket = SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap()- .as_secs()- / CACHE_BUCKET_SIZE;-- // Verify the counts in Redis- let decide_count: i64 = redis_client- .hget(decide_key.clone(), time_bucket.to_string())- .await- .unwrap()- .parse()- .unwrap();- let flag_definitions_count: i64 = redis_client- .hget(flag_definitions_key.clone(), time_bucket.to_string())- .await- .unwrap()- .parse()- .unwrap();-- assert_eq!(decide_count, count);- assert_eq!(flag_definitions_count, count);-- // Clean up Redis after the test- redis_client.del(decide_key).await.unwrap();- redis_client.del(flag_definitions_key).await.unwrap();- }-- #[tokio::test]- async fn test_increment_request_count_with_sdk() {- let redis_client = setup_redis_client(None).await;-- let team_id = 999;- let count = 10;-- let decide_key = get_team_request_key(team_id, FlagRequestType::Decide);- let library_key =- get_team_request_library_key(team_id, FlagRequestType::Decide, Library::PosthogNode);-- redis_client.del(decide_key.clone()).await.unwrap();- redis_client.del(library_key.clone()).await.unwrap();-- increment_request_count(- redis_client.clone(),- team_id,- count,- FlagRequestType::Decide,- Some(Library::PosthogNode),- )- .await- .unwrap();-- let time_bucket = SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap()- .as_secs()- / CACHE_BUCKET_SIZE;-- let decide_count: i64 = redis_client- .hget(decide_key.clone(), time_bucket.to_string())- .await- .unwrap()- .parse()- .unwrap();- let library_count: i64 = redis_client- .hget(library_key.clone(), time_bucket.to_string())- .await- .unwrap()- .parse()- .unwrap();-- assert_eq!(decide_count, count);- assert_eq!(library_count, count);-- redis_client.del(decide_key).await.unwrap();- redis_client.del(library_key).await.unwrap();- }-- #[tokio::test]- async fn test_increment_request_count_without_library() {- let redis_client = setup_redis_client(None).await;-- let team_id = 888;- let count = 7;-- let decide_key = get_team_request_key(team_id, FlagRequestType::Decide);- // Use a sample library key to verify it doesn't get created- let library_key =- get_team_request_library_key(team_id, FlagRequestType::Decide, Library::PosthogNode);-- redis_client.del(decide_key.clone()).await.unwrap();- redis_client.del(library_key.clone()).await.unwrap();-- increment_request_count(- redis_client.clone(),- team_id,- count,- FlagRequestType::Decide,- None,- )- .await- .unwrap();-- let time_bucket = SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap()- .as_secs()- / CACHE_BUCKET_SIZE;-- let decide_count: i64 = redis_client- .hget(decide_key.clone(), time_bucket.to_string())- .await- .unwrap()- .parse()- .unwrap();-- assert_eq!(decide_count, count);-- // Verify no library key was created when None was passed- // hget returns empty string for non-existent keys in this implementation- let library_value: String = redis_client- .hget(library_key.clone(), time_bucket.to_string())- .await- .unwrap_or_default();- assert!(- library_value.is_empty(),- "Library key should not exist when None is passed"- );-- redis_client.del(decide_key).await.unwrap();- }-- #[tokio::test]- async fn test_multiple_libraries_same_team() {- let redis_client = setup_redis_client(None).await;-- let team_id = 777;- let count = 3;-- let decide_key = get_team_request_key(team_id, FlagRequestType::Decide);- let js_key =- get_team_request_library_key(team_id, FlagRequestType::Decide, Library::PosthogJs);- let node_key =- get_team_request_library_key(team_id, FlagRequestType::Decide, Library::PosthogNode);-- redis_client.del(decide_key.clone()).await.unwrap();- redis_client.del(js_key.clone()).await.unwrap();- redis_client.del(node_key.clone()).await.unwrap();-- increment_request_count(- redis_client.clone(),- team_id,- count,- FlagRequestType::Decide,- Some(Library::PosthogJs),- )- .await- .unwrap();-- increment_request_count(- redis_client.clone(),- team_id,- count,- FlagRequestType::Decide,- Some(Library::PosthogNode),- )- .await- .unwrap();-- let time_bucket = SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap()- .as_secs()- / CACHE_BUCKET_SIZE;-- let decide_count: i64 = redis_client- .hget(decide_key.clone(), time_bucket.to_string())- .await- .unwrap()- .parse()- .unwrap();- let js_count: i64 = redis_client- .hget(js_key.clone(), time_bucket.to_string())- .await- .unwrap()- .parse()- .unwrap();- let node_count: i64 = redis_client- .hget(node_key.clone(), time_bucket.to_string())- .await- .unwrap()- .parse()- .unwrap();-- assert_eq!(decide_count, count * 2);- assert_eq!(js_count, count);- assert_eq!(node_count, count);-- redis_client.del(decide_key).await.unwrap();- redis_client.del(js_key).await.unwrap();- redis_client.del(node_key).await.unwrap();- }}diff --git a/rust/feature-flags/src/handler/billing.rs b/rust/feature-flags/src/handler/billing.rsindex 18071212e0ff..874e5af08456 100644--- a/rust/feature-flags/src/handler/billing.rs+++ b/rust/feature-flags/src/handler/billing.rs@@ -1,40 +1,15 @@use crate::{api::{errors::FlagError, types::FlagsResponse},- billing::{aggregator::classify_redis_error, AggregatorMode, BillingAggregator},flags::{- flag_analytics::{increment_request_count, is_billable_flag_key},- flag_models::FeatureFlagList,+ flag_analytics::is_billable_flag_key, flag_models::FeatureFlagList,flag_request::FlagRequestType,},- metrics::consts::{FLAG_BILLING_INCREMENT_TIME, FLAG_REQUEST_REDIS_ERROR},};-use common_metrics::{histogram, inc};-use common_redis::{Client as RedisClient, CustomRedisError};use limiters::redis::ServiceName;use std::collections::HashMap;-use std::sync::Arc;-use std::time::Instant;-use super::canonical_log::with_canonical_log;use super::types::{Library, RequestContext};-/// Emit the `flags_billing_increment_time_ms` histogram for a completed-/// `increment_request_count` call, bucketing the Redis result into-/// `outcome="ok" | "timeout" | "error"` to isolate the happy path from-/// Redis timeouts.-pub fn record_billing_increment_timing(result: &Result<(), CustomRedisError>, elapsed_ms: u64) {- let outcome = match result {- Ok(()) => "ok",- Err(CustomRedisError::Timeout) => "timeout",- Err(_) => "error",- };- histogram(- FLAG_BILLING_INCREMENT_TIME,- &[("outcome".to_string(), outcome.to_string())],- elapsed_ms as f64,- );-}-pub async fn check_limits(context: &RequestContext,verified_token: &str,@@ -56,111 +31,43 @@ pub async fn check_limits(Ok(None)}-/// Records a billable request against the production billing keyspace.-///-/// Caller is responsible for the predicate (skip_writes, billable flags,-/// internal requests, etc.) — by the time this is called the request is-/// known to be billable.-///-/// Behavior depends on the aggregator's mode:-///-/// - **No aggregator, or `AggregatorMode::Shadow`**: the authoritative write-/// is the synchronous per-request `increment_request_count`. The shadow-/// tee fires only when the synchronous write succeeds — recording a-/// request the production keyspace did not capture would surface as a-/// false "aggregator over-counted" signal during reconciliation, masking-/// any real over-count bug in the aggregator. Tying the two writes-/// together keeps the reconciliation invariant a strict equality: if-/// shadow > prod and `flag_request_redis_error` is flat, the aggregator-/// is the cause.-/// - **`AggregatorMode::Authoritative`**: the aggregator *is* the-/// authoritative writer. We skip `increment_request_count` (no-/// per-request Redis I/O on this path) and `aggregator.record()` is the-/// only billing write. The reconciliation invariant from shadow mode no-/// longer applies — pending records live in process memory until the-/// next flush, so `flags_billing_pending_records` and-/// `flags_billing_seconds_since_successful_flush` become-/// billing-critical signals.-pub async fn record_billing_increment(- redis: Arc<dyn RedisClient + Send + Sync>,- aggregator: Option<&Arc<BillingAggregator>>,- team_id: i32,- request_type: FlagRequestType,- library: Library,-) {- if let Some(aggregator) = aggregator {- if aggregator.mode() == AggregatorMode::Authoritative {- // billing_duration_ms measures in-process record latency (not Redis- // RTT) for dashboard continuity across cutover.- let start = Instant::now();- aggregator.record(team_id, request_type, Some(library));- let elapsed_ms = start.elapsed().as_millis() as u64;- with_canonical_log(|log| log.billing_duration_ms = Some(elapsed_ms));- return;- }- }-- let start = Instant::now();- let result = increment_request_count(redis, team_id, 1, request_type, Some(library)).await;- let elapsed_ms = start.elapsed().as_millis() as u64;-- record_billing_increment_timing(&result, elapsed_ms);- // No-op outside a canonical-log scope (e.g. /flags/definitions), so safe- // to call from every site.- with_canonical_log(|log| log.billing_duration_ms = Some(elapsed_ms));-- match result {- Ok(()) => {- if let Some(aggregator) = aggregator {- aggregator.record(team_id, request_type, Some(library));- }- }- Err(e) => {- // Bounded `error_type` label (e.g. "timeout"/"transport") —- // never the raw error message. The full `CustomRedisError::Display`- // can include unbounded transport details that would explode- // metric cardinality if used as a Prometheus label.- inc(- FLAG_REQUEST_REDIS_ERROR,- &[(- "error_type".to_string(),- classify_redis_error(&e).to_string(),- )],- 1,- );- }- }-}-/// Records usage metrics for feature flag requests. Survey and product tour/// targeting flags are not billable. The `library` parameter is detected-/// once at the start of request processing and reused.-pub async fn record_usage(+/// once at the start of request processing and reused. The aggregator's+/// periodic flush is the only writer of these counts —+/// `flags_billing_pending_records` and+/// `flags_billing_seconds_since_successful_flush` are billing-critical+/// signals.+pub fn record_usage(context: &RequestContext,filtered_flags: &FeatureFlagList,team_id: i32,library: Library,is_internal: bool,) {- if *context.state.config.skip_writes {- return;- }- // Skip billing for internal requests.- if is_internal {- return;- }- if !contains_billable_flags(filtered_flags) {- return;+ if should_record_billable_request(+ *context.state.config.skip_writes,+ is_internal,+ filtered_flags,+ ) {+ context+ .state+ .billing_aggregator+ .record(team_id, FlagRequestType::Decide, Some(library));}+}- record_billing_increment(- context.state.redis_client.clone(),- context.state.billing_aggregator.as_ref(),- team_id,- FlagRequestType::Decide,- library,- )- .await;+/// Predicate gate for `record_usage`. Extracted so the predicate ordering+/// (`skip_writes` → internal-request → billable-flag) can be unit-tested+/// without standing up a full `RequestContext`. Internal requests must+/// short-circuit before the billable-flag check so an internal request with+/// billable flags doesn't slip past.+pub(crate) fn should_record_billable_request(+ skip_writes: bool,+ is_internal: bool,+ filtered_flags: &FeatureFlagList,+) -> bool {+ !skip_writes && !is_internal && contains_billable_flags(filtered_flags)}/// Checks if the flag list contains any billable flags.@@ -177,7 +84,6 @@ fn contains_billable_flags(filtered_flags: &FeatureFlagList) -> bool {#[cfg(test)]mod tests {use super::*;- use crate::billing::BillingAggregatorConfig;use crate::flags::feature_flag_list::PreparedFlags;use crate::flags::flag_analytics::{PRODUCT_TOUR_TARGETING_FLAG_PREFIX, SURVEY_TARGETING_FLAG_PREFIX,@@ -185,52 +91,9 @@ mod tests {use crate::flags::flag_models::FeatureFlag;use crate::mock;use crate::utils::mock::MockInto;- use common_redis::MockRedisClient;- use rstest::rstest;use std::collections::HashSet;- /// Pins the cutover branch in `record_billing_increment`: in `Authoritative`- /// mode the per-request HINCRBY is skipped (aggregator is the only writer);- /// in `Shadow` mode the per-request HINCRBY runs and the aggregator tees the- /// record on success.- #[rstest]- #[case::authoritative(AggregatorMode::Authoritative, false)]- #[case::shadow(AggregatorMode::Shadow, true)]- #[tokio::test]- async fn record_billing_increment_routes_by_mode(- #[case] mode: AggregatorMode,- #[case] expect_per_request_redis_call: bool,- ) {- let per_request_redis = Arc::new(MockRedisClient::new());- let aggregator_redis = Arc::new(MockRedisClient::new());- let aggregator = BillingAggregator::for_tests_with_mode(- aggregator_redis,- BillingAggregatorConfig::default(),- mode,- );-- record_billing_increment(- per_request_redis.clone(),- Some(&aggregator),- 42,- FlagRequestType::Decide,- Library::PosthogJs,- )- .await;-- assert_eq!(- !per_request_redis.get_calls().is_empty(),- expect_per_request_redis_call,- "per-request Redis call expectation mismatch for mode {mode:?}"- );- assert_eq!(- aggregator.pending_total(),- 1,- "aggregator must hold the recorded count regardless of mode"- );- }-#[test]fn test_contains_billable_flags_only_survey_flags() {let flag_list: FeatureFlagList = vec![@@ -409,4 +272,22 @@ mod tests {// Should record usage: first flag doesn't START with prefix, second does start with prefixassert!(contains_billable_flags(&flag_list));}++ /// Pin the predicate ordering for `record_usage`: any of `skip_writes`,+ /// `is_internal`, or "no billable flags" must skip the aggregator write.+ /// Integration tests cover `skip_writes` but not `is_internal` (no header+ /// path), so this unit test is the only guard for that branch.+ #[test]+ fn should_record_billable_request_obeys_each_guard() {+ let billable: FeatureFlagList =+ vec![mock!(FeatureFlag, id: 1, key: "billable-flag".mock_into())].mock_into();+ let non_billable: FeatureFlagList =+ vec![mock!(FeatureFlag, id: 1, key: format!("{SURVEY_TARGETING_FLAG_PREFIX}survey1"))]+ .mock_into();++ assert!(should_record_billable_request(false, false, &billable));+ assert!(!should_record_billable_request(true, false, &billable));+ assert!(!should_record_billable_request(false, true, &billable));+ assert!(!should_record_billable_request(false, false, &non_billable));+ }}diff --git a/rust/feature-flags/src/handler/canonical_log.rs b/rust/feature-flags/src/handler/canonical_log.rsindex 15b877ec39d2..6e35d1884503 100644--- a/rust/feature-flags/src/handler/canonical_log.rs+++ b/rust/feature-flags/src/handler/canonical_log.rs@@ -292,14 +292,6 @@ pub struct FlagsCanonicalLogLine {/// `team_id` is resolved.pub phases: PhaseDurations,- /// Duration of the synchronous Redis HINCRBY billing increment in- /// milliseconds. Only populated from endpoints that run inside a canonical- /// log scope (currently `/flags` and `/decide`). `None` when billing was- /// skipped (no billable flags or `skip_writes`), or when called from an- /// endpoint that does not emit a canonical log line (e.g.- /// `/flags/definitions`).- pub billing_duration_ms: Option<u64>,-// Cache sources (populated during data fetching)/// Where team metadata was fetched from: "redis", "s3", "fallback", or None if not fetchedpub team_cache_source: Option<&'static str>,@@ -361,7 +353,6 @@ impl Default for FlagsCanonicalLogLine {concurrency_limit_wait_ms: None,body_read_ms: None,phases: PhaseDurations::default(),- billing_duration_ms: None,team_cache_source: None,http_status: 200,error_code: None,@@ -434,7 +425,6 @@ impl FlagsCanonicalLogLine {pre_handler_duration_ms = self.pre_handler_duration_ms,concurrency_limit_wait_ms = self.concurrency_limit_wait_ms,body_read_ms = self.body_read_ms,- billing_duration_ms = self.billing_duration_ms,team_cache_source = self.team_cache_source,error_code = self.error_code,is_bot = self.is_bot,diff --git a/rust/feature-flags/src/handler/mod.rs b/rust/feature-flags/src/handler/mod.rsindex 25fcbcaaa30a..0233dcee0f2b 100644--- a/rust/feature-flags/src/handler/mod.rs+++ b/rust/feature-flags/src/handler/mod.rs@@ -268,8 +268,7 @@ async fn process_request_inner(team.id,metrics_data.library,is_internal,- )- .await;+ );}responsediff --git a/rust/feature-flags/src/handler/phases.rs b/rust/feature-flags/src/handler/phases.rsindex 76398ba49337..7500b4b931b6 100644--- a/rust/feature-flags/src/handler/phases.rs+++ b/rust/feature-flags/src/handler/phases.rs@@ -3,11 +3,10 @@//! The handler's async body is a sequence of contiguous spans of work//! between state transitions: `auth → billing_check → cookieless →//! fetch_and_filter → evaluate → record_billing → config_response`.-//! Existing histograms (e.g. `flags_properties_db_fetch_time`,-//! `flags_billing_increment_time_ms`) cover individual downstream calls,-//! but a phase-level breakdown is the only way to attribute a multi-second-//! request spike to the responsible await site when the underlying-//! resource is itself un-instrumented.+//! Existing histograms (e.g. `flags_properties_db_fetch_time`) cover+//! individual downstream calls, but a phase-level breakdown is the only way+//! to attribute a multi-second request spike to the responsible await site+//! when the underlying resource is itself un-instrumented.//!//! [`PhaseGuard`] is the entry point. Construct one at the start of each//! phase; on drop it:@@ -56,8 +55,8 @@ pub enum Phase {/// Flag evaluation: dependency graph build, per-flag matching,/// hash-key override resolution, group/cohort fetches.Evaluate = 4,- /// On-path billing increment (Redis HINCRBY) plus shadow-keyspace tee.- /// Awaited, not fire-and-forget; counts toward request latency.+ /// In-process aggregator record for the billable request. No Redis I/O+ /// on this path; the aggregator flushes batched counts asynchronously.RecordBilling = 5,/// Building the response payload from the cached config blob.ConfigResponse = 6,diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex c3805b64ed81..701cab5f8cd6 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -141,18 +141,6 @@ pub const DB_CONNECTION_POOL_IDLE_COUNTER: &str = "flags_db_connection_pool_idlepub const DB_CONNECTION_POOL_MAX_COUNTER: &str = "flags_db_connection_pool_max_total";pub const DB_CONNECTION_POOL_SIZE_GAUGE: &str = "flags_db_connection_pool_size";-// Synchronous-path billing increment timing.-// Labeled by `outcome` ("ok" | "timeout" | "error") to isolate the happy-// path from Redis timeouts.-pub const FLAG_BILLING_INCREMENT_TIME: &str = "flags_billing_increment_time_ms";--// Counter for Redis errors observed during the synchronous billing-// increment. Labeled by `error_type` ("timeout" | "transport" | "not_found"-// | "parse" | "config") — same classification the billing flusher uses, so-// breakdowns line up across both paths. The raw error message is never used-// as a label (cardinality risk).-pub const FLAG_REQUEST_REDIS_ERROR: &str = "flag_request_redis_error";-// Billing aggregator metrics// See `src/billing/aggregator.rs`. The accounting identity// flags_billing_records_total ≈ flags_billing_entries_flushed_totaldiff --git a/rust/feature-flags/src/router.rs b/rust/feature-flags/src/router.rsindex 4b35e5d2ab39..bf357159ebe8 100644--- a/rust/feature-flags/src/router.rs+++ b/rust/feature-flags/src/router.rs@@ -105,9 +105,9 @@ pub struct State {pub auth_token_cache: Arc<ReadThroughCacheWithMetrics>,/// Provider for realtime/behavioral cohort membership lookupspub cohort_membership_provider: Arc<dyn CohortMembershipProvider>,- /// Shadow-keyspace billing aggregator. See `crate::billing` for the- /// dual-write contract.- pub billing_aggregator: Option<Arc<BillingAggregator>>,+ /// Authoritative writer for the production billing keyspace. See+ /// `crate::billing` for the aggregation/flush contract.+ pub billing_aggregator: Arc<BillingAggregator>,/// Per-team request/response body logging for `/flags`. Refreshed/// every ~60s from `posthog_instancesetting`.pub body_logger: Arc<BodyLogger>,@@ -135,7 +135,7 @@ pub fn router(team_negative_cache: NegativeCache,auth_token_cache: Arc<ReadThroughCacheWithMetrics>,cohort_membership_provider: Arc<dyn CohortMembershipProvider>,- billing_aggregator: Option<Arc<BillingAggregator>>,+ billing_aggregator: Arc<BillingAggregator>,config: Config,) -> Router {// Initialize flag definitions rate limiter with default and custom team ratesdiff --git a/rust/feature-flags/src/server.rs b/rust/feature-flags/src/server.rsindex e8b1d471d9dd..06fcf4a8f0d0 100644--- a/rust/feature-flags/src/server.rs+++ b/rust/feature-flags/src/server.rs@@ -2,9 +2,7 @@ use std::net::SocketAddr;use std::sync::Arc;use std::time::Duration;-use crate::billing::{- BillingAggregator, BillingAggregatorConfig, FeatureFlagsLimiter, SessionReplayLimiter,-};+use crate::billing::{BillingAggregator, FeatureFlagsLimiter, SessionReplayLimiter};use crate::cohorts::cohort_cache_manager::CohortCacheManager;use crate::cohorts::membership::{CachedCohortMembershipProvider, CohortMembershipProvider, NoOpCohortMembershipProvider,@@ -500,21 +498,8 @@ pub async fn serve(tokio_monitor.start_monitoring(tokio_monitor_handle).await;});- let billing_aggregator: Option<Arc<BillingAggregator>> =- config.billing_aggregator_mode.into_runtime().map(|mode| {- BillingAggregator::start(- redis_client.clone(),- BillingAggregatorConfig {- flush_interval: Duration::from_millis(config.billing_flush_interval_ms),- max_pending_entries: config.billing_max_pending_entries,- per_flush_batch_size: config.billing_per_flush_batch_size,- shutdown_flush_timeout: Duration::from_millis(- config.billing_shutdown_flush_timeout_ms,- ),- },- mode,- )- });+ let billing_aggregator: Arc<BillingAggregator> =+ BillingAggregator::start(redis_client.clone(), config.get_billing_aggregator_config());let app = router::router(redis_client,@@ -559,9 +544,7 @@ pub async fn serve(// Must run *after* `axum::serve(...).await` resolves so axum has drained// in-flight requests; flushing earlier would miss late-arriving records.- if let Some(ref aggregator) = billing_aggregator {- aggregator.shutdown().await;- }+ billing_aggregator.shutdown().await;match serve_result {Ok(()) => http_handle.work_completed(),diff --git a/rust/feature-flags/tests/common/mod.rs b/rust/feature-flags/tests/common/mod.rsindex 2754728aac8d..12027ef6cb20 100644--- a/rust/feature-flags/tests/common/mod.rs+++ b/rust/feature-flags/tests/common/mod.rs@@ -370,22 +370,11 @@ impl ServerHandle {feature_flags::flags::flag_definitions_cache::FlagDefinitionsCache::disabled(),);- // `for_tests()` skips the background flusher and the harness- // never exposes a handle, so pending counts populated here never- // reach mock Redis. The construction is intentional: it exercises- // the synchronous `record()` half of the dual-write- // (`handler::billing::record_billing_increment`) so mock-Redis- // coverage doesn't silently regress that codepath. End-to-end- // flush behavior lives in the real-Redis tests in `test_flags.rs`- // (`test_billing_increments_land_in_production_keyspace_per_mode`,- // `test_shutdown_flush_lands_aggregator_target_keyspace_in_redis`).- let billing_aggregator = config.billing_aggregator_mode.into_runtime().map(|mode| {- feature_flags::billing::BillingAggregator::for_tests_with_mode(- redis_writer_client.clone(),- feature_flags::billing::BillingAggregatorConfig::default(),- mode,- )- });+ let billing_aggregator = feature_flags::billing::BillingAggregator::start(+ redis_writer_client.clone(),+ config.get_billing_aggregator_config(),+ );+ let shutdown_for_test = billing_aggregator.clone();let app = feature_flags::router::router(redis_writer_client.clone(), // Use writer client for both reads and writes in tests@@ -425,13 +414,18 @@ impl ServerHandle {config,);- axum::serve(+ // Mirror `server::serve`: capture the serve result, then await the+ // aggregator shutdown *unconditionally* before propagating any+ // serve error. Otherwise a `.unwrap()` on a serve failure would+ // panic the spawned task and leak the flusher into the next test.+ let serve_result = axum::serve(listener,app.into_make_service_with_connect_info::<SocketAddr>(),).with_graceful_shutdown(handles.http.shutdown_signal())- .await- .unwrap();+ .await;+ shutdown_for_test.shutdown().await;+ serve_result.unwrap();handles.http.work_completed();});diff --git a/rust/feature-flags/tests/test_flag_definitions.rs b/rust/feature-flags/tests/test_flag_definitions.rsindex 9906099ad8fa..33e95f5971c9 100644--- a/rust/feature-flags/tests/test_flag_definitions.rs+++ b/rust/feature-flags/tests/test_flag_definitions.rs@@ -2557,7 +2557,7 @@ async fn test_db_rate_limit_allowlist() {.unwrap();}-/// Verifies the synchronous billing path writes (or, when `skip_writes=true`,+/// Verifies the billing path writes (or, when `skip_writes=true`,/// suppresses) the FlagDefinitions counter for `/flags/definitions`. The/// `/flags` endpoint is covered by tests in `test_flags.rs`; this test is/// the equivalent for the FlagDefinitions code path so a regression that@@ -2624,19 +2624,19 @@ async fn test_flag_definitions_billing_counter(#[case] skip_writes: bool) {response.text().await.unwrap());- // Synchronous path writes inline before the response returns, so we can- // read back without polling.- let counter = redis.hget(billing_key, bucket_field).await;-if skip_writes {+ // Sleep ~5 flush windows so even a slow CI scheduler couldn't hide+ // an erroneous `record()` behind a delayed first tick.+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;+ let counter = redis.hget(billing_key, bucket_field).await;assert!(counter.is_err(),- "FlagDefinitions billing counter should NOT be incremented when skip_writes=true"+ "FlagDefinitions billing counter should NOT be incremented when skip_writes=true, got {counter:?}");} else {+ let counter = common::poll_for_billing_counter(&redis, &billing_key, &bucket_field).await;assert_eq!(- counter.unwrap(),- "1",+ counter, "1","FlagDefinitions billing counter should be incremented once");}diff --git a/rust/feature-flags/tests/test_flags.rs b/rust/feature-flags/tests/test_flags.rsindex 87eb0a95a90d..adfe8e2e5644 100644--- a/rust/feature-flags/tests/test_flags.rs+++ b/rust/feature-flags/tests/test_flags.rs@@ -13,7 +13,7 @@ use serde_json::{json, Value};use crate::common::*;use feature_flags::cohorts::cohort_models::CohortType;-use feature_flags::config::{AggregatorModeConfig, DEFAULT_TEST_CONFIG};+use feature_flags::config::DEFAULT_TEST_CONFIG;use feature_flags::utils::test_utils::{insert_config_in_hypercache, insert_flags_for_team_in_redis,insert_flags_with_metadata_for_team_in_redis, insert_new_team_in_redis, setup_pg_reader_client,@@ -5655,19 +5655,19 @@ async fn test_skip_writes_suppresses_billing_redis_counter(.await;assert_eq!(StatusCode::OK, res.status());- // Synchronous path writes inline before the response returns, so we can- // read back without polling.- let counter = client.hget(billing_key, bucket_field).await;-if skip_writes {+ // Sleep ~5 flush windows so even a slow CI scheduler couldn't hide+ // an erroneous `record()` behind a delayed first tick.+ tokio::time::sleep(std::time::Duration::from_millis(500)).await;+ let counter = client.hget(billing_key, bucket_field).await;assert!(counter.is_err(),- "billing counter should NOT be incremented when skip_writes=true"+ "billing counter should NOT be incremented when skip_writes=true, got {counter:?}");} else {+ let counter = poll_for_billing_counter(&client, &billing_key, &bucket_field).await;assert_eq!(- counter.unwrap(),- "1",+ counter, "1","billing counter should be incremented when skip_writes=false");}@@ -5677,41 +5677,19 @@ async fn test_skip_writes_suppresses_billing_redis_counter(/// Verifies that an SDK request lands counts at the team-level and the/// library-level Redis hashes in the production keyspace — the load-bearing-/// invariant readers (`calculate_decide_usage`) consume.-///-/// In `Shadow` mode the production keys are written by the synchronous-/// `record_usage` path and the aggregator tees the same counts to the-/// `:shadow` keyspace for offline reconciliation. In `Authoritative` mode-/// the synchronous path is skipped — the aggregator's flush *is* the-/// production write, and the shadow keyspace must stay silent (any write-/// there is a double-count).-///-/// Pinning both modes here means the cutover from shadow to authoritative-/// is observable as a swap of *who* writes the production keys, with the-/// same end state from the reader's perspective.-#[rstest]-#[case::shadow(AggregatorModeConfig::Shadow, Some("1"))]-#[case::authoritative(AggregatorModeConfig::Authoritative, None)]+/// invariant readers (`calculate_decide_usage`) consume. The aggregator's+/// periodic flush is the only writer.#[tokio::test]-async fn test_billing_increments_land_in_production_keyspace_per_mode(- #[case] mode: AggregatorModeConfig,- #[case] expected_shadow: Option<&str>,-) -> Result<()> {+async fn test_billing_increments_land_in_production_keyspace() -> Result<()> {use feature_flags::config::FlexBool;use feature_flags::flags::flag_analytics::{current_bucket, get_team_request_key, get_team_request_library_key,- get_team_request_library_shadow_key, get_team_request_shadow_key,};use feature_flags::flags::flag_request::FlagRequestType;use feature_flags::handler::types::Library;let mut config = DEFAULT_TEST_CONFIG.clone();config.skip_writes = FlexBool(false);- config.billing_aggregator_mode = mode;- // Tight flush interval so the aggregator lands its write within the- // polling window. In authoritative mode the production key has no- // synchronous fallback, so this interval bounds the test latency.- config.billing_flush_interval_ms = 100;let distinct_id = format!("billing_lib_test_{}", rand::thread_rng().gen::<u32>());@@ -5745,13 +5723,8 @@ async fn test_billing_increments_land_in_production_keyspace_per_mode(let team_key = get_team_request_key(team.id, FlagRequestType::Decide);let library_key =get_team_request_library_key(team.id, FlagRequestType::Decide, Library::PosthogNode);- let team_shadow_key = get_team_request_shadow_key(team.id, FlagRequestType::Decide);- let library_shadow_key =- get_team_request_library_shadow_key(team.id, FlagRequestType::Decide, Library::PosthogNode);client.del(team_key.clone()).await.unwrap();client.del(library_key.clone()).await.unwrap();- client.del(team_shadow_key.clone()).await.unwrap();- client.del(library_shadow_key.clone()).await.unwrap();let server = ServerHandle::for_config(config).await;@@ -5775,9 +5748,6 @@ async fn test_billing_increments_land_in_production_keyspace_per_mode(.await?;assert_eq!(StatusCode::OK, res.status());- // Production keyspace — the load-bearing invariant. In shadow mode- // it's written synchronously; in authoritative it lands via the next- // aggregator flush. Polling absorbs both timings.let team_counter = poll_for_billing_counter(&client, &team_key, &bucket_field).await;assert_eq!(team_counter, "1", "team key should reflect one request");@@ -5787,83 +5757,24 @@ async fn test_billing_increments_land_in_production_keyspace_per_mode("library key should reflect one request");- // Shadow keyspace — populated only in shadow mode. In authoritative- // mode the same write must NOT appear here, or we've double-counted- // the request once the per-request HINCRBY is removed.- match expected_shadow {- Some(expected) => {- let team_shadow_counter =- poll_for_billing_counter(&client, &team_shadow_key, &bucket_field).await;- assert_eq!(- team_shadow_counter, expected,- "shadow team key should reflect the aggregator's tee"- );-- let library_shadow_counter =- poll_for_billing_counter(&client, &library_shadow_key, &bucket_field).await;- assert_eq!(- library_shadow_counter, expected,- "shadow library key should reflect the aggregator's tee"- );- }- None => {- // The production write has already landed (we polled for it- // above). Wait one more flush window so any erroneous shadow- // write would have landed too, then assert it didn't.- tokio::time::sleep(std::time::Duration::from_millis(200)).await;- let team_shadow = client- .hget(team_shadow_key.clone(), bucket_field.clone())- .await;- assert!(- team_shadow.is_err(),- "authoritative mode must not write the shadow team key, got {team_shadow:?}"- );- let library_shadow = client- .hget(library_shadow_key.clone(), bucket_field.clone())- .await;- assert!(- library_shadow.is_err(),- "authoritative mode must not write the shadow library key, got {library_shadow:?}"- );- }- }-Ok(())}/// End-to-end shutdown-flush path. Sets a flush interval much longer than/// the test's runtime so the periodic flusher cannot fire — the only way-/// the aggregator's target counter can land in Redis is via+/// the production billing counter can land in Redis is via/// `BillingAggregator::shutdown()` after axum's graceful drain. Catches a/// regression that drops the `billing_aggregator.shutdown().await` call in-/// `serve()`, swaps in `for_tests()`, or wires up the lifecycle ordering-/// wrong (flushing before axum drains).-///-/// The aggregator's target keyspace differs by mode:-///-/// - **Shadow**: target = `:shadow` keys. The synchronous production--/// keyspace write is unaffected by the aggregator's lifecycle and is-/// verified by `test_skip_writes_suppresses_billing_redis_counter`.-/// - **Authoritative**: target = production keys. The synchronous path is-/// gone, so the shutdown flush is the *only* path the production key-/// has — making this case strictly stronger than the shadow one.-#[rstest]-#[case::shadow(AggregatorModeConfig::Shadow)]-#[case::authoritative(AggregatorModeConfig::Authoritative)]+/// `serve()` or wires up the lifecycle ordering wrong (flushing before+/// axum drains).#[tokio::test]-async fn test_shutdown_flush_lands_aggregator_target_keyspace_in_redis(- #[case] mode: AggregatorModeConfig,-) -> Result<()> {+async fn test_shutdown_flush_writes_production_billing_counter() -> Result<()> {use feature_flags::config::FlexBool;- use feature_flags::flags::flag_analytics::{- current_bucket, get_team_request_key, get_team_request_shadow_key,- };+ use feature_flags::flags::flag_analytics::{current_bucket, get_team_request_key};use feature_flags::flags::flag_request::FlagRequestType;let mut config = DEFAULT_TEST_CONFIG.clone();config.skip_writes = FlexBool(false);- // The aggregator must be on for this test to mean anything.- config.billing_aggregator_mode = mode;// Long enough that no periodic flush can fire during the test. If the// counter shows up in Redis, the shutdown path is what put it there.config.billing_flush_interval_ms = 60_000;@@ -5894,18 +5805,7 @@ async fn test_shutdown_flush_lands_aggregator_target_keyspace_in_redis(}]);insert_flags_for_team_in_redis(client.clone(), team.id, Some(flag_json.to_string())).await?;- // The aggregator's target key is the only one the test asserts- // against. In authoritative mode that's the production key; in- // shadow mode it's the `:shadow` mirror.- let billing_key = match mode {- AggregatorModeConfig::Shadow => {- get_team_request_shadow_key(team.id, FlagRequestType::Decide)- }- AggregatorModeConfig::Authoritative => {- get_team_request_key(team.id, FlagRequestType::Decide)- }- AggregatorModeConfig::Off => unreachable!("test cases set the mode explicitly"),- };+ let billing_key = get_team_request_key(team.id, FlagRequestType::Decide);let bucket_field = current_bucket().to_string();client.del(billing_key.clone()).await.unwrap();@@ -5933,7 +5833,7 @@ async fn test_shutdown_flush_lands_aggregator_target_keyspace_in_redis(// Trigger graceful shutdown. axum drains in-flight requests, then// `serve()` calls `billing_aggregator.shutdown().await` which performs- // the final flush to the aggregator's target keyspace.+ // the final flush to the production billing keyspace.server.shutdown_now();// Poll for the counter to land. The helper polls for ~1s