: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): add cymbal notifications mode (#65245)
Hugues Pouillot22aa7e8e2394
diff --git a/rust/cymbal/src/core/mod.rs b/rust/cymbal/src/core/mod.rsindex 1ab0b7c9d6af..bf1a4a7ccdd9 100644--- a/rust/cymbal/src/core/mod.rs+++ b/rust/cymbal/src/core/mod.rs@@ -10,5 +10,6 @@ pub mod ids;pub mod metric_consts;pub mod resolver;pub mod sanitize;+pub mod shutdown;pub mod symbolication;pub mod types;diff --git a/rust/cymbal/src/core/shutdown.rs b/rust/cymbal/src/core/shutdown.rsnew file mode 100644index 000000000000..c079b5fe921e--- /dev/null+++ b/rust/cymbal/src/core/shutdown.rs@@ -0,0 +1,13 @@+use tokio::sync::watch;++pub async fn wait_for_shutdown(mut shutdown_rx: watch::Receiver<bool>) {+ if *shutdown_rx.borrow() {+ return;+ }++ while shutdown_rx.changed().await.is_ok() {+ if *shutdown_rx.borrow() {+ return;+ }+ }+}diff --git a/rust/cymbal/src/core/types/mod.rs b/rust/cymbal/src/core/types/mod.rsindex bf3b8efc0407..a0313fb26b60 100644--- a/rust/cymbal/src/core/types/mod.rs+++ b/rust/cymbal/src/core/types/mod.rs@@ -7,6 +7,7 @@ use serde::{Deserialize, Serialize};pub mod exception;pub mod frames;pub mod langs;+pub mod notification;pub mod stacktrace;pub use exception::*;diff --git a/rust/cymbal/src/core/types/notification.rs b/rust/cymbal/src/core/types/notification.rsnew file mode 100644index 000000000000..15dbfb5e72ce--- /dev/null+++ b/rust/cymbal/src/core/types/notification.rs@@ -0,0 +1,81 @@+//! The wire contract for the `error-tracking-ingestion-notifications` Kafka+//! topic. The processing mode produces these; the notifications mode consumes+//! them.++use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::types::OutputErrProps;++/// A notification emitted by error-tracking ingestion. Serialized as+/// internally-tagged JSON (`{"type": "issue_created", ...}`) so new variants can+/// be added without breaking existing consumers — an unknown `type` simply fails+/// to deserialize and is skipped as a poison pill.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(tag = "type", rename_all = "snake_case")]+pub enum IngestionNotification {+ /// A new issue was created during ingestion.+ IssueCreated(IssueCreated),+}++/// Payload for [`IngestionNotification::IssueCreated`].+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct IssueCreated {+ pub team_id: i32,+ pub issue_id: Uuid,+ pub fingerprint: String,+ pub event_uuid: Uuid,+ pub event_timestamp: String,+ /// Full final exception event properties after Cymbal processing.+ pub event_properties: OutputErrProps,+}++impl IngestionNotification {+ pub fn issue_created(+ team_id: i32,+ issue_id: Uuid,+ fingerprint: String,+ event_uuid: Uuid,+ event_timestamp: String,+ event_properties: OutputErrProps,+ ) -> Self {+ Self::IssueCreated(IssueCreated {+ team_id,+ issue_id,+ fingerprint,+ event_uuid,+ event_timestamp,+ event_properties,+ })+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn issue_created_round_trips_with_type_tag() {+ let notification = IngestionNotification::issue_created(+ 42,+ Uuid::nil(),+ "abc".to_string(),+ Uuid::nil(),+ "1970-01-01T00:00:00Z".to_string(),+ OutputErrProps {+ fingerprint: "abc".to_string(),+ ..Default::default()+ },+ );++ let json = serde_json::to_value(¬ification).unwrap();+ assert_eq!(json["type"], "issue_created");+ assert_eq!(json["team_id"], 42);+ assert_eq!(json["fingerprint"], "abc");+ assert_eq!(json["event_properties"]["$exception_fingerprint"], "abc");++ // Round-trips back to the same JSON through the typed enum.+ let decoded: IngestionNotification = serde_json::from_value(json.clone()).unwrap();+ assert_eq!(serde_json::to_value(&decoded).unwrap(), json);+ }+}diff --git a/rust/cymbal/src/main.rs b/rust/cymbal/src/main.rsindex ec5faaa01069..37170a07135a 100644--- a/rust/cymbal/src/main.rs+++ b/rust/cymbal/src/main.rs@@ -1,3 +1,4 @@+use cymbal::modes::notifications::NotificationsConfig;use cymbal::modes::processing::ProcessingConfig;use cymbal::modes::resolution::ResolutionConfig;use cymbal::modes::{self, CymbalMode};@@ -56,6 +57,17 @@ async fn main() {std::process::exit(1);}}+ CymbalMode::Notifications => {+ let config = NotificationsConfig::init_with_defaults().unwrap();+ let _profiling_agent = start_profiling(&config.continuous_profiling);+ init_posthog(+ "cymbal-notifications",+ &config.posthog_api_key,+ &config.posthog_endpoint,+ )+ .await;+ modes::notifications::run(config).await;+ }}}diff --git a/rust/cymbal/src/modes/mod.rs b/rust/cymbal/src/modes/mod.rsindex cedbef24bb7b..dda95d984e04 100644--- a/rust/cymbal/src/modes/mod.rs+++ b/rust/cymbal/src/modes/mod.rs@@ -6,6 +6,7 @@use std::str::FromStr;+pub mod notifications;pub mod processing;pub mod resolution;@@ -17,6 +18,8 @@ pub enum CymbalMode {Processing,/// `cymbal.resolution.v1` gRPC symbol-resolution service.Resolution,+ /// Consumes the error-tracking ingestion notifications topic and logs it.+ Notifications,}impl FromStr for CymbalMode {@@ -26,8 +29,9 @@ impl FromStr for CymbalMode {match s.trim().to_ascii_lowercase().as_str() {"processing" => Ok(Self::Processing),"resolution" => Ok(Self::Resolution),+ "notifications" => Ok(Self::Notifications),other => Err(format!(- "unknown CYMBAL_MODE '{other}', expected 'processing' or 'resolution'"+ "unknown CYMBAL_MODE '{other}', expected 'processing', 'resolution', or 'notifications'")),}}diff --git a/rust/cymbal/src/modes/notifications/config.rs b/rust/cymbal/src/modes/notifications/config.rsnew file mode 100644index 000000000000..c30e0c8b150d--- /dev/null+++ b/rust/cymbal/src/modes/notifications/config.rs@@ -0,0 +1,44 @@+use common_continuous_profiling::ContinuousProfilingConfig;+use common_kafka::config::{ConsumerConfig, KafkaConfig};+use envconfig::Envconfig;++/// Topic carrying error-tracking ingestion notifications. Overridable via+/// `KAFKA_CONSUMER_TOPIC`.+pub const DEFAULT_CONSUMER_TOPIC: &str = "error-tracking-ingestion-notifications";++/// Consumer group for the notifications mode. Overridable via+/// `KAFKA_CONSUMER_GROUP`.+pub const DEFAULT_CONSUMER_GROUP: &str = "error-tracking-ingestion-notifications";++/// Top-level config for notifications mode. Owns only what a read-and-log+/// consumer needs: a Kafka client, a single-topic consumer, and the metrics+/// server port — none of the processing-only knobs.+#[derive(Envconfig, Clone)]+pub struct NotificationsConfig {+ #[envconfig(nested = true)]+ pub continuous_profiling: ContinuousProfilingConfig,++ #[envconfig(nested = true)]+ pub kafka: KafkaConfig,++ #[envconfig(nested = true)]+ pub consumer: ConsumerConfig,++ /// HTTP bind port for liveness, readiness, and Prometheus metrics.+ #[envconfig(from = "METRICS_PORT", default = "9102")]+ pub metrics_port: u16,++ pub posthog_api_key: Option<String>,++ #[envconfig(default = "https://us.i.posthog.com/capture")]+ pub posthog_endpoint: String,+}++impl NotificationsConfig {+ pub fn init_with_defaults() -> Result<Self, envconfig::Error> {+ // We only read and log, so at-most-once delivery is fine — let the+ // consumer auto-commit stored offsets.+ ConsumerConfig::set_defaults(DEFAULT_CONSUMER_GROUP, DEFAULT_CONSUMER_TOPIC, true);+ Self::init_from_env()+ }+}diff --git a/rust/cymbal/src/modes/notifications/mod.rs b/rust/cymbal/src/modes/notifications/mod.rsnew file mode 100644index 000000000000..c77cb293e371--- /dev/null+++ b/rust/cymbal/src/modes/notifications/mod.rs@@ -0,0 +1,184 @@+//! Notifications mode: consumes the `error-tracking-ingestion-notifications`+//! Kafka topic and logs each message. This is the initial read-and-display+//! stage; downstream handling (routing, delivery) is layered on later. It+//! starts only a Kafka consumer plus the metrics/health server — no Postgres,+//! Redis, symbol resolution, or HTTP `/process` pipeline.++use std::sync::{+ atomic::{AtomicBool, Ordering},+ Arc,+};+use std::time::Duration;++use axum::{http::StatusCode, routing::get, Router};+use common_kafka::kafka_consumer::{RecvErr, SingleTopicConsumer};+use tokio::sync::watch;+use tokio::task::JoinHandle;+use tracing::{error, info, warn};++use crate::core::{shutdown::wait_for_shutdown, types::notification::IngestionNotification};++pub mod config;++pub use config::NotificationsConfig;++const NOTIFICATIONS_RECEIVED_TOTAL: &str = "cymbal_notifications_received_total";+const NOTIFICATIONS_SKIPPED_TOTAL: &str = "cymbal_notifications_skipped_total";+const NOTIFICATIONS_KAFKA_ERRORS_TOTAL: &str = "cymbal_notifications_kafka_errors_total";++/// Boot the notifications consumer plus its metrics/health server and run until+/// shutdown.+pub async fn run(config: NotificationsConfig) {+ let consumer = SingleTopicConsumer::new(config.kafka.clone(), config.consumer.clone())+ .expect("failed to create notifications Kafka consumer");++ info!(+ topic = %config.consumer.kafka_consumer_topic,+ group = %config.consumer.kafka_consumer_group,+ "Starting cymbal-notifications consumer",+ );++ let (shutdown_tx, shutdown_rx) = watch::channel(false);+ let draining = Arc::new(AtomicBool::new(false));+ let shutdown_handle = spawn_shutdown_listener(shutdown_tx.clone(), draining.clone());+ let metrics_handle =+ spawn_metrics_server(config.metrics_port, shutdown_rx.clone(), draining.clone());++ consume_loop(consumer, shutdown_rx).await;++ let _ignored = shutdown_tx.send(true);+ if let Err(err) = metrics_handle.await {+ warn!(error = %err, "metrics server task failed during shutdown");+ }+ shutdown_handle.abort();+}++/// Receive messages until shutdown, logging each one. Offsets for successfully+/// received messages are stored and auto-committed by the consumer; serde and+/// empty failures are auto-stored as poison pills inside `json_recv`.+async fn consume_loop(consumer: SingleTopicConsumer, mut shutdown_rx: watch::Receiver<bool>) {+ loop {+ tokio::select! {+ biased;+ changed = shutdown_rx.changed() => {+ if changed.is_err() || *shutdown_rx.borrow() {+ info!("notifications consumer shutting down");+ break;+ }+ }+ result = consumer.json_recv::<IngestionNotification>() => {+ match result {+ Ok((notification, offset)) => {+ log_notification_summary(¬ification);+ metrics::counter!(NOTIFICATIONS_RECEIVED_TOTAL).increment(1);+ if let Err(e) = offset.store() {+ warn!(error = %e, "failed to store notification offset");+ }+ }+ Err(RecvErr::Serde(e)) => {+ warn!(error = %e, "notification serde error (poison pill skipped)");+ metrics::counter!(NOTIFICATIONS_SKIPPED_TOTAL, "reason" => "serde").increment(1);+ }+ Err(RecvErr::Empty) => {+ metrics::counter!(NOTIFICATIONS_SKIPPED_TOTAL, "reason" => "empty").increment(1);+ }+ Err(RecvErr::Kafka(e)) => {+ error!(error = %e, "notifications kafka error");+ metrics::counter!(NOTIFICATIONS_KAFKA_ERRORS_TOTAL).increment(1);+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ }+ }+ }+ }+}++fn log_notification_summary(notification: &IngestionNotification) {+ match notification {+ IngestionNotification::IssueCreated(issue_created) => {+ info!(+ notification_type = "issue_created",+ team_id = issue_created.team_id,+ issue_id = %issue_created.issue_id,+ event_uuid = %issue_created.event_uuid,+ "received error-tracking ingestion notification"+ );+ }+ }+}++fn spawn_metrics_server(+ port: u16,+ shutdown_rx: watch::Receiver<bool>,+ draining: Arc<AtomicBool>,+) -> JoinHandle<()> {+ tokio::spawn(async move {+ let readiness_draining = draining.clone();+ let router = Router::new()+ .route("/_liveness", get(|| async { "ok" }))+ .route(+ "/_readiness",+ get(move || readiness(readiness_draining.clone())),+ );+ let router =+ common_metrics::setup_metrics_routes_for_product(router, "cymbal-notifications");++ let bind = format!("0.0.0.0:{port}");+ info!("Metrics server listening on {}", bind);+ let listener = match tokio::net::TcpListener::bind(&bind).await {+ Ok(listener) => listener,+ Err(e) => {+ error!("Metrics server bind error: {e}");+ return;+ }+ };+ if let Err(e) = axum::serve(listener, router)+ .with_graceful_shutdown(wait_for_shutdown(shutdown_rx))+ .await+ {+ error!("Metrics server error: {e}");+ }+ })+}++fn spawn_shutdown_listener(+ shutdown_tx: watch::Sender<bool>,+ draining: Arc<AtomicBool>,+) -> JoinHandle<()> {+ tokio::spawn(async move {+ shutdown_signal().await;+ info!("shutdown signal received, marking cymbal-notifications as draining");+ draining.store(true, Ordering::Relaxed);+ let _ignored = shutdown_tx.send(true);+ })+}++async fn readiness(draining: Arc<AtomicBool>) -> (StatusCode, &'static str) {+ if draining.load(Ordering::Relaxed) {+ return (StatusCode::SERVICE_UNAVAILABLE, "draining");+ }++ (StatusCode::OK, "ok")+}++#[cfg(unix)]+async fn shutdown_signal() {+ use tokio::signal::unix::{signal, SignalKind};++ let mut sigterm = signal(SignalKind::terminate()).expect("failed to listen for SIGTERM");+ tokio::select! {+ result = tokio::signal::ctrl_c() => {+ if let Err(err) = result {+ warn!(error = %err, "failed to listen for Ctrl+C");+ }+ }+ _ = sigterm.recv() => {}+ }+}++#[cfg(not(unix))]+async fn shutdown_signal() {+ if let Err(err) = tokio::signal::ctrl_c().await {+ warn!(error = %err, "failed to listen for Ctrl+C");+ }+}diff --git a/rust/cymbal/src/modes/resolution/mod.rs b/rust/cymbal/src/modes/resolution/mod.rsindex 4be5dd1518a0..25e8befcf5cc 100644--- a/rust/cymbal/src/modes/resolution/mod.rs+++ b/rust/cymbal/src/modes/resolution/mod.rs@@ -18,7 +18,7 @@ use tokio::task::JoinHandle;use tonic::transport::Server;use tracing::{info, warn};-use crate::core::config::ResolverConfig;+use crate::core::{config::ResolverConfig, shutdown::wait_for_shutdown};pub mod app_context;pub mod auth;@@ -171,18 +171,6 @@ async fn readiness(draining: Arc<AtomicBool>) -> (StatusCode, &'static str) {(StatusCode::OK, "ok")}-async fn wait_for_shutdown(mut shutdown_rx: watch::Receiver<bool>) {- if *shutdown_rx.borrow() {- return;- }-- while shutdown_rx.changed().await.is_ok() {- if *shutdown_rx.borrow() {- return;- }- }-}-#[cfg(unix)]async fn shutdown_signal() {use tokio::signal::unix::{signal, SignalKind};