: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(usage): report feature flag usage records (#87011)
Ben White4e6031d09cff
diff --git a/docs/internal/usage-record-producers.md b/docs/internal/usage-record-producers.mdindex 6c3b1cf1a5fc..f113d665a3e3 100644--- a/docs/internal/usage-record-producers.md+++ b/docs/internal/usage-record-producers.md@@ -32,8 +32,15 @@ Measured locally: two identical batches landing in separate parts read as 6 rows| `cdp` | `cdp_billable_invocations` | invocations | `event:{eventUuid}` / `flow:{invocationId}:{actionStepCount}:{kind}` / `webhook:{invocationId}` | CDP consumers || `feature-flags` | `feature_flag_requests` | requests | fresh UUIDv7 per flush | feature flags service |-Every producer reads one env var, `USAGE_INGESTION_REPORT_TEAMS`: `''` reports nothing, `*` every team, `1,2` those teams.-Each producer above is its own deployment, so one name still rolls out per producer, set in that service's config.+Every producer reads the same four env vars, and each one is its own deployment, so one name still rolls out per producer from that service's own config.++| Env var | Default | Meaning |+| ------------------------------ | ---------------- | ------------------------------------------------------------------------------------------------------ |+| `USAGE_INGESTION_REPORT_TEAMS` | `''` | `''` reports nothing, `*` every team, `1,2` those teams. |+| `USAGE_INGESTION_ADDR` | `''` outside dev | `host:port` of the gateway. Empty also reports nothing. |+| `USAGE_INGESTION_TLS` | `false` | Plaintext in-cluster. The flags service refuses `true` at startup, because its tonic build has no TLS. |+| `USAGE_INGESTION_TIMEOUT_MS` | `5000` | Per attempt, not per batch. The flags sender retries a transient failure three times. |+Empty is the default everywhere, so nothing reports until it is set.There is deliberately no percentage option: sampling a share of a team's events would bill that team a fraction of what it used.@@ -182,7 +189,7 @@ Then point a producer at it and turn its team matcher on:```shUSAGE_INGESTION_ADDR=localhost:7143 USAGE_INGESTION_REPORT_TEAMS='*' ./bin/start-FLAGS_USAGE_INGESTION_URL=http://localhost:7143 USAGE_INGESTION_REPORT_TEAMS='*' cargo run -p feature-flags+USAGE_INGESTION_ADDR=localhost:7143 USAGE_INGESTION_REPORT_TEAMS='*' cargo run -p feature-flags```Records land within one flush interval:diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 8bc4479bb799..fa2cb5067ead 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -4423,13 +4423,16 @@ dependencies = ["thiserror 2.0.18","tokio","tokio-retry",+ "tokio-stream","tokio-util",+ "tonic 0.12.3","tower 0.4.13","tower-http 0.5.2","tracing","tracing-opentelemetry","tracing-subscriber","url",+ "usage-ingestion-proto","uuid",]diff --git a/rust/feature-flags/Cargo.toml b/rust/feature-flags/Cargo.tomlindex b4d2dc055132..4e4d5563c8a8 100644--- a/rust/feature-flags/Cargo.toml+++ b/rust/feature-flags/Cargo.toml@@ -47,6 +47,8 @@ fancy-regex.workspace = truebase64.workspace = truefernet = { workspace = true }sqlx = { workspace = true, features = ["rust_decimal"] }+tonic = { workspace = true }+usage-ingestion-proto = { path = "../usage-ingestion-proto" }uuid = { workspace = true }common-cache = { path = "../common/cache" }common-compression = { path = "../common/compression" }@@ -121,4 +123,5 @@ futures = "0.3.30"test-case = "3.3.1"tokio = { workspace = true, features = ["test-util"] }tokio-util = { workspace = true }+tokio-stream = "0.1"metrics-util = { workspace = true }diff --git a/rust/feature-flags/src/billing/aggregator.rs b/rust/feature-flags/src/billing/aggregator.rsindex 47787a6e5031..71b2f004a5e6 100644--- a/rust/feature-flags/src/billing/aggregator.rs+++ b/rust/feature-flags/src/billing/aggregator.rs@@ -81,6 +81,7 @@ use rand::Rng;use tokio::sync::Notify;use tokio::task::JoinHandle;+use crate::billing::usage_reporter::UsageReporter;use crate::flags::flag_analytics::{current_bucket, get_team_request_key, get_team_request_library_key,};@@ -328,14 +329,17 @@ struct Inner {record_count_decide: AtomicU64,record_count_flag_definitions: AtomicU64,shutdown_signal: Notify,+ usage_reporter: Option<Arc<UsageReporter>>,}impl Inner {fn new(redis: Arc<dyn RedisClient + Send + Sync>,config: BillingAggregatorConfig,+ usage_reporter: Option<Arc<UsageReporter>>,) -> Arc<Self> {Arc::new(Self {+ usage_reporter,config,redis,pending: Mutex::new(HashMap::new()),@@ -371,6 +375,15 @@ impl BillingAggregator {pub fn start(redis: Arc<dyn RedisClient + Send + Sync>,config: BillingAggregatorConfig,+ ) -> Arc<Self> {+ Self::start_with_usage_reporter(redis, config, None)+ }++ /// As `start`, but also mirrors every credited flush into usage-ingestion.+ pub fn start_with_usage_reporter(+ redis: Arc<dyn RedisClient + Send + Sync>,+ config: BillingAggregatorConfig,+ usage_reporter: Option<Arc<UsageReporter>>,) -> Arc<Self> {// Fail fast on misconfiguration. A misconfigured FLAGS_BILLING_*// env var would otherwise panic the flusher task silently, or silently@@ -383,7 +396,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);+ let inner = Inner::new(redis, config, usage_reporter);let flusher = tokio::spawn(run_flusher(inner.clone()));let metrics_sampler = tokio::spawn(run_metrics_sampler(inner.clone()));@@ -518,6 +531,14 @@ impl BillingAggregator {}}}++ // After the final flush, so the records it just queued are drained rather than+ // dropped with the runtime.+ if let Some(reporter) = &self.inner.usage_reporter {+ reporter+ .shutdown(self.inner.config.shutdown_flush_timeout)+ .await;+ }}#[cfg(test)]@@ -563,7 +584,7 @@ impl BillingAggregator {config: BillingAggregatorConfig,) -> Arc<Self> {Arc::new(Self {- inner: Inner::new(redis, config),+ inner: Inner::new(redis, config, None),flusher: Mutex::new(None),metrics_sampler: Mutex::new(None),})@@ -660,6 +681,7 @@ async fn flush_chunk(// strand counts already written to Redis under an unincremented// `entries_flushed_total`.inc(FLAGS_BILLING_ENTRIES_FLUSHED, &[], chunk_counts);+ report_usage(inner, chunk_entries);chunk_entries.clear();ChunkOutcome::Ok}@@ -676,6 +698,7 @@ async fn flush_chunk(if outcome == FlushOutcome::Applied {*flushed_counts += chunk_counts;inc(FLAGS_BILLING_ENTRIES_FLUSHED, &[], chunk_counts);+ report_usage(inner, chunk_entries);chunk_entries.clear();// Under `BailOnError` we still need to signal an error so// the caller stops attempting subsequent chunks on a@@ -713,6 +736,12 @@ async fn flush_chunk(}}+fn report_usage(inner: &Arc<Inner>, chunk_entries: &[(AggregationKey, u64)]) {+ if let Some(reporter) = &inner.usage_reporter {+ reporter.report(chunk_entries, now_epoch_ms() as i64);+ }+}+/// Swap the pending map, flush the drained batch to Redis, record metrics.////// Chunks at `AggregationKey` boundaries (never splits a key's team-level@@ -1159,6 +1188,8 @@ fn pick_jitter(flush_interval: Duration) -> Duration {#[cfg(test)]mod tests {use super::*;+ use crate::billing::usage_test_support::{serve, RecordingIngestion};+ use crate::config::TeamIdCollection;use common_redis::{MockRedisClient, MockRedisValue};use rstest::rstest;@@ -1183,10 +1214,18 @@ mod tests {fn new_test_aggregator_with_redis(redis: MockRedisClient,config: BillingAggregatorConfig,+ ) -> (Arc<MockRedisClient>, Arc<BillingAggregator>) {+ new_test_aggregator_with_reporter(redis, config, None)+ }++ fn new_test_aggregator_with_reporter(+ redis: MockRedisClient,+ config: BillingAggregatorConfig,+ usage_reporter: Option<Arc<UsageReporter>>,) -> (Arc<MockRedisClient>, Arc<BillingAggregator>) {let redis = Arc::new(redis);let agg = Arc::new(BillingAggregator {- inner: Inner::new(redis.clone(), config),+ inner: Inner::new(redis.clone(), config, usage_reporter),flusher: Mutex::new(None),metrics_sampler: Mutex::new(None),});@@ -1366,6 +1405,40 @@ mod tests {assert_eq!(agg.pending_total(), 3, "all three records must requeue");}+ /// The reporter only ever sees a chunk Redis already credited, so this asserts the+ /// mirror of a successful flush rather than the reporter's own behavior.+ #[tokio::test]+ async fn test_flush_once_mirrors_credited_counts_to_usage_ingestion() {+ let service = RecordingIngestion::default();+ let addr = serve(service.clone()).await;+ let reporter = UsageReporter::new(&addr.to_string(), false, TeamIdCollection::All, 1_000)+ .unwrap()+ .unwrap();+ let (_redis, agg) = new_test_aggregator_with_reporter(+ MockRedisClient::new(),+ test_config(),+ Some(reporter.clone()),+ );++ agg.record(42, FlagRequestType::Decide, Some(Library::PosthogJs));+ agg.record(42, FlagRequestType::Decide, Some(Library::PosthogJs));+ agg.record(7, FlagRequestType::Decide, None);++ flush_once(&agg.inner, FlushPolicy::BailOnError).await;+ reporter.shutdown(Duration::from_secs(5)).await;++ let records: Vec<_> = service.requests().into_iter().flatten().collect();+ // One record per aggregation entry, not per Redis write: an entry that carries a+ // library writes both a team key and an SDK key, and billing counts the request once.+ assert_eq!(records.len(), 2);+ assert!(records+ .iter()+ .any(|record| record.team_id == 42 && record.quantity == 2));+ assert!(records+ .iter()+ .any(|record| record.team_id == 7 && record.quantity == 1));+ }+#[tokio::test]async fn test_flush_once_writes_pipelined_hincrby() {let (redis, agg) = new_test_aggregator(test_config());diff --git a/rust/feature-flags/src/billing/mod.rs b/rust/feature-flags/src/billing/mod.rsindex dd7bf16a409b..a3476878c755 100644--- a/rust/feature-flags/src/billing/mod.rs+++ b/rust/feature-flags/src/billing/mod.rs@@ -7,6 +7,10 @@pub mod aggregator;pub mod limiters;+pub mod usage_reporter;+#[cfg(test)]+pub mod usage_test_support;pub use aggregator::{AggregationKey, BillingAggregator, BillingAggregatorConfig};pub use limiters::{FeatureFlagsLimiter, SessionReplayLimiter};+pub use usage_reporter::UsageReporter;diff --git a/rust/feature-flags/src/billing/usage_reporter.rs b/rust/feature-flags/src/billing/usage_reporter.rsnew file mode 100644index 000000000000..35a6ab582fe4--- /dev/null+++ b/rust/feature-flags/src/billing/usage_reporter.rs@@ -0,0 +1,338 @@+//! Mirrors flushed billing counts into the usage-ingestion service. Records are emitted only for a+//! chunk already credited to Redis, so a Redis retry cannot bill twice.+//!+//! `record_id` is a fresh UUID per emission, not derived from the aggregation key: a Redis outage+//! rebuckets and merges requeued entries, so one key legitimately carries different quantities+//! across flushes. A retry reuses the record it already built, which is what makes retrying safe:+//! the service deduplicates on `record_id`, including when Kafka took only part of the batch.++use std::sync::Arc;+use std::sync::Mutex;++use common_metrics::inc;+use tokio::sync::mpsc;+use tokio::task::JoinHandle;+use tonic::transport::{Channel, Endpoint};+use tonic::Code;+use usage_ingestion_proto::usage_ingestion::v1::{+ usage_ingestion_client::UsageIngestionClient, BillingUsageRecord, IngestBillingUsageRequest,+};+use uuid::Uuid;++use crate::config::TeamIdCollection;+use crate::metrics::consts::{FLAGS_USAGE_RECORDS_FAILED, FLAGS_USAGE_RECORDS_SENT};++use super::AggregationKey;++const PRODUCER_ID: &str = "feature-flags";+const USAGE_KEY: &str = "feature_flag_requests";+const UNIT: &str = "requests";+const MAX_BATCH_SIZE: usize = 500;+/// Queued sends waiting on the sender task. A full queue drops rather than growing+/// unboundedly; the drop is counted, and Redis still holds the authoritative count.+const QUEUE_CAPACITY: usize = 64;+/// Attempts per chunk, including the first. The sender is one task, so a chunk that+/// keeps failing holds up the queue behind it — hence a small number and a short wait.+const SEND_ATTEMPTS: u32 = 3;+const RETRY_BACKOFF: std::time::Duration = std::time::Duration::from_millis(100);++struct SenderState {+ queue: mpsc::Sender<Vec<BillingUsageRecord>>,+ task: JoinHandle<()>,+}++pub struct UsageReporter {+ teams: TeamIdCollection,+ state: Mutex<Option<SenderState>>,+}++impl UsageReporter {+ /// `None` when no URL is configured or no team is enabled, so the aggregator+ /// skips the work entirely.+ pub fn new(+ addr: &str,+ use_tls: bool,+ teams: TeamIdCollection,+ timeout_ms: u64,+ ) -> Result<Option<Arc<Self>>, String> {+ if addr.is_empty() || matches!(teams, TeamIdCollection::None) {+ return Ok(None);+ }+ // tonic is built here without its TLS feature, so an https endpoint fails at connect+ // time with nothing naming the cause. Refuse at startup instead.+ if use_tls {+ return Err("USAGE_INGESTION_TLS is not supported by the flags reporter".to_string());+ }+ let endpoint = Endpoint::from_shared(format!("http://{addr}"))+ .map_err(|e| format!("invalid USAGE_INGESTION_ADDR: {e}"))?+ .timeout(std::time::Duration::from_millis(timeout_ms));+ let client = UsageIngestionClient::new(endpoint.connect_lazy());++ // One owned task drains the queue, so concurrency is bounded by construction and+ // `shutdown` has something to await. Spawning per flush chunk left thousands of+ // untracked tasks that a shutdown could not drain.+ let (queue, receiver) = mpsc::channel(QUEUE_CAPACITY);+ let task = tokio::spawn(run_sender(client, receiver));++ Ok(Some(Arc::new(Self {+ teams,+ state: Mutex::new(Some(SenderState { queue, task })),+ })))+ }++ /// `timestamp_ms` must be the reporter's own clock, never anything derived from a request.+ /// toDate of it is part of the storage sorting key, so a caller-controlled value would+ /// decide whether these records deduplicate.+ pub fn report(&self, entries: &[(AggregationKey, u64)], timestamp_ms: i64) {+ let records = build_records(entries, &self.teams, timestamp_ms);+ if records.is_empty() {+ return;+ }+ let record_count = records.len() as u64;+ let queued = match self.state.lock().unwrap().as_ref() {+ Some(state) => state.queue.try_send(records).is_ok(),+ None => false,+ };+ if !queued {+ inc(FLAGS_USAGE_RECORDS_FAILED, &[], record_count);+ tracing::warn!(+ records = record_count,+ "usage-ingestion send queue is full or closed; dropped usage records"+ );+ }+ }++ /// Closes the queue and awaits the sender so a graceful shutdown does not lose records+ /// the Redis flush already credited. Bounded by `timeout`.+ pub async fn shutdown(&self, timeout: std::time::Duration) {+ let state = self.state.lock().unwrap().take();+ let Some(SenderState { queue, task }) = state else {+ return;+ };+ // Dropping the only sender closes the channel, so the task drains its queue and returns.+ drop(queue);+ let abort = task.abort_handle();+ match tokio::time::timeout(timeout, task).await {+ Ok(_) => tracing::info!("UsageReporter: drained pending usage records"),+ Err(_) => {+ abort.abort();+ tracing::warn!(+ timeout_ms = timeout.as_millis() as u64,+ "UsageReporter: timed out draining usage records"+ );+ }+ }+ }+}++/// A code the service returns for a condition that clears on its own: an unreachable+/// or draining pod, a timeout, a full queue. The rest, `invalid_argument` above all,+/// describe the records themselves and would fail the same way forever.+fn is_retryable(code: Code) -> bool {+ matches!(+ code,+ Code::Unavailable | Code::DeadlineExceeded | Code::ResourceExhausted | Code::Aborted+ )+}++async fn run_sender(+ client: UsageIngestionClient<Channel>,+ mut receiver: mpsc::Receiver<Vec<BillingUsageRecord>>,+) {+ while let Some(records) = receiver.recv().await {+ for chunk in records.chunks(MAX_BATCH_SIZE) {+ send_chunk(&client, chunk).await;+ }+ }+}++/// Retries the same records, never rebuilt ones, so the service's `record_id` dedup holds.+/// A bounded retry is the ceiling here: a crash still loses what the queue holds, and Redis+/// plus the nightly report stay authoritative for what a team owes.+async fn send_chunk(client: &UsageIngestionClient<Channel>, chunk: &[BillingUsageRecord]) {+ let count = chunk.len() as u64;+ let request = IngestBillingUsageRequest {+ records: chunk.to_vec(),+ };+ for attempt in 1..=SEND_ATTEMPTS {+ let mut client = client.clone();+ match client.ingest_billing_usage(request.clone()).await {+ Ok(_) => {+ inc(FLAGS_USAGE_RECORDS_SENT, &[], count);+ return;+ }+ Err(status) => {+ let retryable = is_retryable(status.code());+ if !retryable || attempt == SEND_ATTEMPTS {+ inc(FLAGS_USAGE_RECORDS_FAILED, &[], count);+ tracing::warn!(+ records = count,+ attempts = attempt,+ code = %status.code(),+ "failed to report feature flag usage records"+ );+ return;+ }+ tokio::time::sleep(RETRY_BACKOFF * attempt).await;+ }+ }+ }+}++fn build_records(+ entries: &[(AggregationKey, u64)],+ teams: &TeamIdCollection,+ timestamp_ms: i64,+) -> Vec<BillingUsageRecord> {+ entries+ .iter()+ .filter(|(key, count)| *count > 0 && teams.includes_team(key.team_id))+ .map(|(key, count)| BillingUsageRecord {+ record_id: Uuid::now_v7().to_string(),+ producer_id: PRODUCER_ID.to_string(),+ team_id: i64::from(key.team_id),+ usage_key: USAGE_KEY.to_string(),+ unit: UNIT.to_string(),+ quantity: i64::try_from(*count).unwrap_or(i64::MAX),+ timestamp_ms,+ })+ .collect()+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::billing::usage_test_support::{serve, RecordingIngestion};+ use crate::flags::flag_request::FlagRequestType;+ use crate::handler::types::Library;++ fn key(team_id: i32, library: Option<Library>) -> AggregationKey {+ AggregationKey {+ team_id,+ request_type: FlagRequestType::Decide,+ library,+ bucket: 7,+ }+ }++ #[test]+ fn build_records_applies_the_team_filter() {+ let entries = vec![(key(1, None), 5), (key(2, None), 9)];+ let records = build_records(+ &entries,+ &TeamIdCollection::TeamIds(vec![2]),+ 1_700_000_000_000,+ );++ assert_eq!(records.len(), 1);+ assert_eq!(records[0].team_id, 2);+ assert_eq!(records[0].quantity, 9);+ }++ #[test]+ fn build_records_skips_zero_counts() {+ let entries = vec![(key(1, None), 0)];+ assert!(build_records(&entries, &TeamIdCollection::All, 1).is_empty());+ }++ #[test]+ fn build_records_gives_every_emission_its_own_id() {+ let entries = vec![(key(1, None), 1), (key(2, None), 1)];+ let records = build_records(&entries, &TeamIdCollection::All, 1);++ assert_ne!(records[0].record_id, records[1].record_id);+ }++ #[tokio::test]+ async fn shutdown_is_idempotent_and_closes_the_queue() {+ let reporter = UsageReporter::new("127.0.0.1:1", false, TeamIdCollection::All, 50)+ .unwrap()+ .unwrap();++ reporter+ .shutdown(std::time::Duration::from_millis(200))+ .await;+ // A second shutdown must not panic on the already-taken sender, and a late report must be+ // counted as dropped rather than queued onto a closed channel.+ reporter+ .shutdown(std::time::Duration::from_millis(200))+ .await;+ reporter.report(&[(key(1, None), 1)], 1);+ }++ #[tokio::test]+ async fn new_is_disabled_without_an_address_or_teams() {+ assert!(UsageReporter::new("", false, TeamIdCollection::All, 100)+ .unwrap()+ .is_none());+ assert!(+ UsageReporter::new("localhost:7143", false, TeamIdCollection::None, 100)+ .unwrap()+ .is_none()+ );+ assert!(+ UsageReporter::new("localhost:7143", false, TeamIdCollection::All, 100)+ .unwrap()+ .is_some()+ );+ }++ #[tokio::test]+ async fn new_refuses_tls_it_cannot_honor() {+ assert!(UsageReporter::new("localhost:7143", true, TeamIdCollection::All, 100).is_err());+ }++ async fn reporter_for(addr: std::net::SocketAddr) -> Arc<UsageReporter> {+ UsageReporter::new(&addr.to_string(), false, TeamIdCollection::All, 1_000)+ .unwrap()+ .unwrap()+ }++ /// `shutdown` is the drain, so it also stands in for a wait: it returns once the sender+ /// task has emptied the queue, which is what the aggregator's ordering promises.+ #[tokio::test]+ async fn a_queued_record_reaches_the_service_by_shutdown() {+ let service = RecordingIngestion::default();+ let reporter = reporter_for(serve(service.clone()).await).await;++ reporter.report(&[(key(7, None), 4)], 1_700_000_000_000);+ reporter.shutdown(std::time::Duration::from_secs(5)).await;++ let requests = service.requests();+ assert_eq!(requests.len(), 1);+ assert_eq!(requests[0].len(), 1);+ assert_eq!(requests[0][0].team_id, 7);+ assert_eq!(requests[0][0].quantity, 4);+ assert_eq!(requests[0][0].producer_id, PRODUCER_ID);+ assert_eq!(requests[0][0].usage_key, USAGE_KEY);+ }++ #[tokio::test]+ async fn retries_a_transient_failure_with_the_same_record_id() {+ let service = RecordingIngestion::default();+ service.fail_next(Code::Unavailable);+ let reporter = reporter_for(serve(service.clone()).await).await;++ reporter.report(&[(key(7, None), 1)], 1_700_000_000_000);+ reporter.shutdown(std::time::Duration::from_secs(5)).await;++ let requests = service.requests();+ assert_eq!(requests.len(), 2);+ // Reusing the ID is what makes the retry safe: the service deduplicates on it, so a+ // batch Kafka took only part of does not bill twice.+ assert_eq!(requests[0][0].record_id, requests[1][0].record_id);+ }++ #[tokio::test]+ async fn does_not_retry_a_rejected_batch() {+ let service = RecordingIngestion::default();+ // The records themselves are wrong, so every attempt fails the same way.+ service.fail_next(Code::InvalidArgument);+ let reporter = reporter_for(serve(service.clone()).await).await;++ reporter.report(&[(key(7, None), 1)], 1_700_000_000_000);+ reporter.shutdown(std::time::Duration::from_secs(5)).await;++ assert_eq!(service.requests().len(), 1);+ }+}diff --git a/rust/feature-flags/src/billing/usage_test_support.rs b/rust/feature-flags/src/billing/usage_test_support.rsnew file mode 100644index 000000000000..91327ed47348--- /dev/null+++ b/rust/feature-flags/src/billing/usage_test_support.rs@@ -0,0 +1,70 @@+//! In-process usage-ingestion server for tests. `usage-ingestion-proto` builds the server+//! stubs alongside the client, so a test can watch what the reporter actually sent instead+//! of asserting that a counter moved.++use std::collections::VecDeque;+use std::net::SocketAddr;+use std::sync::{Arc, Mutex};++use tonic::{Code, Request, Response, Status};+use usage_ingestion_proto::usage_ingestion::v1::usage_ingestion_server::{+ UsageIngestion, UsageIngestionServer,+};+use usage_ingestion_proto::usage_ingestion::v1::{+ BillingUsageRecord, IngestBillingUsageRequest, IngestBillingUsageResponse,+};++/// Records every request, and answers with the queued codes before it starts accepting.+#[derive(Clone, Default)]+pub struct RecordingIngestion {+ requests: Arc<Mutex<Vec<Vec<BillingUsageRecord>>>>,+ replies: Arc<Mutex<VecDeque<Code>>>,+}++impl RecordingIngestion {+ /// Fails the next request with `code`. Queue more than one to fail more attempts.+ pub fn fail_next(&self, code: Code) {+ self.replies.lock().unwrap().push_back(code);+ }++ /// One entry per request received, in arrival order.+ pub fn requests(&self) -> Vec<Vec<BillingUsageRecord>> {+ self.requests.lock().unwrap().clone()+ }+}++#[tonic::async_trait]+impl UsageIngestion for RecordingIngestion {+ async fn ingest_billing_usage(+ &self,+ request: Request<IngestBillingUsageRequest>,+ ) -> Result<Response<IngestBillingUsageResponse>, Status> {+ let records = request.into_inner().records;+ let accepted_record_ids = records+ .iter()+ .map(|record| record.record_id.clone())+ .collect();+ self.requests.lock().unwrap().push(records);+ if let Some(code) = self.replies.lock().unwrap().pop_front() {+ return Err(Status::new(code, "test"));+ }+ Ok(Response::new(IngestBillingUsageResponse {+ accepted_record_ids,+ }))+ }+}++/// Serves `service` on an ephemeral port and returns its address. The listener is bound+/// before this returns, so a client can connect while the server task is still starting.+pub async fn serve(service: RecordingIngestion) -> SocketAddr {+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ tokio::spawn(async move {+ tonic::transport::Server::builder()+ .add_service(UsageIngestionServer::new(service))+ .serve_with_incoming(tokio_stream::wrappers::TcpListenerStream::new(listener))+ .await+ .unwrap();+ });+ addr+}diff --git a/rust/feature-flags/src/config.rs b/rust/feature-flags/src/config.rsindex c96c071faab5..b99391e3a55a 100644--- a/rust/feature-flags/src/config.rs+++ b/rust/feature-flags/src/config.rs@@ -139,7 +139,7 @@ impl FromStr for TeamIdCollection {let s = s.trim();if s.eq_ignore_ascii_case("all") || s == "*" {Ok(TeamIdCollection::All)- } else if s.eq_ignore_ascii_case("none") {+ } else if s.is_empty() || s.eq_ignore_ascii_case("none") {Ok(TeamIdCollection::None)} else {let mut team_ids = Vec::new();@@ -921,6 +921,19 @@ pub struct Config {// comfortably within the pod's `terminationGracePeriodSeconds`.#[envconfig(from = "FLAGS_BILLING_SHUTDOWN_FLUSH_TIMEOUT_MS", default = "15000")]pub billing_shutdown_flush_timeout_ms: u64,++ // Usage-ingestion mirror. Empty address or empty teams disables it, so it+ // rolls out per team independently of the Redis billing keyspace. These carry+ // the names every usage producer reads, because each producer is its own+ // deployment and sets them in its own config.+ #[envconfig(from = "USAGE_INGESTION_ADDR", default = "")]+ pub usage_ingestion_addr: String,+ #[envconfig(from = "USAGE_INGESTION_TLS", default = "false")]+ pub usage_ingestion_tls: bool,+ #[envconfig(from = "USAGE_INGESTION_REPORT_TEAMS", default = "")]+ pub usage_ingestion_teams: TeamIdCollection,+ #[envconfig(from = "USAGE_INGESTION_TIMEOUT_MS", default = "5000")]+ pub usage_ingestion_timeout_ms: u64,}/// Thread counts for Tokio (async I/O) and Rayon (CPU-bound parallel evaluation).@@ -1159,6 +1172,10 @@ impl Config {billing_max_pending_entries: 500_000,billing_per_flush_batch_size: 200,billing_shutdown_flush_timeout_ms: 15_000,+ usage_ingestion_addr: "".to_string(),+ usage_ingestion_tls: false,+ usage_ingestion_teams: TeamIdCollection::None,+ usage_ingestion_timeout_ms: 5_000,}}@@ -1391,6 +1408,12 @@ mod tests {assert_eq!(team_ids, TeamIdCollection::None);}+ #[test]+ fn test_team_ids_to_track_empty() {+ let team_ids: TeamIdCollection = "".parse().unwrap();+ assert_eq!(team_ids, TeamIdCollection::None);+ }+#[test]fn test_team_ids_to_track_single_ids() {let team_ids: TeamIdCollection = "1,5,7,13".parse().unwrap();diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex 6c9e3d8c5d7e..ee7822cc3e94 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -227,6 +227,12 @@ pub const FLAGS_BILLING_SECONDS_SINCE_SUCCESSFUL_FLUSH: &str =pub const FLAGS_BILLING_FLUSH_DURATION_MS: &str = "flags_billing_flush_duration_ms";+// Counters: records the usage-ingestion mirror accepted / gave up on. A gap+// between them and `flags_billing_entries_flushed_total` is expected while the+// mirror is rolled out to a subset of teams.+pub const FLAGS_USAGE_RECORDS_SENT: &str = "flags_usage_records_sent_total";+pub const FLAGS_USAGE_RECORDS_FAILED: &str = "flags_usage_records_failed_total";+// Histogram of per-call `record()` latency in microseconds, with no labels// to keep the hot-path emission allocation-free. The expected uncontended// p50 is sub-microsecond (one atomic increment + a hash + a HashMap entrydiff --git a/rust/feature-flags/src/server.rs b/rust/feature-flags/src/server.rsindex 3e9467f2aefa..075ac5b39f8f 100644--- a/rust/feature-flags/src/server.rs+++ b/rust/feature-flags/src/server.rs@@ -2,7 +2,7 @@ use std::net::SocketAddr;use std::sync::Arc;use std::time::Duration;-use crate::billing::{BillingAggregator, FeatureFlagsLimiter, SessionReplayLimiter};+use crate::billing::{BillingAggregator, FeatureFlagsLimiter, SessionReplayLimiter, UsageReporter};use crate::cohorts::cohort_cache_manager::CohortCacheManager;use crate::cohorts::membership::{CachedCohortMembershipProvider, CohortMembershipProvider, NoOpCohortMembershipProvider,@@ -547,8 +547,18 @@ pub async fn serve(tokio_monitor.start_monitoring(tokio_monitor_handle).await;});- let billing_aggregator: Arc<BillingAggregator> =- BillingAggregator::start(redis_client.clone(), config.get_billing_aggregator_config());+ let usage_reporter = UsageReporter::new(+ &config.usage_ingestion_addr,+ config.usage_ingestion_tls,+ config.usage_ingestion_teams.clone(),+ config.usage_ingestion_timeout_ms,+ )+ .expect("invalid usage-ingestion configuration");+ let billing_aggregator: Arc<BillingAggregator> = BillingAggregator::start_with_usage_reporter(+ redis_client.clone(),+ config.get_billing_aggregator_config(),+ usage_reporter,+ );let app = router::router(redis_client,