: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): add gRPC request metrics, and stop one team failing a batch (#92452)
Ben White8692927c771c
diff --git a/nodejs/package.json b/nodejs/package.jsonindex ec41038fd693..b7ff31f8c08e 100644--- a/nodejs/package.json+++ b/nodejs/package.json@@ -49,6 +49,7 @@"build:replay-anonymizer:dev": "pnpm --filter=@posthog/replay-anonymizer run build:dev","generate:personhog-proto": "cd ../proto && buf generate --template ../nodejs/buf.gen.yaml --path personhog/service --path personhog/identity --path personhog/lifecycle --path personhog/types . && cd ../nodejs && eslint --fix src/common/generated/personhog && prettier --write src/common/generated/personhog","generate:ingestion-worker-proto": "cd ../proto && buf generate --template ../nodejs/buf.gen.ingestion-worker.yaml --path ingestion/worker . && cd ../nodejs && eslint --fix src/common/generated/ingestion-worker && prettier --write src/common/generated/ingestion-worker",+ "generate:usage-ingestion-proto": "cd ../proto && buf generate --template ../nodejs/buf.gen.usage-ingestion.yaml --path usage_ingestion . && cd ../nodejs && eslint --fix src/common/generated/usage-ingestion && prettier --write src/common/generated/usage-ingestion","update-ai-costs": "ts-node src/ingestion/pipelines/ai/costs/scripts/update-ai-costs.ts","gen:ingestion-warning-types": "ts-node src/ingestion/common/scripts/generate-ingestion-warning-types.ts","sync-segment-icons": "DATABASE_URL=something ts-node src/cdp/segment/sync-segment-icons.ts",diff --git a/nodejs/src/common/generated/usage-ingestion/usage_ingestion/v1/service_pb.ts b/nodejs/src/common/generated/usage-ingestion/usage_ingestion/v1/service_pb.tsindex 0ceac46548e4..f4d0f3663b88 100644--- a/nodejs/src/common/generated/usage-ingestion/usage_ingestion/v1/service_pb.ts+++ b/nodejs/src/common/generated/usage-ingestion/usage_ingestion/v1/service_pb.ts@@ -96,10 +96,13 @@ export const IngestBillingUsageRequestSchema: GenMessage<IngestBillingUsageReque*/export type IngestBillingUsageResponse = Message<'usage_ingestion.v1.IngestBillingUsageResponse'> & {/**- * The service validates a whole batch before producing, so validation failures accept no- * records. The RPC waits for Kafka delivery confirmation, so callers must use it off their- * request-critical path. A retry after an unavailable response is safe because record_id is- * the deduplication identity, including when Kafka delivered only part of the batch.+ * A subset of the records sent: the service skips a record it can never accept, such as one+ * whose team has no organization, so that one team cannot discard the whole batch. Compare+ * this against what you sent to learn what was dropped, because a dropped record is reported+ * here rather than as an error. The RPC waits for Kafka delivery confirmation, so callers must+ * use it off their request-critical path. A retry after an unavailable response is safe+ * because record_id is the deduplication identity, including when Kafka delivered only part+ * of the batch.** @generated from field: repeated string accepted_record_ids = 1;*/diff --git a/nodejs/src/common/usage-ingestion/client.test.ts b/nodejs/src/common/usage-ingestion/client.test.tsnew file mode 100644index 000000000000..310b77c0c8b1--- /dev/null+++ b/nodejs/src/common/usage-ingestion/client.test.ts@@ -0,0 +1,97 @@+import { Code, ConnectError } from '@connectrpc/connect'+import { register } from 'prom-client'++import { UsageIngestionClient, UsageRecordInput } from './client'++describe('UsageIngestionClient', () => {+ let client: UsageIngestionClient+ let acceptedRecordIds: string[]+ let calls: number+ let headers: (Record<string, string> | undefined)[]++ const record = (teamId: number): UsageRecordInput => ({+ recordId: `record-${teamId}`,+ teamId,+ usageKey: 'feature_flag_requests',+ unit: 'requests',+ quantity: 1,+ timestampMs: 1_700_000_000_000,+ })++ const counted = async (name: string): Promise<{ labels: Record<string, unknown>; value: number }[]> => {+ const metric = register.getSingleMetric(name) as any+ const data = await metric.get()+ return data.values+ }++ beforeEach(() => {+ register.resetMetrics()+ calls = 0+ acceptedRecordIds = []+ headers = []+ client = new UsageIngestionClient({ addr: 'localhost:1', producerId: 'cdp' })+ // The transport is built in the constructor, so the stub replaces it rather than+ // standing up a server. Everything under test sits above the RPC.+ ;(client as any).client = {+ ingestBillingUsage: (_request: unknown, options?: { headers?: Record<string, string> }) => {+ calls += 1+ headers.push(options?.headers)+ return Promise.resolve({ acceptedRecordIds })+ },+ }+ })++ // The service drops a record it cannot attribute and still answers Ok, so the accepted+ // list is the only thing that says what landed. Counting the chunk instead bills nobody+ // for those records while the sent counter claims otherwise.+ test.each([+ { name: 'a partly rejected batch', teams: [7, 8, 9], accepted: [7, 9], sent: 2, rejected: 1 },+ { name: 'a fully rejected batch', teams: [7, 8], accepted: [], sent: 0, rejected: 2 },+ { name: 'a fully accepted batch', teams: [7, 8], accepted: [7, 8], sent: 2, rejected: 0 },+ ])('counts what the service accepted for $name', async ({ teams, accepted, sent, rejected }) => {+ acceptedRecordIds = accepted.map((teamId) => `record-${teamId}`)++ await client.ingest(teams.map(record))++ expect(await counted('usage_ingestion_records_sent_total')).toEqual(+ sent === 0 ? [] : [expect.objectContaining({ value: sent })]+ )+ expect(await counted('usage_ingestion_records_failed_total')).toEqual(+ rejected === 0+ ? []+ : [+ expect.objectContaining({+ labels: expect.objectContaining({ error_code: 'rejected' }),+ value: rejected,+ }),+ ]+ )+ // The service already decided; re-sending would drop the same record again.+ expect(calls).toBe(1)+ })++ it('names the producer to the service on every request', async () => {+ // Without the header the service's request metrics read client=unknown for everyone.+ acceptedRecordIds = ['record-7']++ await client.ingest([record(7)])++ expect(headers).toEqual([{ 'x-client-name': 'cdp' }])+ })++ it('counts the whole chunk as failed when the call itself fails', async () => {+ ;(client as any).client = {+ ingestBillingUsage: () => {+ calls += 1+ return Promise.reject(new ConnectError('nope', Code.NotFound))+ },+ }++ await client.ingest([record(7), record(8)])++ expect(calls).toBe(1)+ expect(await counted('usage_ingestion_records_failed_total')).toEqual([+ expect.objectContaining({ labels: expect.objectContaining({ error_code: 'NotFound' }), value: 2 }),+ ])+ })+})diff --git a/nodejs/src/common/usage-ingestion/client.ts b/nodejs/src/common/usage-ingestion/client.tsindex 46708e4b1c3d..da21508d42fa 100644--- a/nodejs/src/common/usage-ingestion/client.ts+++ b/nodejs/src/common/usage-ingestion/client.ts@@ -24,6 +24,22 @@ const usageRecordsFailedCounter = new Counter({const RETRYABLE_CODES = new Set([Code.Unavailable, Code.DeadlineExceeded, Code.ResourceExhausted, Code.Aborted])+/**+ * The record IDs the service left out of its accepted list. The service skips a record it can+ * never accept, such as one whose team has no organization, so a successful call can still+ * drop records.+ */+export function rejectedRecords(chunk: UsageRecordInput[], acceptedRecordIds: string[]): Set<string> {+ const accepted = new Set(acceptedRecordIds)+ return new Set(chunk.filter((record) => !accepted.has(record.recordId)).map((record) => record.recordId))+}++/** The teams behind the rejected records, deduplicated so a repeated team reads as one lead. */+export function rejectedTeams(chunk: UsageRecordInput[], rejected: Set<string>): number[] {+ const teams = new Set(chunk.filter((record) => rejected.has(record.recordId)).map((record) => record.teamId))+ return [...teams].sort((a, b) => a - b)+}+export interface UsageRecordInput {/** Unique per (teamId, producerId, usageKey). Reused verbatim on retry, which is what makes ingest idempotent. */recordId: string@@ -87,10 +103,36 @@ export class UsageIngestionClient {})try {- await this.client.ingestBillingUsage(request)+ // The header names this producer in the service's own request metrics, which+ // otherwise aggregate every caller into one series.+ const response = await this.client.ingestBillingUsage(request, {+ headers: { 'x-client-name': this.producerId },+ })+ const rejected = rejectedRecords(chunk, response.acceptedRecordIds)for (const record of chunk) {+ if (rejected.has(record.recordId)) {+ continue+ }usageRecordsSentCounter.inc({ producer_id: this.producerId, usage_key: record.usageKey })}+ // The service drops records it cannot attribute rather than failing the batch, so a+ // success can still leave some behind. Retrying them would fail the same way.+ if (rejected.size > 0) {+ for (const record of chunk) {+ if (rejected.has(record.recordId)) {+ usageRecordsFailedCounter.inc({+ producer_id: this.producerId,+ usage_key: record.usageKey,+ error_code: 'rejected',+ })+ }+ }+ logger.warn('⚠️', 'usage-ingestion rejected usage records', {+ producerId: this.producerId,+ records: rejected.size,+ teams: rejectedTeams(chunk, rejected),+ })+ }} catch (error) {const code = error instanceof ConnectError ? error.code : Code.Unknownif (attempt === 0 && RETRYABLE_CODES.has(code)) {diff --git a/proto/usage_ingestion/v1/service.proto b/proto/usage_ingestion/v1/service.protoindex 5c1d4b6287e0..0fda20cecbf9 100644--- a/proto/usage_ingestion/v1/service.proto+++ b/proto/usage_ingestion/v1/service.proto@@ -39,9 +39,12 @@ message IngestBillingUsageRequest {}message IngestBillingUsageResponse {- // The service validates a whole batch before producing, so validation failures accept no- // records. The RPC waits for Kafka delivery confirmation, so callers must use it off their- // request-critical path. A retry after an unavailable response is safe because record_id is- // the deduplication identity, including when Kafka delivered only part of the batch.+ // A subset of the records sent: the service skips a record it can never accept, such as one+ // whose team has no organization, so that one team cannot discard the whole batch. Compare+ // this against what you sent to learn what was dropped, because a dropped record is reported+ // here rather than as an error. The RPC waits for Kafka delivery confirmation, so callers must+ // use it off their request-critical path. A retry after an unavailable response is safe+ // because record_id is the deduplication identity, including when Kafka delivered only part+ // of the batch.repeated string accepted_record_ids = 1;}diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 027e70019fa4..32a9efa72695 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2844,6 +2844,19 @@ dependencies = ["tracing",]+[[package]]+name = "common-grpc"+version = "0.1.0"+dependencies = [+ "http 1.4.0",+ "metrics",+ "metrics-util",+ "pin-project",+ "tokio",+ "tonic 0.12.3",+ "tower 0.4.13",+]+[[package]]name = "common-hypercache"version = "0.1.0"@@ -13864,6 +13877,7 @@ dependencies = ["axum 0.7.9","chrono","common-database",+ "common-grpc","common-kafka","common-liveness","envconfig",diff --git a/rust/Cargo.toml b/rust/Cargo.tomlindex e854bd7b0484..eb8e63859593 100644--- a/rust/Cargo.toml+++ b/rust/Cargo.toml@@ -19,6 +19,7 @@ members = ["common/cookieless","common/database","common/dns",+ "common/grpc","common/health","common/kafka","common/kafka-consumer",diff --git a/rust/common/grpc/Cargo.toml b/rust/common/grpc/Cargo.tomlnew file mode 100644index 000000000000..ebe9358ddf16--- /dev/null+++ b/rust/common/grpc/Cargo.toml@@ -0,0 +1,20 @@+[package]+name = "common-grpc"+version = "0.1.0"+edition = "2021"+publish = false++[dependencies]+http = { workspace = true }+metrics = { workspace = true }+pin-project = "1.1"+tonic = { workspace = true }+tower = { workspace = true }++[dev-dependencies]+metrics-util = { workspace = true }+tokio = { workspace = true, features = ["macros", "rt"] }+tower = { workspace = true, features = ["util"] }++[lints]+workspace = truediff --git a/rust/common/grpc/src/lib.rs b/rust/common/grpc/src/lib.rsnew file mode 100644index 000000000000..0d5033f7f1ff--- /dev/null+++ b/rust/common/grpc/src/lib.rs@@ -0,0 +1,402 @@+//! Serving middleware for PostHog gRPC servers.+//!+//! `personhog-common` carries its own copy of this layer alongside personhog's routing+//! contract. This crate holds the part that is not about personhog, so a service can take+//! request metrics without taking `personhog-proto`, sqlx, and the persons modules with it.++use std::future::Future;+use std::pin::Pin;+use std::sync::Arc;+use std::task::{Context, Poll};+use std::time::Instant;++use http::{Request, Response};+use metrics::{counter, gauge, histogram};+use pin_project::{pin_project, pinned_drop};+use tower::{Layer, Service};++/// Header a caller sets to name itself. Requests without it are labelled `unknown`.+const CLIENT_NAME_HEADER: &str = "x-client-name";++/// Label for a failure carrying no gRPC status at all. Part of the same vocabulary as+/// [`code_as_str`], and deliberately distinct from its `unknown`, which is a real code a+/// server can return.+pub const NON_STATUS: &str = "non_status";++/// Stable snake_case name for a gRPC status code, for use as a metric label. Codes are a+/// fixed vocabulary, which is what makes them safe to label with; status *messages* never+/// are.+pub fn code_as_str(code: tonic::Code) -> &'static str {+ use tonic::Code;+ match code {+ Code::Ok => "ok",+ Code::Cancelled => "cancelled",+ Code::Unknown => "unknown",+ Code::InvalidArgument => "invalid_argument",+ Code::DeadlineExceeded => "deadline_exceeded",+ Code::NotFound => "not_found",+ Code::AlreadyExists => "already_exists",+ Code::PermissionDenied => "permission_denied",+ Code::ResourceExhausted => "resource_exhausted",+ Code::FailedPrecondition => "failed_precondition",+ Code::Aborted => "aborted",+ Code::OutOfRange => "out_of_range",+ Code::Unimplemented => "unimplemented",+ Code::Internal => "internal",+ Code::Unavailable => "unavailable",+ Code::DataLoss => "data_loss",+ Code::Unauthenticated => "unauthenticated",+ }+}++const MAX_HEADER_TAG_LEN: usize = 128;++fn is_safe_tag_char(c: char) -> bool {+ c.is_ascii_alphanumeric() || matches!(c, '/' | '_' | '-' | ':' | '.')+}++/// A caller-controlled value becomes a metric label, so an unbounded or hostile one becomes+/// unbounded cardinality. Anything outside the safe set collapses to `unknown`.+fn sanitize_header_tag(raw: &str) -> &str {+ let value = if raw.len() > MAX_HEADER_TAG_LEN {+ &raw[..MAX_HEADER_TAG_LEN]+ } else {+ raw+ };+ if value.chars().all(is_safe_tag_char) {+ value+ } else {+ "unknown"+ }+}++fn extract_client_name<B>(request: &Request<B>) -> Arc<str> {+ request+ .headers()+ .get(CLIENT_NAME_HEADER)+ .and_then(|value| value.to_str().ok())+ .filter(|value| !value.is_empty())+ .map(sanitize_header_tag)+ .unwrap_or("unknown")+ .into()+}++/// Extract the method name from a gRPC URI path, which looks like+/// `/package.Service/MethodName`.+///+/// `Server::layer` wraps tonic's router, so this runs before routing and sees the path of a+/// request no method will serve. The value is therefore caller-controlled and goes through+/// the same sanitizer as a header, or one client calling a wrong path mints a series per+/// path it tries.+fn extract_grpc_method(path: &str) -> &str {+ let method = path+ .rsplit_once('/')+ .map(|(_, method)| method)+ .filter(|method| !method.is_empty())+ .unwrap_or("unknown");+ sanitize_header_tag(method)+}++/// The `code` label for a response, in the [`code_as_str`] vocabulary.+///+/// A failed gRPC call is a trailers-only response: an empty body with `grpc-status` in the+/// headers. tonic gives a handler error that shape, so the layer reads the status at the+/// head and never polls the body. An absent header therefore means the handler returned Ok,+/// whose `grpc-status: 0` rides the body trailers instead.+///+/// This holds while every method is unary. A server-streaming method that failed part way+/// through its stream would read as `ok` here, and would need the trailers read from the+/// response body.+fn response_code(headers: &http::HeaderMap) -> &'static str {+ let Some(raw) = headers.get("grpc-status") else {+ return "ok";+ };+ raw.to_str()+ .ok()+ .and_then(|value| value.parse::<i32>().ok())+ .map_or(NON_STATUS, |code| code_as_str(tonic::Code::from_i32(code)))+}++/// Tower layer that instruments gRPC requests with timing and concurrency metrics.+///+/// Records:+/// - `grpc_server_requests_total` — counter with method, client and code labels+/// - `grpc_server_request_duration_ms` — histogram with method and client labels+/// - `grpc_server_requests_in_flight` — gauge with method and client labels+#[derive(Clone, Default)]+pub struct GrpcMetricsLayer;++impl<S> Layer<S> for GrpcMetricsLayer {+ type Service = GrpcMetricsService<S>;++ fn layer(&self, service: S) -> Self::Service {+ GrpcMetricsService { inner: service }+ }+}++#[derive(Clone)]+pub struct GrpcMetricsService<S> {+ inner: S,+}++impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for GrpcMetricsService<S>+where+ S: Service<Request<ReqBody>, Response = Response<ResBody>>,+{+ type Response = S::Response;+ type Error = S::Error;+ type Future = GrpcMetricsFuture<S::Future>;++ fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {+ self.inner.poll_ready(cx)+ }++ fn call(&mut self, request: Request<ReqBody>) -> Self::Future {+ let method: Arc<str> = Arc::from(extract_grpc_method(request.uri().path()));+ let client = extract_client_name(&request);+ gauge!("grpc_server_requests_in_flight", "method" => method.clone(), "client" => client.clone())+ .increment(1.0);++ GrpcMetricsFuture {+ inner: self.inner.call(request),+ method,+ client,+ start: Instant::now(),+ }+ }+}++/// Future returned by [`GrpcMetricsService`]. Lives inline in the caller's async state+/// machine, so instrumenting a request costs no heap allocation.+#[pin_project(PinnedDrop)]+pub struct GrpcMetricsFuture<F> {+ #[pin]+ inner: F,+ method: Arc<str>,+ client: Arc<str>,+ start: Instant,+}++impl<F, ResBody, E> Future for GrpcMetricsFuture<F>+where+ F: Future<Output = Result<Response<ResBody>, E>>,+{+ type Output = F::Output;++ fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {+ let this = self.project();+ let Poll::Ready(result) = this.inner.poll(cx) else {+ return Poll::Pending;+ };++ // A transport-level error never reached the handler, so it carries no gRPC status.+ let code = match result {+ Ok(ref response) => response_code(response.headers()),+ Err(_) => NON_STATUS,+ };+ counter!("grpc_server_requests_total",+ "method" => this.method.clone(),+ "client" => this.client.clone(),+ "code" => code)+ .increment(1);+ histogram!("grpc_server_request_duration_ms",+ "method" => this.method.clone(),+ "client" => this.client.clone())+ .record(this.start.elapsed().as_secs_f64() * 1000.0);++ Poll::Ready(result)+ }+}++/// Decrements the in-flight gauge on both normal completion and cancellation.+#[pinned_drop]+impl<F> PinnedDrop for GrpcMetricsFuture<F> {+ fn drop(self: Pin<&mut Self>) {+ let this = self.project();+ gauge!("grpc_server_requests_in_flight",+ "method" => this.method.clone(),+ "client" => this.client.clone())+ .decrement(1.0);+ }+}++#[cfg(test)]+mod tests {+ use std::convert::Infallible;++ use tower::ServiceExt;++ use super::*;++ /// Serves whatever response it is built with, so a test can drive the layer with the+ /// exact shape tonic produces.+ #[derive(Clone)]+ struct FixedService(http::StatusCode, Option<&'static str>);++ impl Service<Request<()>> for FixedService {+ type Response = Response<()>;+ type Error = Infallible;+ type Future = std::future::Ready<Result<Response<()>, Infallible>>;++ fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {+ Poll::Ready(Ok(()))+ }++ fn call(&mut self, _request: Request<()>) -> Self::Future {+ let mut builder = Response::builder().status(self.0);+ if let Some(status) = self.1 {+ builder = builder.header("grpc-status", status);+ }+ std::future::ready(Ok(builder.body(()).unwrap()))+ }+ }++ fn grpc_request(path: &str) -> Request<()> {+ Request::builder().uri(path).body(()).unwrap()+ }++ #[tokio::test]+ async fn the_layer_passes_the_response_through_untouched() {+ let service = GrpcMetricsLayer.layer(FixedService(http::StatusCode::OK, None));++ let response = service+ .oneshot(grpc_request("/pkg.Svc/Method"))+ .await+ .unwrap();++ assert_eq!(response.status(), 200);+ assert!(response.headers().get("grpc-status").is_none());+ }++ /// Serves the response tonic builds for a failed handler, which is the shape the layer+ /// has to read the status out of.+ #[derive(Clone)]+ struct StatusService(tonic::Code);++ impl Service<Request<()>> for StatusService {+ type Response = Response<tonic::body::BoxBody>;+ type Error = Infallible;+ type Future = std::future::Ready<Result<Self::Response, Infallible>>;++ fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {+ Poll::Ready(Ok(()))+ }++ fn call(&mut self, _request: Request<()>) -> Self::Future {+ std::future::ready(Ok(tonic::Status::new(self.0, "test").into_http()))+ }+ }++ #[test]+ fn the_counter_carries_the_method_client_and_code_of_a_real_response() {+ let recorder = metrics_util::debugging::DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let runtime = tokio::runtime::Builder::new_current_thread()+ .build()+ .unwrap();++ metrics::with_local_recorder(&recorder, || {+ let service = GrpcMetricsLayer.layer(StatusService(tonic::Code::NotFound));+ let request = Request::builder()+ .uri("/usage_ingestion.v1.UsageIngestion/IngestBillingUsage")+ .header("x-client-name", "feature-flags")+ .body(())+ .unwrap();+ runtime.block_on(service.oneshot(request)).unwrap();+ });++ let labels = snapshotter+ .snapshot()+ .into_vec()+ .into_iter()+ .find(|(key, _, _, _)| key.key().name() == "grpc_server_requests_total")+ .map(|(key, _, _, _)| {+ let mut labels = key+ .key()+ .labels()+ .map(|l| format!("{}={}", l.key(), l.value()))+ .collect::<Vec<_>>();+ labels.sort();+ labels+ })+ .expect("the layer must count the request");++ assert_eq!(+ labels,+ vec![+ "client=feature-flags",+ "code=not_found",+ "method=IngestBillingUsage"+ ]+ );+ }++ #[test]+ fn a_handler_error_reads_as_its_own_code() {+ // Pinned against tonic rather than a hand-built response: the whole design rests on+ // tonic putting the status in the headers of a trailers-only response.+ let response = tonic::Status::not_found("nope").into_http();++ assert_eq!(response_code(response.headers()), "not_found");+ }++ #[test]+ fn response_code_vocabulary() {+ let code_for = |header: Option<&str>| {+ let mut headers = http::HeaderMap::new();+ if let Some(value) = header {+ headers.insert("grpc-status", value.parse().unwrap());+ }+ response_code(&headers)+ };++ // Absent means the handler returned Ok and grpc-status rides the body trailers.+ assert_eq!(code_for(None), "ok");+ assert_eq!(code_for(Some("0")), "ok");+ assert_eq!(code_for(Some("14")), "unavailable");+ // An out-of-range code is still a code; only an unparseable one is non_status.+ assert_eq!(code_for(Some("99")), "unknown");+ assert_eq!(code_for(Some("not-a-number")), NON_STATUS);+ }++ #[test]+ fn extract_method_from_grpc_path() {+ assert_eq!(+ extract_grpc_method("/package.Service/IngestBillingUsage"),+ "IngestBillingUsage"+ );+ assert_eq!(extract_grpc_method("/"), "unknown");+ assert_eq!(extract_grpc_method(""), "unknown");+ }++ #[test]+ fn a_method_that_would_blow_up_cardinality_becomes_unknown() {+ // This layer sits above tonic's router, so it labels paths no method will serve.+ assert_eq!(extract_grpc_method("/pkg.Svc/not a method"), "unknown");+ assert_eq!(+ extract_grpc_method(&format!("/pkg.Svc/{}", "a".repeat(8192))).len(),+ MAX_HEADER_TAG_LEN+ );+ }++ #[test]+ fn a_client_name_that_would_blow_up_cardinality_becomes_unknown() {+ let named = |value: &str| {+ let request = Request::builder()+ .uri("/pkg.Svc/Method")+ .header("x-client-name", value)+ .body(())+ .unwrap();+ extract_client_name(&request)+ };++ assert_eq!(&*named("feature-flags"), "feature-flags");+ assert_eq!(&*named(""), "unknown");+ assert_eq!(&*named("bad name!"), "unknown");+ assert_eq!(named(&"b".repeat(200)).len(), MAX_HEADER_TAG_LEN);+ assert_eq!(+ &*extract_client_name(&grpc_request("/pkg.Svc/Method")),+ "unknown"+ );+ }+}diff --git a/rust/feature-flags/src/billing/usage_reporter.rs b/rust/feature-flags/src/billing/usage_reporter.rsindex 5658dd7876c4..fe707d2a4304 100644--- a/rust/feature-flags/src/billing/usage_reporter.rs+++ b/rust/feature-flags/src/billing/usage_reporter.rs@@ -6,6 +6,7 @@//! 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::collections::HashSet;use std::sync::Arc;use std::sync::Mutex;@@ -151,14 +152,30 @@ async fn run_sender(/// 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 {+ let message = 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);+ match client.ingest_billing_usage(tagged(message.clone())).await {+ Ok(response) => {+ let accepted = response.into_inner().accepted_record_ids;+ inc(FLAGS_USAGE_RECORDS_SENT, &[], accepted.len() as u64);+ // The service drops records it cannot attribute rather than failing the+ // batch, so a success can still leave some behind. Retrying them would fail+ // the same way, and the teams are the only lead worth logging.+ if accepted.len() < chunk.len() {+ inc(+ FLAGS_USAGE_RECORDS_FAILED,+ &[],+ count - accepted.len() as u64,+ );+ tracing::warn!(+ records = count - accepted.len() as u64,+ teams = ?rejected_teams(chunk, &accepted),+ "usage-ingestion rejected feature flag usage records"+ );+ }return;}Err(status) => {@@ -169,6 +186,7 @@ async fn send_chunk(client: &UsageIngestionClient<Channel>, chunk: &[BillingUsagrecords = count,attempts = attempt,code = %status.code(),+ teams = ?distinct_teams(chunk),"failed to report feature flag usage records");return;@@ -179,6 +197,40 @@ async fn send_chunk(client: &UsageIngestionClient<Channel>, chunk: &[BillingUsag}}+/// Names this producer in the service's own request metrics, which otherwise aggregate every+/// caller into one series.+fn tagged(message: IngestBillingUsageRequest) -> tonic::Request<IngestBillingUsageRequest> {+ let mut request = tonic::Request::new(message);+ request.metadata_mut().insert(+ "x-client-name",+ tonic::metadata::MetadataValue::from_static(PRODUCER_ID),+ );+ request+}++/// The teams behind the records the service did not accept, deduplicated so a chunk that+/// repeats a team reads as one lead rather than many.+fn rejected_teams(chunk: &[BillingUsageRecord], accepted: &[String]) -> Vec<i64> {+ let accepted: HashSet<&str> = accepted.iter().map(String::as_str).collect();+ dedup(+ chunk+ .iter()+ .filter(|record| !accepted.contains(record.record_id.as_str()))+ .map(|record| record.team_id),+ )+}++fn distinct_teams(chunk: &[BillingUsageRecord]) -> Vec<i64> {+ dedup(chunk.iter().map(|record| record.team_id))+}++fn dedup(teams: impl Iterator<Item = i64>) -> Vec<i64> {+ let mut teams = teams.collect::<Vec<_>>();+ teams.sort_unstable();+ teams.dedup();+ teams+}+/// The two billable request types are priced apart — the nightly report weighs one local/// evaluation as ten decide requests — so they cannot share a key. The weighting itself stays/// out of here: a producer reports what happened, and pricing is applied downstream.@@ -344,6 +396,18 @@ mod tests {assert_eq!(requests[0][0].usage_key, usage_key(FlagRequestType::Decide));}+ #[tokio::test]+ async fn every_request_names_this_producer_to_the_service() {+ // Without the header the service's request metrics read client=unknown for everyone.+ let service = RecordingIngestion::default();+ 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.client_names(), vec![Some(PRODUCER_ID.to_string())]);+ }+#[tokio::test]async fn retries_a_transient_failure_with_the_same_record_id() {let service = RecordingIngestion::default();@@ -360,6 +424,75 @@ mod tests {assert_eq!(requests[0][0].record_id, requests[1][0].record_id);}+ /// Counter totals by name, captured while the reporter ran. The recorder is+ /// thread-scoped, so the sender task has to be driven on this thread.+ fn counted(run: impl FnOnce(&tokio::runtime::Runtime)) -> Vec<(String, u64)> {+ let recorder = metrics_util::debugging::DebuggingRecorder::new();+ let snapshotter = recorder.snapshotter();+ let runtime = tokio::runtime::Builder::new_current_thread()+ .enable_all()+ .build()+ .unwrap();++ metrics::with_local_recorder(&recorder, || run(&runtime));++ let mut totals = snapshotter+ .snapshot()+ .into_vec()+ .into_iter()+ .filter_map(|(key, _, _, value)| match value {+ metrics_util::debugging::DebugValue::Counter(count) => {+ Some((key.key().name().to_string(), count))+ }+ _ => None,+ })+ .collect::<Vec<_>>();+ totals.sort();+ totals+ }++ #[test]+ fn a_partially_accepted_batch_counts_only_what_the_service_took() {+ let totals = counted(|runtime| {+ runtime.block_on(async {+ let service = RecordingIngestion::default();+ service.reject_team(8);+ let reporter = reporter_for(serve(service.clone()).await).await;++ reporter.report(+ &[(key(7, None), 1), (key(8, None), 1), (key(9, None), 1)],+ 1_700_000_000_000,+ );+ reporter.shutdown(std::time::Duration::from_secs(5)).await;++ // The service already decided; re-sending would drop the same record again.+ assert_eq!(service.requests().len(), 1);+ });+ });++ assert_eq!(+ totals,+ vec![+ (FLAGS_USAGE_RECORDS_FAILED.to_string(), 1),+ (FLAGS_USAGE_RECORDS_SENT.to_string(), 2),+ ]+ );+ }++ #[test]+ fn a_fully_accepted_batch_counts_nothing_as_failed() {+ let totals = counted(|runtime| {+ runtime.block_on(async {+ let reporter = reporter_for(serve(RecordingIngestion::default()).await).await;++ reporter.report(&[(key(7, None), 1), (key(8, None), 1)], 1_700_000_000_000);+ reporter.shutdown(std::time::Duration::from_secs(5)).await;+ });+ });++ assert_eq!(totals, vec![(FLAGS_USAGE_RECORDS_SENT.to_string(), 2)]);+ }+#[tokio::test]async fn does_not_retry_a_rejected_batch() {let service = RecordingIngestion::default();diff --git a/rust/feature-flags/src/billing/usage_test_support.rs b/rust/feature-flags/src/billing/usage_test_support.rsindex 91327ed47348..e188d8eed24c 100644--- a/rust/feature-flags/src/billing/usage_test_support.rs+++ b/rust/feature-flags/src/billing/usage_test_support.rs@@ -19,6 +19,8 @@ use usage_ingestion_proto::usage_ingestion::v1::{pub struct RecordingIngestion {requests: Arc<Mutex<Vec<Vec<BillingUsageRecord>>>>,replies: Arc<Mutex<VecDeque<Code>>>,+ rejected_teams: Arc<Mutex<Vec<i64>>>,+ client_names: Arc<Mutex<Vec<Option<String>>>>,}impl RecordingIngestion {@@ -27,10 +29,22 @@ impl RecordingIngestion {self.replies.lock().unwrap().push_back(code);}+ /// Leaves `team_id` out of every accepted list, the way the real service answers a team+ /// it cannot attribute: the batch succeeds without those records.+ pub fn reject_team(&self, team_id: i64) {+ self.rejected_teams.lock().unwrap().push(team_id);+ }+/// One entry per request received, in arrival order.pub fn requests(&self) -> Vec<Vec<BillingUsageRecord>> {self.requests.lock().unwrap().clone()}++ /// The `x-client-name` each request carried, which is the label the service's request+ /// metrics slice by.+ pub fn client_names(&self) -> Vec<Option<String>> {+ self.client_names.lock().unwrap().clone()+ }}#[tonic::async_trait]@@ -39,9 +53,18 @@ impl UsageIngestion for RecordingIngestion {&self,request: Request<IngestBillingUsageRequest>,) -> Result<Response<IngestBillingUsageResponse>, Status> {+ self.client_names.lock().unwrap().push(+ request+ .metadata()+ .get("x-client-name")+ .and_then(|value| value.to_str().ok())+ .map(str::to_string),+ );let records = request.into_inner().records;+ let rejected_teams = self.rejected_teams.lock().unwrap().clone();let accepted_record_ids = records.iter()+ .filter(|record| !rejected_teams.contains(&record.team_id)).map(|record| record.record_id.clone()).collect();self.requests.lock().unwrap().push(records);diff --git a/rust/usage-ingestion/Cargo.toml b/rust/usage-ingestion/Cargo.tomlindex c9325b82efb7..751b189c4fc9 100644--- a/rust/usage-ingestion/Cargo.toml+++ b/rust/usage-ingestion/Cargo.toml@@ -9,6 +9,7 @@ async-trait = { workspace = true }axum = { workspace = true }chrono = { workspace = true }common-database = { path = "../common/database" }+common-grpc = { path = "../common/grpc" }common-kafka = { path = "../common/kafka" }common-liveness = { path = "../common/liveness" }envconfig = { workspace = true }diff --git a/rust/usage-ingestion/src/main.rs b/rust/usage-ingestion/src/main.rsindex 435727732208..bf56372b9a62 100644--- a/rust/usage-ingestion/src/main.rs+++ b/rust/usage-ingestion/src/main.rs@@ -3,11 +3,12 @@ use std::time::Duration;use axum::{routing::get, Router};use common_database::{get_pool_with_config, PoolConfig};+use common_grpc::GrpcMetricsLayer;use common_kafka::config::KafkaConfig;use common_kafka::kafka_producer::create_kafka_producer;use envconfig::Envconfig;use health::HealthRegistry;-use metrics_exporter_prometheus::PrometheusBuilder;+use metrics_exporter_prometheus::{Matcher, PrometheusBuilder};use tonic::transport::Server;use tracing::level_filters::LevelFilter;use tracing_subscriber::fmt::format::FmtSpan;@@ -82,7 +83,18 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {config.topic.clone(),);- let metrics_handle = PrometheusBuilder::new().install_recorder()?;+ // Buckets only for the shared gRPC histogram, so it renders the same way personhog's does+ // and quantiles aggregate across pods. Left global, these millisecond bounds would also+ // apply to kafka_delivery_seconds, which is in seconds and would land in one bucket.+ const GRPC_DURATION_BUCKETS_MS: &[f64] = &[+ 1.0, 5.0, 10.0, 50.0, 100.0, 250.0, 500.0, 1000.0, 2000.0, 5000.0, 10000.0,+ ];+ let metrics_handle = PrometheusBuilder::new()+ .set_buckets_for_metric(+ Matcher::Full("grpc_server_request_duration_ms".to_string()),+ GRPC_DURATION_BUCKETS_MS,+ )?+ .install_recorder()?;let metrics_address = config.metrics_address.clone();let health_for_routes = health.clone();tokio::spawn(async move {@@ -111,6 +123,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {// This listener is limited to trusted in-cluster callers. Add authenticated caller identity// before exposing it beyond that boundary because records affect tenant billing.Server::builder()+ .layer(GrpcMetricsLayer).add_service(UsageIngestionServer::new(service)).serve(config.grpc_address.parse()?).await?;diff --git a/rust/usage-ingestion/src/service.rs b/rust/usage-ingestion/src/service.rsindex 6e8ada5ce454..68573fd9dceb 100644--- a/rust/usage-ingestion/src/service.rs+++ b/rust/usage-ingestion/src/service.rs@@ -42,29 +42,81 @@ impl UsageIngestionService {async fn prepare(&self,record: BillingUsageRecord,- resolved: &mut HashMap<i64, Uuid>,- ) -> Result<KafkaBillingUsageRecord, Status> {+ resolved: &mut HashMap<i64, Result<Uuid, &'static str>>,+ ) -> Result<KafkaBillingUsageRecord, PrepareError> {if record.team_id <= 0 || record.team_id > i64::from(i32::MAX) {- return Err(Status::invalid_argument(- "team_id must be a positive 32-bit integer",- ));+ return Err(PrepareError::Rejected("invalid_team_id"));}+ // A rejection is memoized alongside a success, so a batch of 500 records from one+ // unmapped team costs one resolver call rather than 500 cache reads counted as hits.let organization_id = match resolved.get(&record.team_id) {- Some(value) => *value,- None => {- let value = self- .resolver- .resolve(record.team_id)- .await- .map_err(resolve_status)?;- resolved.insert(record.team_id, value);- value- }+ Some(Ok(value)) => *value,+ Some(Err(reason)) => return Err(PrepareError::Rejected(reason)),+ None => match self.resolver.resolve(record.team_id).await {+ Ok(value) => {+ resolved.insert(record.team_id, Ok(value));+ value+ }+ Err(error) => {+ let error = prepare_error(error);+ if let PrepareError::Rejected(reason) = error {+ resolved.insert(record.team_id, Err(reason));+ }+ return Err(error);+ }+ },};KafkaBillingUsageRecord::from_proto(record, organization_id, Utc::now())- .map_err(|error| Status::invalid_argument(error.to_string()))+ .map_err(|_| PrepareError::Rejected("invalid_record"))}++ /// Returns the records to produce and what was dropped on the way. A rejected record fails+ /// the same way however often it is re-sent, so keeping the batch alive is the difference+ /// between losing one team's usage and losing every team's usage that happened to share+ /// the batch with it.+ async fn prepare_batch(+ &self,+ records: Vec<BillingUsageRecord>,+ ) -> Result<(Vec<KafkaBillingUsageRecord>, Vec<Rejection>), Status> {+ // One resolver call per distinct team, not per record: a full batch from one+ // team would otherwise be 500 Redis reads and 500 queries on a cold cache.+ let mut resolved = HashMap::new();+ let mut prepared = Vec::with_capacity(records.len());+ let mut rejected = Vec::new();+ for record in records {+ let team_id = record.team_id;+ match self.prepare(record, &mut resolved).await {+ Ok(record) => prepared.push(record),+ Err(PrepareError::Rejected(reason)) => {+ metrics::counter!("usage_ingestion_records_rejected_total", "reason" => reason)+ .increment(1);+ rejected.push(Rejection { team_id, reason });+ }+ Err(PrepareError::Unavailable(status)) => return Err(status),+ }+ }+ rejected.sort_unstable();+ rejected.dedup();+ Ok((prepared, rejected))+ }+}++/// Splits a failed record by what the producer should do about it. Anything a retry cannot+/// change is skipped; anything the service could not determine fails the whole batch, so the+/// producer sends it again.+#[derive(Debug)]+enum PrepareError {+ Rejected(&'static str),+ Unavailable(Status),+}++/// A team the service dropped records for, and why. Deduplicated per batch, so a team that+/// fails the same way twice reads as one lead.+#[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]+struct Rejection {+ team_id: i64,+ reason: &'static str,}#[tonic::async_trait]@@ -83,13 +135,17 @@ impl UsageIngestion for UsageIngestionService {));}- // One resolver call per distinct team, not per record: a full batch from one- // team would otherwise be 500 Redis reads and 500 queries on a cold cache.- let mut resolved = HashMap::new();- let mut prepared = Vec::with_capacity(records.len());- for record in records {- prepared.push(self.prepare(record, &mut resolved).await?);+ let (prepared, rejected) = self.prepare_batch(records).await?;+ if !rejected.is_empty() {+ tracing::warn!(+ rejected = ?rejected,+ "dropped usage records the service cannot accept"+ );+ }+ if prepared.is_empty() {+ return Ok(Response::new(IngestBillingUsageResponse::default()));}+let accepted_record_ids = prepared.iter().map(|record| record.record_id.clone())@@ -125,20 +181,20 @@ impl UsageIngestion for UsageIngestionService {}}-fn resolve_status(error: ResolveError) -> Status {+fn prepare_error(error: ResolveError) -> PrepareError {match error {- ResolveError::InvalidTeamId => {- Status::invalid_argument("team_id must be a positive 32-bit integer")- }- ResolveError::Missing => Status::not_found("team organization mapping was not found"),- ResolveError::Database(error) => {- Status::unavailable(format!("team organization lookup failed: {error}"))- }+ ResolveError::InvalidTeamId => PrepareError::Rejected("invalid_team_id"),+ ResolveError::Missing => PrepareError::Rejected("organization_missing"),+ ResolveError::Database(error) => PrepareError::Unavailable(Status::unavailable(format!(+ "team organization lookup failed: {error}"+ ))),}}#[cfg(test)]mod tests {+ use std::sync::atomic::{AtomicUsize, Ordering};+use async_trait::async_trait;use common_liveness::SyncLivenessReporter;use rdkafka::ClientConfig;@@ -164,18 +220,45 @@ mod tests {}}- fn service() -> UsageIngestionService {- // prepare() never produces, so the producer only has to exist.+ /// Resolves every team except `unmapped`, which stands in for a team whose organization+ /// row is gone. Counts its calls, so a test can pin how often a batch asks.+ #[derive(Default)]+ struct PartialResolver {+ unmapped: i64,+ calls: AtomicUsize,+ }++ #[async_trait]+ impl OrganizationResolver for PartialResolver {+ async fn resolve(&self, team_id: i64) -> Result<Uuid, ResolveError> {+ self.calls.fetch_add(1, Ordering::Relaxed);+ if team_id == self.unmapped {+ return Err(ResolveError::Missing);+ }+ Ok(Uuid::parse_str(TEAM_ORGANIZATION).unwrap())+ }+ }++ struct UnreachableResolver;++ #[async_trait]+ impl OrganizationResolver for UnreachableResolver {+ async fn resolve(&self, _team_id: i64) -> Result<Uuid, ResolveError> {+ Err(ResolveError::Database(sqlx::Error::PoolTimedOut))+ }+ }++ fn service_with(resolver: Arc<dyn OrganizationResolver>) -> UsageIngestionService {+ // prepare_batch() never produces, so the producer only has to exist.let producer = ClientConfig::new().set("bootstrap.servers", "localhost:9092").create_with_context(KafkaContext::new(AlwaysHealthy)).expect("failed to build the test producer");- UsageIngestionService::new(- producer,- Arc::new(FixedResolver),- 500,- "test-topic".to_string(),- )+ UsageIngestionService::new(producer, resolver, 500, "test-topic".to_string())+ }++ fn service() -> UsageIngestionService {+ service_with(Arc::new(FixedResolver))}fn record() -> BillingUsageRecord {@@ -190,6 +273,14 @@ mod tests {}}+ fn record_for(team_id: i64) -> BillingUsageRecord {+ BillingUsageRecord {+ record_id: format!("018f7c8e-4c08-7c5e-9bc0-15c9f5cc9f{team_id:02}"),+ team_id,+ ..record()+ }+ }+#[tokio::test]async fn the_resolved_organization_is_stamped_on_the_record() {let prepared = service()@@ -202,4 +293,82 @@ mod tests {Uuid::parse_str(TEAM_ORGANIZATION).unwrap());}++ #[tokio::test]+ async fn an_unattributable_team_does_not_discard_the_rest_of_the_batch() {+ let resolver = Arc::new(PartialResolver {+ unmapped: 11,+ ..Default::default()+ });+ let service = service_with(resolver.clone());++ let (prepared, rejected) = service+ .prepare_batch(vec![record_for(10), record_for(11), record_for(12)])+ .await+ .expect("a rejected record must not fail the batch");++ assert_eq!(+ prepared.iter().map(|r| r.team_id).collect::<Vec<_>>(),+ vec![10, 12]+ );+ assert_eq!(+ rejected,+ vec![Rejection {+ team_id: 11,+ reason: "organization_missing"+ }]+ );+ }++ #[tokio::test]+ async fn a_batch_asks_the_resolver_once_per_team_even_when_it_says_no() {+ let resolver = Arc::new(PartialResolver {+ unmapped: 11,+ ..Default::default()+ });+ let service = service_with(resolver.clone());+ let records = (0..4).map(|_| record_for(11)).collect();++ let (prepared, rejected) = service.prepare_batch(records).await.unwrap();++ assert!(prepared.is_empty());+ // One lead per team, and one lookup, however many of its records the batch held.+ assert_eq!(rejected.len(), 1);+ assert_eq!(resolver.calls.load(Ordering::Relaxed), 1);+ }++ #[tokio::test]+ async fn a_record_the_service_can_never_accept_is_skipped() {+ // Validation the record itself fails, rather than anything about its team.+ let unbillable = BillingUsageRecord {+ quantity: 0,+ ..record_for(10)+ };++ let (prepared, rejected) = service()+ .prepare_batch(vec![unbillable, record_for(12)])+ .await+ .expect("a rejected record must not fail the batch");++ assert_eq!(prepared.len(), 1);+ assert_eq!(+ rejected,+ vec![Rejection {+ team_id: 10,+ reason: "invalid_record"+ }]+ );+ }++ #[tokio::test]+ async fn a_lookup_that_could_not_be_answered_still_fails_the_batch() {+ // The producer has to retry this one, so it must not look like an accepted batch+ // that happened to drop records.+ let status = service_with(Arc::new(UnreachableResolver))+ .prepare_batch(vec![record_for(10)])+ .await+ .expect_err("an unavailable lookup must fail the batch");++ assert_eq!(status.code(), tonic::Code::Unavailable);+ }}