: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(error-tracking): cap issue-created workflow starts per team (#87055)
Aleksander Błaszkiewicz0271e5685c24
diff --git a/bin/start-rust-service b/bin/start-rust-serviceindex b16f094d4583..4482c586cbfe 100755--- a/bin/start-rust-service+++ b/bin/start-rust-service@@ -186,6 +186,29 @@ case "$RS_SVC" inexport POSTHOG_API_KEY="${CYMBAL_NOTIFICATIONS_POSTHOG_API_KEY:-phc_localposthogprojecttoken}"export POSTHOG_ENDPOINT="${CYMBAL_NOTIFICATIONS_POSTHOG_ENDPOINT:-http://localhost:3307}"export TEMPORAL_HOST="${TEMPORAL_HOST:-temporal}"+ export TEMPORAL_PORT="${TEMPORAL_PORT:-7233}"+ export TEMPORAL_NAMESPACE="${TEMPORAL_NAMESPACE:-default}"+ # posthog/settings/temporal.py collapses every queue onto this one name when+ # DEBUG is set, and the local worker polls only it. Without this the started+ # workflows sit Running with no poller, which Temporal accepts silently.+ export ERROR_TRACKING_LIFECYCLE_TASK_QUEUE="${ERROR_TRACKING_LIFECYCLE_TASK_QUEUE:-development-task-queue}"+ # The local Temporal serves plaintext gRPC. Without this flag an unset+ # TEMPORAL_CLIENT_CERT is a boot failure, which is what production wants.+ export TEMPORAL_INSECURE="${TEMPORAL_INSECURE:-true}"+ # Match Django's Fernet key derivation (posthog/temporal/common/codec.py,+ # _resize_key): left-pad a short SECRET_KEY with NUL bytes to 32, so the+ # Python workers can decrypt the payloads this service writes.+ if [ -z "${TEMPORAL_SECRET_KEY:-}" ]; then+ TEMPORAL_SECRET_KEY="base64:$(+ POSTHOG_SECRET_KEY="${SECRET_KEY:-<randomly generated secret key>}" python3 -c \+ 'import base64, os; k = os.environ["POSTHOG_SECRET_KEY"].encode(); print(base64.b64encode((b"\0" * max(32 - len(k), 0) + k)[:32]).decode())'+ )"+ fi+ export TEMPORAL_SECRET_KEY+ # Setting the Redis URL is what turns the limiter on. The cap matches the+ # production default; lower it to exercise the limit itself.+ export ERROR_TRACKING_NOTIFICATIONS_RATE_LIMIT_REDIS_URL="${ERROR_TRACKING_NOTIFICATIONS_RATE_LIMIT_REDIS_URL:-$DEFAULT_REDIS}"+ export ERROR_TRACKING_NOTIFICATIONS_RATE_LIMIT_PER_HOUR="${ERROR_TRACKING_NOTIFICATIONS_RATE_LIMIT_PER_HOUR:-1000}";;embedding-worker)diff --git a/rust/common/redis/src/client.rs b/rust/common/redis/src/client.rsindex 75b283a52e69..3446c1bae64d 100644--- a/rust/common/redis/src/client.rs+++ b/rust/common/redis/src/client.rs@@ -313,6 +313,39 @@ impl RedisClient {}}+/// Run a Lua script and decode its integer-array reply. Behind a trait so callers+/// can be unit-tested against an in-memory fake, including a failing one that+/// proves a limiter fails open.+#[async_trait]+pub trait ScriptRunner: Send + Sync {+ async fn eval_int_vec(+ &self,+ script: &str,+ keys: Vec<String>,+ args: Vec<String>,+ ) -> Result<Vec<i64>, CustomRedisError>;++ /// Rebuild the underlying connection after a connection-class failure; see+ /// [`Client::heal`]. The default no-op keeps test fakes trivial.+ async fn heal(&self) {}+}++#[async_trait]+impl ScriptRunner for RedisClient {+ async fn eval_int_vec(+ &self,+ script: &str,+ keys: Vec<String>,+ args: Vec<String>,+ ) -> Result<Vec<i64>, CustomRedisError> {+ RedisClient::eval_int_vec(self, script, keys, args).await+ }++ async fn heal(&self) {+ self.heal_connection().await;+ }+}+#[async_trait]impl Client for RedisClient {async fn heal(&self) {@@ -1292,7 +1325,7 @@ mod integration_tests {}assert!(ready, "redis container never came back");- healed_client.heal().await;+ Client::heal(&healed_client).await;assert!(healed_client.set("k".to_string(), "v".to_string()).awaitdiff --git a/rust/common/redis/src/lib.rs b/rust/common/redis/src/lib.rsindex a1867aec9748..4b5b142f0eba 100644--- a/rust/common/redis/src/lib.rs+++ b/rust/common/redis/src/lib.rs@@ -337,7 +337,7 @@ mod pipeline;mod read_write;// Re-export public APIs-pub use client::RedisClient;+pub use client::{RedisClient, ScriptRunner};pub use mock::{MockRedisCall, MockRedisClient, MockRedisValue};pub use read_write::{ReadWriteClient, ReadWriteClientConfig};diff --git a/rust/common/temporal/src/lib.rs b/rust/common/temporal/src/lib.rsindex 7ef1787cb5ef..7ad70ccb1bd9 100644--- a/rust/common/temporal/src/lib.rs+++ b/rust/common/temporal/src/lib.rs@@ -36,6 +36,43 @@ pub struct TemporalClientConfig {pub server_root_ca_cert: Option<String>,pub payload_encryption_key: String,pub identity: String,+ /// Connect without TLS. Only the local dev stack serves plaintext gRPC.+ pub insecure: bool,+}++impl TemporalClientConfig {+ /// mTLS settings, or `None` when the caller asked for a plaintext connection.+ ///+ /// A missing certificate is an error rather than an implicit downgrade, so a+ /// credential mount that renders empty fails at boot instead of dropping TLS+ /// silently. The local dev stack serves plaintext gRPC and sets `insecure`.+ fn tls_options(&self) -> Result<Option<TlsOptions>, TemporalClientError> {+ if self.insecure {+ if !self.client_cert.is_empty() || !self.client_key.is_empty() {+ return Err(TemporalClientError::ConflictingConfig(+ "TEMPORAL_INSECURE is set alongside a client certificate",+ ));+ }+ return Ok(None);+ }++ require_config("TEMPORAL_CLIENT_CERT", &self.client_cert)?;+ require_config("TEMPORAL_CLIENT_KEY", &self.client_key)?;++ Ok(Some(TlsOptions {+ server_root_ca_cert: self+ .server_root_ca_cert+ .as_ref()+ .filter(|value| !value.is_empty())+ .map(|value| value.as_bytes().to_vec()),+ domain: Some(self.host.clone()),+ client_tls_options: Some(ClientTlsOptions {+ client_cert: self.client_cert.as_bytes().to_vec(),+ client_private_key: self.client_key.as_bytes().to_vec(),+ }),+ server_cert_verifier: None,+ }))+ }}/// Options that identify and route one workflow execution.@@ -85,6 +122,8 @@ pub enum StartWorkflowOutcome {pub enum TemporalClientError {#[error("missing Temporal client configuration: {0}")]MissingConfig(&'static str),+ #[error("conflicting Temporal client configuration: {0}")]+ ConflictingConfig(&'static str),#[error("invalid Temporal target: {0}")]InvalidTarget(#[from] url::ParseError),#[error("invalid Temporal payload encryption key: {0}")]@@ -114,29 +153,24 @@ impl TemporalWorkflowClient {pub async fn connect(config: TemporalClientConfig) -> Result<Self, TemporalClientError> {require_config("TEMPORAL_HOST", &config.host)?;require_config("TEMPORAL_NAMESPACE", &config.namespace)?;- require_config("TEMPORAL_CLIENT_CERT", &config.client_cert)?;- require_config("TEMPORAL_CLIENT_KEY", &config.client_key)?;require_config("TEMPORAL_SECRET_KEY", &config.payload_encryption_key)?;require_config("identity", &config.identity)?;- let target = url::Url::parse(&format!("https://{}:{}", config.host, config.port))?;- let tls_options = TlsOptions {- server_root_ca_cert: config- .server_root_ca_cert- .as_ref()- .filter(|value| !value.is_empty())- .map(|value| value.as_bytes().to_vec()),- domain: Some(config.host.clone()),- client_tls_options: Some(ClientTlsOptions {- client_cert: config.client_cert.as_bytes().to_vec(),- client_private_key: config.client_key.as_bytes().to_vec(),- }),- server_cert_verifier: None,+ let tls = config.tls_options()?;+ let scheme = if tls.is_some() { "https" } else { "http" };+ let target = url::Url::parse(&format!("{scheme}://{}:{}", config.host, config.port))?;++ // The builder is typestate-based, so `tls_options` changes its type and the+ // two arms cannot share one binding.+ let connection_options = match tls {+ Some(tls) => ConnectionOptions::new(target)+ .identity(config.identity.clone())+ .tls_options(tls)+ .build(),+ None => ConnectionOptions::new(target)+ .identity(config.identity.clone())+ .build(),};- let connection_options = ConnectionOptions::new(target)- .identity(config.identity.clone())- .tls_options(tls_options)- .build();let connection = Connection::connect(connection_options).await?;let client = Client::new(connection, ClientOptions::new(config.namespace).build())?;@@ -317,6 +351,52 @@ mod tests {name: &'a str,}+ fn config(client_cert: &str, client_key: &str, insecure: bool) -> TemporalClientConfig {+ TemporalClientConfig {+ host: "temporal".to_string(),+ port: 7233,+ namespace: "default".to_string(),+ client_cert: client_cert.to_string(),+ client_key: client_key.to_string(),+ server_root_ca_cert: None,+ payload_encryption_key: "key".to_string(),+ identity: "test".to_string(),+ insecure,+ }+ }++ #[test]+ fn tls_is_required_unless_the_caller_asked_for_plaintext() {+ assert!(config("cert", "key", false)+ .tls_options()+ .unwrap()+ .is_some());+ assert!(config("", "", true).tls_options().unwrap().is_none());++ // An empty credential must fail closed. A secret that renders empty is+ // the case this protects: without it, TLS would be dropped silently.+ for (cert, key, missing) in [+ ("", "", "TEMPORAL_CLIENT_CERT"),+ ("cert", "", "TEMPORAL_CLIENT_KEY"),+ ("", "key", "TEMPORAL_CLIENT_CERT"),+ ] {+ let error = config(cert, key, false).tls_options().unwrap_err();+ assert!(+ matches!(error, TemporalClientError::MissingConfig(name) if name == missing),+ "expected {missing}, got {error}"+ );+ }+ }++ #[test]+ fn plaintext_alongside_a_certificate_is_rejected() {+ let error = config("cert", "key", true).tls_options().unwrap_err();+ assert!(+ matches!(error, TemporalClientError::ConflictingConfig(_)),+ "expected a conflict, got {error}"+ );+ }+fn options() -> StartWorkflowOptions {StartWorkflowOptions::idempotent("python-workflow",diff --git a/rust/cymbal/README.md b/rust/cymbal/README.mdindex ff54e8014951..a781ead218e5 100644--- a/rust/cymbal/README.md+++ b/rust/cymbal/README.md@@ -9,7 +9,66 @@ pipeline, the `cymbal.resolution.v1` gRPC symbol-resolution service(`CYMBAL_MODE=resolution`), or the Kafka notification consumer(`CYMBAL_MODE=notifications`). The notification consumer starts the matchingTemporal lifecycle workflow for every issue-created, issue-reopened, or-issue-spiking notification.+issue-spiking notification. Issue-created is capped per team per hour (see+[Issue-created rate limit](#issue-created-rate-limit-notifications-mode)).++## Issue-created rate limit (notifications mode)++Notifications mode caps issue-created workflow starts per team. One Redis token+bucket per team, so a team that exhausts it gets no issue-created workflow, and+therefore no embedding and no alert for new issues, until the bucket refills.++The setting is both the bucket size and the hourly refill. A team that sits idle,+spends the full bucket, then waits out the refill, gets up to twice the setting+inside one rolling hour. The sustained rate is the setting. Size Temporal worker+and embedding capacity against the peak rather than the sustained rate.++Only issue-created is charged. It is the one notification type with no ceiling of+its own, because a high-cardinality fingerprint mints issues as fast as a team+sends events. Reopens need somebody to have resolved the issue first, and spikes+already carry a per-issue Redis cooldown. Issue-created is also the only type+that runs an embedding. A throttled team therefore keeps its reopen and spike+alerts.++The gate sits in the consumer rather than in processing mode, because the+consumer is what starts the workflows. The Kafka payload carries no decision, so+a replayed notification is judged the same way every time. `start_workflow` is+idempotent on the workflow id, so a replay starts nothing, and the token it+charged is credited back. `cymbal_issue_created_rate_limit_refunds` counts those+credits, under an `error` label when the credit itself failed and the team kept+the charge.++A Redis failure while the consumer is running fails open: the notification is+admitted and `cymbal_issue_created_rate_limit_fail_open` goes up, because a+limiter outage must not silence alerts. A Redis that is configured but+unreachable at startup is fatal instead, so a pod cannot come up and quietly run+without the limit it was told to enforce.++The variables are prefixed by the service, while the metrics and the Redis key+are named for what is actually capped. Only issue-created is charged.++| Variable | Default | Effect |+| --- | --- | --- |+| `ERROR_TRACKING_NOTIFICATIONS_RATE_LIMIT_REDIS_URL` | none | Required. The service does not start without it. |+| `ERROR_TRACKING_NOTIFICATIONS_RATE_LIMIT_PER_HOUR` | `1000` | Bucket size, and the tokens a team earns back per hour. Zero or less disables the limit. |+| `ERROR_TRACKING_NOTIFICATIONS_RATE_LIMIT_KEY_PREFIX` | `@posthog/error-tracking-notifications-rate-limiter` | Key namespace. It must differ from the event limiter's prefix. |+| `ERROR_TRACKING_NOTIFICATIONS_RATE_LIMIT_BUCKET_TTL_SECONDS` | `3600` | Idle buckets expire and free the memory. A value below 3600 is raised to 3600, because a bucket takes an hour to refill and a shorter TTL would loosen the limit. |++The limit covers every team. To size it before it cuts anything, set `PER_HOUR`+far above real traffic, watch `cymbal_issue_created_rate_limit_outcomes`, then+lower it. Setting `PER_HOUR` to zero or less switches the limit off.++Set the Redis URL in every environment before this ships. It carries no default,+so a pod without it fails to start.++That counter carries an `outcome` label of `admitted` or `limited`, never both,+so the two series sum to the notifications the limiter judged.++The bucket lives in+[`src/modes/notifications/token_bucket.rs`](src/modes/notifications/token_bucket.rs).+It is deliberately separate from the per-event limiter in processing mode, which+runs at event volume and charges a variable number of tokens against two fused+keys.Symbol resolution runs in resolution-mode pods via the`cymbal.resolution.v1` contract. Processing has no inline fallback.diff --git a/rust/cymbal/src/core/metric_consts.rs b/rust/cymbal/src/core/metric_consts.rsindex d70a7a2c7142..9ffffa6c1675 100644--- a/rust/cymbal/src/core/metric_consts.rs+++ b/rust/cymbal/src/core/metric_consts.rs@@ -172,3 +172,12 @@ pub const REMOTE_RESOLUTION_OVERLOAD_ESCALATIONS: &str =pub const REMOTE_RESOLUTION_REROUTE_DEPTH: &str = "cymbal_remote_resolution_reroute_depth";pub const REMOTE_RESOLUTION_LOAD_SUBSCRIPTIONS: &str ="cymbal_remote_resolution_load_subscriptions_total";++// `outcome` is either `admitted` or `limited` and never both, so the two series+// sum to the notifications the limiter judged.+pub const ISSUE_CREATED_RATE_LIMIT_OUTCOMES: &str = "cymbal_issue_created_rate_limit_outcomes";+pub const ISSUE_CREATED_RATE_LIMIT_FAIL_OPEN: &str = "cymbal_issue_created_rate_limit_fail_open";+// Tokens handed back after a charge that started no workflow, labeled `refunded`+// or `error`. Kept off the `outcomes` counter, because a refund is not a+// judgment on a notification and would break that counter's two-series sum.+pub const ISSUE_CREATED_RATE_LIMIT_REFUNDS: &str = "cymbal_issue_created_rate_limit_refunds";diff --git a/rust/cymbal/src/lib.rs b/rust/cymbal/src/lib.rsindex b81adac76c38..d895a152056d 100644--- a/rust/cymbal/src/lib.rs+++ b/rust/cymbal/src/lib.rs@@ -1,5 +1,8 @@pub mod core;pub mod modes;++#[cfg(test)]+mod test_support;// Compat re-exports: the shared kernel physically lives under `core/`, but much// of the crate still imports it by the old crate-root paths. Prefer// `crate::core::*` in new code.diff --git a/rust/cymbal/src/modes/notifications/analytics.rs b/rust/cymbal/src/modes/notifications/analytics.rsindex cede6dc30be3..17c6dd018e2b 100644--- a/rust/cymbal/src/modes/notifications/analytics.rs+++ b/rust/cymbal/src/modes/notifications/analytics.rs@@ -6,13 +6,21 @@ use crate::core::analytics::capture_event;const ISSUE_CREATED: &str = "error_tracking_issue_created";const ISSUE_REOPENED: &str = "error_tracking_issue_reopened";-pub fn capture_issue_created(team_id: i32, issue_id: Uuid, sentry_integration: bool) {+pub fn capture_issue_created(+ team_id: i32,+ issue_id: Uuid,+ sentry_integration: bool,+ workflow_rate_limited: bool,+) {let mut event = Event::new_anon(ISSUE_CREATED);event.insert_prop("team_id", team_id).unwrap();event.insert_prop("issue_id", issue_id.to_string()).unwrap();event.insert_prop("sentry_integration", sentry_integration).unwrap();+ event+ .insert_prop("workflow_rate_limited", workflow_rate_limited)+ .unwrap();capture_event(event);}diff --git a/rust/cymbal/src/modes/notifications/config.rs b/rust/cymbal/src/modes/notifications/config.rsindex 01f5a5201524..70ca2c4bb9ba 100644--- a/rust/cymbal/src/modes/notifications/config.rs+++ b/rust/cymbal/src/modes/notifications/config.rs@@ -46,6 +46,11 @@ pub struct NotificationsConfig {#[envconfig(from = "TEMPORAL_CLIENT_KEY", default = "")]pub temporal_client_key: String,+ /// Connect to Temporal without TLS. Only the local dev stack serves plaintext+ /// gRPC, so leaving this off keeps a missing certificate a boot failure.+ #[envconfig(from = "TEMPORAL_INSECURE", default = "false")]+ pub temporal_insecure: bool,+#[envconfig(from = "TEMPORAL_SECRET_KEY", default = "")]pub temporal_secret_key: String,@@ -54,6 +59,40 @@ pub struct NotificationsConfig {default = "error-tracking-lifecycle-task-queue")]pub error_tracking_lifecycle_task_queue: String,++ /// Redis backing the per-team cap on issue-created workflows. It carries no+ /// default, so envconfig rejects a boot that does not set it.+ #[envconfig(from = "ERROR_TRACKING_NOTIFICATIONS_RATE_LIMIT_REDIS_URL")]+ pub notifications_rate_limit_redis_url: String,++ /// Bucket size, and the tokens a team earns back per hour. Zero or less+ /// disables the limit.+ #[envconfig(+ from = "ERROR_TRACKING_NOTIFICATIONS_RATE_LIMIT_PER_HOUR",+ default = "1000"+ )]+ pub notifications_rate_limit_per_hour: i64,++ #[envconfig(+ from = "ERROR_TRACKING_NOTIFICATIONS_RATE_LIMIT_KEY_PREFIX",+ default = "@posthog/error-tracking-notifications-rate-limiter"+ )]+ pub notifications_rate_limit_key_prefix: String,++ /// Idle buckets expire after this long. A bucket always takes an hour to+ /// refill, so anything below 3600 is raised to 3600: a shorter TTL would+ /// drop a partly refilled bucket and hand the next caller a full one.+ #[envconfig(+ from = "ERROR_TRACKING_NOTIFICATIONS_RATE_LIMIT_BUCKET_TTL_SECONDS",+ default = "3600"+ )]+ pub notifications_rate_limit_bucket_ttl_seconds: u64,++ #[envconfig(default = "100")]+ pub redis_response_timeout_ms: u64,++ #[envconfig(default = "5000")]+ pub redis_connection_timeout_ms: u64,}impl NotificationsConfig {diff --git a/rust/cymbal/src/modes/notifications/context.rs b/rust/cymbal/src/modes/notifications/context.rsindex 73351506b640..c781f75afcd5 100644--- a/rust/cymbal/src/modes/notifications/context.rs+++ b/rust/cymbal/src/modes/notifications/context.rs@@ -1,10 +1,14 @@+use std::sync::Arc;+use crate::core::error::UnhandledError;use crate::modes::notifications::config::NotificationsConfig;+use crate::modes::notifications::rate_limit::IssueCreatedRateLimiter;use crate::modes::notifications::temporal::IssueLifecycleWorkflowStarters;#[derive(Clone)]pub struct NotificationsContext {pub issue_lifecycle_workflow_starters: IssueLifecycleWorkflowStarters,+ pub issue_created_limiter: Arc<IssueCreatedRateLimiter>,}impl NotificationsContext {@@ -12,6 +16,7 @@ impl NotificationsContext {Ok(Self {issue_lifecycle_workflow_starters: IssueLifecycleWorkflowStarters::from_config(config).await?,+ issue_created_limiter: Arc::new(IssueCreatedRateLimiter::from_config(config).await?),})}}diff --git a/rust/cymbal/src/modes/notifications/issue_handler.rs b/rust/cymbal/src/modes/notifications/issue_handler.rsindex 203ebdf6fc0b..3b4d78387e8b 100644--- a/rust/cymbal/src/modes/notifications/issue_handler.rs+++ b/rust/cymbal/src/modes/notifications/issue_handler.rs@@ -1,3 +1,5 @@+use common_temporal::StartWorkflowOutcome;+use crate::core::{error::UnhandledError,types::notification::{IssueCreated, IssueReopened, IssueSpiking},@@ -9,21 +11,34 @@ pub async fn handle_issue_created(context: &NotificationsContext,notification: IssueCreated,) -> Result<(), UnhandledError> {- context- .issue_lifecycle_workflow_starters- .start_created(¬ification)- .await?;-+ let team_id = notification.meta.team_id;+ let issue_id = notification.issue.issue_id;let sentry_integration = notification.issue.event_properties.properties().contains_key("$sentry_event_id");- capture_issue_created(- notification.meta.team_id,- notification.issue.issue_id,- sentry_integration,- );++ if !context.issue_created_limiter.admit(team_id).await {+ // The issue was still created, so it still counts. Only the workflow,+ // and with it the embedding and the alert, was cut.+ capture_issue_created(team_id, issue_id, sentry_integration, true);+ return Ok(());+ }++ let outcome = context+ .issue_lifecycle_workflow_starters+ .start_created(¬ification)+ .await?;++ // A replayed notification carries the same workflow id, so this start bought+ // nothing. Hand the token back rather than let redelivery spend the team's+ // budget on work Temporal is already doing.+ if matches!(outcome, StartWorkflowOutcome::Existing { .. }) {+ context.issue_created_limiter.refund(team_id).await;+ }++ capture_issue_created(team_id, issue_id, sentry_integration, false);Ok(())}diff --git a/rust/cymbal/src/modes/notifications/mod.rs b/rust/cymbal/src/modes/notifications/mod.rsindex 2c15503abc46..c56e5579d763 100644--- a/rust/cymbal/src/modes/notifications/mod.rs+++ b/rust/cymbal/src/modes/notifications/mod.rs@@ -22,7 +22,9 @@ mod consumer_loop;mod context;mod handler;mod issue_handler;+pub mod rate_limit;pub mod temporal;+mod token_bucket;pub use config::NotificationsConfig;diff --git a/rust/cymbal/src/modes/notifications/rate_limit.rs b/rust/cymbal/src/modes/notifications/rate_limit.rsnew file mode 100644index 000000000000..37bd27ca9a72--- /dev/null+++ b/rust/cymbal/src/modes/notifications/rate_limit.rs@@ -0,0 +1,161 @@+//! Per-team cap on issue-created workflow starts.+//!+//! Only issue-created is charged, because it is the only notification type with+//! no ceiling of its own: reopens need somebody to have resolved the issue first,+//! and spikes carry a per-issue Redis cooldown. It is also the only type that+//! runs an embedding.++use std::sync::Arc;++use common_redis::RedisClient;+use tracing::{info, warn};++use crate::core::error::UnhandledError;+use crate::core::metric_consts::{+ ISSUE_CREATED_RATE_LIMIT_FAIL_OPEN, ISSUE_CREATED_RATE_LIMIT_OUTCOMES,+ ISSUE_CREATED_RATE_LIMIT_REFUNDS,+};+use crate::modes::notifications::config::NotificationsConfig;+use crate::modes::notifications::token_bucket::TokenBucket;+use crate::modes::processing::redis_heal::is_connection_error;++pub struct IssueCreatedRateLimiter {+ /// `None` disables the limit: every notification is admitted.+ bucket: Option<TokenBucket>,+}++impl IssueCreatedRateLimiter {+ pub async fn from_config(config: &NotificationsConfig) -> Result<Self, UnhandledError> {+ if config.notifications_rate_limit_per_hour <= 0 {+ info!("Error-tracking issue-created rate limiter disabled: limit is zero or less");+ return Ok(Self { bucket: None });+ }++ // Fatal on purpose: a pod that cannot reach the Redis it was told to use+ // must not come up and run without the limit. Runtime failures differ,+ // because `admit` fails open rather than silence a serving pod's alerts.+ let client = RedisClient::with_config(+ config.notifications_rate_limit_redis_url.clone(),+ common_redis::CompressionConfig::disabled(),+ common_redis::RedisValueFormat::Utf8,+ optional_millis(config.redis_response_timeout_ms),+ optional_millis(config.redis_connection_timeout_ms),+ )+ .await?;++ info!(+ per_hour = config.notifications_rate_limit_per_hour,+ "Error-tracking issue-created rate limiter enabled for all teams",+ );++ Ok(Self {+ bucket: Some(TokenBucket::per_hour(+ Arc::new(client),+ config.notifications_rate_limit_key_prefix.clone(),+ config.notifications_rate_limit_per_hour as f64,+ config.notifications_rate_limit_bucket_ttl_seconds,+ )),+ })+ }++ /// Charge one token. `false` means the team is out of budget, so the+ /// notification starts no workflow. A Redis failure admits, because a limiter+ /// outage must not silence alerts.+ pub async fn admit(&self, team_id: i32) -> bool {+ let Some(bucket) = self.bucket.as_ref() else {+ return true;+ };++ match bucket.charge(team_id).await {+ Ok(true) => {+ record("admitted");+ true+ }+ Ok(false) => {+ record("limited");+ false+ }+ Err(e) => {+ // Without this, one Redis failover leaves this pod admitting+ // everything for its whole lifetime, which is the state+ // `from_config` refuses to boot into.+ if is_connection_error(&e) {+ bucket.spawn_heal();+ }+ warn!("issue-created rate limiter failed open for team {team_id}: {e}");+ metrics::counter!(ISSUE_CREATED_RATE_LIMIT_FAIL_OPEN).increment(1);+ true+ }+ }+ }++ /// Hand back a token charged for a workflow that turned out to be already+ /// running, so a Kafka replay does not spend a team's budget twice. Best+ /// effort: a failed refund costs the team one token and is not retried,+ /// because a retry risks crediting twice. A refund that follows a+ /// failed-open charge credits a token that was never spent, which the bucket+ /// size caps and which errs the way the rest of the limiter already does.+ pub async fn refund(&self, team_id: i32) {+ let Some(bucket) = self.bucket.as_ref() else {+ return;+ };++ match bucket.refund(team_id).await {+ Ok(()) => record_refund("refunded"),+ Err(e) => {+ if is_connection_error(&e) {+ bucket.spawn_heal();+ }+ warn!("issue-created rate limiter could not refund team {team_id}: {e}");+ record_refund("error");+ }+ }+ }+}++fn record(outcome: &'static str) {+ metrics::counter!(ISSUE_CREATED_RATE_LIMIT_OUTCOMES, "outcome" => outcome).increment(1);+}++fn record_refund(outcome: &'static str) {+ metrics::counter!(ISSUE_CREATED_RATE_LIMIT_REFUNDS, "outcome" => outcome).increment(1);+}++fn optional_millis(millis: u64) -> Option<std::time::Duration> {+ (millis > 0).then(|| std::time::Duration::from_millis(millis))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::test_support::FakeRunner;++ fn limiter_with(runner: Arc<FakeRunner>) -> IssueCreatedRateLimiter {+ IssueCreatedRateLimiter {+ bucket: Some(TokenBucket::per_hour(+ runner,+ "test".to_string(),+ 1000.0,+ 3600,+ )),+ }+ }++ #[tokio::test]+ async fn a_denied_charge_limits_the_notification() {+ let limiter = limiter_with(FakeRunner::returning(vec![0]));+ assert!(!limiter.admit(42).await);+ }++ #[tokio::test]+ async fn a_redis_error_fails_open() {+ let limiter = limiter_with(FakeRunner::failing());+ assert!(limiter.admit(42).await);+ }++ #[tokio::test]+ async fn a_disabled_limiter_admits_everything() {+ let limiter = IssueCreatedRateLimiter { bucket: None };+ assert!(limiter.admit(42).await);+ }+}diff --git a/rust/cymbal/src/modes/notifications/temporal.rs b/rust/cymbal/src/modes/notifications/temporal.rsindex d089196a3c10..794c41dbb32c 100644--- a/rust/cymbal/src/modes/notifications/temporal.rs+++ b/rust/cymbal/src/modes/notifications/temporal.rs@@ -48,6 +48,7 @@ impl IssueLifecycleWorkflowStarters {server_root_ca_cert: None,payload_encryption_key: config.temporal_secret_key.clone(),identity: "cymbal-notifications".to_string(),+ insecure: config.temporal_insecure,}).await.map_err(|error| UnhandledError::Other(error.to_string()))?;@@ -58,7 +59,12 @@ impl IssueLifecycleWorkflowStarters {})}- pub async fn start_created(&self, notification: &IssueCreated) -> Result<(), UnhandledError> {+ /// Returns the outcome, because the caller charged a rate-limit token for+ /// this start and gives it back when the workflow was already running.+ pub async fn start_created(+ &self,+ notification: &IssueCreated,+ ) -> Result<StartWorkflowOutcome, UnhandledError> {self.start(notification.meta.notification_id,&IssueCreatedWorkflowInput::from(notification),@@ -74,6 +80,7 @@ impl IssueLifecycleWorkflowStarters {ISSUE_REOPENED_WORKFLOW,).await+ .map(|_outcome| ())}pub async fn start_spiking(&self, notification: &IssueSpiking) -> Result<(), UnhandledError> {@@ -83,6 +90,7 @@ impl IssueLifecycleWorkflowStarters {ISSUE_SPIKING_WORKFLOW,).await+ .map(|_outcome| ())}async fn start<T: Serialize>(@@ -90,17 +98,17 @@ impl IssueLifecycleWorkflowStarters {notification_id: Uuid,input: &T,workflow: WorkflowDefinition,- ) -> Result<(), UnhandledError> {+ ) -> Result<StartWorkflowOutcome, UnhandledError> {let options = start_options(notification_id, &self.task_queue, workflow);match self.client.start_workflow(input, &options).await {- Ok(StartWorkflowOutcome::Started { .. }) => {+ Ok(outcome @ StartWorkflowOutcome::Started { .. }) => {metrics::counter!(workflow.starts_metric, "outcome" => "started").increment(1);- Ok(())+ Ok(outcome)}- Ok(StartWorkflowOutcome::Existing { .. }) => {+ Ok(outcome @ StartWorkflowOutcome::Existing { .. }) => {metrics::counter!(workflow.starts_metric, "outcome" => "already_started").increment(1);- Ok(())+ Ok(outcome)}Err(error) => {metrics::counter!(workflow.starts_metric, "outcome" => "error").increment(1);diff --git a/rust/cymbal/src/modes/notifications/token_bucket.rs b/rust/cymbal/src/modes/notifications/token_bucket.rsnew file mode 100644index 000000000000..e6de6658c72e--- /dev/null+++ b/rust/cymbal/src/modes/notifications/token_bucket.rs@@ -0,0 +1,217 @@+//! The per-team token bucket behind the issue-created rate limit.+//!+//! The Lua is deliberately not shared with the per-event limiter in+//! [`crate::modes::processing::stages::rate_limiting`], because sharing would move+//! that script's SHA and put a load-bearing ingestion path in reach of a change+//! made for this one.++use std::sync::Arc;++use chrono::Utc;+use common_redis::{CustomRedisError, ScriptRunner};+use tracing::warn;++use crate::modes::processing::redis_heal::HealGate;++const SECONDS_PER_HOUR: f64 = 3600.0;++/// Spend one token. Returns 1 when the bucket paid, 0 when it was empty. An empty+/// bucket still writes back its refill, so the next call does not recompute the+/// same elapsed window.+const CHARGE_SCRIPT: &str = r#"+local key = KEYS[1]+local max, rate, ttl, now = tonumber(ARGV[1]), tonumber(ARGV[2]), tonumber(ARGV[3]), tonumber(ARGV[4])++local cur = redis.call('hmget', key, 'ts', 'pool')+local tokens, ts+if cur[1] == false then+ tokens, ts = max, now+else+ local stored_ts = tonumber(cur[1])+ local elapsed = now - stored_ts+ if elapsed < 0 then elapsed = 0 end++ tokens = tonumber(cur[2]) + elapsed * rate+ if tokens > max then tokens = max end++ -- Never move `ts` backwards. `now` is the calling pod's wall clock, so a lagging+ -- pod would inflate `elapsed` on the next forward call and over-refill.+ ts = now+ if now < stored_ts then ts = stored_ts end+end++local admitted = 0+if tokens >= 1 then+ admitted = 1+ tokens = tokens - 1+end++redis.call('hset', key, 'ts', ts, 'pool', tokens)+redis.call('expire', key, ttl)+return { admitted }+"#;++/// Put one token back. Returns 1 when the bucket took it, 0 when there was no+/// bucket to credit.+const REFUND_SCRIPT: &str = r#"+local key = KEYS[1]+local max, ttl = tonumber(ARGV[1]), tonumber(ARGV[2])++-- A missing bucket is already a full one, so there is nothing to credit and no+-- reason to allocate a key.+local pool = redis.call('hget', key, 'pool')+if pool == false then return { 0 } end++local tokens = tonumber(pool) + 1+if tokens > max then tokens = max end++-- `ts` is left where it is. The charge script refills from it, so the window+-- since the last charge survives this write.+redis.call('hset', key, 'pool', tokens)+redis.call('expire', key, ttl)+return { 1 }+"#;++pub struct TokenBucket {+ redis: Arc<dyn ScriptRunner>,+ key_prefix: String,+ max: f64,+ rate: f64,+ ttl_seconds: u64,+ heal_gate: HealGate,+}++impl TokenBucket {+ /// A bucket that bursts to `per_hour` and sustains the same rate. `max /+ /// rate` is therefore always one hour, and `ttl_seconds` is raised to match:+ /// a shorter TTL drops a partly refilled bucket and hands the next caller a+ /// full one, which loosens the very limit the operator was tuning.+ pub fn per_hour(+ redis: Arc<dyn ScriptRunner>,+ key_prefix: String,+ per_hour: f64,+ ttl_seconds: u64,+ ) -> Self {+ let refill_window_seconds = SECONDS_PER_HOUR as u64;+ if ttl_seconds < refill_window_seconds {+ warn!(+ requested = ttl_seconds,+ using = refill_window_seconds,+ "issue-created bucket TTL raised to the refill window",+ );+ }++ Self {+ redis,+ key_prefix,+ max: per_hour,+ rate: per_hour / SECONDS_PER_HOUR,+ ttl_seconds: ttl_seconds.max(refill_window_seconds),+ heal_gate: HealGate::new(),+ }+ }++ /// Kick a background heal of the bucket's Redis connection, for a caller+ /// that saw a connection-class error. `MultiplexedConnection` never+ /// reconnects on its own, so without this one failover leaves the limiter+ /// admitting everything until the pod restarts. Never blocks the caller.+ pub fn spawn_heal(&self) {+ let redis = self.redis.clone();+ self.heal_gate.spawn_heal(async move { redis.heal().await });+ }++ /// Spend one of the team's tokens. `false` means the team is out of budget.+ pub async fn charge(&self, team_id: i32) -> Result<bool, CustomRedisError> {+ let args = vec![+ self.max.to_string(),+ self.rate.to_string(),+ self.ttl_seconds.to_string(),+ Utc::now().timestamp().to_string(),+ ];+ let res = self+ .redis+ .eval_int_vec(CHARGE_SCRIPT, vec![self.key(team_id)], args)+ .await?;+ Ok(res.first().copied().unwrap_or(0) > 0)+ }++ /// Give one token back, for a charge that bought nothing. A bucket that has+ /// since expired stays missing, because a missing bucket is already a full+ /// one.+ pub async fn refund(&self, team_id: i32) -> Result<(), CustomRedisError> {+ let args = vec![self.max.to_string(), self.ttl_seconds.to_string()];+ self.redis+ .eval_int_vec(REFUND_SCRIPT, vec![self.key(team_id)], args)+ .await?;+ Ok(())+ }++ fn key(&self, team_id: i32) -> String {+ // The braces are a Redis Cluster hash tag, so a team's keys share one slot.+ format!("{}/{{{team_id}}}/issue_created", self.key_prefix)+ }+}++/// The Redis-backed tests are ignored by default, because they need Docker. Run+/// them with:+/// ```sh+/// cargo test -p cymbal token_bucket::tests -- --ignored --test-threads=1+/// ```+#[cfg(test)]+mod tests {+ use super::*;+ use crate::test_support::{start_redis, FakeRunner};+ use common_redis::RedisClient;++ fn bucket(client: Arc<RedisClient>, prefix: &str, per_hour: f64) -> TokenBucket {+ TokenBucket::per_hour(client, prefix.to_string(), per_hour, 3600)+ }++ #[tokio::test]+ #[ignore]+ async fn charge_admits_up_to_capacity_then_denies() {+ let (client, _container) = start_redis().await;+ let bucket = bucket(client, "tb/charge", 3.0);++ for _ in 0..3 {+ assert!(bucket.charge(1).await.unwrap());+ }+ assert!(!bucket.charge(1).await.unwrap());+ }++ #[tokio::test]+ #[ignore]+ async fn a_refund_hands_the_token_back() {+ let (client, _container) = start_redis().await;+ let bucket = bucket(client, "tb/refund", 1.0);++ assert!(bucket.charge(1).await.unwrap());+ assert!(!bucket.charge(1).await.unwrap());++ bucket.refund(1).await.unwrap();+ assert!(bucket.charge(1).await.unwrap());+ }++ #[test]+ fn a_ttl_below_the_refill_window_is_raised_to_it() {+ let bucket = TokenBucket::per_hour(+ FakeRunner::returning(vec![1]),+ "tb/ttl".to_string(),+ 1000.0,+ 60,+ );++ assert_eq!(bucket.ttl_seconds, SECONDS_PER_HOUR as u64);+ }++ #[tokio::test]+ #[ignore]+ async fn teams_hold_separate_budgets() {+ let (client, _container) = start_redis().await;+ let bucket = bucket(client, "tb/teams", 1.0);++ assert!(bucket.charge(1).await.unwrap());+ assert!(!bucket.charge(1).await.unwrap());+ assert!(bucket.charge(2).await.unwrap());+ }+}diff --git a/rust/cymbal/src/modes/processing/stages/rate_limiting/limiter.rs b/rust/cymbal/src/modes/processing/stages/rate_limiting/limiter.rsindex d7e3b9a22338..2a241037d135 100644--- a/rust/cymbal/src/modes/processing/stages/rate_limiting/limiter.rs+++ b/rust/cymbal/src/modes/processing/stages/rate_limiting/limiter.rs@@ -1,8 +1,7 @@use std::sync::Arc;-use async_trait::async_trait;use chrono::Utc;-use common_redis::{CustomRedisError, RedisClient};+use common_redis::{CustomRedisError, ScriptRunner};use uuid::Uuid;use crate::modes::processing::redis_heal::HealGate;@@ -71,41 +70,6 @@ local team_admitted = take(KEYS[2], issue_admitted, tonumber(ARGV[6]), tonumberreturn { issue_admitted, team_admitted }"#;-/// The single Redis operation the limiter needs: run the Lua script and decode-/// its integer-array reply. Behind a trait so the rate-limiting stage can be-/// unit-tested with an in-memory fake — including a failing one, to prove the-/// stage fails open. Production uses the real `RedisClient`.-#[async_trait]-pub trait ScriptRunner: Send + Sync {- async fn eval_int_vec(- &self,- script: &str,- keys: Vec<String>,- args: Vec<String>,- ) -> Result<Vec<i64>, CustomRedisError>;-- /// Rebuild the underlying connection after a connection-class failure;- /// see `common_redis::Client::heal`. Default no-op keeps test fakes- /// trivial.- async fn heal(&self) {}-}--#[async_trait]-impl ScriptRunner for RedisClient {- async fn eval_int_vec(- &self,- script: &str,- keys: Vec<String>,- args: Vec<String>,- ) -> Result<Vec<i64>, CustomRedisError> {- RedisClient::eval_int_vec(self, script, keys, args).await- }-- async fn heal(&self) {- self.heal_connection().await;- }-}-pub struct RedisRateLimiter {redis: Arc<dyn ScriptRunner>,key_prefix: String,@@ -200,49 +164,8 @@ impl RedisRateLimiter {#[cfg(test)]mod tests {use super::*;- use common_redis::{CompressionConfig, RedisValueFormat};- use std::time::Duration;- use testcontainers::core::{IntoContainerPort, WaitFor};- use testcontainers::runners::AsyncRunner;- use testcontainers::{ContainerAsync, GenericImage};-- /// Boot a throwaway Redis and return a connected client. The readiness banner- /// can land a hair before the socket accepts, so we probe with a trivial- /// script until it answers — otherwise the first command occasionally races- /// the container and flakes with "connection refused".- async fn start_redis() -> (Arc<RedisClient>, ContainerAsync<GenericImage>) {- let container = GenericImage::new("redis", "7-alpine")- .with_exposed_port(6379.tcp())- .with_wait_for(WaitFor::message_on_stdout("Ready to accept connections"))- .start()- .await- .unwrap();- let host = container.get_host().await.unwrap();- let port = container.get_host_port_ipv4(6379).await.unwrap();- let url = format!("redis://{host}:{port}");-- for _ in 0..20 {- if let Ok(client) = RedisClient::with_config(- url.clone(),- CompressionConfig::disabled(),- RedisValueFormat::Utf8,- None,- None,- )- .await- {- if client- .eval_int_vec("return {1, 1}", vec![], vec![])- .await- .is_ok()- {- return (Arc::new(client), container);- }- }- tokio::time::sleep(Duration::from_millis(100)).await;- }- panic!("redis container never became ready");- }+ use crate::test_support::{start_redis, RedisContainer};+ use common_redis::RedisClient;// ===================================================================// Layer 1 — semi-unit tests: the token-bucket script, called directly.@@ -511,7 +434,7 @@ mod tests {struct TestHarness {limiter: Arc<RedisRateLimiter>,next_team_id: AtomicI32,- _container: ContainerAsync<GenericImage>,+ _container: RedisContainer,}impl TestHarness {diff --git a/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs b/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rsindex bf631428806a..8e8ed2d4be31 100644--- a/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs+++ b/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs@@ -30,7 +30,7 @@ use crate::{use crate::modes::processing::rules::bypass::BypassRule;use crate::modes::processing::rules::rate_limit::RateLimitSettings;-pub use limiter::{RateLimitDecision, RedisRateLimiter, ScriptRunner, RATE_LIMIT_LUA};+pub use limiter::{RateLimitDecision, RedisRateLimiter, RATE_LIMIT_LUA};/// Ceiling on concurrent Redis admits per batch — bounds the pathological tail (many/// tiny, all-distinct issues). Normal batches stay under it and fan out fully.@@ -598,7 +598,7 @@ mod tests {ExceptionList,};use async_trait::async_trait;- use common_redis::CustomRedisError;+ use common_redis::{CustomRedisError, ScriptRunner};use std::sync::atomic::{AtomicUsize, Ordering};/// A `ScriptRunner` that never touches Redis: returns a canned reply, or andiff --git a/rust/cymbal/src/test_support.rs b/rust/cymbal/src/test_support.rsnew file mode 100644index 000000000000..7db7882b722f--- /dev/null+++ b/rust/cymbal/src/test_support.rs@@ -0,0 +1,79 @@+//! Test-only scaffolding shared across the crate.++use std::sync::Arc;+use std::time::Duration;++use async_trait::async_trait;+use common_redis::{+ CompressionConfig, CustomRedisError, RedisClient, RedisValueFormat, ScriptRunner,+};+use testcontainers::core::{IntoContainerPort, WaitFor};+use testcontainers::runners::AsyncRunner;+use testcontainers::{ContainerAsync, GenericImage};++/// Dropping this stops the container, so tests hold it for their duration.+pub type RedisContainer = ContainerAsync<GenericImage>;++/// Boot a throwaway Redis and return a connected client. The readiness banner can+/// land just before the socket accepts, so the connect and a probe script are+/// retried, otherwise the first command flakes with "connection refused".+pub async fn start_redis() -> (Arc<RedisClient>, RedisContainer) {+ let container = GenericImage::new("redis", "7-alpine")+ .with_exposed_port(6379.tcp())+ .with_wait_for(WaitFor::message_on_stdout("Ready to accept connections"))+ .start()+ .await+ .unwrap();+ let host = container.get_host().await.unwrap();+ let port = container.get_host_port_ipv4(6379).await.unwrap();+ let url = format!("redis://{host}:{port}");++ for _ in 0..20 {+ if let Ok(client) = RedisClient::with_config(+ url.clone(),+ CompressionConfig::disabled(),+ RedisValueFormat::Utf8,+ None,+ None,+ )+ .await+ {+ if client+ .eval_int_vec("return { 1 }", vec![], vec![])+ .await+ .is_ok()+ {+ return (Arc::new(client), container);+ }+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ panic!("redis container never became ready");+}++/// A [`ScriptRunner`] that never touches Redis: a canned reply, or an error.+pub struct FakeRunner {+ reply: Option<Vec<i64>>,+}++impl FakeRunner {+ pub fn returning(reply: Vec<i64>) -> Arc<Self> {+ Arc::new(Self { reply: Some(reply) })+ }++ pub fn failing() -> Arc<Self> {+ Arc::new(Self { reply: None })+ }+}++#[async_trait]+impl ScriptRunner for FakeRunner {+ async fn eval_int_vec(+ &self,+ _script: &str,+ _keys: Vec<String>,+ _args: Vec<String>,+ ) -> Result<Vec<i64>, CustomRedisError> {+ self.reply.clone().ok_or(CustomRedisError::Timeout)+ }+}