: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(capture-apm-metrics): send metric series labels once per window (#96468)
Frank Hamand9b52f1a0736c
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex a1e3394486cc..4a8d109de85a 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2228,12 +2228,25 @@ name = "capture-apm-metrics"version = "0.1.0"dependencies = ["axum 0.7.9",+ "bytes","capture","capture-logs",+ "chrono","common-alloc",+ "common-compression","common-metrics",+ "common-redis",+ "dashmap 6.1.0",+ "envconfig","health","limiters",+ "metrics",+ "opentelemetry-proto 0.29.0",+ "prost 0.13.5",+ "serde",+ "serde_json",+ "siphasher 1.0.2",+ "thiserror 2.0.18","tokio","tower-http 0.5.2","tracing",diff --git a/rust/capture-apm-metrics/Cargo.toml b/rust/capture-apm-metrics/Cargo.tomlindex a1e3e4caccba..f1a9ccbcf915 100644--- a/rust/capture-apm-metrics/Cargo.toml+++ b/rust/capture-apm-metrics/Cargo.toml@@ -15,7 +15,20 @@ common-alloc = { path = "../common/alloc" }limiters = { path = "../common/limiters" }capture = { path = "../capture" }capture-logs = { path = "../capture-logs" }+common-compression = { path = "../common/compression" }+common-redis = { path = "../common/redis" }tower-http = { workspace = true }+envconfig = { workspace = true }+bytes = { workspace = true }+chrono = { workspace = true }+dashmap = { workspace = true }+metrics = { workspace = true }+opentelemetry-proto = { workspace = true }+prost = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+siphasher = { workspace = true }+thiserror = { workspace = true }[lints]workspace = truediff --git a/rust/capture-apm-metrics/README.md b/rust/capture-apm-metrics/README.mdindex e751c39d6270..82781b540eca 100644--- a/rust/capture-apm-metrics/README.md+++ b/rust/capture-apm-metrics/README.md@@ -2,7 +2,31 @@Receives OTLP metrics (`/i/v1/metrics`) and Prometheus remote-write (`/i/v1/prometheus/write`) and writes them to Kafka.-This binary is the metrics half of [`capture-logs`](../capture-logs/README.md). It links the `capture-logs` library and mounts only the metrics routes, so metrics traffic can scale and deploy on its own. Configuration, authentication, response codes, and the Kafka sink are the ones documented for `capture-logs`.+This binary is the metrics half of [`capture-logs`](../capture-logs/README.md). It links the `capture-logs` library for parsing, authentication, and the Kafka sink, so metrics traffic can scale and deploy on its own. The base configuration, authentication, and response codes are the ones documented for `capture-logs`. The settings below are specific to this service.++## Configuration++| Variable | Default | Description |+|----------|---------|-------------|+| REDIS_URL | (none) | Redis that shares the set of recently labelled metric series between pods. Unset means local cache only |+| METRICS_SERIES_LABEL_GATE_ENABLED | false | Strip label maps from repeat metric rows (see below). When false the gate only reports metrics |+| METRICS_SERIES_LABEL_INTERVAL_SECS | 1800 | How often the labels of one metric series go out |+| METRICS_SERIES_REDIS_TIMEOUT_MS | 250 | Budget for one Redis write batch |+| METRICS_SERIES_REDIS_SEED_TIMEOUT_MS | 15000 | Longest the service waits at startup for the cache seed. After that it starts with a partial cache |+| METRICS_SERIES_REDIS_PULL_TIMEOUT_MS | 5000 | Budget for one periodic pull from Redis |+| METRICS_SERIES_REDIS_PULL_INTERVAL_SECS | 60 | How often the local cache pulls new series from Redis |+| METRICS_SERIES_CACHE_MAX_ENTRIES | 20000000 | Most series one pod remembers, across all tokens |+| METRICS_SERIES_CACHE_MAX_ENTRIES_PER_TOKEN | 2000000 | Most series one pod remembers for one token |++### Metric series label gate++Every metric row carries `series_fingerprint`. The label maps (`attributes`, `resource_attributes`) of a series go out on one row per `METRICS_SERIES_LABEL_INTERVAL_SECS`, with `has_labels = true`. All other rows of that series in the window have empty label maps and `has_labels = false`. The ClickHouse rollups build the series and attribute tables from labelled rows only.++The decision uses a local in-memory cache and never waits on Redis. Redis holds the set of series any pod has labelled: new series are pushed from a background task, and the cache pulls from Redis at startup and every `METRICS_SERIES_REDIS_PULL_INTERVAL_SECS`. Pulls read the set in pages of 50,000 members and merge each page as it arrives; the startup seed stops at `METRICS_SERIES_REDIS_SEED_TIMEOUT_MS` and keeps what it has. A Redis failure only makes labels go out more often.++Pull metrics, all with a `kind` label of `seed` or `periodic`: `capture_metrics_series_redis_pulls` (with `outcome` = `ok`, `timeout`, or `error`), `capture_metrics_series_redis_pull_duration_seconds` (same labels), `capture_metrics_series_redis_pull_pages`, `capture_metrics_series_redis_pull_members_read`, `capture_metrics_series_redis_pull_bytes` (member payload, without protocol framing), and `capture_metrics_series_redis_pulled` (members new to this pod).++The cache is bounded. When the global or the per-token cap is full, a new series keeps its labels on every row and is not cached or pushed to Redis, until pruning frees a slot. `capture_metrics_series_cache_full` counts those rows.## Running the servicediff --git a/rust/capture-apm-metrics/src/config.rs b/rust/capture-apm-metrics/src/config.rsnew file mode 100644index 000000000000..c18112391aa1--- /dev/null+++ b/rust/capture-apm-metrics/src/config.rs@@ -0,0 +1,64 @@+use envconfig::Envconfig;++#[derive(Envconfig, Clone)]+pub struct Config {+ /// Bind addresses, Kafka, body limits: the same settings as capture-logs.+ #[envconfig(nested = true)]+ pub base: capture_logs::config::Config,++ /// Shares the set of recently labelled metric series between pods. Unset+ /// means the series label gate runs with its local cache only.+ #[envconfig(from = "REDIS_URL")]+ pub redis_url: Option<String>,++ /// When false the gate still tracks series and reports metrics but leaves+ /// every row labelled, so the switch can flip once the metrics2 read path+ /// takes labels from the series rollup.+ #[envconfig(from = "METRICS_SERIES_LABEL_GATE_ENABLED", default = "false")]+ pub metrics_series_label_gate_enabled: bool,++ #[envconfig(from = "METRICS_SERIES_LABEL_INTERVAL_SECS", default = "1800")]+ pub metrics_series_label_interval_secs: u64,++ #[envconfig(from = "METRICS_SERIES_REDIS_TIMEOUT_MS", default = "250")]+ pub metrics_series_redis_timeout_ms: u64,++ /// Total time the service waits at startup for the series cache seed. When+ /// it runs out the service starts with the pages read so far.+ #[envconfig(from = "METRICS_SERIES_REDIS_SEED_TIMEOUT_MS", default = "15000")]+ pub metrics_series_redis_seed_timeout_ms: u64,++ /// Budget for one periodic pull. Each pull reads only the series labelled+ /// since the previous one, so it is much smaller than the seed.+ #[envconfig(from = "METRICS_SERIES_REDIS_PULL_TIMEOUT_MS", default = "5000")]+ pub metrics_series_redis_pull_timeout_ms: u64,++ #[envconfig(from = "METRICS_SERIES_REDIS_PULL_INTERVAL_SECS", default = "60")]+ pub metrics_series_redis_pull_interval_secs: u64,++ /// Caps on the local series cache, in entries. Ingestion input drives the+ /// cache, so without them a caller with a valid token shape and changing+ /// labels could grow it without limit.+ #[envconfig(from = "METRICS_SERIES_CACHE_MAX_ENTRIES", default = "20000000")]+ pub metrics_series_cache_max_entries: usize,++ #[envconfig(+ from = "METRICS_SERIES_CACHE_MAX_ENTRIES_PER_TOKEN",+ default = "2000000"+ )]+ pub metrics_series_cache_max_entries_per_token: usize,+}++impl Config {+ pub fn init_with_defaults() -> Result<Self, envconfig::Error> {+ let config = Self::init_from_env()?;+ // A zero pull interval panics the puller task, which would stop+ // cross-pod convergence while the service keeps serving traffic.+ if config.metrics_series_redis_pull_interval_secs == 0 {+ return Err(envconfig::Error::ParseError {+ name: "METRICS_SERIES_REDIS_PULL_INTERVAL_SECS",+ });+ }+ Ok(config)+ }+}diff --git a/rust/capture-apm-metrics/src/lib.rs b/rust/capture-apm-metrics/src/lib.rsnew file mode 100644index 000000000000..c344319596f9--- /dev/null+++ b/rust/capture-apm-metrics/src/lib.rs@@ -0,0 +1,4 @@+pub mod config;+pub mod prometheus;+pub mod series_label_gate;+pub mod service;diff --git a/rust/capture-apm-metrics/src/main.rs b/rust/capture-apm-metrics/src/main.rsindex 0f212971221c..142f8a57c385 100644--- a/rust/capture-apm-metrics/src/main.rs+++ b/rust/capture-apm-metrics/src/main.rs@@ -8,14 +8,16 @@ use std::time::Duration;use axum::{extract::DefaultBodyLimit, http::Method, routing::get, routing::post, Router};use capture::metrics_middleware::track_metrics;+use capture_apm_metrics::config::Config;+use capture_apm_metrics::prometheus;+use capture_apm_metrics::series_label_gate::{spawn_redis_writer, CacheLimits, SeriesLabelGate};+use capture_apm_metrics::service::{export_metrics_http, MetricsService};use capture_logs::authorizer::Authorizer;-use capture_logs::config::Config;-use capture_logs::endpoints::prometheus;use capture_logs::kafka::KafkaSink;use capture_logs::middleware::translate_compression_query_param;-use capture_logs::service::Service;-use capture_logs::service::{export_metrics_http, options_handler};+use capture_logs::service::options_handler;use common_metrics::setup_metrics_routes;+use common_redis::{Client, CompressionConfig, RedisClient, RedisValueFormat};use std::future::ready;use std::net::SocketAddr;@@ -69,6 +71,65 @@ pub async fn index() -> &'static str {"}+/// Build the series label gate and, when Redis is configured, its background+/// tasks. The Redis client is optional on purpose: without it the gate still+/// dedupes labels within this pod.+async fn start_series_label_gate(config: &Config) -> Arc<SeriesLabelGate> {+ let window = Duration::from_secs(config.metrics_series_label_interval_secs);+ let enabled = config.metrics_series_label_gate_enabled;+ let limits = CacheLimits {+ max_entries: config.metrics_series_cache_max_entries,+ max_entries_per_token: config.metrics_series_cache_max_entries_per_token,+ };+ info!(+ "Series label gate {} (window {}s)",+ if enabled {+ "enabled"+ } else {+ "in dry-run mode"+ },+ window.as_secs()+ );++ let Some(redis_url) = config.redis_url.clone() else {+ info!("REDIS_URL unset, series label gate runs with the local cache only");+ let gate = SeriesLabelGate::local_only(window, enabled, limits);+ gate.spawn_pruner();+ return gate;+ };++ let redis_timeout = Duration::from_millis(config.metrics_series_redis_timeout_ms);+ let seed_budget = Duration::from_millis(config.metrics_series_redis_seed_timeout_ms);+ let pull_timeout = Duration::from_millis(config.metrics_series_redis_pull_timeout_ms);+ let pull_interval = Duration::from_secs(config.metrics_series_redis_pull_interval_secs);+ let client: Arc<dyn Client> = match RedisClient::with_config(+ redis_url,+ CompressionConfig::disabled(),+ RedisValueFormat::Utf8,+ Some(pull_timeout),+ Some(pull_timeout),+ )+ .await+ {+ Ok(client) => Arc::new(client),+ Err(e) => {+ error!(+ "Could not connect to Redis, series label gate runs with the local cache only: {e}"+ );+ let gate = SeriesLabelGate::local_only(window, enabled, limits);+ gate.spawn_pruner();+ return gate;+ }+ };++ let (gate, rx) = SeriesLabelGate::new(window, enabled, limits);+ gate.seed_from_redis(client.as_ref(), seed_budget).await;+ gate.spawn_redis_puller(Arc::clone(&client), pull_interval, pull_timeout);+ gate.spawn_pruner();+ spawn_redis_writer(client, rx, redis_timeout, window);+ gate+}+#[tokio::main]async fn main() {setup_tracing();@@ -77,7 +138,7 @@ async fn main() {let config = Config::init_with_defaults().unwrap();// Start continuous profiling if enabled (keep _agent alive for the duration of the program)- let _profiling_agent = match config.continuous_profiling.start_agent() {+ let _profiling_agent = match config.base.continuous_profiling.start_agent() {Ok(agent) => agent,Err(e) => {tracing::warn!("Failed to start continuous profiling agent: {e}");@@ -101,7 +162,7 @@ async fn main() {.await;let kafka_sink = KafkaSink::new(- config.kafka.clone(),+ config.base.kafka.clone(),logs_sink_liveness,traces_sink_liveness,metrics_sink_liveness,@@ -117,23 +178,26 @@ async fn main() {get(move || ready(health_registry.get_status())),);let management_router = setup_metrics_routes(management_router);- let management_bind = format!("{}:{}", config.management_host, config.management_port);+ let management_bind = format!(+ "{}:{}",+ config.base.management_host, config.base.management_port+ );info!("Healthcheck and metrics listening on {}", management_bind);let management_listener = tokio::net::TcpListener::bind(management_bind).await.expect("could not bind management port");- let token_dropper = TokenDropper::new(&config.drop_events_by_token.unwrap_or_default());+ let series_label_gate = start_series_label_gate(&config).await;+ let token_dropper =+ TokenDropper::new(&config.base.drop_events_by_token.clone().unwrap_or_default());let authorizer = Authorizer::new(Arc::new(token_dropper));- let metrics_service =- match Service::new(kafka_sink, authorizer, config.max_request_body_size_bytes).await {- Ok(service) => service,- Err(e) => {- error!("Failed to initialize metrics service: {}", e);- panic!("Could not start metrics capture service: {e}");- }- };- let http_bind = format!("{}:{}", config.host, config.port);+ let metrics_service = MetricsService::new(+ kafka_sink,+ authorizer,+ config.base.max_request_body_size_bytes,+ series_label_gate,+ );+ let http_bind = format!("{}:{}", config.base.host, config.base.port);info!("Listening on {}", http_bind);let http_listener = tokio::net::TcpListener::bind(http_bind).await@@ -156,7 +220,9 @@ async fn main() {post(export_metrics_http).options(options_handler),).with_state(metrics_service.clone())- .layer(DefaultBodyLimit::max(config.max_request_body_size_bytes))+ .layer(DefaultBodyLimit::max(+ config.base.max_request_body_size_bytes,+ )).layer(axum::middleware::from_fn(track_metrics)).layer(RequestDecompressionLayer::new()).layer(axum::middleware::from_fn(translate_compression_query_param));@@ -175,7 +241,9 @@ async fn main() {post(prometheus::export_prometheus_remote_write_http).options(options_handler),).with_state(metrics_service)- .layer(DefaultBodyLimit::max(config.max_request_body_size_bytes))+ .layer(DefaultBodyLimit::max(+ config.base.max_request_body_size_bytes,+ )).layer(axum::middleware::from_fn(track_metrics));let http_router = http_router.merge(prometheus_router).layer(cors);diff --git a/rust/capture-apm-metrics/src/prometheus.rs b/rust/capture-apm-metrics/src/prometheus.rsnew file mode 100644index 000000000000..1335a47d0fc5--- /dev/null+++ b/rust/capture-apm-metrics/src/prometheus.rs@@ -0,0 +1,150 @@+//! Prometheus remote-write handler. Copied from+//! `capture_logs::endpoints::prometheus::export_prometheus_remote_write_http`+//! so the series label gate can run between row building and the Kafka write+//! without a change to capture-logs. Decoding and row building still come from+//! the capture-logs library.++use axum::extract::{Path, Query, State};+use axum::http::{HeaderMap, StatusCode};+use axum::Json;+use bytes::Bytes;+use capture_logs::authorizer::Signal;+use capture_logs::endpoints::prometheus::{+ decode_write_request, estimate_expanded_bytes, write_request_to_kafka_rows,+};+use serde::Deserialize;+use serde_json::json;+use tracing::{debug, error, instrument};++use crate::service::MetricsService;++/// How much larger than the (already decompression-capped) request body the+/// expanded row set may be. Row building clones the series label map per+/// sample and the whole batch becomes a single Kafka message, so a 2 wire-byte+/// sample expands to hundreds of bytes — legitimate senders (Prometheus+/// defaults to 2k samples per send, vmagent to 10k rows per block) stay far+/// below this; only expansion-bomb payloads exceed it.+const MAX_EXPANSION_FACTOR: u64 = 16;++#[derive(Deserialize)]+pub struct RemoteWriteQueryParams {+ token: Option<String>,+}++/// Resolve the project token from (in order) the URL path, the Authorization+/// header (Bearer or bare), or the `token` query param — matching the+/// flexibility remote-write senders actually have.+fn extract_token(+ path_token: Option<String>,+ headers: &HeaderMap,+ query_token: Option<&str>,+) -> Option<String> {+ if let Some(token) = path_token {+ if !token.is_empty() {+ return Some(token);+ }+ }+ if let Some(auth) = headers.get("authorization").and_then(|v| v.to_str().ok()) {+ let token = auth+ .strip_prefix("Bearer ")+ .or_else(|| auth.strip_prefix("bearer "))+ .unwrap_or(auth)+ .trim();+ if !token.is_empty() {+ return Some(token.to_string());+ }+ }+ query_token.filter(|t| !t.is_empty()).map(str::to_string)+}++/// Prometheus remote-write v1 ingestion endpoint.+///+/// Snappy-decodes the protobuf body, maps it to `KafkaMetricRow` records, and+/// produces them through the shared `KafkaSink` so the rest of the pipeline is+/// identical to OTLP ingestion. Response codes follow remote-write semantics:+/// 204 on success, 400 on a permanent decode failure (sender drops the batch),+/// 5xx on a transient produce failure (sender retries).+#[instrument(skip_all, fields(+ token = tracing::field::Empty,+ user_agent = %headers.get("user-agent")+ .and_then(|v| v.to_str().ok())+ .unwrap_or(""),+ content_length = %headers.get("content-length")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")))+]+pub async fn export_prometheus_remote_write_http(+ State(service): State<MetricsService>,+ path_token: Option<Path<String>>,+ Query(query_params): Query<RemoteWriteQueryParams>,+ headers: HeaderMap,+ body: Bytes,+) -> Result<StatusCode, (StatusCode, Json<serde_json::Value>)> {+ let token = match extract_token(+ path_token.map(|Path(t)| t),+ &headers,+ query_params.token.as_deref(),+ ) {+ Some(token) => token,+ None => {+ error!("No token provided");+ return Err((+ StatusCode::UNAUTHORIZED,+ Json(json!({"error": "No token provided"})),+ ));+ }+ };++ service+ .authorizer+ .authorize_token(&token, Signal::Metrics)?;++ tracing::Span::current().record("token", &token);++ let (write_request, uncompressed_bytes) =+ match decode_write_request(&body, service.max_request_body_size_bytes) {+ Ok(decoded) => decoded,+ Err(e) => {+ error!("Failed to decode remote-write request: {e}");+ return Err((+ StatusCode::BAD_REQUEST,+ Json(json!({ "error": format!("{e}") })),+ ));+ }+ };++ // 400, not 5xx: a batch that expands past the limit will never fit, so the+ // sender must drop it rather than retry it forever.+ let expanded = estimate_expanded_bytes(&write_request);+ let max_expanded = MAX_EXPANSION_FACTOR * service.max_request_body_size_bytes as u64;+ if expanded > max_expanded {+ error!(+ "Rejecting remote-write request expanding to ~{expanded} bytes (limit {max_expanded})"+ );+ return Err((+ StatusCode::BAD_REQUEST,+ Json(json!({+ "error": format!("request expands to too many samples (~{expanded} > {max_expanded} bytes); send smaller batches")+ })),+ ));+ }++ let (mut rows, timestamps_overridden) = write_request_to_kafka_rows(write_request);+ service.series_label_gate.apply(&token, &mut rows);+ let row_count = rows.len();++ if let Err(e) = service+ .sink+ .write_metrics(&token, rows, uncompressed_bytes, timestamps_overridden)+ .await+ {+ error!("Failed to send remote-write metrics to Kafka: {e}");+ return Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json!({"error": "Internal server error"})),+ ));+ }++ debug!("Sent {row_count} remote-write data points to Kafka");+ Ok(StatusCode::NO_CONTENT)+}diff --git a/rust/capture-apm-metrics/src/series_label_gate.rs b/rust/capture-apm-metrics/src/series_label_gate.rsnew file mode 100644index 000000000000..459d0fb33838--- /dev/null+++ b/rust/capture-apm-metrics/src/series_label_gate.rs@@ -0,0 +1,1013 @@+//! Sends the label maps of a metric series once per window instead of on every+//! row. The metrics2 ClickHouse chain builds its series and attribute rollups+//! from rows with `has_labels = true`, so one labelled row per series per+//! window is enough; every other row only needs the fingerprint and the value.+//!+//! The decision runs on the request path against a local cache and never+//! awaits. Redis only shares the set of recently labelled series between pods:+//! new series are pushed from a background task, and the cache is pulled from+//! Redis at startup and on an interval. Every Redis failure is ignored, which+//! can only make labels go out more often, never less.+//!+//! Ingestion input drives the cache, so it is bounded. A global cap and a+//! per-token cap limit how many series one pod remembers; a row that finds a+//! cap full keeps its labels and is not cached. The same "more labels, never+//! less" direction as a Redis failure.++use std::collections::BTreeMap;+use std::hash::Hasher;+use std::sync::atomic::{AtomicUsize, Ordering};+use std::sync::Arc;+use std::time::Duration;++use chrono::Utc;+use common_redis::{Client, CustomRedisError, PipelineCommand};+use dashmap::DashMap;+use metrics::{counter, gauge, histogram};+use siphasher::sip::SipHasher13;+use tokio::sync::mpsc;+use tracing::{debug, info, warn};++use capture_logs::metric_record::KafkaMetricRow;++const REDIS_KEY_PREFIX: &str = "capture-logs:metric-series-labels";+/// Members are spread over hour buckets so keys expire on their own and no+/// prune command is needed.+const REDIS_BUCKET_SECS: i64 = 3600;+/// Members written by another pod just before a pull started can carry a score+/// below the pull's `since` because of clock skew. The next pull starts this+/// much earlier; members already in the cache are a no-op.+const PULL_OVERLAP_SECS: i64 = 60;+/// Members per `ZRANGEBYSCORE ... LIMIT` call. Small enough that one call is+/// a short, non-blocking read on Redis and a small reply here; large enough+/// that a full seed of millions of series takes hundreds of calls, not tens+/// of thousands.+const PULL_PAGE_SIZE: usize = 50_000;+const WRITER_CHANNEL_CAPACITY: usize = 10_000;+const WRITER_BATCH_SIZE: usize = 500;+const WRITER_FLUSH_INTERVAL: Duration = Duration::from_secs(1);+const PRUNE_INTERVAL: Duration = Duration::from_secs(300);++pub type Clock = Arc<dyn Fn() -> i64 + Send + Sync>;++/// Gate key and the unix second its labels went out.+type SeenSeries = (u64, i64);++/// Which pull is running, for the metric label.+#[derive(Debug, Clone, Copy)]+pub enum PullKind {+ /// The startup read of the whole window.+ Seed,+ /// The incremental read on the pull interval.+ Periodic,+}++impl PullKind {+ fn as_str(self) -> &'static str {+ match self {+ PullKind::Seed => "seed",+ PullKind::Periodic => "periodic",+ }+ }+}++/// What one pull read from Redis and did with it.+#[derive(Default)]+struct PullStats {+ pages: u64,+ members_read: u64,+ /// Sum of member lengths: the payload bytes, without RESP framing.+ bytes: u64,+ merged: usize,+ cache_full: u64,+}++/// Upper bounds on the local cache. Both count entries, not bytes; one entry+/// is a few tens of bytes.+#[derive(Debug, Clone, Copy)]+pub struct CacheLimits {+ /// Entries across all tokens, including series pulled from Redis.+ pub max_entries: usize,+ /// Entries one token can hold. Series pulled from Redis carry no token and+ /// count only toward `max_entries`.+ pub max_entries_per_token: usize,+}++struct Entry {+ last_seen: i64,+ /// `None` for a series pulled from Redis, whose token is unknown here.+ token_hash: Option<u64>,+}++pub struct SeriesLabelGate {+ cache: DashMap<u64, Entry>,+ /// Exact entry count. `DashMap::len` walks every shard, and the request+ /// path checks the cap per row.+ len: AtomicUsize,+ per_token: DashMap<u64, usize>,+ limits: CacheLimits,+ tx: Option<mpsc::Sender<SeenSeries>>,+ window_secs: i64,+ enabled: bool,+ clock: Clock,+}++impl SeriesLabelGate {+ /// Gate backed by Redis. The receiver goes to [`spawn_redis_writer`].+ pub fn new(+ window: Duration,+ enabled: bool,+ limits: CacheLimits,+ ) -> (Arc<Self>, mpsc::Receiver<SeenSeries>) {+ let (tx, rx) = mpsc::channel(WRITER_CHANNEL_CAPACITY);+ let gate = Self::build(window, enabled, limits, Some(tx), Arc::new(unix_now));+ (Arc::new(gate), rx)+ }++ /// Gate with the local cache only. Used when `REDIS_URL` is unset.+ pub fn local_only(window: Duration, enabled: bool, limits: CacheLimits) -> Arc<Self> {+ Arc::new(Self::build(+ window,+ enabled,+ limits,+ None,+ Arc::new(unix_now),+ ))+ }++ fn build(+ window: Duration,+ enabled: bool,+ limits: CacheLimits,+ tx: Option<mpsc::Sender<SeenSeries>>,+ clock: Clock,+ ) -> Self {+ Self {+ cache: DashMap::new(),+ len: AtomicUsize::new(0),+ per_token: DashMap::new(),+ limits,+ tx,+ window_secs: window.as_secs() as i64,+ enabled,+ clock,+ }+ }++ /// Decide per row whether it carries the series labels. The first row for a+ /// series in the window keeps them; later rows get empty label maps and+ /// `has_labels = false`. Synchronous: never waits on Redis.+ pub fn apply(&self, token: &str, rows: &mut [KafkaMetricRow]) {+ let now = (self.clock)();+ let token_hash = token_key(token);+ let mut sent = 0u64;+ let mut skipped = 0u64;+ let mut queue_full = 0u64;+ let mut cache_full = 0u64;++ for row in rows.iter_mut() {+ let key = gate_key(token, row.series_fingerprint);+ if self.seen_within_window(key, now) {+ skipped += 1;+ if self.enabled {+ strip_labels(row);+ }+ continue;+ }++ // The row keeps its labels either way. Only a cached series is+ // pushed to Redis, so other pods never learn about series this+ // pod refused to remember.+ sent += 1;+ if !self.remember(key, now, Some(token_hash)) {+ cache_full += 1;+ continue;+ }+ if let Some(tx) = &self.tx {+ if tx.try_send((key, now)).is_err() {+ queue_full += 1;+ }+ }+ }++ counter!("capture_metrics_series_labels_sent").increment(sent);+ counter!("capture_metrics_series_labels_skipped").increment(skipped);+ if queue_full > 0 {+ counter!("capture_metrics_series_redis_queue_full").increment(queue_full);+ }+ if cache_full > 0 {+ counter!("capture_metrics_series_cache_full", "source" => "request")+ .increment(cache_full);+ }+ }++ fn seen_within_window(&self, key: u64, now: i64) -> bool {+ self.cache+ .get(&key)+ .is_some_and(|entry| now - entry.last_seen < self.window_secs)+ }++ /// Record that `key` was labelled at `seen_at`. An entry past its window+ /// is refreshed in place and keeps its slot. A new entry needs a free slot+ /// under both caps; returns `false` when there is none.+ fn remember(&self, key: u64, seen_at: i64, token_hash: Option<u64>) -> bool {+ match self.cache.entry(key) {+ dashmap::Entry::Occupied(mut slot) => {+ slot.get_mut().last_seen = seen_at;+ true+ }+ dashmap::Entry::Vacant(slot) => {+ if !self.reserve(token_hash) {+ return false;+ }+ slot.insert(Entry {+ last_seen: seen_at,+ token_hash,+ });+ true+ }+ }+ }++ /// Take one slot under the global cap and, when the token is known, its+ /// per-token cap. Undoes the global take when the per-token cap is full.+ fn reserve(&self, token_hash: Option<u64>) -> bool {+ if self.len.fetch_add(1, Ordering::AcqRel) >= self.limits.max_entries {+ self.len.fetch_sub(1, Ordering::AcqRel);+ return false;+ }+ let Some(token_hash) = token_hash else {+ return true;+ };+ let mut count = self.per_token.entry(token_hash).or_insert(0);+ if *count >= self.limits.max_entries_per_token {+ drop(count);+ self.len.fetch_sub(1, Ordering::AcqRel);+ return false;+ }+ *count += 1;+ true+ }++ /// Drop entries older than the window and release their slots.+ fn prune(&self, now: i64) {+ self.cache.retain(|_, entry| {+ if now - entry.last_seen < self.window_secs {+ return true;+ }+ self.len.fetch_sub(1, Ordering::AcqRel);+ if let Some(token_hash) = entry.token_hash {+ if let Some(mut count) = self.per_token.get_mut(&token_hash) {+ *count = count.saturating_sub(1);+ }+ }+ false+ });+ self.per_token.retain(|_, count| *count > 0);+ gauge!("capture_metrics_series_cache_size").set(self.len.load(Ordering::Acquire) as f64);+ }++ /// Read every series labelled by any pod in the current window. Runs once+ /// before the service accepts traffic. `budget` bounds the wait: when it+ /// runs out the pages already merged stay and the service starts with a+ /// partial cache, which only means more labelled rows until the next pulls+ /// fill the gap.+ pub async fn seed_from_redis(&self, client: &dyn Client, budget: Duration) {+ let now = (self.clock)();+ match self+ .pull_from_redis(client, PullKind::Seed, now - self.window_secs, budget)+ .await+ {+ Ok(merged) => info!("Seeded series label cache with {merged} series from Redis"),+ Err(PullError::Timeout { merged }) => warn!(+ "Series label cache seed hit its {}s budget after {merged} series, starting with a partial cache",+ budget.as_secs()+ ),+ Err(e) => warn!("Could not seed series label cache from Redis, starting empty: {e}"),+ }+ }++ /// Merge the series with a score at or after `since` into the cache. A+ /// series this pod already knows keeps its exact local timestamp; a series+ /// another pod labelled is recorded as seen now. Returns how many were new.+ ///+ /// Reads in pages and merges each page as it arrives, so a `budget` that+ /// runs out loses only the pages not yet read.+ pub async fn pull_from_redis(+ &self,+ client: &dyn Client,+ kind: PullKind,+ since: i64,+ budget: Duration,+ ) -> Result<usize, PullError> {+ self.pull_pages(client, kind, since, PULL_PAGE_SIZE, budget)+ .await+ }++ async fn pull_pages(+ &self,+ client: &dyn Client,+ kind: PullKind,+ since: i64,+ page_size: usize,+ budget: Duration,+ ) -> Result<usize, PullError> {+ let started = tokio::time::Instant::now();+ let deadline = started + budget;+ let mut stats = PullStats::default();+ let result = self+ .walk_pages(client, since, page_size, deadline, &mut stats)+ .await;+ let outcome = match &result {+ Ok(()) => "ok",+ Err(PullError::Timeout { .. }) => "timeout",+ Err(PullError::Redis(_)) => "error",+ };+ record_pull(kind, outcome, &stats, started.elapsed());+ result.map(|()| stats.merged)+ }++ /// Read every page of every bucket in the range into `stats`. Stops at+ /// `deadline`; what was merged before that stays in the cache.+ async fn walk_pages(+ &self,+ client: &dyn Client,+ since: i64,+ page_size: usize,+ deadline: tokio::time::Instant,+ stats: &mut PullStats,+ ) -> Result<(), PullError> {+ let now = (self.clock)();+ let min = since.to_string();++ for key in bucket_keys(since.max(now - self.window_secs), now) {+ let mut offset = 0usize;+ loop {+ if tokio::time::Instant::now() >= deadline {+ return Err(PullError::Timeout {+ merged: stats.merged,+ });+ }+ let page = client.zrangebyscore_limit(+ key.clone(),+ min.clone(),+ "+inf".to_string(),+ offset as isize,+ page_size as isize,+ );+ let page = match tokio::time::timeout_at(deadline, page).await {+ Ok(page) => page?,+ Err(_) => {+ return Err(PullError::Timeout {+ merged: stats.merged,+ })+ }+ };+ let page_len = page.len();+ stats.pages += 1;+ stats.members_read += page_len as u64;+ stats.bytes += page.iter().map(|m| m.len() as u64).sum::<u64>();+ self.merge_members(page, now, stats);+ if page_len < page_size {+ break;+ }+ offset += page_len;+ }+ }+ Ok(())+ }++ fn merge_members(&self, members: Vec<String>, now: i64, stats: &mut PullStats) {+ for member in members {+ let Ok(key) = member.parse::<u64>() else {+ continue;+ };+ let dashmap::Entry::Vacant(slot) = self.cache.entry(key) else {+ continue;+ };+ if !self.reserve(None) {+ stats.cache_full += 1;+ continue;+ }+ slot.insert(Entry {+ last_seen: now - seed_jitter(key, self.window_secs),+ token_hash: None,+ });+ stats.merged += 1;+ }+ }++ /// Repeat [`Self::pull_from_redis`] every `interval`, each time reading only+ /// members added since the previous pull (with an overlap for clock skew).+ pub fn spawn_redis_puller(+ self: &Arc<Self>,+ client: Arc<dyn Client>,+ interval: Duration,+ timeout: Duration,+ ) {+ let gate = Arc::clone(self);+ tokio::spawn(async move {+ let mut since = (gate.clock)() - PULL_OVERLAP_SECS;+ let mut ticker = tokio::time::interval(interval);+ ticker.tick().await;+ loop {+ ticker.tick().await;+ let started = (gate.clock)();+ match gate+ .pull_from_redis(client.as_ref(), PullKind::Periodic, since, timeout)+ .await+ {+ Ok(merged) => {+ debug!("Pulled {merged} new series from Redis");+ since = started - PULL_OVERLAP_SECS;+ }+ Err(e) => {+ // `since` stays put, so the next tick re-reads the gap.+ debug!("Series label pull from Redis failed: {e}");+ }+ }+ }+ });+ }++ /// Drop cache entries older than the window so memory tracks the number of+ /// active series, not the number ever seen.+ pub fn spawn_pruner(self: &Arc<Self>) {+ let gate = Arc::clone(self);+ tokio::spawn(async move {+ let mut ticker = tokio::time::interval(PRUNE_INTERVAL);+ ticker.tick().await;+ loop {+ ticker.tick().await;+ gate.prune((gate.clock)());+ }+ });+ }++ #[cfg(test)]+ fn cache_len(&self) -> usize {+ self.cache.len()+ }++ #[cfg(test)]+ fn seen_at(&self, key: u64) -> Option<i64> {+ self.cache.get(&key).map(|entry| entry.last_seen)+ }+}++/// Batch newly labelled series into `ZADD` pipelines. One flush per+/// [`WRITER_BATCH_SIZE`] series or per [`WRITER_FLUSH_INTERVAL`], whichever+/// comes first. Failures are counted and dropped; the next pull from another+/// pod, or this pod's own cache, covers the gap.+pub fn spawn_redis_writer(+ client: Arc<dyn Client>,+ mut rx: mpsc::Receiver<SeenSeries>,+ timeout: Duration,+ window: Duration,+) {+ let ttl_secs = window.as_secs() + REDIS_BUCKET_SECS as u64;+ tokio::spawn(async move {+ let mut batch: Vec<SeenSeries> = Vec::with_capacity(WRITER_BATCH_SIZE);+ loop {+ let Some(first) = rx.recv().await else {+ return;+ };+ batch.push(first);++ let flush_at = tokio::time::sleep(WRITER_FLUSH_INTERVAL);+ tokio::pin!(flush_at);+ while batch.len() < WRITER_BATCH_SIZE {+ tokio::select! {+ item = rx.recv() => match item {+ Some(item) => batch.push(item),+ None => break,+ },+ _ = &mut flush_at => break,+ }+ }++ let commands = zadd_commands(&batch, ttl_secs);+ let pushed = batch.len() as u64;+ batch.clear();+ match tokio::time::timeout(timeout, client.execute_pipeline(commands)).await {+ Ok(Ok(_)) => {+ counter!("capture_metrics_series_redis_pushed").increment(pushed);+ }+ Ok(Err(e)) => {+ counter!("capture_metrics_series_redis_push_failed").increment(pushed);+ debug!("Series label push to Redis failed: {e}");+ }+ Err(_) => {+ counter!("capture_metrics_series_redis_push_failed").increment(pushed);+ debug!("Series label push to Redis timed out");+ }+ }+ }+ });+}++/// One set of counters per pull, labelled by which pull ran and how it ended.+/// `members_read` counts every member Redis returned; `pulled` counts the ones+/// that were new to this pod.+fn record_pull(kind: PullKind, outcome: &'static str, stats: &PullStats, elapsed: Duration) {+ let kind = kind.as_str();+ counter!("capture_metrics_series_redis_pulls", "kind" => kind, "outcome" => outcome)+ .increment(1);+ histogram!("capture_metrics_series_redis_pull_duration_seconds", "kind" => kind, "outcome" => outcome)+ .record(elapsed.as_secs_f64());+ counter!("capture_metrics_series_redis_pull_pages", "kind" => kind).increment(stats.pages);+ counter!("capture_metrics_series_redis_pull_members_read", "kind" => kind)+ .increment(stats.members_read);+ counter!("capture_metrics_series_redis_pull_bytes", "kind" => kind).increment(stats.bytes);+ counter!("capture_metrics_series_redis_pulled", "kind" => kind).increment(stats.merged as u64);+ if stats.cache_full > 0 {+ counter!("capture_metrics_series_cache_full", "source" => "pull")+ .increment(stats.cache_full);+ }+}++/// A pulled series gets a timestamp that is a little in the past, so that+/// series seeded together do not all expire in the same second. Without this,+/// every pod relabels every seeded series at the same moment one window after+/// startup. The offset is derived from the key so all pods pick the same one.+fn seed_jitter(key: u64, window_secs: i64) -> i64 {+ let spread = (window_secs / 4).max(1);+ (key % spread as u64) as i64+}++/// One ZADD per bucket carrying every member, plus one EXPIRE per bucket.+fn zadd_commands(batch: &[SeenSeries], ttl_secs: u64) -> Vec<PipelineCommand> {+ let mut by_bucket: BTreeMap<String, Vec<(i64, String)>> = BTreeMap::new();+ for (key, seen_at) in batch {+ by_bucket+ .entry(bucket_key(*seen_at))+ .or_default()+ .push((*seen_at, key.to_string()));+ }+ let mut commands = Vec::with_capacity(by_bucket.len() * 2);+ for (bucket, members) in by_bucket {+ commands.push(PipelineCommand::ZAdd {+ key: bucket.clone(),+ members,+ });+ commands.push(PipelineCommand::Expire {+ key: bucket,+ seconds: ttl_secs,+ });+ }+ commands+}++#[derive(Debug, thiserror::Error)]+pub enum PullError {+ #[error("redis error: {0}")]+ Redis(#[from] CustomRedisError),+ #[error("timed out after merging {merged} series")]+ Timeout { merged: usize },+}++/// `series_fingerprint` is computed without the token, and ClickHouse tables+/// are per team, so two teams with identical series must not share a gate+/// entry. The token is hashed in rather than stored, so no key reaches Redis.+fn gate_key(token: &str, series_fingerprint: i64) -> u64 {+ let mut hasher = SipHasher13::new();+ hasher.write(&(token.len() as u64).to_le_bytes());+ hasher.write(token.as_bytes());+ hasher.write(&series_fingerprint.to_le_bytes());+ hasher.finish()+}++/// Per-token accounting key. Hashed so the token itself is not kept in memory+/// beyond the request.+fn token_key(token: &str) -> u64 {+ let mut hasher = SipHasher13::new();+ hasher.write(token.as_bytes());+ hasher.finish()+}++fn strip_labels(row: &mut KafkaMetricRow) {+ row.has_labels = false;+ row.attributes.clear();+ row.resource_attributes.clear();+}++fn bucket_key(unix_secs: i64) -> String {+ format!(+ "{REDIS_KEY_PREFIX}:{}",+ unix_secs.div_euclid(REDIS_BUCKET_SECS)+ )+}++/// Bucket keys that can hold a member with a score in `[from, to]`.+fn bucket_keys(from: i64, to: i64) -> Vec<String> {+ let first = from.div_euclid(REDIS_BUCKET_SECS);+ let last = to.div_euclid(REDIS_BUCKET_SECS);+ (first..=last)+ .map(|bucket| format!("{REDIS_KEY_PREFIX}:{bucket}"))+ .collect()+}++fn unix_now() -> i64 {+ Utc::now().timestamp()+}++#[cfg(test)]+mod tests {+ use std::collections::HashMap;+ use std::sync::atomic::{AtomicI64, Ordering};++ use common_redis::{MockRedisClient, MockRedisValue};++ use super::*;++ const WINDOW: Duration = Duration::from_secs(1800);+ const START: i64 = 1_800_000_000;+ const NO_LIMITS: CacheLimits = CacheLimits {+ max_entries: usize::MAX,+ max_entries_per_token: usize::MAX,+ };++ fn gate(+ enabled: bool,+ with_redis: bool,+ ) -> (+ SeriesLabelGate,+ Arc<AtomicI64>,+ Option<mpsc::Receiver<SeenSeries>>,+ ) {+ gate_with_limits(enabled, with_redis, NO_LIMITS)+ }++ fn gate_with_limits(+ enabled: bool,+ with_redis: bool,+ limits: CacheLimits,+ ) -> (+ SeriesLabelGate,+ Arc<AtomicI64>,+ Option<mpsc::Receiver<SeenSeries>>,+ ) {+ let now = Arc::new(AtomicI64::new(START));+ let clock_now = Arc::clone(&now);+ let clock: Clock = Arc::new(move || clock_now.load(Ordering::SeqCst));+ let (tx, rx) = if with_redis {+ let (tx, rx) = mpsc::channel(WRITER_CHANNEL_CAPACITY);+ (Some(tx), Some(rx))+ } else {+ (None, None)+ };+ (+ SeriesLabelGate::build(WINDOW, enabled, limits, tx, clock),+ now,+ rx,+ )+ }++ fn row(series_fingerprint: i64) -> KafkaMetricRow {+ KafkaMetricRow {+ uuid: String::new(),+ trace_id: String::new(),+ span_id: String::new(),+ trace_flags: 0,+ timestamp: Utc::now(),+ observed_timestamp: Utc::now(),+ service_name: "svc".into(),+ metric_name: "m".into(),+ metric_type: "gauge".into(),+ value: 1.0,+ count: 1,+ histogram_bounds: vec![],+ histogram_counts: vec![],+ unit: String::new(),+ aggregation_temporality: String::new(),+ is_monotonic: false,+ resource_attributes: HashMap::from([("service.name".into(), "\"svc\"".into())]),+ instrumentation_scope: String::new(),+ attributes: HashMap::from([("env".into(), "\"prod\"".into())]),+ series_fingerprint,+ has_labels: true,+ retention_days: None,+ }+ }++ fn assert_labelled(row: &KafkaMetricRow) {+ assert!(row.has_labels);+ assert!(!row.attributes.is_empty());+ assert!(!row.resource_attributes.is_empty());+ }++ fn assert_stripped(row: &KafkaMetricRow) {+ assert!(!row.has_labels);+ assert!(row.attributes.is_empty());+ assert!(row.resource_attributes.is_empty());+ }++ #[test]+ fn first_row_keeps_labels_and_later_rows_in_window_are_stripped() {+ let (gate, now, _) = gate(true, false);++ let mut rows = vec![row(7), row(7)];+ gate.apply("token-a", &mut rows);+ assert_labelled(&rows[0]);+ assert_stripped(&rows[1]);++ now.fetch_add(WINDOW.as_secs() as i64 - 1, Ordering::SeqCst);+ let mut rows = vec![row(7)];+ gate.apply("token-a", &mut rows);+ assert_stripped(&rows[0]);++ now.fetch_add(1, Ordering::SeqCst);+ let mut rows = vec![row(7)];+ gate.apply("token-a", &mut rows);+ assert_labelled(&rows[0]);+ }++ #[test]+ fn global_cap_leaves_extra_series_labelled_and_uncached() {+ let limits = CacheLimits {+ max_entries: 2,+ ..NO_LIMITS+ };+ let (gate, now, rx) = gate_with_limits(true, true, limits);+ let mut rx = rx.unwrap();++ let mut rows = vec![row(1), row(2), row(3), row(3)];+ gate.apply("token-a", &mut rows);+ assert_labelled(&rows[2]);+ // Series 3 was never cached, so its repeat is labelled too.+ assert_labelled(&rows[3]);+ assert_eq!(gate.cache_len(), 2);+ // Only cached series reach Redis.+ assert_eq!(rx.try_recv().unwrap().0, gate_key("token-a", 1));+ assert_eq!(rx.try_recv().unwrap().0, gate_key("token-a", 2));+ assert!(rx.try_recv().is_err());++ // A refresh after the window keeps its slot and does not need a new one.+ now.fetch_add(WINDOW.as_secs() as i64, Ordering::SeqCst);+ let mut rows = vec![row(1), row(1)];+ gate.apply("token-a", &mut rows);+ assert_labelled(&rows[0]);+ assert_stripped(&rows[1]);+ assert_eq!(gate.cache_len(), 2);++ // Pruning frees the slots.+ gate.prune(now.load(Ordering::SeqCst));+ assert_eq!(gate.cache_len(), 1);+ let mut rows = vec![row(3), row(3)];+ gate.apply("token-a", &mut rows);+ assert_stripped(&rows[1]);+ assert_eq!(gate.cache_len(), 2);+ }++ #[test]+ fn per_token_cap_does_not_starve_other_tokens() {+ let limits = CacheLimits {+ max_entries_per_token: 1,+ ..NO_LIMITS+ };+ let (gate, now, _) = gate_with_limits(true, false, limits);++ let mut rows = vec![row(1), row(2), row(2)];+ gate.apply("token-a", &mut rows);+ assert_labelled(&rows[2]);++ let mut rows = vec![row(1), row(1)];+ gate.apply("token-b", &mut rows);+ assert_stripped(&rows[1]);+ assert_eq!(gate.cache_len(), 2);++ now.fetch_add(WINDOW.as_secs() as i64, Ordering::SeqCst);+ gate.prune(now.load(Ordering::SeqCst));+ let mut rows = vec![row(2), row(2)];+ gate.apply("token-a", &mut rows);+ assert_stripped(&rows[1]);+ }++ #[tokio::test]+ async fn pull_reads_a_bucket_in_pages_and_merges_each_page() {+ let (gate, _, _) = gate(true, false);+ let mut client = MockRedisClient::new();+ for key in bucket_keys(START - WINDOW.as_secs() as i64, START) {+ client = client.zrangebyscore_ret(&key, vec![]);+ }+ let members: Vec<String> = (1..=5).map(|k| k.to_string()).collect();+ let client = client.zrangebyscore_ret(&bucket_key(START), members);++ let merged = gate+ .pull_pages(+ &client,+ PullKind::Periodic,+ START - 60,+ 2,+ Duration::from_secs(1),+ )+ .await+ .unwrap();+ assert_eq!(merged, 5);+ assert_eq!(gate.cache_len(), 5);++ // 5 members at 2 per page: pages of 2, 2, 1. The short last page ends+ // the walk without an extra empty read.+ let pages = client+ .get_calls()+ .into_iter()+ .filter(|c| c.op == "zrangebyscore_limit" && c.key == bucket_key(START))+ .count();+ assert_eq!(pages, 3);+ }++ #[tokio::test]+ async fn pull_stops_reading_once_the_budget_is_gone() {+ let (gate, _, _) = gate(true, false);+ let mut client = MockRedisClient::new();+ for key in bucket_keys(START - WINDOW.as_secs() as i64, START) {+ client = client.zrangebyscore_ret(&key, vec![]);+ }+ let client = client.zrangebyscore_ret(&bucket_key(START), vec!["1".into(), "2".into()]);++ // A spent budget stops the walk before the next page is requested and+ // reports what was merged so far.+ let result = gate+ .pull_pages(&client, PullKind::Periodic, START - 60, 1, Duration::ZERO)+ .await;+ assert!(matches!(result, Err(PullError::Timeout { merged: 0 })));+ assert_eq!(gate.cache_len(), 0);+ assert!(client.get_calls().is_empty());++ let merged = gate+ .pull_pages(+ &client,+ PullKind::Periodic,+ START - 60,+ 1,+ Duration::from_secs(5),+ )+ .await+ .unwrap();+ assert_eq!(merged, 2);+ }++ #[tokio::test]+ async fn pull_stops_at_the_global_cap() {+ let limits = CacheLimits {+ max_entries: 1,+ ..NO_LIMITS+ };+ let (gate, _, _) = gate_with_limits(true, false, limits);+ let mut client = MockRedisClient::new();+ for key in bucket_keys(START - WINDOW.as_secs() as i64, START) {+ client = client.zrangebyscore_ret(&key, vec![]);+ }+ let client = client.zrangebyscore_ret(&bucket_key(START), vec!["1".into(), "2".into()]);++ let merged = gate+ .pull_from_redis(+ &client,+ PullKind::Periodic,+ START - 60,+ Duration::from_secs(1),+ )+ .await+ .unwrap();+ assert_eq!(merged, 1);+ assert_eq!(gate.cache_len(), 1);+ }++ #[test]+ fn same_fingerprint_under_different_tokens_are_separate_series() {+ let (gate, _, _) = gate(true, false);++ let mut rows = vec![row(7)];+ gate.apply("token-a", &mut rows);+ let mut rows = vec![row(7)];+ gate.apply("token-b", &mut rows);+ assert_labelled(&rows[0]);+ }++ #[test]+ fn disabled_gate_tracks_series_but_leaves_rows_untouched() {+ let (gate, _, _) = gate(false, false);++ let mut rows = vec![row(7), row(7)];+ gate.apply("token-a", &mut rows);+ assert_labelled(&rows[0]);+ assert_labelled(&rows[1]);+ assert_eq!(gate.cache_len(), 1);+ }++ #[test]+ fn new_series_are_queued_for_redis_and_known_series_are_not() {+ let (gate, _, rx) = gate(true, true);+ let mut rx = rx.unwrap();++ let mut rows = vec![row(7), row(7), row(8)];+ gate.apply("token-a", &mut rows);++ let mut queued = Vec::new();+ while let Ok(item) = rx.try_recv() {+ queued.push(item);+ }+ assert_eq!(queued.len(), 2);+ assert!(queued.iter().all(|(_, seen_at)| *seen_at == START));+ }++ #[tokio::test]+ async fn pull_marks_other_pods_series_as_seen_without_overwriting_local_entries() {+ let (gate, now, _) = gate(true, false);+ let local_key = gate_key("token-a", 7);+ let remote_key = gate_key("token-a", 8);++ // The local series was labelled 20 minutes ago; the pull must not+ // reset it to now, or it would go out 20 minutes late.+ let mut rows = vec![row(7)];+ gate.apply("token-a", &mut rows);+ now.fetch_add(1200, Ordering::SeqCst);++ let mut client = MockRedisClient::new();+ for key in bucket_keys(START + 1200 - WINDOW.as_secs() as i64, START + 1200) {+ client = client.zrangebyscore_ret(&key, vec![]);+ }+ let client = client.zrangebyscore_ret(+ &bucket_key(START + 1200),+ vec![local_key.to_string(), remote_key.to_string(), "junk".into()],+ );++ let merged = gate+ .pull_from_redis(&client, PullKind::Periodic, START, Duration::from_secs(1))+ .await+ .unwrap();+ assert_eq!(merged, 1);++ // Seeded within the last quarter window, so it is seen but does not+ // expire in lockstep with the other seeded series.+ let seeded_at = gate.seen_at(remote_key).unwrap();+ let pulled_at = START + 1200;+ assert!(seeded_at <= pulled_at && seeded_at > pulled_at - WINDOW.as_secs() as i64 / 4);++ let mut rows = vec![row(8)];+ gate.apply("token-a", &mut rows);+ assert_stripped(&rows[0]);++ now.fetch_add(600, Ordering::SeqCst);+ let mut rows = vec![row(7)];+ gate.apply("token-a", &mut rows);+ assert_labelled(&rows[0]);+ }++ #[tokio::test]+ async fn pull_failure_leaves_cache_unchanged() {+ let (gate, _, _) = gate(true, false);+ let client = MockRedisClient::new();++ let result = gate+ .pull_from_redis(+ &client,+ PullKind::Periodic,+ START - 60,+ Duration::from_secs(1),+ )+ .await;+ assert!(matches!(result, Err(PullError::Redis(_))));+ assert_eq!(gate.cache_len(), 0);+ }++ #[tokio::test]+ async fn writer_pushes_batches_as_zadd_with_bucket_expiry() {+ let (tx, rx) = mpsc::channel(WRITER_CHANNEL_CAPACITY);+ let client = MockRedisClient::new();+ let shared: Arc<dyn Client> = Arc::new(client.clone());+ spawn_redis_writer(shared, rx, Duration::from_millis(250), WINDOW);++ tx.send((42, START)).await.unwrap();+ tx.send((43, START + 5)).await.unwrap();++ // The writer flushes after WRITER_FLUSH_INTERVAL; poll instead of a fixed sleep.+ let deadline = tokio::time::Instant::now() + WRITER_FLUSH_INTERVAL * 5;+ while client.get_calls().is_empty() && tokio::time::Instant::now() < deadline {+ tokio::time::sleep(Duration::from_millis(50)).await;+ }++ let calls = client.get_calls();+ let zadds: Vec<_> = calls.iter().filter(|c| c.op == "pipeline_zadd").collect();+ assert_eq!(zadds.len(), 2);+ assert_eq!(zadds[0].key, format!("{}:42", bucket_key(START)));+ assert!(matches!(zadds[0].value, MockRedisValue::I64(START)));+ let expires: Vec<_> = calls.iter().filter(|c| c.op == "pipeline_expire").collect();+ assert_eq!(expires.len(), 1);+ assert_eq!(expires[0].key, bucket_key(START));+ }++ #[test]+ fn bucket_keys_cover_the_whole_range() {+ let from = 10 * REDIS_BUCKET_SECS - 1;+ let to = 11 * REDIS_BUCKET_SECS;+ assert_eq!(+ bucket_keys(from, to),+ vec![+ format!("{REDIS_KEY_PREFIX}:9"),+ format!("{REDIS_KEY_PREFIX}:10"),+ format!("{REDIS_KEY_PREFIX}:11"),+ ]+ );+ }+}diff --git a/rust/capture-apm-metrics/src/service.rs b/rust/capture-apm-metrics/src/service.rsnew file mode 100644index 000000000000..683c568b854b--- /dev/null+++ b/rust/capture-apm-metrics/src/service.rs@@ -0,0 +1,189 @@+//! OTLP metrics handler. Copied from `capture_logs::service::export_metrics_http`+//! so the series label gate can run between row building and the Kafka write+//! without a change to capture-logs. Parsing and flattening still come from the+//! capture-logs library.++use std::fs::File;+use std::io::Write;+use std::sync::Arc;++use axum::{+ extract::Query,+ extract::State,+ http::{HeaderMap, StatusCode},+ response::Json,+};+use bytes::Bytes;+use capture_logs::authorizer::{Authorizer, Signal};+use capture_logs::kafka::KafkaSink;+use capture_logs::metric_record::{flatten_metric, KafkaMetricRow};+use capture_logs::service::parse_otel_metrics_message;+use common_compression::{decompress_gzip_capped, has_gzip_magic_header, CompressionError};+use opentelemetry_proto::tonic::collector::metrics::v1::ExportMetricsServiceRequest;+use prost::Message;+use serde::Deserialize;+use serde_json::json;+use tracing::{debug, error, instrument};++use crate::series_label_gate::SeriesLabelGate;++#[derive(Clone)]+pub struct MetricsService {+ pub(crate) sink: KafkaSink,+ pub(crate) authorizer: Authorizer,+ pub(crate) max_request_body_size_bytes: usize,+ pub(crate) series_label_gate: Arc<SeriesLabelGate>,+}++#[derive(Deserialize)]+pub struct QueryParams {+ token: Option<String>,+}++impl MetricsService {+ pub fn new(+ kafka_sink: KafkaSink,+ authorizer: Authorizer,+ max_request_body_size_bytes: usize,+ series_label_gate: Arc<SeriesLabelGate>,+ ) -> Self {+ Self {+ sink: kafka_sink,+ authorizer,+ max_request_body_size_bytes,+ series_label_gate,+ }+ }+}++pub(crate) fn decode_body_if_gzip_magic(+ body: Bytes,+ max_request_body_size_bytes: usize,+) -> Result<Bytes, (StatusCode, Json<serde_json::Value>)> {+ if !has_gzip_magic_header(&body) {+ return Ok(body);+ }++ match decompress_gzip_capped(&body, max_request_body_size_bytes) {+ Ok(decompressed) => Ok(Bytes::from(decompressed)),+ Err(CompressionError::OutputTooLarge {+ decompressed,+ limit,+ }) => Err((+ StatusCode::PAYLOAD_TOO_LARGE,+ Json(json!({+ "error": format!("Decompressed request body exceeds limit ({decompressed} > {limit} bytes)")+ })),+ )),+ Err(e) => Err((+ StatusCode::BAD_REQUEST,+ Json(json!({"error": format!("Failed to decompress gzip request body: {e}")})),+ )),+ }+}++#[instrument(skip_all, fields(+ token = tracing::field::Empty,+ content_type = %headers.get("content-type")+ .and_then(|v| v.to_str().ok())+ .unwrap_or(""),+ user_agent = %headers.get("user-agent")+ .and_then(|v| v.to_str().ok())+ .unwrap_or(""),+ content_length = %headers.get("content-length")+ .and_then(|v| v.to_str().ok())+ .unwrap_or(""),+ content_encoding = %headers.get("content-encoding")+ .and_then(|v| v.to_str().ok())+ .unwrap_or("")))+]+pub async fn export_metrics_http(+ State(service): State<MetricsService>,+ Query(query_params): Query<QueryParams>,+ headers: HeaderMap,+ body: Bytes,+) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {+ let token =+ service+ .authorizer+ .authorize(&headers, query_params.token.as_deref(), Signal::Metrics)?;++ tracing::Span::current().record("token", token);++ let body = decode_body_if_gzip_magic(body, service.max_request_body_size_bytes)?;++ let export_request = match ExportMetricsServiceRequest::decode(body.as_ref()) {+ Ok(request) => request,+ Err(proto_err) => match parse_otel_metrics_message(&body) {+ Ok(request) => request,+ Err(json_err) => {+ if let Err(e) =+ File::create("/tmp/last_failed_metric_event.txt").and_then(|mut file| {+ file.write_all(token.as_bytes())+ .and_then(|_| file.write_all(&body))+ })+ {+ error!("Failed to write last failed metric event to file: {}", e);+ }+ error!(+ "Failed to decode JSON: {} or Protobuf: {}",+ json_err, proto_err+ );+ return Err((+ StatusCode::BAD_REQUEST,+ Json(+ json!({"error": format!("Failed to decode JSON: {} or Protobuf: {}", json_err, proto_err)}),+ ),+ ));+ }+ },+ };++ let mut rows: Vec<KafkaMetricRow> = Vec::new();+ let mut timestamps_overridden: u64 = 0;++ for resource_metrics in &export_request.resource_metrics {+ for scope_metrics in &resource_metrics.scope_metrics {+ for metric in &scope_metrics.metrics {+ let (metric_rows, overridden) = match flatten_metric(+ metric.clone(),+ resource_metrics.resource.as_ref(),+ scope_metrics.scope.as_ref(),+ ) {+ Ok(result) => result,+ Err(e) => {+ error!("Failed to flatten metric: {e}");+ return Err((+ StatusCode::BAD_REQUEST,+ Json(json!({"error": "Bad input format provided"})),+ ));+ }+ };+ timestamps_overridden += overridden;+ rows.extend(metric_rows);+ }+ }+ }++ service.series_label_gate.apply(token, &mut rows);++ let row_count = rows.len();+ if let Err(e) = service+ .sink+ .write_metrics(token, rows, body.len() as u64, timestamps_overridden)+ .await+ {+ error!("Failed to send metrics to Kafka: {}", e);+ return Err((+ StatusCode::INTERNAL_SERVER_ERROR,+ Json(json!({"error": "Internal server error"})),+ ));+ } else {+ debug!(+ "Successfully sent {} metric data points to Kafka",+ row_count+ );+ }++ Ok(Json(json!({})))+}diff --git a/rust/common/redis/src/client.rs b/rust/common/redis/src/client.rsindex 3446c1bae64d..f9aadc19396d 100644--- a/rust/common/redis/src/client.rs+++ b/rust/common/redis/src/client.rs@@ -363,6 +363,19 @@ impl Client for RedisClient {Ok(results)}+ async fn zrangebyscore_limit(+ &self,+ k: String,+ min: String,+ max: String,+ offset: isize,+ count: isize,+ ) -> Result<Vec<String>, CustomRedisError> {+ let mut conn = self.conn();+ let results = conn.zrangebyscore_limit(k, min, max, offset, count).await?;+ Ok(results)+ }+async fn zadd(&self, k: String, member: String, score: i64) -> Result<(), CustomRedisError> {let mut conn = self.conn();conn.zadd::<_, _, _, ()>(k, member, score).await?;@@ -707,6 +720,12 @@ impl Client for RedisClient {PipelineCommand::SAdd { key, member } => {pipe.cmd("SADD").arg(key).arg(member);}+ PipelineCommand::ZAdd { key, members } => {+ let cmd = pipe.cmd("ZADD").arg(key);+ for (score, member) in members {+ cmd.arg(*score).arg(member);+ }+ }PipelineCommand::Expire { key, seconds } => {pipe.cmd("EXPIRE").arg(key).arg(*seconds);}@@ -769,6 +788,7 @@ impl RedisClient {PipelineCommand::Set { .. }| PipelineCommand::SetEx { .. }| PipelineCommand::Del { .. }+ | PipelineCommand::ZAdd { .. }| PipelineCommand::HIncrBy { .. } => Ok(PipelineResult::Ok),PipelineCommand::Expire { .. } => {// EXPIRE returns 1 if the timeout was set, 0 if the key does not existdiff --git a/rust/common/redis/src/lib.rs b/rust/common/redis/src/lib.rsindex 4b5b142f0eba..77658aeb3908 100644--- a/rust/common/redis/src/lib.rs+++ b/rust/common/redis/src/lib.rs@@ -201,6 +201,17 @@ pub trait Client: Send + Sync {max: String,) -> Result<Vec<String>, CustomRedisError>;+ /// `ZRANGEBYSCORE ... LIMIT offset count`: one page of a sorted set, so a+ /// large set can be read without one reply that holds every member.+ async fn zrangebyscore_limit(+ &self,+ k: String,+ min: String,+ max: String,+ offset: isize,+ count: isize,+ ) -> Result<Vec<String>, CustomRedisError>;+/// Add a single (member, score) pair to a sorted set.async fn zadd(&self, k: String, member: String, score: i64) -> Result<(), CustomRedisError>;diff --git a/rust/common/redis/src/mock.rs b/rust/common/redis/src/mock.rsindex 40f2a713cc7f..24c5a7018517 100644--- a/rust/common/redis/src/mock.rs+++ b/rust/common/redis/src/mock.rs@@ -248,6 +248,35 @@ impl Client for MockRedisClient {}}+ /// Pages over the same `zrangebyscore_ret` list, so a test can check how a+ /// caller walks a set.+ async fn zrangebyscore_limit(+ &self,+ key: String,+ min: String,+ max: String,+ offset: isize,+ count: isize,+ ) -> Result<Vec<String>, CustomRedisError> {+ let mut calls = self.lock_calls();+ calls.push(MockRedisCall {+ op: "zrangebyscore_limit".to_string(),+ key: key.clone(),+ value: MockRedisValue::MinMax(min, max),+ });++ let Some(all) = self.zrangebyscore_ret.get(&key) else {+ return Err(CustomRedisError::NotFound);+ };+ let start = usize::try_from(offset).unwrap_or(0).min(all.len());+ let end = if count < 0 {+ all.len()+ } else {+ start.saturating_add(count as usize).min(all.len())+ };+ Ok(all[start..end].to_vec())+ }+async fn zadd(&self, key: String, member: String, score: i64) -> Result<(), CustomRedisError> {let mut calls = self.lock_calls();calls.push(MockRedisCall {@@ -714,6 +743,16 @@ impl MockRedisClient {self.record_call("pipeline_sadd", &key, MockRedisValue::String(member));Self::lookup_or_ok(&self.sadd_ret, &key).map(|_| PipelineResult::Count(1))}+ PipelineCommand::ZAdd { key, members } => {+ for (score, member) in members {+ self.record_call(+ "pipeline_zadd",+ format!("{key}:{member}"),+ MockRedisValue::I64(score),+ );+ }+ Ok(PipelineResult::Ok)+ }PipelineCommand::Expire { key, seconds } => {let ttl_i64 = i64::try_from(seconds).unwrap_or(i64::MAX);self.record_call("pipeline_expire", &key, MockRedisValue::I64(ttl_i64));diff --git a/rust/common/redis/src/pipeline.rs b/rust/common/redis/src/pipeline.rsindex 90e3221be58f..a7d82e8e17d0 100644--- a/rust/common/redis/src/pipeline.rs+++ b/rust/common/redis/src/pipeline.rs@@ -27,7 +27,7 @@ use crate::{Client, CustomRedisError, RedisValueFormat};/// Each variant corresponds to the return type of a Redis command.#[derive(Debug, Clone, PartialEq)]pub enum PipelineResult {- /// Success — return value intentionally discarded (SET, DEL, HINCRBY, SADD, etc.)+ /// Success — return value intentionally discarded (SET, DEL, HINCRBY, ZADD, etc.)Ok,/// String value (GET)String(String),@@ -35,7 +35,7 @@ pub enum PipelineResult {Bytes(Vec<u8>),/// Boolean result (SET NX EX, EXPIRE)Bool(bool),- /// Count result (SCARD)+ /// Count result (SCARD, SADD)Count(u64),/// List of strings (ZRANGEBYSCORE)Strings(Vec<String>),@@ -87,6 +87,11 @@ pub enum PipelineCommand {key: String,member: String,},+ /// One ZADD with every `(score, member)` pair, so a batch is a single command.+ ZAdd {+ key: String,+ members: Vec<(i64, String)>,+ },Expire {key: String,seconds: u64,@@ -253,6 +258,15 @@ impl<C> Pipeline<C> {self}+ /// Add a ZADD command to the pipeline.+ pub fn zadd(mut self, key: impl Into<String>, members: Vec<(i64, String)>) -> Self {+ self.commands.push(PipelineCommand::ZAdd {+ key: key.into(),+ members,+ });+ self+ }+/// Add an EXPIRE command to the pipeline.pub fn expire(mut self, key: impl Into<String>, seconds: u64) -> Self {self.commands.push(PipelineCommand::Expire {diff --git a/rust/common/redis/src/read_write.rs b/rust/common/redis/src/read_write.rsindex 17db25225a6f..703705e8d1a0 100644--- a/rust/common/redis/src/read_write.rs+++ b/rust/common/redis/src/read_write.rs@@ -341,6 +341,33 @@ impl Client for ReadWriteClient {}}+ async fn zrangebyscore_limit(+ &self,+ k: String,+ min: String,+ max: String,+ offset: isize,+ count: isize,+ ) -> Result<Vec<String>, CustomRedisError> {+ match self+ .reader+ .zrangebyscore_limit(k.clone(), min.clone(), max.clone(), offset, count)+ .await+ {+ Ok(value) => Ok(value),+ Err(err) if !err.is_unrecoverable_error() => {+ warn!(+ "Replica zrangebyscore_limit failed for key '{}', falling back to primary: {}",+ k, err+ );+ self.writer+ .zrangebyscore_limit(k, min, max, offset, count)+ .await+ }+ Err(err) => Err(err),+ }+ }+async fn scard(&self, k: String) -> Result<u64, CustomRedisError> {match self.reader.scard(k.clone()).await {Ok(value) => Ok(value),