: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): instrument inner request phases (#57841)
Matheus Batista88a8f3a605da
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 9229d1ccf75e..09618cd67fb3 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -3360,6 +3360,7 @@ dependencies = ["futures","governor","hex",+ "http-body-util","json5","lifecycle","limiters",diff --git a/rust/feature-flags/Cargo.toml b/rust/feature-flags/Cargo.tomlindex 484a1eece66e..e8ee42960550 100644--- a/rust/feature-flags/Cargo.toml+++ b/rust/feature-flags/Cargo.toml@@ -27,6 +27,7 @@ tokio = { workspace = true }tracing = { workspace = true }tracing-subscriber = { workspace = true, features = ["env-filter", "json"] }bytes = { workspace = true }+http-body-util = "0.1"url = "2.5"once_cell = { workspace = true }rand = { workspace = true }diff --git a/rust/feature-flags/src/api/body_read_metrics.rs b/rust/feature-flags/src/api/body_read_metrics.rsnew file mode 100644index 000000000000..86df46601217--- /dev/null+++ b/rust/feature-flags/src/api/body_read_metrics.rs@@ -0,0 +1,328 @@+//! Tower-layer instrumentation for inbound POST body buffering.+//!+//! axum's `Bytes` extractor reads and buffers the entire request body+//! before the handler observes it, but that buffering happens *inside*+//! the handler's invocation — so on a slow client upload, the latency+//! is charged to the handler with no per-step visibility. This shim+//! buffers the body explicitly inside a middleware layer placed+//! immediately after [`crate::api::concurrency_metrics::record_concurrency_wait`]+//! and before the handler. Side effects:+//!+//! 1. The elapsed wall-clock duration of `axum::body::to_bytes` is+//! stamped onto the request extensions as [`BodyReadDuration`].+//! 2. The original body is replaced with `Body::from(bytes)`, so the+//! handler's `body: Bytes` extractor reads from in-memory and the+//! overall behavior is unchanged.+//!+//! Layer wiring lives in `router::router` — see the comment block there.+//! The shim no-ops gracefully on the `Bytes` extractor's downstream+//! contract: if buffering fails, the framework's existing 400 response+//! shape is preserved.+//!+//! # Why no team_id label+//!+//! Body buffering happens before authentication resolves a team. The+//! histogram is pod-level by design, mirroring+//! `flags_concurrency_limit_wait_ms`.++use std::time::{Duration, Instant};++use axum::{+ body::Body,+ extract::Request,+ http::StatusCode,+ middleware::Next,+ response::{IntoResponse, Response},+};+use common_metrics::inc;++use crate::metrics::consts::{FLAG_BODY_READ_FAILED_COUNTER, FLAG_BODY_READ_TOO_LARGE_COUNTER};++/// Maximum inbound POST body size for `/flags` and `/decide`. Kept in+/// lockstep with the `DefaultBodyLimit` layer on the same sub-router so+/// the streaming cap (here) and the extractor cap (downstream) reject at+/// the same boundary.+pub const MAX_FLAGS_BODY_BYTES: usize = 2 * 1024 * 1024;++/// Wall-clock duration spent buffering the inbound request body. Inserted+/// into request extensions by [`record_body_read`] and read by the+/// `flags` handler to populate `FlagsCanonicalLogLine::body_read_ms`.+#[derive(Clone, Copy, Debug)]+pub struct BodyReadDuration(pub Duration);++/// Buffers the request body to memory while timing the operation, then+/// forwards a request with an in-memory body so the handler's `Bytes`+/// extractor short-circuits.+///+/// Bodies above [`MAX_FLAGS_BODY_BYTES`] are rejected with 413; transport+/// errors are rejected with 400. Both responses use the same body string+/// that axum's `BytesRejection::FailedToBufferBody` would produce.+pub async fn record_body_read(req: Request, next: Next) -> Response {+ let (parts, body) = req.into_parts();+ let start = Instant::now();+ let bytes = match axum::body::to_bytes(body, MAX_FLAGS_BODY_BYTES).await {+ Ok(bytes) => bytes,+ Err(err) => {+ // `to_bytes` wraps the underlying http_body_util error. Walk+ // the full `Error::source` chain rather than just the first+ // level: axum currently wraps `LengthLimitError` one layer+ // deep, but that depth is internal to axum/http-body-util,+ // not a contract. A future bump that adds another wrapper+ // layer would silently misclassify 413s as 400s and stop+ // firing `flags_body_read_too_large_total`.+ let too_large = std::iter::successors(std::error::Error::source(&err), |s| s.source())+ .any(|s| s.is::<http_body_util::LengthLimitError>());+ if too_large {+ inc(FLAG_BODY_READ_TOO_LARGE_COUNTER, &[], 1);+ tracing::warn!(+ error = %err,+ limit = MAX_FLAGS_BODY_BYTES,+ "request body exceeded limit"+ );+ return (+ StatusCode::PAYLOAD_TOO_LARGE,+ "Failed to buffer the request body",+ )+ .into_response();+ }+ inc(FLAG_BODY_READ_FAILED_COUNTER, &[], 1);+ tracing::warn!(error = %err, "failed to buffer request body");+ return (StatusCode::BAD_REQUEST, "Failed to buffer the request body").into_response();+ }+ };+ let elapsed = start.elapsed();++ let mut req = Request::from_parts(parts, Body::from(bytes));+ req.extensions_mut().insert(BodyReadDuration(elapsed));+ next.run(req).await+}++#[cfg(test)]+mod tests {+ //! These tests exercise the shim's contract directly — buffer the+ //! body, time the operation, hand off a request with an in-memory+ //! body — without depending on the rest of the layer chain. The+ //! placement after `record_concurrency_wait` is enforced by the+ //! router wiring; we test the shim itself here.++ use super::*;+ use axum::{+ body::Body,+ extract::Extension,+ http::{Request as HttpRequest, StatusCode},+ routing::post,+ Router,+ };+ use bytes::Bytes;+ use metrics_util::debugging::{DebugValue, DebuggingRecorder};+ use tower::ServiceExt;++ /// Encodes responses as `<wait_micros|"missing">|<body_bytes>` so+ /// tests can split on the first `|` and compare body bytes verbatim.+ const ECHO_DELIM: u8 = b'|';++ async fn echo_body_read(+ wait: Option<Extension<BodyReadDuration>>,+ body: Bytes,+ ) -> (StatusCode, Vec<u8>) {+ let wait_repr = wait+ .map(|Extension(w)| w.0.as_micros().to_string())+ .unwrap_or_else(|| "missing".to_string());+ let mut out = wait_repr.into_bytes();+ out.push(ECHO_DELIM);+ out.extend_from_slice(&body);+ (StatusCode::OK, out)+ }++ fn make_request(body: &str) -> HttpRequest<Body> {+ HttpRequest::builder()+ .method("POST")+ .uri("/")+ .body(Body::from(body.to_owned()))+ .unwrap()+ }++ async fn read_response_bytes(resp: Response) -> Vec<u8> {+ axum::body::to_bytes(resp.into_body(), usize::MAX)+ .await+ .unwrap()+ .to_vec()+ }++ fn split_echo(payload: &[u8]) -> (&str, &[u8]) {+ let i = payload+ .iter()+ .position(|b| *b == ECHO_DELIM)+ .expect("echo response must contain the delimiter");+ let wait =+ std::str::from_utf8(&payload[..i]).expect("wait segment must be ASCII micros/marker");+ (wait, &payload[i + 1..])+ }++ #[tokio::test]+ async fn shim_records_duration_and_preserves_body_bytes() {+ // Mix of NUL, invalid UTF-8, and high-bit bytes — picked so any+ // accidental string conversion or truncation surfaces.+ let body: Vec<u8> = vec![+ 0x00, 0xFF, 0xC3, 0x28, b'h', b'e', b'l', b'l', b'o', 0x80, 0x81, 0x82,+ ];+ let app = Router::new()+ .route("/", post(echo_body_read))+ .layer(axum::middleware::from_fn(record_body_read));++ let req = HttpRequest::builder()+ .method("POST")+ .uri("/")+ .body(Body::from(body.clone()))+ .unwrap();+ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let payload = read_response_bytes(resp).await;+ let (wait, echoed_body) = split_echo(&payload);+ assert_ne!(wait, "missing");+ assert_eq!(echoed_body, body);+ }++ #[tokio::test]+ async fn shim_handles_empty_body() {+ // POST with an empty body still produces a (~0 ms) duration and+ // forwards without error.+ let app = Router::new()+ .route("/", post(echo_body_read))+ .layer(axum::middleware::from_fn(record_body_read));++ let req = HttpRequest::builder()+ .method("POST")+ .uri("/")+ .body(Body::empty())+ .unwrap();++ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let payload = read_response_bytes(resp).await;+ let (wait, echoed_body) = split_echo(&payload);+ assert_ne!(wait, "missing");+ assert!(echoed_body.is_empty());+ }++ #[tokio::test]+ async fn shim_extension_absent_when_layer_omitted() {+ let app = Router::new().route("/", post(echo_body_read));+ let resp = app.oneshot(make_request("payload")).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let payload = read_response_bytes(resp).await;+ let (wait, echoed_body) = split_echo(&payload);+ assert_eq!(wait, "missing");+ assert_eq!(echoed_body, b"payload");+ }++ #[tokio::test]+ async fn shim_returns_400_and_increments_failed_counter_on_buffering_error() {+ use futures::stream;++ // `set_default_local_recorder` returns a thread-local guard;+ // safe across `.await` because `#[tokio::test]` defaults to a+ // current-thread runtime.+ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let _guard = metrics::set_default_local_recorder(&recorder);++ let app = Router::new()+ .route("/", post(echo_body_read))+ .layer(axum::middleware::from_fn(record_body_read));++ let err_stream = stream::once(async {+ Err::<Bytes, std::io::Error>(std::io::Error::other("simulated upload failure"))+ });+ let req = HttpRequest::builder()+ .method("POST")+ .uri("/")+ .body(Body::from_stream(err_stream))+ .unwrap();++ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::BAD_REQUEST);+ // Pin the shim's own 400 message so we know the response did+ // not come from a downstream that observed an empty `Bytes`.+ let body_bytes = read_response_bytes(resp).await;+ assert_eq!(body_bytes, b"Failed to buffer the request body");++ let snapshot = snapshotter.snapshot().into_vec();+ let failed = snapshot.iter().find_map(|(ckey, _, _, value)| {+ (ckey.key().name() == FLAG_BODY_READ_FAILED_COUNTER).then_some(value)+ });+ match failed {+ Some(DebugValue::Counter(n)) => assert_eq!(*n, 1),+ other => {+ panic!("expected `{FLAG_BODY_READ_FAILED_COUNTER}` Counter sample, got {other:?}")+ }+ }+ }++ #[tokio::test]+ async fn shim_accepts_body_at_limit() {+ let body = vec![b'a'; MAX_FLAGS_BODY_BYTES];+ let app = Router::new()+ .route("/", post(echo_body_read))+ .layer(axum::middleware::from_fn(record_body_read));++ let req = HttpRequest::builder()+ .method("POST")+ .uri("/")+ .body(Body::from(body.clone()))+ .unwrap();++ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let payload = read_response_bytes(resp).await;+ let (wait, echoed_body) = split_echo(&payload);+ assert_ne!(wait, "missing");+ assert_eq!(echoed_body, body);+ }++ #[tokio::test]+ async fn shim_returns_413_and_increments_too_large_counter_when_body_exceeds_limit() {+ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let _guard = metrics::set_default_local_recorder(&recorder);++ let app = Router::new()+ .route("/", post(echo_body_read))+ .layer(axum::middleware::from_fn(record_body_read));++ let body = vec![b'a'; MAX_FLAGS_BODY_BYTES + 1];+ let req = HttpRequest::builder()+ .method("POST")+ .uri("/")+ .body(Body::from(body))+ .unwrap();++ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);+ let body_bytes = read_response_bytes(resp).await;+ assert_eq!(body_bytes, b"Failed to buffer the request body");++ let snapshot = snapshotter.snapshot().into_vec();+ let too_large = snapshot.iter().find_map(|(ckey, _, _, value)| {+ (ckey.key().name() == FLAG_BODY_READ_TOO_LARGE_COUNTER).then_some(value)+ });+ match too_large {+ Some(DebugValue::Counter(n)) => assert_eq!(*n, 1),+ other => panic!(+ "expected `{FLAG_BODY_READ_TOO_LARGE_COUNTER}` Counter sample, got {other:?}"+ ),+ }+ // The transport-failure counter must stay clean — the two paths+ // are split on purpose, so a regression that collapses them back+ // would cross-fire here.+ let failed = snapshot.iter().find_map(|(ckey, _, _, value)| {+ (ckey.key().name() == FLAG_BODY_READ_FAILED_COUNTER).then_some(value)+ });+ if let Some(DebugValue::Counter(n)) = failed {+ assert_eq!(+ *n, 0,+ "transport-failure counter must not fire on size-exceeded path"+ );+ }+ }+}diff --git a/rust/feature-flags/src/api/endpoint.rs b/rust/feature-flags/src/api/endpoint.rsindex 3aa169c90cda..446e71fc5e32 100644--- a/rust/feature-flags/src/api/endpoint.rs+++ b/rust/feature-flags/src/api/endpoint.rs@@ -1,5 +1,6 @@use crate::{api::{+ body_read_metrics::BodyReadDuration,concurrency_metrics::ConcurrencyLimitWait,errors::{ClientFacingError, FlagError},flags_rate_limiter::RateLimitResult,@@ -209,6 +210,11 @@ pub async fn flags(// `ConcurrencyLimitLayer` hands off a permit. Optional so the handler// tolerates the layer pair being removed or temporarily disabled.concurrency_wait: Option<Extension<ConcurrencyLimitWait>>,+ // Populated by the `record_body_read` middleware after it buffers+ // the inbound POST body to memory. Optional so the handler tolerates+ // the shim being removed or absent on routes that bypass it (e.g. a+ // future `/flags`-only sub-router).+ body_read_duration: Option<Extension<BodyReadDuration>>,headers: HeaderMap,method: Method,path: MatchedPath,@@ -292,6 +298,13 @@ pub async fn flags(// would take longer than the age of the universe.let concurrency_limit_wait_ms = concurrency_wait.map(|Extension(w)| w.0.as_millis() as u64);+ // Body-buffering wall-clock, captured by `record_body_read`. Sub-ms+ // precision (paired with the sub-ms-floor `BODY_READ_BUCKETS_MS`):+ // integer-ms truncation would collapse fast in-memory POSTs into the+ // 0-ms bucket and hide the very tail behavior the buckets exist to+ // surface.+ let body_read_ms = body_read_duration.map(|Extension(d)| d.0.as_secs_f64() * 1000.0);+// Initialize canonical log with all upfront request metadata.// Fields discovered during processing (team_id, flags_evaluated, etc.) are set via with_canonical_log().let canonical_log = FlagsCanonicalLogLine {@@ -304,6 +317,7 @@ pub async fn flags(api_version: query_params.version.clone(),queue_time_ms,concurrency_limit_wait_ms,+ body_read_ms,..Default::default()};@@ -431,6 +445,10 @@ pub async fn flags(// Emit queue/pre-handler/concurrency-wait histograms with team_id labels.// Must run after `process_request` returns so `log.team_id` is populated.log.emit_timing_metrics();+ // Emit per-phase histograms accumulated by `PhaseGuard` drops inside+ // `process_request_inner`. Same `team_id` resolution requirement as+ // `emit_timing_metrics`, so it must run alongside it.+ log.emit_phase_metrics();match result {Ok(response) => {diff --git a/rust/feature-flags/src/api/mod.rs b/rust/feature-flags/src/api/mod.rsindex 339b38d92f60..7cbc839cef9a 100644--- a/rust/feature-flags/src/api/mod.rs+++ b/rust/feature-flags/src/api/mod.rs@@ -1,4 +1,5 @@pub mod auth;+pub mod body_read_metrics;pub mod concurrency_metrics;pub mod endpoint;pub mod errors;diff --git a/rust/feature-flags/src/flags/flag_definitions_cache.rs b/rust/feature-flags/src/flags/flag_definitions_cache.rsindex da0cba4ccda2..46c08f82b231 100644--- a/rust/feature-flags/src/flags/flag_definitions_cache.rs+++ b/rust/feature-flags/src/flags/flag_definitions_cache.rs@@ -1,5 +1,5 @@use std::sync::Arc;-use std::time::Duration;+use std::time::{Duration, Instant};use common_hypercache::CacheSource;use common_metrics::{gauge, inc};@@ -13,9 +13,52 @@ use crate::flags::flag_models::{FeatureFlagList, HypercacheFlagsWrapper, Prepareuse crate::metrics::consts::{FLAG_DEFINITIONS_INMEM_CACHE_ENTRIES_GAUGE, FLAG_DEFINITIONS_INMEM_CACHE_HIT_COUNTER,FLAG_DEFINITIONS_INMEM_CACHE_MISS_COUNTER, FLAG_DEFINITIONS_INMEM_CACHE_NO_VERSION_COUNTER,- FLAG_DEFINITIONS_INMEM_CACHE_SIZE_BYTES_GAUGE,+ FLAG_DEFINITIONS_INMEM_CACHE_SIZE_BYTES_GAUGE, FLAG_DEFINITIONS_INMEM_LOAD_MS,};+/// Outcome of a single `get_or_load` call. Used as the `outcome` label on+/// `flags_definitions_inmem_load_ms`. Six variants total; cardinality is+/// `6 × buckets` per pod.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum LoadOutcome {+ /// In-memory cache returned a value without invoking the loader.+ Hit,+ /// Loader ran successfully via HyperCache → Redis/S3 and the result+ /// was cached under the etag.+ MissLoadOk,+ /// `get_or_load_classified` returned `Err`. Covers both loader+ /// infrastructure failures (HyperCache stall, Redis/S3 outage) and+ /// `compile_from_wrapper` data-parsing failures on otherwise healthy+ /// loader output. The two are indistinguishable at this label, so an+ /// `outcome="miss_load_err"` spike with healthy upstreams points at+ /// data-shape regressions, not infra.+ MissLoadErr,+ /// `etag` was `Some` but the loader returned a non-empty wrapper for+ /// which no etag is in Redis — version-key drift.+ EtagMissing,+ /// `etag` was `None` and the loader returned `__missing__` (Django's+ /// empty-team marker).+ Sentinel,+ /// Loader fell through to PG. The result is not cached under the+ /// etag (see struct doc); split from `MissLoadOk` so a PG fallback+ /// storm is visually separable from an etag-rollover thunder herd.+ Fallback,+}++impl LoadOutcome {+ /// Stable label value, kept in sync with the dashboard contract.+ const fn label(self) -> &'static str {+ match self {+ LoadOutcome::Hit => "hit",+ LoadOutcome::MissLoadOk => "miss_load_ok",+ LoadOutcome::MissLoadErr => "miss_load_err",+ LoadOutcome::EtagMissing => "etag_missing",+ LoadOutcome::Sentinel => "sentinel",+ LoadOutcome::Fallback => "fallback",+ }+ }+}+/// In-memory cache for regex-compiled flag definitions, keyed on/// `(team_id, etag)` where `etag` is the version tag Django writes alongside/// the hypercache payload (`HyperCache(enable_etag=True)`).@@ -64,12 +107,60 @@ impl FlagDefinitionsCache {/// runs, the result is compiled, and only `Redis`/`S3`-source values are/// inserted. The returned `CacheSource` is `Redis` for in-memory hits/// and whatever the loader reports otherwise.+ ///+ /// Total wall-clock duration of this call is recorded into+ /// [`FLAG_DEFINITIONS_INMEM_LOAD_MS`] with an `outcome` label. Hits+ /// resolve in microseconds; misses dominate the p99 because the loader+ /// chain (HyperCache → Pickle/JSON decode → regex compile) is sync-+ /// heavy. A spike in `outcome="miss_load_ok"` p99 is the dashboard+ /// signature of an etag-rollover thunder herd (see struct doc).pub async fn get_or_load<F, Fut>(&self,team_id: TeamId,etag: Option<String>,load_payload: F,) -> Result<(Arc<PreparedFlagDefinitions>, CacheSource), FlagError>+ where+ F: FnOnce() -> Fut,+ Fut: std::future::Future<+ Output = Result<(Option<HypercacheFlagsWrapper>, CacheSource), FlagError>,+ >,+ {+ let start = Instant::now();+ let result = self+ .get_or_load_classified(team_id, etag, load_payload)+ .await;+ let outcome = match &result {+ Ok((_, _, oc)) => *oc,+ Err(_) => LoadOutcome::MissLoadErr,+ };+ // Sub-ms-precision recording paired with the sub-ms-floor bucket+ // override registered in `metrics::buckets`. Hits would otherwise+ // collapse into the lowest integer-ms bucket and hide tail behavior.+ // Direct `metrics::histogram!` (not `common_metrics::histogram`) so+ // the `&'static str` outcome label avoids per-call `String`+ // allocations on the hot read path; this metric has no `team_id`+ // label, so the allowlist filter does not apply.+ metrics::histogram!(+ FLAG_DEFINITIONS_INMEM_LOAD_MS,+ "outcome" => outcome.label(),+ )+ .record(start.elapsed().as_secs_f64() * 1000.0);+ result.map(|(prepared, src, _)| (prepared, src))+ }++ /// Inner worker for [`Self::get_or_load`]. Returns the success outcome+ /// alongside the value so the wrapper can pick the histogram label+ /// without re-deriving control flow. `Err` is treated as+ /// [`LoadOutcome::MissLoadErr`] uniformly at the wrapper level —+ /// including `compile_from_wrapper` parse failures, which are+ /// indistinguishable from infrastructure errors at the metric level.+ async fn get_or_load_classified<F, Fut>(+ &self,+ team_id: TeamId,+ etag: Option<String>,+ load_payload: F,+ ) -> Result<(Arc<PreparedFlagDefinitions>, CacheSource, LoadOutcome), FlagError>whereF: FnOnce() -> Fut,Fut: std::future::Future<@@ -82,25 +173,25 @@ impl FlagDefinitionsCache {// missing etag is real version-key drift. Splitting the labels// lets dashboards exclude steady-state empty teams from alerts.let (wrapper, src) = load_payload().await?;- let reason = if wrapper.is_none() {- "sentinel"+ let outcome = if wrapper.is_none() {+ LoadOutcome::Sentinel} else {- "etag_missing"+ LoadOutcome::EtagMissing};inc(FLAG_DEFINITIONS_INMEM_CACHE_NO_VERSION_COUNTER,- &[("reason".to_string(), reason.to_string())],+ &[("reason".to_string(), outcome.label().to_string())],1,);let prepared = compile_from_wrapper(team_id, wrapper)?;- return Ok((prepared, src));+ return Ok((prepared, src, outcome));};let cache_key = (team_id, etag);if let Some(prepared) = self.cache.get(&cache_key).await {inc(FLAG_DEFINITIONS_INMEM_CACHE_HIT_COUNTER, &[], 1);- return Ok((prepared, CacheSource::Redis));+ return Ok((prepared, CacheSource::Redis, LoadOutcome::Hit));}let (wrapper, src) = load_payload().await?;@@ -108,13 +199,16 @@ impl FlagDefinitionsCache {inc(FLAG_DEFINITIONS_INMEM_CACHE_MISS_COUNTER, &[], 1);self.report_cache_metrics();- // Source is checked after the loader returns so a fall-through to PG- // never persists under the etag (see struct doc).- if !matches!(src, CacheSource::Fallback) {+ // Fallback (PG) results aren't persisted under the etag (see+ // struct doc) and get their own outcome label.+ let outcome = if matches!(src, CacheSource::Fallback) {+ LoadOutcome::Fallback+ } else {self.cache.insert(cache_key, Arc::clone(&prepared)).await;- }+ LoadOutcome::MissLoadOk+ };- Ok((prepared, src))+ Ok((prepared, src, outcome))}/// Starts periodic monitoring of cache metrics. Honors the lifecycle@@ -337,6 +431,112 @@ mod tests {);}+ /// Snapshots the `outcome` label of the most recent+ /// `flags_definitions_inmem_load_ms` sample. Returns `None` when no+ /// sample was recorded. Shared by the per-outcome tests below.+ fn last_load_outcome_label(+ snapshotter: &metrics_util::debugging::Snapshotter,+ ) -> Option<String> {+ snapshotter+ .snapshot()+ .into_vec()+ .into_iter()+ .rfind(|(ckey, _, _, _)| ckey.key().name() == FLAG_DEFINITIONS_INMEM_LOAD_MS)+ .and_then(|(ckey, _, _, _)| {+ ckey.key()+ .labels()+ .find(|l| l.key() == "outcome")+ .map(|l| l.value().to_string())+ })+ }++ #[tokio::test]+ async fn test_pg_fallback_emits_fallback_outcome_label() {+ use metrics_util::debugging::DebuggingRecorder;++ // `set_default_local_recorder` returns a thread-local guard;+ // safe across `.await` because `#[tokio::test]` defaults to a+ // current-thread runtime.+ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let _guard = metrics::set_default_local_recorder(&recorder);++ let cache = FlagDefinitionsCache::new(None, None);+ let w = make_test_wrapper(vec![make_flag_with_regex(1, r"^t@.*$")]);+ let fallback_loader = move || -> LoaderFuture {+ Box::pin(async move { Ok::<_, FlagError>((Some(w), CacheSource::Fallback)) })+ };+ let (_, src) = cache+ .get_or_load(1, Some("etag-present".into()), fallback_loader)+ .await+ .unwrap();+ assert!(matches!(src, CacheSource::Fallback));++ assert_eq!(+ last_load_outcome_label(&snapshotter).as_deref(),+ Some("fallback")+ );+ }++ /// Pins the dashboard contract for the `miss_load_ok` label: a+ /// cache miss with a healthy Redis-source loader must classify as+ /// `miss_load_ok`, not `fallback` or `miss_load_err`. Without this+ /// assertion, a regression that swapped the `Fallback` arm in+ /// `get_or_load_classified` would not fail any other test.+ #[tokio::test]+ async fn test_etag_present_redis_loader_emits_miss_load_ok_label() {+ use metrics_util::debugging::DebuggingRecorder;++ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let _guard = metrics::set_default_local_recorder(&recorder);++ let cache = FlagDefinitionsCache::new(None, None);+ let w = make_test_wrapper(vec![make_flag_with_regex(1, r"^t@.*$")]);+ cache+ .get_or_load(1, Some("fresh-etag".into()), loader_for(w))+ .await+ .unwrap();++ assert_eq!(+ last_load_outcome_label(&snapshotter).as_deref(),+ Some("miss_load_ok")+ );+ }++ /// Pins the dashboard contract for `miss_load_err`: an `Err` from+ /// the loader (here `DatabaseUnavailable`) must classify as+ /// `miss_load_err`. The same label also covers+ /// `compile_from_wrapper` parse failures — see the `LoadOutcome`+ /// doc — so an alert on this label cannot distinguish the two+ /// without correlating against upstream health.+ #[tokio::test]+ async fn test_loader_error_emits_miss_load_err_label() {+ use metrics_util::debugging::DebuggingRecorder;++ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let _guard = metrics::set_default_local_recorder(&recorder);++ let cache = FlagDefinitionsCache::new(None, None);+ let loader = || -> LoaderFuture {+ Box::pin(async {+ Err::<(Option<HypercacheFlagsWrapper>, CacheSource), _>(+ FlagError::DatabaseUnavailable,+ )+ })+ };+ cache+ .get_or_load(1, Some("e".into()), loader)+ .await+ .expect_err("loader error must surface");++ assert_eq!(+ last_load_outcome_label(&snapshotter).as_deref(),+ Some("miss_load_err")+ );+ }+/// When the etag GET succeeds but the loader returns `Fallback` (e.g./// payload evicted before the etag key), the value must not land in/// the cache under the still-fresh etag — otherwise single-stage PGdiff --git a/rust/feature-flags/src/handler/canonical_log.rs b/rust/feature-flags/src/handler/canonical_log.rsindex 3db25923df8f..18acf71940ca 100644--- a/rust/feature-flags/src/handler/canonical_log.rs+++ b/rust/feature-flags/src/handler/canonical_log.rs@@ -1,8 +1,9 @@use crate::api::errors::FlagError;use crate::flags::flag_matching::EvaluationType;+use crate::handler::phases::PhaseDurations;use crate::metrics::consts::{- FLAG_CONCURRENCY_LIMIT_WAIT_TIME_MS, FLAG_DB_OPERATIONS_PER_REQUEST, FLAG_PRE_HANDLER_TIME_MS,- FLAG_QUEUE_TIME_MS,+ FLAG_BODY_READ_TIME_MS, FLAG_CONCURRENCY_LIMIT_WAIT_TIME_MS, FLAG_DB_OPERATIONS_PER_REQUEST,+ FLAG_PHASE_DURATION_MS, FLAG_PRE_HANDLER_TIME_MS, FLAG_QUEUE_TIME_MS,};use std::cell::RefCell;use std::future::Future;@@ -271,6 +272,25 @@ pub struct FlagsCanonicalLogLine {/// phase ships; while None, `emit_timing_metrics` skips emission.pub concurrency_limit_wait_ms: Option<u64>,+ /// Wall-clock duration of inbound request body buffering, in+ /// milliseconds with sub-ms precision. Captured by the+ /// `record_body_read` middleware shim, populated on the request+ /// extensions, and seeded onto the canonical log at handler entry.+ /// `None` only when the shim is absent on the route that reached the+ /// handler (the production wiring installs it on `/flags|/decide`,+ /// so this is the rollout-safety / test fallback path); the shim+ /// itself records a duration for every method, including empty+ /// bodies. `f64` (not `u64`) because `BODY_READ_BUCKETS_MS` has+ /// sub-ms boundaries — integer-ms truncation would hide warm+ /// in-memory POSTs in the bottom bucket.+ pub body_read_ms: Option<f64>,++ /// Per-phase wall-clock breakdown of `process_request_inner`.+ /// Populated by [`crate::handler::phases::PhaseGuard`] drops; emitted+ /// as a labeled histogram by [`Self::emit_phase_metrics`] once the+ /// `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@@ -329,6 +349,8 @@ impl Default for FlagsCanonicalLogLine {queue_time_ms: None,pre_handler_duration_ms: None,concurrency_limit_wait_ms: None,+ body_read_ms: None,+ phases: PhaseDurations::default(),billing_duration_ms: None,team_cache_source: None,http_status: 200,@@ -398,6 +420,7 @@ impl FlagsCanonicalLogLine {queue_time_ms = self.queue_time_ms,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,@@ -503,6 +526,49 @@ impl FlagsCanonicalLogLine {if let Some(wait) = self.concurrency_limit_wait_ms {common_metrics::histogram(FLAG_CONCURRENCY_LIMIT_WAIT_TIME_MS, &[], wait as f64);}++ if let Some(body_read) = self.body_read_ms {+ // No `team_id` label — body buffering happens before+ // authentication, mirroring `concurrency_limit_wait_ms`.+ common_metrics::histogram(FLAG_BODY_READ_TIME_MS, &[], body_read);+ }+ }++ /// Emit `flags_phase_duration_ms` histograms for every phase that ran.+ ///+ /// Each entry is labeled `phase=<name>` and `team_id=<id>` (filtered+ /// through the existing team allowlist; non-allowlisted teams collapse+ /// to `unknown`). Phases that never ran on this request — e.g.+ /// `record_billing` for a non-billable request, `cookieless` for a+ /// quota-limited request — are silently skipped.+ ///+ /// Call once per request, after `team_id` has been resolved (i.e.+ /// after `process_request` returns). Idempotent only in the trivial+ /// sense: calling twice would double-count, so callers must not.+ pub fn emit_phase_metrics(&self) {+ let team_id_label_value = self+ .team_id+ .map(|id| id.to_string())+ .unwrap_or_else(|| "unknown".to_string());++ for (phase, elapsed) in self.phases.iter() {+ // The phase label varies per iteration; team_id is constant+ // for the request. We have to go through `common_metrics::+ // histogram` (rather than `metrics::histogram!` directly) to+ // pick up the team-id allowlist filter — without it cardinality+ // is `phase_count × every_team`, not `phase_count ×+ // allowlist_size`. Allocations are bounded: ~four short+ // `String`s per phase, ~28 per request total.+ let labels = [+ ("phase".to_string(), phase.name().to_string()),+ ("team_id".to_string(), team_id_label_value.clone()),+ ];+ common_metrics::histogram(+ FLAG_PHASE_DURATION_MS,+ &labels,+ elapsed.as_secs_f64() * 1000.0,+ );+ }}/// Merge evaluation counters accumulated on a rayon thread back into this log.@@ -535,6 +601,40 @@ mod tests {use super::*;use crate::api::errors::{ClientFacingError, FlagError};use crate::utils::graph_utils::DependencyType;+ use metrics_util::debugging::{DebugValue, DebuggingRecorder};++ /// Shared metric-snapshot fixture for the `emit_*_metrics` test+ /// modules below. Both modules need the same captured-sample shape+ /// (name + sorted labels + raw value) and the same conversion from+ /// `DebuggingRecorder`'s nested-tuple snapshot.+ struct MetricSample {+ name: String,+ labels: Vec<(String, String)>,+ #[allow(dead_code)]+ value: DebugValue,+ }++ fn snapshot_metrics(recorder: &DebuggingRecorder) -> Vec<MetricSample> {+ recorder+ .snapshotter()+ .snapshot()+ .into_vec()+ .into_iter()+ .map(|(ckey, _, _, value)| {+ let key = ckey.key();+ let mut labels: Vec<(String, String)> = key+ .labels()+ .map(|l| (l.key().to_string(), l.value().to_string()))+ .collect();+ labels.sort();+ MetricSample {+ name: key.name().to_string(),+ labels,+ value,+ }+ })+ .collect()+ }#[test]fn test_new_creates_with_defaults() {@@ -628,38 +728,8 @@ mod tests {mod emit_timing_metrics_tests {use super::*;- use metrics_util::debugging::{DebugValue, DebuggingRecorder};use rstest::rstest;- struct MetricSample {- name: String,- labels: Vec<(String, String)>,- #[allow(dead_code)]- value: DebugValue,- }-- fn snapshot_metrics(recorder: &DebuggingRecorder) -> Vec<MetricSample> {- recorder- .snapshotter()- .snapshot()- .into_vec()- .into_iter()- .map(|(ckey, _, _, value)| {- let key = ckey.key();- let mut labels: Vec<(String, String)> = key- .labels()- .map(|l| (l.key().to_string(), l.value().to_string()))- .collect();- labels.sort();- MetricSample {- name: key.name().to_string(),- labels,- value,- }- })- .collect()- }-fn set_queue_time(log: &mut FlagsCanonicalLogLine) {log.queue_time_ms = Some(150);}@@ -749,7 +819,6 @@ mod tests {let recorder = DebuggingRecorder::new();metrics::with_local_recorder(&recorder, || {let log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());- // All three timing fields default to None.log.emit_timing_metrics();});@@ -758,6 +827,7 @@ mod tests {"flags_queue_time_ms","flags_pre_handler_time_ms","flags_concurrency_limit_wait_ms",+ "flags_body_read_ms",] {assert!(!metrics.iter().any(|s| s.name == name),@@ -779,6 +849,125 @@ mod tests {let metrics = snapshot_metrics(&recorder);assert!(!metrics.iter().any(|s| s.name == "flags_queue_time_ms"));}++ #[test]+ fn test_body_read_emitted_without_team_id_label() {+ let recorder = DebuggingRecorder::new();+ metrics::with_local_recorder(&recorder, || {+ let mut log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());+ log.team_id = Some(123);+ log.body_read_ms = Some(7.0);+ log.emit_timing_metrics();+ });++ let metrics = snapshot_metrics(&recorder);+ let sample = metrics+ .iter()+ .find(|s| s.name == "flags_body_read_ms")+ .expect("flags_body_read_ms not emitted");+ // Pod-level: must NOT carry team_id, mirroring concurrency_limit_wait_ms.+ assert!(+ !sample.labels.iter().any(|(k, _)| k == "team_id"),+ "body_read_ms should not carry team_id, got {:?}",+ sample.labels+ );+ }+ }++ mod emit_phase_metrics_tests {+ use super::*;+ use crate::handler::phases::Phase;+ use std::time::Duration;++ #[test]+ fn test_emits_one_sample_per_recorded_phase() {+ let recorder = DebuggingRecorder::new();+ metrics::with_local_recorder(&recorder, || {+ let mut log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());+ log.team_id = Some(42);+ log.phases.record(Phase::Auth, Duration::from_millis(3));+ log.phases+ .record(Phase::Evaluate, Duration::from_millis(50));+ log.emit_phase_metrics();+ });++ let metrics = snapshot_metrics(&recorder);+ let phase_samples: Vec<_> = metrics+ .iter()+ .filter(|s| s.name == "flags_phase_duration_ms")+ .collect();+ assert_eq!(phase_samples.len(), 2);++ let phase_label_values: Vec<&str> = phase_samples+ .iter()+ .flat_map(|s| {+ s.labels+ .iter()+ .filter(|(k, _)| k == "phase")+ .map(|(_, v)| v.as_str())+ })+ .collect();+ assert!(phase_label_values.contains(&"auth"));+ assert!(phase_label_values.contains(&"evaluate"));+ }++ #[test]+ fn test_phase_carries_team_id_label() {+ let recorder = DebuggingRecorder::new();+ metrics::with_local_recorder(&recorder, || {+ let mut log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());+ log.team_id = Some(777);+ log.phases+ .record(Phase::Cookieless, Duration::from_millis(1));+ log.emit_phase_metrics();+ });++ let metrics = snapshot_metrics(&recorder);+ let sample = metrics+ .iter()+ .find(|s| s.name == "flags_phase_duration_ms")+ .expect("flags_phase_duration_ms not emitted");+ assert!(sample+ .labels+ .iter()+ .any(|(k, v)| k == "team_id" && v == "777"));+ assert!(sample+ .labels+ .iter()+ .any(|(k, v)| k == "phase" && v == "cookieless"));+ }++ #[test]+ fn test_phase_unknown_team_when_unresolved() {+ let recorder = DebuggingRecorder::new();+ metrics::with_local_recorder(&recorder, || {+ let mut log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());+ // team_id stays None (e.g. auth failed before team resolution).+ log.phases.record(Phase::Auth, Duration::from_millis(2));+ log.emit_phase_metrics();+ });++ let metrics = snapshot_metrics(&recorder);+ let sample = metrics+ .iter()+ .find(|s| s.name == "flags_phase_duration_ms")+ .expect("flags_phase_duration_ms not emitted");+ assert!(sample+ .labels+ .iter()+ .any(|(k, v)| k == "team_id" && v == "unknown"));+ }++ #[test]+ fn test_no_emission_when_no_phases_recorded() {+ let recorder = DebuggingRecorder::new();+ metrics::with_local_recorder(&recorder, || {+ let log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());+ log.emit_phase_metrics();+ });+ let metrics = snapshot_metrics(&recorder);+ assert!(!metrics.iter().any(|s| s.name == "flags_phase_duration_ms"));+ }}#[test]diff --git a/rust/feature-flags/src/handler/mod.rs b/rust/feature-flags/src/handler/mod.rsindex 39dc8ad8f87b..085a278982e3 100644--- a/rust/feature-flags/src/handler/mod.rs+++ b/rust/feature-flags/src/handler/mod.rs@@ -7,6 +7,7 @@ pub mod decoding;pub mod error_tracking;pub mod evaluation;pub mod flags;+pub mod phases;pub mod properties;pub mod session_recording;pub mod types;@@ -19,6 +20,7 @@ pub use types::*;use crate::{api::{errors::FlagError, types::FlagsResponse},flags::{flag_matching::EvaluationType, flag_service::FlagService},+ handler::phases::{Phase, PhaseGuard},metrics::consts::{FLAG_REQUESTS_COUNTER, FLAG_REQUESTS_LATENCY, FLAG_REQUEST_FAULTS_COUNTER},};use std::collections::HashMap;@@ -128,8 +130,15 @@ async fn process_request_inner(*context.state.config.skip_pg_team_fallback,);- let (original_distinct_id, team, request) =- authentication::parse_and_authenticate(&context, &flag_service).await?;+ let (original_distinct_id, team, request) = {+ // Phase boundary: covers token decoding, team verification+ // (HyperCache → Redis → S3 → PG fallback), and distinct-id+ // extraction. Drop records elapsed time into the canonical+ // log; histogram emission is deferred to `emit_phase_metrics`+ // so the metric carries a `team_id` label.+ let _phase = PhaseGuard::enter(Phase::Auth);+ authentication::parse_and_authenticate(&context, &flag_service).await?+ };let distinct_id_for_logging = original_distinct_id.clone()@@ -169,92 +178,111 @@ async fn process_request_inner(let flags_response = if request.is_flags_disabled() {with_canonical_log(|log| log.flags_disabled = true);FlagsResponse::new(false, HashMap::new(), None, context.request_id)- } else if let Some(quota_limited_response) =- billing::check_limits(&context, &team.api_token).await?- {- warn!("Request quota limited");- with_canonical_log(|log| log.quota_limited = true);- quota_limited_response} else {- let distinct_id = cookieless::handle_distinct_id(- &context,- &request,- &team,- original_distinct_id- .expect("distinct_id should be present when flags are not disabled"),- )- .await?;-- tracing::debug!("Distinct ID resolved: {}", distinct_id);-- // Compute auth status once to avoid repeated header parsing and allocation- let is_internal = authentication::is_internal_request(&context);-- let override_defs = if is_internal {- request.override_flags_definitions.as_ref()- } else {- None+ // Lift the billing-limits await out of the `else if let`+ // chain so the phase guard scope is exactly that one await,+ // matching the rest of the phases in this function.+ let billing_limited = {+ let _phase = PhaseGuard::enter(Phase::BillingCheck);+ billing::check_limits(&context, &team.api_token).await?};- let filtered_flags = flags::fetch_and_filter(- &flag_service,- team.id,- &context.meta,- &context.headers,- request.evaluation_runtime,- request.evaluation_contexts.as_ref(),- override_defs,- )- .await?;-- tracing::debug!("Flags filtered: {} flags found", filtered_flags.flags.len());-- let property_overrides = properties::prepare_overrides(&context, &request)?;-- // Evaluate flags (this will return empty if is_flags_disabled is true)- let response = flags::evaluate_for_request(- &context.state,- team.id,- distinct_id.clone(),- device_id.clone(),- filtered_flags.clone(),- property_overrides.person_properties,- property_overrides.group_properties,- property_overrides.groups,- property_overrides.hash_key,- context.request_id,- request.is_flags_disabled(),- request.flag_keys.clone(),- Some(is_internal && context.meta.detailed_analysis.unwrap_or(false)),- if is_internal {- context.meta.only_use_override_person_properties+ if let Some(quota_limited_response) = billing_limited {+ warn!("Request quota limited");+ with_canonical_log(|log| log.quota_limited = true);+ quota_limited_response+ } else {+ let distinct_id = {+ let _phase = PhaseGuard::enter(Phase::Cookieless);+ cookieless::handle_distinct_id(+ &context,+ &request,+ &team,+ original_distinct_id+ .expect("distinct_id should be present when flags are not disabled"),+ )+ .await?+ };++ tracing::debug!("Distinct ID resolved: {}", distinct_id);++ // Compute auth status once to avoid repeated header parsing and allocation.+ let is_internal = authentication::is_internal_request(&context);++ let override_defs = if is_internal {+ request.override_flags_definitions.as_ref()} else {None- },- )- .await?;-- // Only record billing if flags are not disabled- if !request.is_flags_disabled() {- billing::record_usage(- &context,- &filtered_flags,- team.id,- metrics_data.library,- is_internal,- )- .await;+ };++ let filtered_flags = {+ let _phase = PhaseGuard::enter(Phase::FetchAndFilter);+ flags::fetch_and_filter(+ &flag_service,+ team.id,+ &context.meta,+ &context.headers,+ request.evaluation_runtime,+ request.evaluation_contexts.as_ref(),+ override_defs,+ )+ .await?+ };++ tracing::debug!("Flags filtered: {} flags found", filtered_flags.flags.len());++ let property_overrides = properties::prepare_overrides(&context, &request)?;++ // Evaluate flags (this will return empty if is_flags_disabled is true)+ let response = {+ let _phase = PhaseGuard::enter(Phase::Evaluate);+ flags::evaluate_for_request(+ &context.state,+ team.id,+ distinct_id.clone(),+ device_id.clone(),+ filtered_flags.clone(),+ property_overrides.person_properties,+ property_overrides.group_properties,+ property_overrides.groups,+ property_overrides.hash_key,+ context.request_id,+ request.is_flags_disabled(),+ request.flag_keys.clone(),+ Some(is_internal && context.meta.detailed_analysis.unwrap_or(false)),+ if is_internal {+ context.meta.only_use_override_person_properties+ } else {+ None+ },+ )+ .await?+ };++ {+ let _phase = PhaseGuard::enter(Phase::RecordBilling);+ billing::record_usage(+ &context,+ &filtered_flags,+ team.id,+ metrics_data.library,+ is_internal,+ )+ .await;+ }++ response}-- response};// Build the rest of the FlagsResponse with config from HyperCache.// When config=true, reads pre-computed config from Python's RemoteConfig.// On cache miss, returns fallback config.- let response =+ let response = {+ let _phase = PhaseGuard::enter(Phase::ConfigResponse);config_response_builder::build_response_from_cache(flags_response, &context, &team)- .await?;+ .await?+ };// Populate canonical log with flag evaluation results and read back evaluation_type.// If an earlier step errored (? above), we skip this and evaluation_type staysdiff --git a/rust/feature-flags/src/handler/phases.rs b/rust/feature-flags/src/handler/phases.rsnew file mode 100644index 000000000000..76398ba49337--- /dev/null+++ b/rust/feature-flags/src/handler/phases.rs@@ -0,0 +1,318 @@+//! Per-phase RAII timing for `process_request_inner`.+//!+//! 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.+//!+//! [`PhaseGuard`] is the entry point. Construct one at the start of each+//! phase; on drop it:+//!+//! 1. Records elapsed wall-clock duration into the canonical log via+//! [`with_canonical_log`], deferring histogram emission to+//! [`FlagsCanonicalLogLine::emit_phase_metrics`] so the metric carries+//! a `team_id` label once authentication has resolved it.+//! 2. Decrements the pod-level [`FLAG_INFLIGHT_BY_PHASE`] gauge.+//!+//! The gauge is incremented at construction, not on first poll, so a task+//! parked on its very first await still shows up in the per-phase+//! in-flight count. Pair the gauge with `flags_tokio_alive_tasks`: when+//! alive_tasks jumps and exactly one phase gauge tracks the jump, that+//! phase owns the parking site.+//!+//! Drop side-effect order: histogram-bound duration is recorded **before**+//! the gauge decrement, so a panic mid-phase still preserves the elapsed+//! time the request had accumulated.++use std::time::{Duration, Instant};++use metrics::gauge;++use crate::handler::canonical_log::with_canonical_log;+use crate::metrics::consts::FLAG_INFLIGHT_BY_PHASE;++/// Identifies a top-level phase of `process_request_inner`.+///+/// `name()` returns the value used as the `phase` label on+/// `flags_phase_duration_ms` and `flags_inflight_by_phase`. These names+/// are part of the public dashboard contract — keep them stable. Adding+/// a variant requires updating [`Phase::ALL`] (a `debug_assert!` enforces+/// the length invariant in tests).+#[repr(usize)]+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Phase {+ /// Token extraction, distinct-id parsing, team verification.+ Auth = 0,+ /// Per-team feature-flag billing-limit check (Redis).+ BillingCheck = 1,+ /// Cookieless distinct-id derivation (Redis-backed key).+ Cookieless = 2,+ /// Loading flag definitions and applying static filters.+ FetchAndFilter = 3,+ /// 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.+ RecordBilling = 5,+ /// Building the response payload from the cached config blob.+ ConfigResponse = 6,+}++impl Phase {+ /// Number of distinct phase variants. Used to size the duration+ /// table on the canonical log.+ pub const COUNT: usize = 7;++ /// Iteration order for emission. The order is irrelevant for+ /// correctness but stable for dashboard readability.+ pub const ALL: [Phase; Self::COUNT] = [+ Phase::Auth,+ Phase::BillingCheck,+ Phase::Cookieless,+ Phase::FetchAndFilter,+ Phase::Evaluate,+ Phase::RecordBilling,+ Phase::ConfigResponse,+ ];++ /// Stable label value. Treat as part of the dashboard contract.+ pub const fn name(self) -> &'static str {+ match self {+ Phase::Auth => "auth",+ Phase::BillingCheck => "billing_check",+ Phase::Cookieless => "cookieless",+ Phase::FetchAndFilter => "fetch_and_filter",+ Phase::Evaluate => "evaluate",+ Phase::RecordBilling => "record_billing",+ Phase::ConfigResponse => "config_response",+ }+ }+}++/// RAII guard for a single phase of work.+///+/// Construct with [`PhaseGuard::enter`]; drop ends the phase. The guard+/// is `Send` because it carries only `Copy` state, so it survives across+/// `.await` points without ceremony.+#[must_use = "PhaseGuard records timing on drop; ignoring it ends the phase immediately"]+pub(crate) struct PhaseGuard {+ phase: Phase,+ start: Instant,+}++impl PhaseGuard {+ /// Marks the start of `phase`. Side effects:+ ///+ /// - Increments `flags_inflight_by_phase{phase=…}` by 1.+ /// - Stamps `Instant::now()` for elapsed-time computation on drop.+ pub(crate) fn enter(phase: Phase) -> Self {+ gauge!(FLAG_INFLIGHT_BY_PHASE, "phase" => phase.name()).increment(1.0);+ Self {+ phase,+ start: Instant::now(),+ }+ }+}++impl Drop for PhaseGuard {+ fn drop(&mut self) {+ let elapsed = self.start.elapsed();+ // Log update can no-op (e.g. unit tests with no canonical scope),+ // but the gauge must always decrement to balance `enter`.+ with_canonical_log(|log| log.phases.record(self.phase, elapsed));+ gauge!(FLAG_INFLIGHT_BY_PHASE, "phase" => self.phase.name()).decrement(1.0);+ }+}++/// Per-phase duration accumulator on `FlagsCanonicalLogLine`.+///+/// Indexed by `Phase as usize`. The only writer is [`PhaseGuard::drop`];+/// the only reader is `emit_phase_metrics`. Any phase that never ran+/// (early return before its guard was constructed) stays `None` and is+/// skipped at emission.+#[derive(Clone, Debug, Default)]+pub struct PhaseDurations {+ durations: [Option<Duration>; Phase::COUNT],+}++impl PhaseDurations {+ /// Records the elapsed duration for `phase`. If a phase is entered+ /// twice in the same request — which should not happen, but is+ /// defensible — the most recent value wins.+ pub fn record(&mut self, phase: Phase, elapsed: Duration) {+ self.durations[phase as usize] = Some(elapsed);+ }++ /// Iterates over all recorded `(phase, duration)` pairs. Phases that+ /// never ran are skipped.+ pub fn iter(&self) -> impl Iterator<Item = (Phase, Duration)> + '_ {+ Phase::ALL+ .iter()+ .copied()+ .zip(self.durations.iter())+ .filter_map(|(phase, slot)| slot.map(|d| (phase, d)))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn phase_all_covers_every_variant() {+ // `PhaseDurations::iter` zips `Phase::ALL` with the duration+ // array indexed by `phase as usize`; misaligned indices vs.+ // discriminants would silently mislabel histograms.+ assert_eq!(Phase::ALL.len(), Phase::COUNT);+ for (i, phase) in Phase::ALL.iter().enumerate() {+ assert_eq!(+ *phase as usize, i,+ "Phase::ALL[{i}] = {phase:?} but discriminant is {}",+ *phase as usize+ );+ }+ }++ #[test]+ fn phase_names_are_stable_snake_case() {+ for phase in Phase::ALL {+ let name = phase.name();+ assert!(!name.is_empty());+ assert!(name.chars().all(|c| c.is_ascii_lowercase() || c == '_'));+ }+ }++ #[test]+ fn phase_durations_default_iter_is_empty() {+ let durations = PhaseDurations::default();+ assert_eq!(durations.iter().count(), 0);+ }++ #[test]+ fn phase_durations_records_and_iterates_in_phase_order() {+ let mut durations = PhaseDurations::default();+ durations.record(Phase::Cookieless, Duration::from_millis(2));+ durations.record(Phase::Auth, Duration::from_millis(1));++ // Iteration order matches `Phase::ALL`, not insertion order, so+ // dashboards can rely on a stable label ordering.+ let pairs: Vec<_> = durations.iter().collect();+ assert_eq!(pairs.len(), 2);+ assert_eq!(pairs[0].0, Phase::Auth);+ assert_eq!(pairs[0].1, Duration::from_millis(1));+ assert_eq!(pairs[1].0, Phase::Cookieless);+ assert_eq!(pairs[1].1, Duration::from_millis(2));+ }++ #[test]+ fn phase_durations_overwrite_keeps_latest() {+ let mut durations = PhaseDurations::default();+ durations.record(Phase::Evaluate, Duration::from_millis(10));+ durations.record(Phase::Evaluate, Duration::from_millis(50));+ let (phase, d) = durations.iter().next().unwrap();+ assert_eq!(phase, Phase::Evaluate);+ assert_eq!(d, Duration::from_millis(50));+ }++ #[tokio::test]+ async fn phase_guard_records_into_canonical_log_on_drop() {+ use crate::handler::canonical_log::{run_with_canonical_log, FlagsCanonicalLogLine};+ use uuid::Uuid;++ let log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());+ let (_, final_log) = run_with_canonical_log(log, async {+ {+ let _guard = PhaseGuard::enter(Phase::FetchAndFilter);+ tokio::task::yield_now().await;+ }+ // After the block, the guard has dropped. Nothing else to do.+ })+ .await;++ let pairs: Vec<_> = final_log.phases.iter().collect();+ assert_eq!(pairs.len(), 1);+ assert_eq!(pairs[0].0, Phase::FetchAndFilter);+ // Lower bound 0 (clock can elapse 0ns under release optimizations);+ // upper bound generous to absorb scheduler jitter without flake.+ assert!(pairs[0].1 < Duration::from_secs(1));+ }++ #[tokio::test]+ async fn phase_guard_records_each_phase_independently() {+ use crate::handler::canonical_log::{run_with_canonical_log, FlagsCanonicalLogLine};+ use uuid::Uuid;++ let log = FlagsCanonicalLogLine::new(Uuid::new_v4(), "10.0.0.1".to_string());+ let (_, final_log) = run_with_canonical_log(log, async {+ {+ let _g = PhaseGuard::enter(Phase::Auth);+ tokio::task::yield_now().await;+ }+ {+ let _g = PhaseGuard::enter(Phase::Evaluate);+ tokio::task::yield_now().await;+ }+ })+ .await;++ let phases: Vec<_> = final_log.phases.iter().map(|(p, _)| p).collect();+ assert_eq!(phases, vec![Phase::Auth, Phase::Evaluate]);+ }++ #[test]+ fn phase_guard_outside_canonical_scope_does_not_panic() {+ // Defensive: PhaseGuard's drop must not panic if no canonical log+ // is in scope (e.g. a unit test exercising a downstream module+ // without setting up the task-local). `with_canonical_log`+ // already no-ops in that case; this test pins the contract.+ let _g = PhaseGuard::enter(Phase::ConfigResponse);+ }++ /// `flags_inflight_by_phase` must be balanced: +1 while the guard is+ /// alive, 0 after drop. A regression that moves the increment into+ /// Drop, skips it on an error path, or replaces drop ordering would+ /// leak the gauge permanently with no other test failing.+ #[test]+ fn phase_guard_gauge_is_balanced() {+ use metrics_util::debugging::{DebugValue, DebuggingRecorder};++ fn auth_gauge_value(+ snapshotter: &metrics_util::debugging::Snapshotter,+ ) -> Option<DebugValue> {+ snapshotter+ .snapshot()+ .into_vec()+ .into_iter()+ .find(|(ckey, _, _, _)| {+ ckey.key().name() == FLAG_INFLIGHT_BY_PHASE+ && ckey+ .key()+ .labels()+ .any(|l| l.key() == "phase" && l.value() == "auth")+ })+ .map(|(_, _, _, v)| v)+ }++ let recorder = DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ metrics::with_local_recorder(&recorder, || {+ let guard = PhaseGuard::enter(Phase::Auth);+ let mid = auth_gauge_value(&snapshotter);+ assert!(+ matches!(&mid, Some(DebugValue::Gauge(f)) if f.into_inner() == 1.0),+ "gauge must be 1 while PhaseGuard is alive, got {mid:?}",+ );+ drop(guard);+ let after = auth_gauge_value(&snapshotter);+ assert!(+ matches!(&after, Some(DebugValue::Gauge(f)) if f.into_inner() == 0.0),+ "gauge must be 0 after PhaseGuard is dropped, got {after:?}",+ );+ });+ }+}diff --git a/rust/feature-flags/src/metrics/buckets.rs b/rust/feature-flags/src/metrics/buckets.rsindex a3670c77e262..83b559f4d1ac 100644--- a/rust/feature-flags/src/metrics/buckets.rs+++ b/rust/feature-flags/src/metrics/buckets.rs@@ -35,6 +35,31 @@ const TOKEN_EXTRACT_BUCKETS_MS: &[f64] = &[0.5, 1.0, 2.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 5000.0,];+// Per-phase histograms span the full handler-async budget: warm hits+// (auth/billing_check on cached path) finish in microseconds, while a+// pathological evaluate or fetch_and_filter can run for seconds. Mirror+// the `QUEUE_TIME_BUCKETS_MS` ceiling (30s, ~6× `request_timeout_ms`)+// with a sub-ms floor so warm hits don't collapse into a single bucket.+const PHASE_DURATION_BUCKETS_MS: &[f64] = &[+ 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2500.0, 5000.0,+ 10000.0, 30000.0,+];++// Body buffering. Sub-ms floor catches tiny POSTs; 10s ceiling covers+// slow uploaders / pathological compressed bodies but stays well under+// the 30s tower timeout.+const BODY_READ_BUCKETS_MS: &[f64] = &[+ 0.05, 0.1, 0.5, 1.0, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 5000.0, 10000.0,+];++// In-memory cache `get_or_load` total. Hits resolve in low single-digit+// microseconds; loader misses dominate the p99 (HyperCache fetch ++// Pickle/JSON decode + regex compile). 10s ceiling matches HyperCache's+// outer timeout budget.+const INMEM_LOAD_BUCKETS_MS: &[f64] = &[+ 0.05, 0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 25.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 5000.0, 10000.0,+];+/// Returns the bucket-override matrix for the feature-flags recorder.////// `Matcher::Suffix` is used for `_queue_time_ms` / `_pre_handler_time_ms`@@ -69,5 +94,17 @@ pub fn bucket_overrides() -> Vec<(Matcher, &'static [f64])> {Matcher::Full("flags_token_extract_ms".into()),TOKEN_EXTRACT_BUCKETS_MS,),+ (+ Matcher::Full("flags_phase_duration_ms".into()),+ PHASE_DURATION_BUCKETS_MS,+ ),+ (+ Matcher::Full("flags_body_read_ms".into()),+ BODY_READ_BUCKETS_MS,+ ),+ (+ Matcher::Full("flags_definitions_inmem_load_ms".into()),+ INMEM_LOAD_BUCKETS_MS,+ ),]}diff --git a/rust/feature-flags/src/metrics/consts.rs b/rust/feature-flags/src/metrics/consts.rsindex db1bc1dbd0ff..d02c916e3d3a 100644--- a/rust/feature-flags/src/metrics/consts.rs+++ b/rust/feature-flags/src/metrics/consts.rs@@ -75,6 +75,55 @@ pub const FLAG_TOKEN_EXTRACT_TIME_MS: &str = "flags_token_extract_ms";// because permit wait is a property of pod-level load, not of any one team.pub const FLAG_CONCURRENCY_LIMIT_WAIT_TIME_MS: &str = "flags_concurrency_limit_wait_ms";+// Wall-clock time spent buffering the inbound POST body. Captured by a+// middleware shim placed between `record_concurrency_wait` and the handler+// so the duration excludes permit wait but includes any slow-client+// upload or large-compressed-payload buffering. No `team_id` label+// because this measurement happens before the request is authenticated.+pub const FLAG_BODY_READ_TIME_MS: &str = "flags_body_read_ms";++// Counter for body-buffering failures inside `record_body_read`+// (network error, peer disconnect, malformed framing). Pod-level: no+// `team_id` label, because this happens before authentication.+pub const FLAG_BODY_READ_FAILED_COUNTER: &str = "flags_body_read_failed_total";++// Counter for inbound bodies rejected because they exceeded+// `MAX_FLAGS_BODY_BYTES`. Split from the transport-failure counter so a+// dashboard can distinguish suspected upload abuse from genuine network+// errors. Pod-level: no `team_id` label.+pub const FLAG_BODY_READ_TOO_LARGE_COUNTER: &str = "flags_body_read_too_large_total";++// Per-phase wall-clock duration inside `process_request_inner`. Phases+// match handler-level state transitions:+// `auth → billing_check → cookieless → fetch_and_filter → evaluate →+// record_billing → config_response`. Together they reconstruct the+// majority of the post-pre-handler request budget so a spike in any one+// phase is attributable to the responsible await site.+//+// Labels: `phase` (one of the canonical phase names, see+// `handler::phases::Phase::name`), `team_id` (filtered through the+// existing team allowlist).+pub const FLAG_PHASE_DURATION_MS: &str = "flags_phase_duration_ms";++// Per-phase in-flight gauge. Incremented when a `PhaseGuard` enters a+// phase and decremented on drop. When `flags_tokio_alive_tasks` jumps,+// exactly one phase gauge climbs in lockstep — direct localization of+// the parking site without waiting for the histogram to rebucket.+//+// Pod-level by design: only a `phase` label, no `team_id`.+pub const FLAG_INFLIGHT_BY_PHASE: &str = "flags_inflight_by_phase";++// In-memory `FlagDefinitionsCache::get_or_load` total wall-clock time.+// Labels: `outcome` ∈ {`hit`, `miss_load_ok`, `miss_load_err`,+// `etag_missing`, `sentinel`, `fallback`}. A spike in `miss_load_*`+// means the loader (HyperCache fetch + Pickle/JSON decode + regex+// compile) is stalling; a spike in `hit` would indicate Moka itself is+// slow (very unlikely). Concurrent first-misses are not coalesced, so+// thunder-herd events on etag rollover show up as `miss_load_ok` p99+// climbing while the hit rate stays normal. `fallback` is split out+// from `miss_load_ok` so a PG-fallback storm is visible on its own.+pub const FLAG_DEFINITIONS_INMEM_LOAD_MS: &str = "flags_definitions_inmem_load_ms";+// Performance monitoringpub const DB_CONNECTION_POOL_ACTIVE_COUNTER: &str = "flags_db_connection_pool_active_total";pub const DB_CONNECTION_POOL_IDLE_COUNTER: &str = "flags_db_connection_pool_idle_total";diff --git a/rust/feature-flags/src/router.rs b/rust/feature-flags/src/router.rsindex 3bc4a49f3f82..0329f57bbd2c 100644--- a/rust/feature-flags/src/router.rs+++ b/rust/feature-flags/src/router.rs@@ -9,6 +9,7 @@ use crate::billing::{BillingAggregator, FeatureFlagsLimiter, SessionReplayLimiteuse crate::database_pools::DatabasePools;use axum::{error_handling::HandleErrorLayer,+ extract::DefaultBodyLimit,http::{Method, StatusCode},routing::{any, get},Router,@@ -33,6 +34,7 @@ use tower_http::{use crate::{api::{+ body_read_metrics::{record_body_read, MAX_FLAGS_BODY_BYTES},concurrency_metrics::{record_concurrency_enter, record_concurrency_wait},endpoint, flag_definitions,flag_definitions_rate_limiter::FlagDefinitionsRateLimiter,@@ -255,41 +257,33 @@ pub fn router(get(move || startup(db_pools_for_startup.clone())),);- // flags endpoint- // IP rate limiting is now handled in the endpoint handler for better control and log-only mode support+ // Layer ordering (outermost to innermost, last `.layer()` is outermost):+ // HandleErrorLayer → TimeoutLayer → record_concurrency_enter →+ // ConcurrencyLimitLayer → record_concurrency_wait → (per-sub-router).//- // Layer ordering (outermost to innermost, last .layer() call on Router is outermost):- // 1. HandleErrorLayer (outermost): converts timeout errors into 503 responses.- // 2. TimeoutLayer: cancels the entire request after request_timeout_ms,- // ensuring zombie tasks don't hold connections after Envoy kills the downstream.- // 3. record_concurrency_enter: stamps the request with `Instant::now()`- // just before permit acquisition. Inside `TimeoutLayer` so timeouts- // still fire while the request is parked at the limiter.- // 4. ConcurrencyLimitLayer: bounds in-flight requests.- // 5. record_concurrency_wait (innermost): computes elapsed permit-wait- // immediately after the layer hands off a permit, before the handler.- //- // Note: this entire chain wraps both `/flags|/decide` AND- // `/flags/definitions|/api/feature_flag/local_evaluation`. The shim pair- // is harmless on definitions (the handler never extracts the wait- // extension), but does add ~one extension-insert + one extension-read- // per definitions request. If that overhead ever becomes load-bearing,- // scope the shims to `/flags|/decide` via a dedicated sub-router.- let mut flags_router = Router::new();-+ // The body-read shim and `DefaultBodyLimit` are per-sub-router and only+ // attached to `/flags|/decide`. `/flags/definitions` is GET-only and+ // 405s non-GET before any body is read. `DefaultBodyLimit::max` is the+ // marker the handler's `Bytes` extractor reads; the shim's `to_bytes`+ // cap (see `MAX_FLAGS_BODY_BYTES`) handles the same boundary while the+ // body is being buffered. Both are required.+ let mut flags_endpoints: Router<State> = Router::new();if matches!(config.service_mode, ServiceMode::All | ServiceMode::Flags) {- flags_router = flags_router+ flags_endpoints = flags_endpoints.route("/flags", any(endpoint::flags)).route("/flags/", any(endpoint::flags)).route("/decide", any(endpoint::flags))- .route("/decide/", any(endpoint::flags));+ .route("/decide/", any(endpoint::flags))+ .layer(axum::middleware::from_fn(record_body_read))+ .layer(DefaultBodyLimit::max(MAX_FLAGS_BODY_BYTES));}+ let mut definitions_endpoints: Router<State> = Router::new();if matches!(config.service_mode,ServiceMode::All | ServiceMode::Definitions) {- flags_router = flags_router+ definitions_endpoints = definitions_endpoints.route("/flags/definitions",any(flag_definitions::flags_definitions),@@ -310,15 +304,14 @@ pub fn router();}- let flags_router = flags_router- // Innermost: runs *after* `ConcurrencyLimitLayer` releases a- // permit, so it can compute the elapsed permit-wait before the- // handler runs.+ let flags_router = flags_endpoints+ .merge(definitions_endpoints)+ // After `ConcurrencyLimitLayer` releases a permit, so this measures+ // permit wait excluding body buffering..layer(axum::middleware::from_fn(record_concurrency_wait)).layer(ConcurrencyLimitLayer::new(config.max_concurrency))- // Sandwiched between `TimeoutLayer` and `ConcurrencyLimitLayer`:- // captures `Instant::now()` *after* timeout deadline propagation- // but *before* permit acquisition.+ // Stamps `Instant::now()` after timeout-deadline propagation but+ // before permit acquisition..layer(axum::middleware::from_fn(record_concurrency_enter)).layer(ServiceBuilder::new()