Skip to content

: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.

feat(cymbal): move side effects to notifications (#66021)

Hugues Pouillot56e33d7e08bf
diff --git a/bin/mprocs.yaml b/bin/mprocs.yaml
index f37854aa590c..8f9942182e9f 100755
--- a/bin/mprocs.yaml
+++ b/bin/mprocs.yaml
@@ -309,6 +309,16 @@ procs:
layer: Product services
tech: Rust
+ cymbal-notifications:
+ shell: |-
+ bin/wait-for-docker && \
+ bin/start-rust-service cymbal-notifications
+ capability: error_notifications
+ ready_pattern: 'Starting cymbal-notifications consumer'
+ groups:
+ layer: Product services
+ tech: Rust
+
embedding-worker:
shell: |-
bin/wait-for-docker && \
diff --git a/bin/start-rust-service b/bin/start-rust-service
index e4670736cdab..8e79919186cf 100755
--- a/bin/start-rust-service
+++ b/bin/start-rust-service
@@ -187,6 +187,23 @@ case "$RS_SVC" in
export SUBSCRIBE_TICK_INTERVAL_MS="${SUBSCRIBE_TICK_INTERVAL_MS:-500}"
;;
+ cymbal-notifications)
+ # The cymbal binary in notifications mode consumes the notifications topic
+ # produced by processing mode and runs issue side effects.
+ export CYMBAL_MODE=notifications
+ export DEV_RUST_SVC_OVERRIDE=cymbal
+ export RUST_LOG=debug,rdkafka=warn
+ export RUST_BACKTRACE=1
+ export KAFKA_HOSTS="$DEFAULT_KAFKA"
+ export DATABASE_URL="${DATABASE_URL:-$DEFAULT_PG}"
+ export KAFKA_CONSUMER_OFFSET_RESET="${KAFKA_CONSUMER_OFFSET_RESET:-earliest}"
+ export METRICS_PORT="${METRICS_PORT:-9107}"
+ export POSTHOG_API_KEY="${CYMBAL_NOTIFICATIONS_POSTHOG_API_KEY:-phc_localposthogprojecttoken}"
+ export POSTHOG_ENDPOINT="${CYMBAL_NOTIFICATIONS_POSTHOG_ENDPOINT:-http://localhost:3307}"
+ export SIGNALS_API_BASE_URL="${SIGNALS_API_BASE_URL:-http://localhost:8000}"
+ export INTERNAL_API_SECRET="${INTERNAL_API_SECRET:-posthog123}"
+ ;;
+
embedding-worker)
export RUST_LOG=debug,rdkafka=warn
export RUST_BACKTRACE=1
diff --git a/devenv/intent-map.yaml b/devenv/intent-map.yaml
index cb4e56723f29..64041627b28c 100644
--- a/devenv/intent-map.yaml
+++ b/devenv/intent-map.yaml
@@ -48,6 +48,11 @@ capabilities:
requires: [event_ingestion]
docker_profiles: []
+ error_notifications:
+ description: 'Error tracking ingestion notifications consumer'
+ requires: [event_ingestion]
+ docker_profiles: []
+
flag_evaluation:
description: 'Fast feature flag evaluation service'
requires: [core_infra]
@@ -244,6 +249,7 @@ intents:
[
event_ingestion,
error_symbolication,
+ error_notifications,
embedding_service,
property_definitions,
property_values,
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index c9b88e225da2..cc4bf25e0e06 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -497,6 +497,7 @@ services:
# Auto-create only fires on producer-first writes, so pre-create them here.
TOPICS="document_embeddings_input \
document_embedding_results \
+ error_tracking_ingestion_notifications \
clickhouse_events_json \
clickhouse_ai_events_json \
clickhouse_heatmap_events \
diff --git a/rust/cymbal/src/core/types/notification.rs b/rust/cymbal/src/core/types/notification.rs
index 15dbfb5e72ce..437793e95673 100644
--- a/rust/cymbal/src/core/types/notification.rs
+++ b/rust/cymbal/src/core/types/notification.rs
@@ -1,7 +1,8 @@
-//! The wire contract for the `error-tracking-ingestion-notifications` Kafka
+//! The wire contract for the `error_tracking_ingestion_notifications` Kafka
//! topic. The processing mode produces these; the notifications mode consumes
//! them.
+use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
@@ -16,57 +17,147 @@ use crate::types::OutputErrProps;
pub enum IngestionNotification {
/// A new issue was created during ingestion.
IssueCreated(IssueCreated),
+ /// A resolved issue was reopened during ingestion.
+ IssueReopened(IssueReopened),
+ /// An issue crossed the spike threshold during ingestion.
+ IssueSpiking(IssueSpiking),
}
-/// Payload for [`IngestionNotification::IssueCreated`].
+impl IngestionNotification {
+ pub fn notification_id(&self) -> Uuid {
+ match self {
+ IngestionNotification::IssueCreated(issue_created) => {
+ issue_created.meta.notification_id
+ }
+ IngestionNotification::IssueReopened(issue_reopened) => {
+ issue_reopened.meta.notification_id
+ }
+ IngestionNotification::IssueSpiking(issue_spiking) => {
+ issue_spiking.meta.notification_id
+ }
+ }
+ }
+
+ pub fn team_id(&self) -> i32 {
+ match self {
+ IngestionNotification::IssueCreated(issue_created) => issue_created.meta.team_id,
+ IngestionNotification::IssueReopened(issue_reopened) => issue_reopened.meta.team_id,
+ IngestionNotification::IssueSpiking(issue_spiking) => issue_spiking.meta.team_id,
+ }
+ }
+
+ pub fn partition_key(&self) -> String {
+ match self {
+ IngestionNotification::IssueCreated(issue_created) => {
+ issue_created.issue.partition_key(self.team_id())
+ }
+ IngestionNotification::IssueReopened(issue_reopened) => {
+ issue_reopened.issue.partition_key(self.team_id())
+ }
+ IngestionNotification::IssueSpiking(issue_spiking) => {
+ issue_spiking.issue.partition_key(self.team_id())
+ }
+ }
+ }
+}
+
+/// Shared metadata for every ingestion notification.
#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct IssueCreated {
+pub struct NotificationMeta {
+ /// Stable id for retryable side effects produced from this notification.
+ #[serde(default = "Uuid::now_v7")]
+ pub notification_id: Uuid,
pub team_id: i32,
+}
+
+/// Shared context for notifications that produce issue side effects.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct IssueNotificationContext {
pub issue_id: Uuid,
- pub fingerprint: String,
- pub event_uuid: Uuid,
- pub event_timestamp: String,
+ pub issue: IssueSnapshot,
/// 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,
- })
+impl IssueNotificationContext {
+ pub fn partition_key(&self, team_id: i32) -> String {
+ format!("{}:{}", team_id, self.issue_id)
}
}
+/// Payload for [`IngestionNotification::IssueCreated`].
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct IssueCreated {
+ #[serde(flatten)]
+ pub meta: NotificationMeta,
+ #[serde(flatten)]
+ pub issue: IssueNotificationContext,
+ pub fingerprint: String,
+ pub event_uuid: Uuid,
+ pub event_timestamp: String,
+ pub assignee: Option<String>,
+}
+
+/// Payload for [`IngestionNotification::IssueReopened`].
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct IssueReopened {
+ #[serde(flatten)]
+ pub meta: NotificationMeta,
+ #[serde(flatten)]
+ pub issue: IssueNotificationContext,
+ pub event_timestamp: String,
+ pub assignee: Option<String>,
+}
+
+/// Payload for [`IngestionNotification::IssueSpiking`].
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct IssueSpiking {
+ #[serde(flatten)]
+ pub meta: NotificationMeta,
+ #[serde(flatten)]
+ pub issue: IssueNotificationContext,
+ pub computed_baseline: f64,
+ pub current_bucket_value: f64,
+}
+
+/// Issue state captured when the ingestion transition happened.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct IssueSnapshot {
+ pub name: Option<String>,
+ pub description: Option<String>,
+ pub status: String,
+ pub created_at: DateTime<Utc>,
+}
+
#[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 notification = IngestionNotification::IssueCreated(IssueCreated {
+ meta: NotificationMeta {
+ notification_id: Uuid::nil(),
+ team_id: 42,
+ },
+ issue: IssueNotificationContext {
+ issue_id: Uuid::nil(),
+ issue: IssueSnapshot {
+ name: Some("Example".to_string()),
+ description: Some("Example issue".to_string()),
+ status: "active".to_string(),
+ created_at: DateTime::from_timestamp(0, 0).unwrap(),
+ },
+ event_properties: OutputErrProps {
+ fingerprint: "abc".to_string(),
+ ..Default::default()
+ },
},
- );
+ fingerprint: "abc".to_string(),
+ event_uuid: Uuid::nil(),
+ event_timestamp: "1970-01-01T00:00:00Z".to_string(),
+ assignee: None,
+ });
let json = serde_json::to_value(&notification).unwrap();
assert_eq!(json["type"], "issue_created");
diff --git a/rust/cymbal/src/lib.rs b/rust/cymbal/src/lib.rs
index 9d9f6ee5b53b..c1041bf639a2 100644
--- a/rust/cymbal/src/lib.rs
+++ b/rust/cymbal/src/lib.rs
@@ -16,6 +16,5 @@ pub use core::{error, metric_consts, symbolication};
// Compat re-exports: processing-only modules now live under `modes::processing`.
// Prefer `crate::modes::processing::*` in new code.
pub use modes::processing::{
- analytics, app_context, fingerprinting, issue_resolution, router, server, signals, stages,
- teams, tokenizer, types,
+ app_context, fingerprinting, issue_resolution, router, server, stages, teams, tokenizer, types,
};
diff --git a/rust/cymbal/src/modes/processing/analytics.rs b/rust/cymbal/src/modes/notifications/analytics.rs
similarity index 100%
rename from rust/cymbal/src/modes/processing/analytics.rs
rename to rust/cymbal/src/modes/notifications/analytics.rs
diff --git a/rust/cymbal/src/modes/notifications/config.rs b/rust/cymbal/src/modes/notifications/config.rs
index c30e0c8b150d..1a22141c2042 100644
--- a/rust/cymbal/src/modes/notifications/config.rs
+++ b/rust/cymbal/src/modes/notifications/config.rs
@@ -4,15 +4,14 @@ use envconfig::Envconfig;
/// Topic carrying error-tracking ingestion notifications. Overridable via
/// `KAFKA_CONSUMER_TOPIC`.
-pub const DEFAULT_CONSUMER_TOPIC: &str = "error-tracking-ingestion-notifications";
+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.
+/// Top-level config for notifications mode. Keep this narrow: only Kafka,
+/// Postgres, signal emission, and the metrics server.
#[derive(Envconfig, Clone)]
pub struct NotificationsConfig {
#[envconfig(nested = true)]
@@ -24,10 +23,38 @@ pub struct NotificationsConfig {
#[envconfig(nested = true)]
pub consumer: ConsumerConfig,
+ #[envconfig(default = "postgres://posthog:posthog@localhost:5432/posthog")]
+ pub database_url: String,
+
+ // Rust services connect directly to postgres, not via pgbouncer, so we keep this low.
+ #[envconfig(default = "4")]
+ pub max_pg_connections: u32,
+
+ #[envconfig(default = "")]
+ pub internal_api_secret: String,
+
/// HTTP bind port for liveness, readiness, and Prometheus metrics.
#[envconfig(from = "METRICS_PORT", default = "9102")]
pub metrics_port: u16,
+ // Internal API for signal emission.
+ #[envconfig(default = "")]
+ pub signals_api_base_url: String,
+
+ #[envconfig(default = "document_embeddings_input")]
+ pub embedding_worker_topic: String,
+
+ #[envconfig(default = "cdp_internal_events")]
+ pub internal_events_topic: String,
+
+ // Optional override for the brokers used to produce `cdp_internal_events`.
+ #[envconfig(from = "CYMBAL_CYCLOTRON_KAFKA_HOSTS")]
+ pub cyclotron_kafka_hosts: Option<String>,
+
+ // Optional TLS override for the cyclotron producer.
+ #[envconfig(from = "CYMBAL_CYCLOTRON_KAFKA_TLS")]
+ pub cyclotron_kafka_tls: Option<bool>,
+
pub posthog_api_key: Option<String>,
#[envconfig(default = "https://us.i.posthog.com/capture")]
@@ -36,9 +63,9 @@ pub struct NotificationsConfig {
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);
+ // Commit only after notification handling succeeds. Failed handling should crash
+ // before the offset is committed so Kafka redelivers the message on restart.
+ ConsumerConfig::set_defaults(DEFAULT_CONSUMER_GROUP, DEFAULT_CONSUMER_TOPIC, false);
Self::init_from_env()
}
}
diff --git a/rust/cymbal/src/modes/notifications/consumer_loop.rs b/rust/cymbal/src/modes/notifications/consumer_loop.rs
new file mode 100644
index 000000000000..8394cf077e23
--- /dev/null
+++ b/rust/cymbal/src/modes/notifications/consumer_loop.rs
@@ -0,0 +1,147 @@
+use std::time::Duration;
+
+use common_kafka::kafka_consumer::{Offset, RecvErr, SingleTopicConsumer};
+use tokio::sync::watch;
+use tracing::{debug, error, info, warn};
+
+use crate::core::types::notification::IngestionNotification;
+use crate::modes::notifications::context::NotificationsContext;
+use crate::modes::notifications::handler::handle_notification;
+
+const NOTIFICATIONS_RECEIVED_TOTAL: &str = "cymbal_notifications_received_total";
+const NOTIFICATIONS_HANDLED_TOTAL: &str = "cymbal_notifications_handled_total";
+const NOTIFICATIONS_SKIPPED_TOTAL: &str = "cymbal_notifications_skipped_total";
+const NOTIFICATIONS_KAFKA_ERRORS_TOTAL: &str = "cymbal_notifications_kafka_errors_total";
+const NOTIFICATIONS_HANDLE_ERRORS_TOTAL: &str = "cymbal_notifications_handle_errors_total";
+const NOTIFICATIONS_COMMIT_BATCH_SIZE: usize = 100;
+const NOTIFICATIONS_FETCH_BATCH_TIMEOUT: Duration = Duration::from_millis(250);
+
+/// Receive messages until shutdown. Offsets are stored only after successful
+/// handling, then explicitly committed after each fetched batch. Serde and empty
+/// failures are auto-stored as poison pills inside `json_recv_batch`, so this
+/// loop also explicitly commits those stored offsets.
+pub async fn consume_loop(
+ consumer: SingleTopicConsumer,
+ context: NotificationsContext,
+ mut shutdown_rx: watch::Receiver<bool>,
+) {
+ let mut pending_offsets = 0usize;
+
+ loop {
+ tokio::select! {
+ biased;
+ changed = shutdown_rx.changed() => {
+ if changed.is_err() || *shutdown_rx.borrow() {
+ info!("notifications consumer shutting down");
+ commit_pending_offsets(&consumer, &mut pending_offsets, "shutdown");
+ break;
+ }
+ }
+ batch = consumer.json_recv_batch::<IngestionNotification>(
+ NOTIFICATIONS_COMMIT_BATCH_SIZE,
+ NOTIFICATIONS_FETCH_BATCH_TIMEOUT,
+ ) => {
+ handle_notification_batch(&consumer, &context, batch, &mut pending_offsets).await;
+ commit_pending_offsets(&consumer, &mut pending_offsets, "batch");
+ }
+ }
+ }
+}
+
+async fn handle_notification_batch(
+ consumer: &SingleTopicConsumer,
+ context: &NotificationsContext,
+ batch: Vec<Result<(IngestionNotification, Offset), RecvErr>>,
+ pending_offsets: &mut usize,
+) {
+ for result in batch {
+ match result {
+ Ok((notification, offset)) => {
+ log_notification_summary(&notification);
+ metrics::counter!(NOTIFICATIONS_RECEIVED_TOTAL).increment(1);
+ match handle_notification(context, notification).await {
+ Ok(()) => {
+ metrics::counter!(NOTIFICATIONS_HANDLED_TOTAL).increment(1);
+ // `commit_consumer_state` only commits offsets explicitly stored on the consumer.
+ if let Err(e) = offset.store() {
+ panic!("failed to store notification offset: {e}");
+ }
+ *pending_offsets += 1;
+ }
+ Err(e) => {
+ metrics::counter!(NOTIFICATIONS_HANDLE_ERRORS_TOTAL).increment(1);
+ commit_pending_offsets(consumer, pending_offsets, "before_panic");
+ panic!("failed to handle notification: {e}");
+ }
+ }
+ }
+ Err(RecvErr::Serde(e)) => {
+ warn!(error = %e, "notification serde error (poison pill skipped)");
+ metrics::counter!(NOTIFICATIONS_SKIPPED_TOTAL, "reason" => "serde").increment(1);
+ *pending_offsets += 1;
+ }
+ Err(RecvErr::Empty) => {
+ metrics::counter!(NOTIFICATIONS_SKIPPED_TOTAL, "reason" => "empty").increment(1);
+ *pending_offsets += 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 commit_pending_offsets(
+ consumer: &SingleTopicConsumer,
+ pending_offsets: &mut usize,
+ reason: &str,
+) {
+ if *pending_offsets == 0 {
+ return;
+ }
+
+ if let Err(e) = consumer.commit() {
+ panic!("failed to commit notification offsets: {e}");
+ }
+
+ debug!(
+ count = *pending_offsets,
+ reason, "committed notification offsets"
+ );
+ *pending_offsets = 0;
+}
+
+fn log_notification_summary(notification: &IngestionNotification) {
+ match notification {
+ IngestionNotification::IssueCreated(issue_created) => {
+ debug!(
+ notification_type = "issue_created",
+ notification_id = %issue_created.meta.notification_id,
+ team_id = issue_created.meta.team_id,
+ issue_id = %issue_created.issue.issue_id,
+ event_uuid = %issue_created.event_uuid,
+ "received error-tracking ingestion notification"
+ );
+ }
+ IngestionNotification::IssueReopened(issue_reopened) => {
+ debug!(
+ notification_type = "issue_reopened",
+ notification_id = %issue_reopened.meta.notification_id,
+ team_id = issue_reopened.meta.team_id,
+ issue_id = %issue_reopened.issue.issue_id,
+ "received error-tracking ingestion notification"
+ );
+ }
+ IngestionNotification::IssueSpiking(issue_spiking) => {
+ debug!(
+ notification_type = "issue_spiking",
+ notification_id = %issue_spiking.meta.notification_id,
+ team_id = issue_spiking.meta.team_id,
+ issue_id = %issue_spiking.issue.issue_id,
+ "received error-tracking ingestion notification"
+ );
+ }
+ }
+}
diff --git a/rust/cymbal/src/modes/notifications/context.rs b/rust/cymbal/src/modes/notifications/context.rs
new file mode 100644
index 000000000000..345c3314c165
--- /dev/null
+++ b/rust/cymbal/src/modes/notifications/context.rs
@@ -0,0 +1,87 @@
+use std::time::Duration;
+
+use common_kafka::kafka_producer::{create_kafka_producer, KafkaContext};
+use health::HealthRegistry;
+use rdkafka::producer::FutureProducer;
+use sqlx::{postgres::PgPoolOptions, PgPool};
+
+use crate::core::error::UnhandledError;
+use crate::modes::notifications::config::NotificationsConfig;
+use crate::modes::notifications::signals::{MaybeSignalClient, SignalClient};
+
+#[derive(Clone)]
+pub struct NotificationsContext {
+ pub posthog_pool: PgPool,
+ pub immediate_producer: FutureProducer<KafkaContext>,
+ pub cyclotron_producer: FutureProducer<KafkaContext>,
+ pub signal_client: MaybeSignalClient,
+ pub embedding_worker_topic: String,
+ pub internal_events_topic: String,
+}
+
+impl NotificationsContext {
+ pub async fn from_config(config: &NotificationsConfig) -> Result<Self, UnhandledError> {
+ let posthog_pool = PgPoolOptions::new()
+ .max_connections(config.max_pg_connections)
+ .connect(&config.database_url)
+ .await?;
+ let immediate_producer = build_immediate_producer(config).await?;
+
+ Ok(Self {
+ posthog_pool,
+ cyclotron_producer: build_cyclotron_producer(config, &immediate_producer).await?,
+ immediate_producer,
+ signal_client: build_signal_client(config),
+ embedding_worker_topic: config.embedding_worker_topic.clone(),
+ internal_events_topic: config.internal_events_topic.clone(),
+ })
+ }
+}
+
+async fn build_immediate_producer(
+ config: &NotificationsConfig,
+) -> Result<FutureProducer<KafkaContext>, UnhandledError> {
+ create_kafka_producer(&config.kafka, kafka_liveness("immediate_kafka").await)
+ .await
+ .map_err(Into::into)
+}
+
+async fn build_cyclotron_producer(
+ config: &NotificationsConfig,
+ immediate_producer: &FutureProducer<KafkaContext>,
+) -> Result<FutureProducer<KafkaContext>, UnhandledError> {
+ let Some(hosts) = config
+ .cyclotron_kafka_hosts
+ .as_deref()
+ .filter(|hosts| !hosts.is_empty())
+ else {
+ return Ok(immediate_producer.clone());
+ };
+
+ let mut cyclotron_config = config.kafka.clone();
+ cyclotron_config.kafka_hosts = hosts.to_string();
+ if let Some(tls) = config.cyclotron_kafka_tls {
+ cyclotron_config.kafka_tls = tls;
+ }
+
+ create_kafka_producer(&cyclotron_config, kafka_liveness("cyclotron_kafka").await)
+ .await
+ .map_err(Into::into)
+}
+
+fn build_signal_client(config: &NotificationsConfig) -> MaybeSignalClient {
+ if config.signals_api_base_url.is_empty() {
+ return MaybeSignalClient::disabled();
+ }
+
+ MaybeSignalClient::enabled(SignalClient::new_with_parts(
+ config.signals_api_base_url.clone(),
+ config.internal_api_secret.clone(),
+ ))
+}
+
+async fn kafka_liveness(component: &str) -> health::HealthHandle {
+ HealthRegistry::new("notifications_liveness")
+ .register(component.to_string(), Duration::from_secs(30))
+ .await
+}
diff --git a/rust/cymbal/src/modes/notifications/handler.rs b/rust/cymbal/src/modes/notifications/handler.rs
new file mode 100644
index 000000000000..b5ae247fd26c
--- /dev/null
+++ b/rust/cymbal/src/modes/notifications/handler.rs
@@ -0,0 +1,22 @@
+use crate::core::{error::UnhandledError, types::notification::IngestionNotification};
+use crate::modes::notifications::context::NotificationsContext;
+use crate::modes::notifications::issue_handler::{
+ handle_issue_created, handle_issue_reopened, handle_issue_spiking,
+};
+
+pub async fn handle_notification(
+ context: &NotificationsContext,
+ notification: IngestionNotification,
+) -> Result<(), UnhandledError> {
+ match notification {
+ IngestionNotification::IssueCreated(issue_created) => {
+ handle_issue_created(context, issue_created).await
+ }
+ IngestionNotification::IssueReopened(issue_reopened) => {
+ handle_issue_reopened(context, issue_reopened).await
+ }
+ IngestionNotification::IssueSpiking(issue_spiking) => {
+ handle_issue_spiking(context, issue_spiking).await
+ }
+ }
+}
diff --git a/rust/cymbal/src/modes/notifications/issue_handler.rs b/rust/cymbal/src/modes/notifications/issue_handler.rs
new file mode 100644
index 000000000000..f53b1419a174
--- /dev/null
+++ b/rust/cymbal/src/modes/notifications/issue_handler.rs
@@ -0,0 +1,199 @@
+use chrono::{DateTime, Utc};
+use tracing::warn;
+use uuid::Uuid;
+
+use crate::core::{
+ error::UnhandledError,
+ types::notification::{
+ IssueCreated, IssueNotificationContext, IssueReopened, IssueSnapshot, IssueSpiking,
+ },
+};
+use crate::modes::notifications::analytics::{capture_issue_created, capture_issue_reopened};
+use crate::modes::notifications::context::NotificationsContext;
+use crate::modes::notifications::side_effects::{
+ send_issue_created_internal_event, send_issue_reopened_internal_event,
+ send_issue_spiking_internal_event, send_new_fingerprint_event,
+};
+use crate::modes::notifications::types::IssueNotificationData;
+
+pub async fn handle_issue_created(
+ context: &NotificationsContext,
+ notification: IssueCreated,
+) -> Result<(), UnhandledError> {
+ let IssueCreated {
+ meta,
+ issue,
+ event_uuid,
+ event_timestamp,
+ assignee,
+ ..
+ } = notification;
+ let IssueNotificationContext {
+ issue_id,
+ issue: issue_snapshot,
+ event_properties,
+ } = issue;
+ let issue = issue_from_notification(meta.team_id, issue_id, issue_snapshot);
+
+ send_new_fingerprint_event(
+ &context.immediate_producer,
+ &context.embedding_worker_topic,
+ &issue,
+ &event_properties,
+ )
+ .await?;
+ let sentry_integration = event_properties.other.contains_key("$sentry_event_id");
+
+ send_issue_created_internal_event(
+ &context.cyclotron_producer,
+ &context.internal_events_topic,
+ meta.notification_id,
+ &issue,
+ assignee,
+ &event_properties,
+ &parse_notification_timestamp(&event_timestamp, event_uuid),
+ )
+ .await?;
+
+ context
+ .signal_client
+ .emit_issue_created(&issue, &event_properties);
+
+ capture_issue_created(meta.team_id, issue_id, sentry_integration);
+
+ Ok(())
+}
+
+pub async fn handle_issue_reopened(
+ context: &NotificationsContext,
+ notification: IssueReopened,
+) -> Result<(), UnhandledError> {
+ let IssueReopened {
+ meta,
+ issue,
+ event_timestamp,
+ assignee,
+ } = notification;
+ let IssueNotificationContext {
+ issue_id,
+ issue: issue_snapshot,
+ event_properties,
+ } = issue;
+ let issue = issue_from_notification(meta.team_id, issue_id, issue_snapshot);
+
+ send_issue_reopened_internal_event(
+ &context.cyclotron_producer,
+ &context.internal_events_topic,
+ meta.notification_id,
+ &issue,
+ assignee,
+ &event_properties,
+ &parse_notification_timestamp(&event_timestamp, Uuid::nil()),
+ )
+ .await?;
+
+ context
+ .signal_client
+ .emit_issue_reopened(&issue, &event_properties);
+ capture_issue_reopened(meta.team_id, issue_id);
+
+ Ok(())
+}
+
+pub async fn handle_issue_spiking(
+ context: &NotificationsContext,
+ notification: IssueSpiking,
+) -> Result<(), UnhandledError> {
+ let IssueSpiking {
+ meta,
+ issue,
+ computed_baseline,
+ current_bucket_value,
+ } = notification;
+ let IssueNotificationContext {
+ issue_id,
+ issue: issue_snapshot,
+ event_properties,
+ } = issue;
+ let issue = issue_from_notification(meta.team_id, issue_id, issue_snapshot);
+
+ persist_spike_event(
+ context,
+ meta.notification_id,
+ meta.team_id,
+ issue_id,
+ computed_baseline,
+ current_bucket_value,
+ )
+ .await?;
+ send_issue_spiking_internal_event(
+ &context.cyclotron_producer,
+ &context.internal_events_topic,
+ meta.notification_id,
+ &issue,
+ computed_baseline,
+ current_bucket_value,
+ )
+ .await?;
+
+ context.signal_client.emit_issue_spiking(
+ &issue,
+ &event_properties,
+ computed_baseline,
+ current_bucket_value,
+ );
+
+ Ok(())
+}
+
+fn issue_from_notification(
+ team_id: i32,
+ issue_id: Uuid,
+ issue: IssueSnapshot,
+) -> IssueNotificationData {
+ IssueNotificationData {
+ id: issue_id,
+ team_id,
+ status: issue.status,
+ name: issue.name,
+ description: issue.description,
+ created_at: issue.created_at,
+ }
+}
+
+async fn persist_spike_event(
+ context: &NotificationsContext,
+ notification_id: Uuid,
+ team_id: i32,
+ issue_id: Uuid,
+ computed_baseline: f64,
+ current_bucket_value: f64,
+) -> Result<(), UnhandledError> {
+ let now = Utc::now();
+ sqlx::query(
+ r#"INSERT INTO posthog_errortrackingspikeevent
+ (id, team_id, issue_id, detected_at, computed_baseline, current_bucket_value)
+ VALUES ($1, $2, $3, $4, $5, $6)
+ ON CONFLICT (id) DO NOTHING"#,
+ )
+ .bind(notification_id)
+ .bind(team_id)
+ .bind(issue_id)
+ .bind(now)
+ .bind(computed_baseline)
+ .bind(current_bucket_value as i32)
+ .execute(&context.posthog_pool)
+ .await?;
+
+ Ok(())
+}
+
+fn parse_notification_timestamp(event_timestamp: &str, event_uuid: Uuid) -> DateTime<Utc> {
+ common_types::format::parse_datetime_assuming_utc(event_timestamp).unwrap_or_else(|e| {
+ warn!(
+ event = event_uuid.to_string(),
+ "Failed to get event timestamp, using current time, error: {:?}", e
+ );
+ Utc::now()
+ })
+}
diff --git a/rust/cymbal/src/modes/notifications/mod.rs b/rust/cymbal/src/modes/notifications/mod.rs
index c77cb293e371..03390b607ae3 100644
--- a/rust/cymbal/src/modes/notifications/mod.rs
+++ b/rust/cymbal/src/modes/notifications/mod.rs
@@ -1,36 +1,42 @@
-//! 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.
+//! Notifications mode: consumes the `error_tracking_ingestion_notifications`
+//! Kafka topic and fans ingestion notifications out to downstream side effects.
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 common_kafka::kafka_consumer::SingleTopicConsumer;
use tokio::sync::watch;
use tokio::task::JoinHandle;
use tracing::{error, info, warn};
-use crate::core::{shutdown::wait_for_shutdown, types::notification::IngestionNotification};
+use crate::core::shutdown::wait_for_shutdown;
+use crate::modes::notifications::consumer_loop::consume_loop;
+use crate::modes::notifications::context::NotificationsContext;
+pub mod analytics;
pub mod config;
+mod consumer_loop;
+mod context;
+mod handler;
+mod issue_handler;
+pub mod side_effects;
+pub mod signals;
+pub mod stacktrace;
+pub mod types;
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");
+ let context = NotificationsContext::from_config(&config)
+ .await
+ .expect("failed to create notifications context");
info!(
topic = %config.consumer.kafka_consumer_topic,
@@ -44,7 +50,7 @@ pub async fn run(config: NotificationsConfig) {
let metrics_handle =
spawn_metrics_server(config.metrics_port, shutdown_rx.clone(), draining.clone());
- consume_loop(consumer, shutdown_rx).await;
+ consume_loop(consumer, context, shutdown_rx).await;
let _ignored = shutdown_tx.send(true);
if let Err(err) = metrics_handle.await {
@@ -53,60 +59,6 @@ pub async fn run(config: NotificationsConfig) {
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(&notification);
- 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>,
diff --git a/rust/cymbal/src/modes/notifications/side_effects.rs b/rust/cymbal/src/modes/notifications/side_effects.rs
new file mode 100644
index 000000000000..ebe44b0908d6
--- /dev/null
+++ b/rust/cymbal/src/modes/notifications/side_effects.rs
@@ -0,0 +1,210 @@
+use chrono::{DateTime, Utc};
+use common_kafka::kafka_messages::internal_events::{InternalEvent, InternalEventEvent};
+use common_kafka::kafka_producer::{send_iter_to_kafka, KafkaContext, KafkaProduceError};
+use common_types::embedding::{EmbeddingModel, EmbeddingRequest};
+use rdkafka::producer::FutureProducer;
+use rdkafka::types::RDKafkaErrorCode;
+use uuid::Uuid;
+
+use crate::core::error::UnhandledError;
+use crate::modes::notifications::stacktrace::print_stacktrace;
+use crate::modes::notifications::types::NotificationIssue;
+use crate::types::OutputErrProps;
+
+struct IssueLifecycleInternalEvent<'a, I: NotificationIssue> {
+ event: &'static str,
+ notification_id: Uuid,
+ issue: &'a I,
+ assignee: Option<String>,
+ output_props: &'a OutputErrProps,
+ event_timestamp: &'a DateTime<Utc>,
+}
+
+pub async fn send_new_fingerprint_event<I: NotificationIssue>(
+ producer: &FutureProducer<KafkaContext>,
+ embedding_worker_topic: &str,
+ issue: &I,
+ output_props: &OutputErrProps,
+) -> Result<(), UnhandledError> {
+ let request = fingerprint_embedding_request(issue, output_props);
+
+ let res = send_iter_to_kafka(producer, embedding_worker_topic, &[request])
+ .await
+ .into_iter()
+ .collect::<Result<Vec<_>, _>>();
+ if let Err(err) = res {
+ return Err(UnhandledError::KafkaProduceError(err));
+ }
+ Ok(())
+}
+
+fn fingerprint_embedding_request<I: NotificationIssue>(
+ issue: &I,
+ output_props: &OutputErrProps,
+) -> EmbeddingRequest {
+ EmbeddingRequest {
+ team_id: issue.team_id(),
+ product: "error_tracking".to_string(),
+ document_type: "fingerprint".to_string(),
+ rendering: "type_message_and_stack".to_string(),
+ document_id: output_props.fingerprint.clone(),
+ timestamp: issue.created_at(),
+ content: print_stacktrace(output_props, Some(7000)),
+ models: vec![EmbeddingModel::OpenAITextEmbeddingLarge],
+ metadata: Default::default(),
+ }
+}
+
+pub async fn send_issue_created_internal_event<I: NotificationIssue>(
+ producer: &FutureProducer<KafkaContext>,
+ internal_events_topic: &str,
+ notification_id: Uuid,
+ issue: &I,
+ assignee: Option<String>,
+ output_props: &OutputErrProps,
+ event_timestamp: &DateTime<Utc>,
+) -> Result<(), UnhandledError> {
+ send_internal_event_with_producer(
+ producer,
+ internal_events_topic,
+ IssueLifecycleInternalEvent {
+ event: "$error_tracking_issue_created",
+ notification_id,
+ issue,
+ assignee,
+ output_props,
+ event_timestamp,
+ },
+ )
+ .await
+}
+
+pub async fn send_issue_reopened_internal_event<I: NotificationIssue>(
+ producer: &FutureProducer<KafkaContext>,
+ internal_events_topic: &str,
+ notification_id: Uuid,
+ issue: &I,
+ assignee: Option<String>,
+ output_props: &OutputErrProps,
+ event_timestamp: &DateTime<Utc>,
+) -> Result<(), UnhandledError> {
+ send_internal_event_with_producer(
+ producer,
+ internal_events_topic,
+ IssueLifecycleInternalEvent {
+ event: "$error_tracking_issue_reopened",
+ notification_id,
+ issue,
+ assignee,
+ output_props,
+ event_timestamp,
+ },
+ )
+ .await
+}
+
+pub async fn send_issue_spiking_internal_event<I: NotificationIssue>(
+ producer: &FutureProducer<KafkaContext>,
+ internal_events_topic: &str,
+ notification_id: Uuid,
+ issue: &I,
+ computed_baseline: f64,
+ current_bucket_value: f64,
+) -> Result<(), UnhandledError> {
+ let mut event = InternalEventEvent::new(
+ "$error_tracking_issue_spiking",
+ issue.id(),
+ Utc::now(),
+ None,
+ );
+ event.uuid = notification_id.to_string();
+ event
+ .insert_prop("name", issue.name())
+ .expect("insert_prop for name should never fail");
+ event
+ .insert_prop("description", issue.description())
+ .expect("insert_prop for description should never fail");
+ event
+ .insert_prop("computed_baseline", computed_baseline)
+ .expect("insert_prop for computed_baseline should never fail");
+ event
+ .insert_prop("current_bucket_value", current_bucket_value)
+ .expect("insert_prop for current_bucket_value should never fail");
+
+ let iter = [InternalEvent {
+ team_id: issue.team_id(),
+ event,
+ person: None,
+ }];
+
+ send_iter_to_kafka(producer, internal_events_topic, &iter)
+ .await
+ .into_iter()
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(())
+}
+
+async fn send_internal_event_with_producer<I: NotificationIssue>(
+ producer: &FutureProducer<KafkaContext>,
+ internal_events_topic: &str,
+ request: IssueLifecycleInternalEvent<'_, I>,
+) -> Result<(), UnhandledError> {
+ let IssueLifecycleInternalEvent {
+ event,
+ notification_id,
+ issue,
+ assignee,
+ output_props,
+ event_timestamp,
+ } = request;
+
+ let mut event = InternalEventEvent::new(event, issue.id(), Utc::now(), None);
+ event.uuid = notification_id.to_string();
+ event
+ .insert_prop("name", issue.name())
+ .expect("Strings are serializable");
+ event
+ .insert_prop("description", issue.description())
+ .expect("Strings are serializable");
+ event.insert_prop("status", issue.status())?;
+ event.insert_prop("fingerprint", &output_props.fingerprint)?;
+ event.insert_prop("exception_timestamp", event_timestamp)?;
+ event.insert_prop("exception_props", output_props)?;
+
+ if let Some(assignee) = assignee {
+ event
+ .insert_prop("assignee", assignee)
+ .expect("Strings are serializable");
+ }
+
+ let iter = [InternalEvent {
+ team_id: issue.team_id(),
+ event,
+ person: None,
+ }];
+
+ let res = send_iter_to_kafka(producer, internal_events_topic, &iter)
+ .await
+ .into_iter()
+ .collect::<Result<Vec<_>, _>>();
+
+ match res {
+ Ok(_) => Ok(()),
+ Err(KafkaProduceError::KafkaProduceError { error })
+ if matches!(
+ error.rdkafka_error_code(),
+ Some(RDKafkaErrorCode::MessageSizeTooLarge)
+ ) =>
+ {
+ let mut iter = iter;
+ iter[0].event.properties.remove("exception_props");
+ iter[0].event.insert_prop("message_was_too_large", true)?;
+ send_iter_to_kafka(producer, internal_events_topic, &iter)
+ .await
+ .into_iter()
+ .collect::<Result<Vec<_>, _>>()?;
+ Ok(())
+ }
+ Err(e) => Err(e.into()),
+ }
+}
diff --git a/rust/cymbal/src/modes/processing/signals.rs b/rust/cymbal/src/modes/notifications/signals.rs
similarity index 74%
rename from rust/cymbal/src/modes/processing/signals.rs
rename to rust/cymbal/src/modes/notifications/signals.rs
index 772b4250923e..c4443732d852 100644
--- a/rust/cymbal/src/modes/processing/signals.rs
+++ b/rust/cymbal/src/modes/notifications/signals.rs
@@ -3,10 +3,9 @@ use std::sync::Arc;
use serde::Serialize;
use tracing::warn;
-use crate::issue_resolution::Issue;
use crate::metric_consts::{SIGNAL_EMITTED, SIGNAL_EMIT_FAILED, SIGNAL_EMIT_RESPONSE};
-use crate::modes::processing::config::ProcessingConfig;
-use crate::tokenizer::CL100K_BPE;
+use crate::modes::notifications::stacktrace::print_stacktrace;
+use crate::modes::notifications::types::NotificationIssue;
use crate::types::OutputErrProps;
/// Signal payload matching the Django internal API contract.
@@ -21,8 +20,8 @@ pub struct EmitSignalRequest {
}
/// Context for building a signal from an issue + its error properties.
-pub struct IssueSignalContext<'a> {
- pub issue: &'a Issue,
+pub struct IssueSignalContext<'a, I: NotificationIssue> {
+ pub issue: &'a I,
pub props: &'a OutputErrProps,
pub source_type: &'static str,
/// Brief LLM-facing explanation of what this signal means, e.g. "New issue" or "Issue reopened".
@@ -31,22 +30,24 @@ pub struct IssueSignalContext<'a> {
pub extra: serde_json::Value,
}
-impl<'a> From<IssueSignalContext<'a>> for EmitSignalRequest {
- fn from(ctx: IssueSignalContext<'a>) -> Self {
+impl<I: NotificationIssue> From<IssueSignalContext<'_, I>> for EmitSignalRequest {
+ fn from(ctx: IssueSignalContext<'_, I>) -> Self {
let header = format!(
"{}:\n{}: {}\n",
ctx.preamble,
- ctx.issue.name.as_deref().unwrap_or("Unknown"),
- ctx.issue.description.as_deref().unwrap_or(""),
+ ctx.issue.name().unwrap_or("Unknown"),
+ ctx.issue.description().unwrap_or("")
);
- let header_tokens = CL100K_BPE.encode_with_special_tokens(&header).len();
- let stacktrace = ctx.props.print_stacktrace(Some(8000 - header_tokens));
+ let header_tokens = crate::tokenizer::CL100K_BPE
+ .encode_with_special_tokens(&header)
+ .len();
+ let stacktrace = print_stacktrace(ctx.props, Some(8000 - header_tokens));
let description = format!("{header}\n```\n{stacktrace}\n```");
EmitSignalRequest {
source_product: "error_tracking",
source_type: ctx.source_type,
- source_id: ctx.issue.id.to_string(),
+ source_id: ctx.issue.id().to_string(),
description,
weight: ctx.weight,
extra: ctx.extra,
@@ -65,18 +66,22 @@ pub struct SignalClient {
}
impl SignalClient {
- pub fn new(config: &ProcessingConfig) -> Self {
+ pub fn new_with_parts(base_url: String, secret: String) -> Self {
Self {
http: reqwest::Client::builder()
.no_proxy()
.build()
.expect("Failed to build SignalClient HTTP client"),
- base_url: config.signals_api_base_url.clone(),
- secret: config.resolver.internal_api_secret.clone(),
+ base_url,
+ secret,
}
}
- pub async fn emit_issue_created(&self, issue: &Issue, props: &OutputErrProps) {
+ pub async fn emit_issue_created<I: NotificationIssue>(
+ &self,
+ issue: &I,
+ props: &OutputErrProps,
+ ) {
let request = EmitSignalRequest::from(IssueSignalContext {
issue,
props,
@@ -87,10 +92,14 @@ impl SignalClient {
"fingerprint": props.fingerprint,
}),
});
- self.send(issue.team_id, request).await;
+ self.send(issue.team_id(), request).await;
}
- pub async fn emit_issue_reopened(&self, issue: &Issue, props: &OutputErrProps) {
+ pub async fn emit_issue_reopened<I: NotificationIssue>(
+ &self,
+ issue: &I,
+ props: &OutputErrProps,
+ ) {
let request = EmitSignalRequest::from(IssueSignalContext {
issue,
props,
@@ -101,12 +110,12 @@ impl SignalClient {
"fingerprint": props.fingerprint,
}),
});
- self.send(issue.team_id, request).await;
+ self.send(issue.team_id(), request).await;
}
- pub async fn emit_issue_spiking(
+ pub async fn emit_issue_spiking<I: NotificationIssue>(
&self,
- issue: &Issue,
+ issue: &I,
props: &OutputErrProps,
computed_baseline: f64,
current_bucket_value: f64,
@@ -126,7 +135,7 @@ impl SignalClient {
"fingerprint": props.fingerprint,
}),
});
- self.send(issue.team_id, request).await;
+ self.send(issue.team_id(), request).await;
}
async fn send(&self, team_id: i32, body: EmitSignalRequest) {
@@ -161,7 +170,8 @@ impl SignalClient {
}
}
-/// Wraps an optional SignalClient. When signals are disabled, all calls are no-ops.
+/// Wraps an optional SignalClient. Signals are best-effort: callers should emit
+/// them after durable side effects, and failures only affect signal metrics/logs.
#[derive(Clone)]
pub struct MaybeSignalClient(Option<Arc<SignalClient>>);
@@ -174,7 +184,10 @@ impl MaybeSignalClient {
Self(Some(Arc::new(client)))
}
- pub fn emit_issue_created(&self, issue: &Issue, props: &OutputErrProps) {
+ pub fn emit_issue_created<I>(&self, issue: &I, props: &OutputErrProps)
+ where
+ I: NotificationIssue + Clone + Send + Sync + 'static,
+ {
if let Some(c) = self.0.clone() {
let issue = issue.clone();
let props = props.clone();
@@ -184,7 +197,10 @@ impl MaybeSignalClient {
}
}
- pub fn emit_issue_reopened(&self, issue: &Issue, props: &OutputErrProps) {
+ pub fn emit_issue_reopened<I>(&self, issue: &I, props: &OutputErrProps)
+ where
+ I: NotificationIssue + Clone + Send + Sync + 'static,
+ {
if let Some(c) = self.0.clone() {
let issue = issue.clone();
let props = props.clone();
@@ -194,13 +210,15 @@ impl MaybeSignalClient {
}
}
- pub fn emit_issue_spiking(
+ pub fn emit_issue_spiking<I>(
&self,
- issue: &Issue,
+ issue: &I,
props: &OutputErrProps,
computed_baseline: f64,
current_bucket_value: f64,
- ) {
+ ) where
+ I: NotificationIssue + Clone + Send + Sync + 'static,
+ {
if let Some(c) = self.0.clone() {
let issue = issue.clone();
let props = props.clone();
diff --git a/rust/cymbal/src/modes/notifications/stacktrace.rs b/rust/cymbal/src/modes/notifications/stacktrace.rs
new file mode 100644
index 000000000000..db5e05f48953
--- /dev/null
+++ b/rust/cymbal/src/modes/notifications/stacktrace.rs
@@ -0,0 +1,104 @@
+use crate::frames::Frame;
+use crate::tokenizer::CL100K_BPE;
+use crate::types::OutputErrProps;
+
+/// Render exception types, messages, and stack frames as a human-readable string.
+///
+/// If `max_tokens` is `Some(limit)`, the output is measured against `limit`
+/// tokens (using the cl100k_base tiktoken encoding). When the full output
+/// would exceed the limit, only the first and last frame of each exception
+/// are kept with a `...` marker between them. If the truncated output is
+/// still over the limit, the string is hard-truncated to exactly `limit`
+/// tokens.
+pub fn print_stacktrace(props: &OutputErrProps, max_tokens: Option<usize>) -> String {
+ let full = render_stacktrace(props, false);
+
+ let Some(limit) = max_tokens else {
+ return full;
+ };
+
+ let bpe = &*CL100K_BPE;
+ let tokens = bpe.encode_with_special_tokens(&full);
+
+ if tokens.len() <= limit {
+ return full;
+ }
+
+ let truncated = render_stacktrace(props, true);
+ let tokens = bpe.encode_with_special_tokens(&truncated);
+
+ if tokens.len() <= limit {
+ return truncated;
+ }
+
+ let mut tokens: Vec<_> = tokens.into_iter().take(limit).collect();
+ loop {
+ match bpe.decode(tokens.clone()) {
+ Ok(text) => break text,
+ Err(_) => {
+ tokens.pop();
+ }
+ }
+ }
+}
+
+fn render_stacktrace(props: &OutputErrProps, truncate: bool) -> String {
+ let mut content = String::with_capacity(2048);
+
+ for exception in &props.exception_list.0 {
+ let type_and_value = format!(
+ "{}: {}\n",
+ exception.exception_type,
+ exception
+ .exception_message
+ .chars()
+ .take(300)
+ .collect::<String>()
+ );
+
+ content.push_str(&type_and_value);
+
+ let Some(stack) = &exception.stack else {
+ continue;
+ };
+
+ let frames = stack.get_frames();
+
+ if truncate && frames.len() > 2 {
+ content.push_str(&render_frame(&frames[0]));
+ content.push_str("...\n");
+ content.push_str(&render_frame(frames.last().unwrap()));
+ } else {
+ for frame in frames {
+ content.push_str(&render_frame(frame));
+ }
+ }
+ }
+
+ content
+}
+
+fn render_frame(frame: &Frame) -> String {
+ let mut output = String::new();
+
+ if let Some(resolved_name) = &frame.resolved_name {
+ output.push_str(resolved_name);
+ } else {
+ output.push_str(&frame.mangled_name);
+ }
+
+ if let Some(source) = &frame.source {
+ output.push_str(&format!(" in {source}"));
+ }
+
+ if let Some(line) = frame.line {
+ output.push_str(&format!(" line {line}"));
+ }
+
+ if let Some(column) = frame.column {
+ output.push_str(&format!(" column {column}"));
+ }
+
+ output.push('\n');
+ output
+}
diff --git a/rust/cymbal/src/modes/notifications/types.rs b/rust/cymbal/src/modes/notifications/types.rs
new file mode 100644
index 000000000000..4448068f3125
--- /dev/null
+++ b/rust/cymbal/src/modes/notifications/types.rs
@@ -0,0 +1,54 @@
+use chrono::{DateTime, Utc};
+use uuid::Uuid;
+
+pub trait NotificationIssue {
+ fn id(&self) -> Uuid;
+ fn team_id(&self) -> i32;
+ fn name(&self) -> Option<&str>;
+ fn description(&self) -> Option<&str>;
+ fn status(&self) -> &str;
+ fn created_at(&self) -> DateTime<Utc>;
+}
+
+#[derive(Debug, Clone, sqlx::FromRow)]
+pub struct IssueNotificationData {
+ pub id: Uuid,
+ pub team_id: i32,
+ pub status: String,
+ pub name: Option<String>,
+ pub description: Option<String>,
+ pub created_at: DateTime<Utc>,
+}
+
+impl NotificationIssue for IssueNotificationData {
+ fn id(&self) -> Uuid {
+ self.id
+ }
+
+ fn team_id(&self) -> i32 {
+ self.team_id
+ }
+
+ fn name(&self) -> Option<&str> {
+ self.name.as_deref()
+ }
+
+ fn description(&self) -> Option<&str> {
+ self.description.as_deref()
+ }
+
+ fn status(&self) -> &str {
+ match self.status.as_str() {
+ "archived" => "Archived",
+ "active" => "Active",
+ "resolved" => "Resolved",
+ "pending_release" => "Pending Release",
+ "suppressed" => "Suppressed",
+ _ => &self.status,
+ }
+ }
+
+ fn created_at(&self) -> DateTime<Utc> {
+ self.created_at
+ }
+}
diff --git a/rust/cymbal/src/modes/processing/app_context.rs b/rust/cymbal/src/modes/processing/app_context.rs
index baa0c43c2aa5..18ce5467b362 100644
--- a/rust/cymbal/src/modes/processing/app_context.rs
+++ b/rust/cymbal/src/modes/processing/app_context.rs
@@ -14,7 +14,6 @@ use crate::{
core::resolver::build_catalog,
error::UnhandledError,
modes::processing::config::{init_global_state, ProcessingConfig},
- signals::{MaybeSignalClient, SignalClient},
stages::rate_limiting::RedisRateLimiter,
stages::resolution::remote::{
dns::TokioDnsResolver, pool::EndpointPool, resolver::RemoteResolutionContext,
@@ -57,7 +56,6 @@ pub struct AppContext {
// Team allowlist for the rate limiter: `None` = all teams, `Some(set)` = only
// these. Parsed from ERROR_TRACKING_RATE_LIMITER_ENABLED_TEAM_IDS.
pub rate_limiter_enabled_team_ids: Option<HashSet<i32>>,
- pub signal_client: MaybeSignalClient,
// Shared `(team_id, fingerprint) -> issue_id` mapping cache. Lives on AppContext so
// it persists across requests — only the stable mapping is cached, never the Issue
// itself, so suppression / reopen always see current PG state (see `IssueLinker`).
@@ -166,16 +164,6 @@ impl AppContext {
let team_manager = TeamManager::new(config);
- let signal_client = if config.signals_api_base_url.is_empty() {
- MaybeSignalClient::disabled()
- } else {
- info!(
- "Signal emission enabled, base_url={}",
- config.signals_api_base_url
- );
- MaybeSignalClient::enabled(SignalClient::new(config))
- };
-
let symbol_resolver = Arc::new(LocalSymbolResolver::new(
&config.resolver,
catalog.clone(),
@@ -212,7 +200,6 @@ impl AppContext {
issue_buckets_redis_client,
rate_limiter,
rate_limiter_enabled_team_ids,
- signal_client,
symbol_resolver,
issue_cache,
remote_resolution,
diff --git a/rust/cymbal/src/modes/processing/config.rs b/rust/cymbal/src/modes/processing/config.rs
index 61f5aa3779ba..f6a627bbe1e1 100644
--- a/rust/cymbal/src/modes/processing/config.rs
+++ b/rust/cymbal/src/modes/processing/config.rs
@@ -67,6 +67,9 @@ pub struct ProcessingConfig {
#[envconfig(default = "document_embeddings_input")]
pub embedding_worker_topic: String,
+ #[envconfig(default = "error_tracking_ingestion_notifications")]
+ pub ingestion_notifications_topic: String,
+
#[envconfig(default = "600")]
pub issue_cache_ttl_seconds: u64,
@@ -160,10 +163,6 @@ pub struct ProcessingConfig {
#[envconfig(default = "")]
pub spike_alert_enabled_team_ids: String,
- // Internal API for signal emission
- #[envconfig(default = "")]
- pub signals_api_base_url: String,
-
// ----------------------------------------------------------------------
// Remote resolution (cymbal.resolution.v1) — Batch 3 client integration.
//
diff --git a/rust/cymbal/src/modes/processing/issue_resolution.rs b/rust/cymbal/src/modes/processing/issue_resolution.rs
index c8f2971ba620..f9aebb3be30b 100644
--- a/rust/cymbal/src/modes/processing/issue_resolution.rs
+++ b/rust/cymbal/src/modes/processing/issue_resolution.rs
@@ -1,19 +1,19 @@
use std::fmt::Display;
use chrono::{DateTime, Utc};
-use common_kafka::kafka_messages::internal_events::{InternalEvent, InternalEventEvent};
-use common_kafka::kafka_producer::{send_iter_to_kafka, KafkaProduceError};
-
-use rdkafka::types::RDKafkaErrorCode;
+use common_kafka::kafka_producer::{
+ send_iter_to_kafka, send_keyed_iter_to_kafka, KafkaProduceError,
+};
use serde::{Deserialize, Serialize};
use uuid::Uuid;
+use crate::core::types::notification::{
+ IngestionNotification, IssueCreated, IssueNotificationContext, IssueReopened, IssueSnapshot,
+ IssueSpiking, NotificationMeta,
+};
use crate::modes::processing::rules::assignment::{Assignee, Assignment};
use crate::types::OutputErrProps;
-use crate::{
- analytics::capture_issue_reopened, app_context::AppContext, error::UnhandledError,
- metric_consts::ISSUE_REOPENED,
-};
+use crate::{app_context::AppContext, error::UnhandledError, metric_consts::ISSUE_REOPENED};
#[derive(Debug, Clone)]
pub struct IssueFingerprintOverride {
@@ -70,18 +70,6 @@ pub enum IssueStatus {
Suppressed,
}
-impl IssueStatus {
- fn as_str(&self) -> &'static str {
- match self {
- IssueStatus::Archived => "Archived",
- IssueStatus::Active => "Active",
- IssueStatus::Resolved => "Resolved",
- IssueStatus::PendingRelease => "Pending Release",
- IssueStatus::Suppressed => "Suppressed",
- }
- }
-}
-
impl Issue {
pub async fn load_by_fingerprint<'c, E>(
executor: E,
@@ -196,7 +184,6 @@ impl Issue {
// (fingerprint_issue_state, internal events) are not stale.
self.status = IssueStatus::Active;
metrics::counter!(ISSUE_REOPENED).increment(1);
- capture_issue_reopened(self.team_id, self.id);
}
Ok(reopened)
@@ -352,130 +339,118 @@ impl IssueFingerprintOverride {
}
}
-pub async fn send_issue_created_alert(
+pub async fn send_issue_created_notification(
context: &AppContext,
issue: &Issue,
assignment: Option<Assignment>,
output_props: OutputErrProps,
+ event_uuid: Uuid,
event_timestamp: &DateTime<Utc>,
) -> Result<(), UnhandledError> {
- send_internal_event(
+ let fingerprint = output_props.fingerprint.clone();
+ publish_ingestion_notification(
context,
- "$error_tracking_issue_created",
- issue,
- assignment,
- output_props,
- event_timestamp,
+ IngestionNotification::IssueCreated(IssueCreated {
+ meta: notification_meta(issue),
+ issue: issue_notification_context(issue, output_props),
+ fingerprint,
+ event_uuid,
+ event_timestamp: event_timestamp.to_rfc3339(),
+ assignee: assignment_to_string(assignment)?,
+ }),
)
.await
}
-pub async fn send_new_fingerprint_event(
+pub async fn send_issue_reopened_notification(
context: &AppContext,
issue: &Issue,
- output_props: &OutputErrProps,
+ assignment: Option<Assignment>,
+ output_props: OutputErrProps,
+ event_timestamp: &DateTime<Utc>,
) -> Result<(), UnhandledError> {
- let request = output_props.to_fingerprint_embedding_request(issue);
-
- let res = send_iter_to_kafka(
- &context.immediate_producer,
- &context.config.embedding_worker_topic,
- &[request],
+ publish_ingestion_notification(
+ context,
+ IngestionNotification::IssueReopened(IssueReopened {
+ meta: notification_meta(issue),
+ issue: issue_notification_context(issue, output_props),
+ event_timestamp: event_timestamp.to_rfc3339(),
+ assignee: assignment_to_string(assignment)?,
+ }),
)
.await
- .into_iter()
- .collect::<Result<Vec<_>, _>>();
- if let Err(err) = res {
- return Err(UnhandledError::KafkaProduceError(err));
- }
- Ok(())
}
-pub async fn send_issue_reopened_alert(
+pub async fn send_issue_spiking_notification(
context: &AppContext,
issue: &Issue,
- assignment: Option<Assignment>,
output_props: OutputErrProps,
- event_timestamp: &DateTime<Utc>,
+ computed_baseline: f64,
+ current_bucket_value: f64,
) -> Result<(), UnhandledError> {
- send_internal_event(
+ publish_ingestion_notification(
context,
- "$error_tracking_issue_reopened",
- issue,
- assignment,
- output_props,
- event_timestamp,
+ IngestionNotification::IssueSpiking(IssueSpiking {
+ meta: notification_meta(issue),
+ issue: issue_notification_context(issue, output_props),
+ computed_baseline,
+ current_bucket_value,
+ }),
)
.await
}
-async fn send_internal_event(
- context: &AppContext,
- event: &str,
+fn notification_meta(issue: &Issue) -> NotificationMeta {
+ NotificationMeta {
+ notification_id: Uuid::now_v7(),
+ team_id: issue.team_id,
+ }
+}
+
+fn issue_notification_context(
issue: &Issue,
- new_assignment: Option<Assignment>,
output_props: OutputErrProps,
- event_timestamp: &DateTime<Utc>,
-) -> Result<(), UnhandledError> {
- let mut event = InternalEventEvent::new(event, issue.id, Utc::now(), None);
- event
- .insert_prop("name", issue.name.clone())
- .expect("Strings are serializable");
- event
- .insert_prop("description", issue.description.clone())
- .expect("Strings are serializable");
- event.insert_prop("status", issue.status.as_str())?;
- event.insert_prop("fingerprint", &output_props.fingerprint)?;
- event.insert_prop("exception_timestamp", event_timestamp)?;
- event.insert_prop("exception_props", output_props)?;
-
- if let Some(assignment) = new_assignment {
- let assignee = Assignee::try_from(&assignment)?;
- let stringified_assignee = serde_json::to_string(&assignee)?;
-
- event
- .insert_prop("assignee", stringified_assignee)
- .expect("Strings are serializable");
+) -> IssueNotificationContext {
+ IssueNotificationContext {
+ issue_id: issue.id,
+ issue: issue_snapshot(issue),
+ event_properties: output_props,
}
+}
- let iter = [InternalEvent {
- team_id: issue.team_id,
- event,
- person: None,
- }];
-
- let res = send_iter_to_kafka(
- &context.cyclotron_producer,
- &context.config.internal_events_topic,
- &iter,
+fn issue_snapshot(issue: &Issue) -> IssueSnapshot {
+ IssueSnapshot {
+ name: issue.name.clone(),
+ description: issue.description.clone(),
+ status: issue.status.to_string(),
+ created_at: issue.created_at,
+ }
+}
+
+async fn publish_ingestion_notification(
+ context: &AppContext,
+ notification: IngestionNotification,
+) -> Result<(), UnhandledError> {
+ send_keyed_iter_to_kafka(
+ &context.immediate_producer,
+ &context.config.ingestion_notifications_topic,
+ |notification| Some(notification.partition_key()),
+ std::iter::once(notification),
)
.await
.into_iter()
- .collect::<Result<Vec<_>, _>>();
-
- match res {
- Ok(_) => Ok(()),
- Err(KafkaProduceError::KafkaProduceError { error })
- if matches!(
- error.rdkafka_error_code(),
- Some(RDKafkaErrorCode::MessageSizeTooLarge)
- ) =>
- {
- let mut iter = iter;
- iter[0].event.properties.remove("exception_props");
- iter[0].event.insert_prop("message_was_too_large", true)?;
- send_iter_to_kafka(
- &context.cyclotron_producer,
- &context.config.internal_events_topic,
- &iter,
- )
- .await
- .into_iter()
- .collect::<Result<Vec<_>, _>>()?;
- Ok(())
- }
- Err(e) => Err(e.into()),
- }
+ .collect::<Result<Vec<_>, KafkaProduceError>>()
+ .map_err(UnhandledError::KafkaProduceError)?;
+ Ok(())
+}
+
+fn assignment_to_string(assignment: Option<Assignment>) -> Result<Option<String>, UnhandledError> {
+ let Some(assignment) = assignment else {
+ return Ok(None);
+ };
+
+ let assignee = Assignee::try_from(&assignment)?;
+ Ok(Some(serde_json::to_string(&assignee)?))
}
impl From<String> for IssueStatus {
diff --git a/rust/cymbal/src/modes/processing/mod.rs b/rust/cymbal/src/modes/processing/mod.rs
index c1ba5f24d431..0f3d70df24a6 100644
--- a/rust/cymbal/src/modes/processing/mod.rs
+++ b/rust/cymbal/src/modes/processing/mod.rs
@@ -9,7 +9,6 @@ use std::sync::Arc;
use crate::app_context::AppContext;
use crate::server::start_server;
-pub mod analytics;
pub mod app_context;
pub mod config;
pub mod fingerprinting;
@@ -17,7 +16,6 @@ pub mod issue_resolution;
pub mod router;
pub mod rules;
pub mod server;
-pub mod signals;
pub mod stages;
pub mod teams;
pub mod tokenizer;
diff --git a/rust/cymbal/src/modes/processing/stages/alerting/spike_detection.rs b/rust/cymbal/src/modes/processing/stages/alerting/spike_detection.rs
index 702238c6eca9..69509ec7c099 100644
--- a/rust/cymbal/src/modes/processing/stages/alerting/spike_detection.rs
+++ b/rust/cymbal/src/modes/processing/stages/alerting/spike_detection.rs
@@ -1,8 +1,6 @@
use std::sync::Arc;
use chrono::{DateTime, Duration, SecondsFormat, Utc};
-use common_kafka::kafka_messages::internal_events::{InternalEvent, InternalEventEvent};
-use common_kafka::kafka_producer::send_iter_to_kafka;
use common_redis::Client;
use std::collections::HashMap;
use tracing::warn;
@@ -10,11 +8,11 @@ use uuid::Uuid;
use crate::app_context::AppContext;
use crate::error::UnhandledError;
-use crate::issue_resolution::Issue;
+use crate::issue_resolution::{send_issue_spiking_notification, Issue};
use crate::metric_consts::{
- SPIKE_ACQUIRE_LOCKS_TIME, SPIKE_EMIT_EVENTS_TIME, SPIKE_GET_SPIKING_ISSUES_TIME,
- SPIKE_INCREMENT_ISSUE_BUCKETS_TIME, SPIKE_INCREMENT_TEAM_BUCKETS_TIME,
- SPIKE_ISSUES_BLOCKED_BY_COOLDOWN, SPIKE_ISSUES_CHECKED, SPIKE_ISSUES_SPIKING,
+ SPIKE_ACQUIRE_LOCKS_TIME, SPIKE_GET_SPIKING_ISSUES_TIME, SPIKE_INCREMENT_ISSUE_BUCKETS_TIME,
+ SPIKE_INCREMENT_TEAM_BUCKETS_TIME, SPIKE_ISSUES_BLOCKED_BY_COOLDOWN, SPIKE_ISSUES_CHECKED,
+ SPIKE_ISSUES_SPIKING,
};
use crate::modes::processing::rules::spike::SpikeDetectionConfig;
use crate::types::OutputErrProps;
@@ -23,7 +21,6 @@ const ISSUE_BUCKET_TTL_SECONDS: usize = 60 * 60;
const ISSUE_BUCKET_INTERVAL_MINUTES: i64 = 5;
const NUM_BUCKETS: usize = 12;
-const ISSUE_SPIKING_EVENT: &str = "$error_tracking_issue_spiking";
const MIN_HISTORICAL_BUCKETS_FOR_ISSUE_BASELINE: usize = 1;
fn issue_bucket_key(issue_id: &Uuid, timestamp: &str) -> String {
@@ -302,85 +299,23 @@ async fn emit_spiking_events(
return;
}
- // Persist spike events to Postgres and emit a signal
+ // Publish spike side effects out of the processing hot path.
+ let mut failed_keys = Vec::new();
for spike in &acquired_locks {
- let id = Uuid::now_v7();
- let now = Utc::now();
- if let Err(e) = sqlx::query(
- r#"INSERT INTO posthog_errortrackingspikeevent
- (id, team_id, issue_id, detected_at, computed_baseline, current_bucket_value)
- VALUES ($1, $2, $3, $4, $5, $6)"#,
+ if let Err(e) = send_issue_spiking_notification(
+ context,
+ &spike.issue,
+ spike.props.clone(),
+ spike.computed_baseline,
+ spike.current_bucket_value as f64,
)
- .bind(id)
- .bind(spike.issue.team_id)
- .bind(spike.issue.id)
- .bind(now)
- .bind(spike.computed_baseline)
- .bind(spike.current_bucket_value as i32)
- .execute(&context.posthog_pool)
.await
{
- warn!("Failed to persist spike event: {e}");
+ warn!("Failed to publish spike notification: {e}");
+ failed_keys.push(cooldown_key(&spike.issue.id));
}
-
- context.signal_client.emit_issue_spiking(
- &spike.issue,
- &spike.props,
- spike.computed_baseline,
- spike.current_bucket_value as f64,
- );
}
- let emit_timer = common_metrics::timing_guard(SPIKE_EMIT_EVENTS_TIME, &[]);
- let events: Vec<(Uuid, InternalEvent)> = acquired_locks
- .iter()
- .map(|spike| {
- let mut event =
- InternalEventEvent::new(ISSUE_SPIKING_EVENT, spike.issue.id, Utc::now(), None);
- event
- .insert_prop("name", spike.issue.name.clone())
- .expect("insert_prop for name should never fail");
- event
- .insert_prop("description", spike.issue.description.clone())
- .expect("insert_prop for description should never fail");
- event
- .insert_prop("computed_baseline", spike.computed_baseline)
- .expect("insert_prop for computed_baseline should never fail");
- event
- .insert_prop("current_bucket_value", spike.current_bucket_value)
- .expect("insert_prop for current_bucket_value should never fail");
- (
- spike.issue.id,
- InternalEvent {
- team_id: spike.issue.team_id,
- event,
- person: None,
- },
- )
- })
- .collect();
-
- let kafka_events: Vec<&InternalEvent> = events.iter().map(|(_, e)| e).collect();
- let results = send_iter_to_kafka(
- &context.cyclotron_producer,
- &context.config.internal_events_topic,
- &kafka_events,
- )
- .await;
-
- let failed_keys: Vec<String> = results
- .into_iter()
- .enumerate()
- .filter_map(|(i, result)| {
- if let Err(e) = result {
- warn!("Failed to emit spiking event: {e}");
- Some(cooldown_key(&events[i].0))
- } else {
- None
- }
- })
- .collect();
-
if !failed_keys.is_empty() {
if let Err(e) = context
.issue_buckets_redis_client
@@ -390,7 +325,6 @@ async fn emit_spiking_events(
warn!("Failed to release cooldown locks after Kafka failure: {e}");
}
}
- emit_timer.fin();
}
fn get_bucket_timestamps() -> Vec<String> {
diff --git a/rust/cymbal/src/modes/processing/stages/linking/issue.rs b/rust/cymbal/src/modes/processing/stages/linking/issue.rs
index 24bcc33b6883..8c907b379064 100644
--- a/rust/cymbal/src/modes/processing/stages/linking/issue.rs
+++ b/rust/cymbal/src/modes/processing/stages/linking/issue.rs
@@ -7,12 +7,11 @@ use tracing::warn;
use uuid::Uuid;
use crate::{
- analytics::capture_issue_created,
app_context::AppContext,
error::UnhandledError,
issue_resolution::{
- send_fingerprint_issue_state, send_issue_created_alert, send_issue_reopened_alert,
- send_new_fingerprint_event, Issue, IssueFingerprintOverride,
+ send_fingerprint_issue_state, send_issue_created_notification,
+ send_issue_reopened_notification, Issue, IssueFingerprintOverride,
},
metric_consts::{ISSUE_CREATED, ISSUE_LINKER_OPERATOR},
modes::processing::rules::assignment::{try_assignment_rules, Assignment},
@@ -206,10 +205,8 @@ async fn load_and_maybe_reopen(
.await?;
let output_props: OutputErrProps = event_properties.to_output(issue.id)?;
drop(conn);
- context
- .signal_client
- .emit_issue_reopened(&issue, &output_props);
- send_issue_reopened_alert(context, &issue, assignment, output_props, &event_timestamp).await?;
+ send_issue_reopened_notification(context, &issue, assignment, output_props, &event_timestamp)
+ .await?;
Ok(Some(issue))
}
@@ -247,11 +244,14 @@ async fn resolve_issue(
.await?;
let output_props: OutputErrProps = event_properties.to_output(issue.id)?;
drop(conn);
- context
- .signal_client
- .emit_issue_reopened(&issue, &output_props);
- send_issue_reopened_alert(context, &issue, assignment, output_props, &event_timestamp)
- .await?;
+ send_issue_reopened_notification(
+ context,
+ &issue,
+ assignment,
+ output_props,
+ &event_timestamp,
+ )
+ .await?;
}
return Ok(issue);
}
@@ -315,11 +315,14 @@ async fn resolve_issue(
drop(conn);
let output_props: OutputErrProps = event_properties.to_output(issue.id)?;
- context
- .signal_client
- .emit_issue_reopened(&issue, &output_props);
- send_issue_reopened_alert(context, &issue, assignment, output_props, &event_timestamp)
- .await?;
+ send_issue_reopened_notification(
+ context,
+ &issue,
+ assignment,
+ output_props,
+ &event_timestamp,
+ )
+ .await?;
}
} else {
metrics::counter!(ISSUE_CREATED).increment(1);
@@ -327,7 +330,6 @@ async fn resolve_issue(
process_assignment(&mut txn, &context.team_manager, &issue, &event_properties).await?;
let output_props = event_properties.clone().to_output(issue.id)?;
- send_new_fingerprint_event(context, &issue, &output_props).await?;
send_fingerprint_issue_state(
context,
&issue,
@@ -340,18 +342,15 @@ async fn resolve_issue(
txn.commit().await?;
drop(conn);
- context
- .signal_client
- .emit_issue_created(&issue, &output_props);
-
- send_issue_created_alert(context, &issue, assignment, output_props, &event_timestamp)
- .await?;
-
- capture_issue_created(
- team_id,
- issue_override.issue_id,
- event_properties.props.contains_key("$sentry_event_id"),
- );
+ send_issue_created_notification(
+ context,
+ &issue,
+ assignment,
+ output_props,
+ event_properties.uuid,
+ &event_timestamp,
+ )
+ .await?;
};
Ok(issue)
diff --git a/rust/cymbal/src/modes/processing/types/mod.rs b/rust/cymbal/src/modes/processing/types/mod.rs
index beac4805cf9e..e26d3fa430ee 100644
--- a/rust/cymbal/src/modes/processing/types/mod.rs
+++ b/rust/cymbal/src/modes/processing/types/mod.rs
@@ -1,4 +1,3 @@
-use common_types::embedding::{EmbeddingModel, EmbeddingRequest};
use common_types::error_tracking::RawFrameId;
use serde::{Deserialize, Serialize};
use serde_json::Value;
@@ -10,10 +9,8 @@ use uuid::Uuid;
use crate::fingerprinting::{FingerprintBuilder, FingerprintComponent, FingerprintRecordPart};
use crate::frames::releases::{ReleaseInfo, ReleaseRecord};
use crate::frames::{Frame, RawFrame};
-use crate::issue_resolution::Issue;
use crate::langs::native::DebugImage;
use crate::metric_consts::POSTHOG_SDK_EXCEPTION_RESOLVED;
-use crate::tokenizer::CL100K_BPE;
pub mod batch;
pub mod event;
@@ -264,128 +261,6 @@ impl OutputErrProps {
}
});
}
-
- /// Render exception types, messages, and stack frames as a human-readable string.
- ///
- /// If `max_tokens` is `Some(limit)`, the output is measured against `limit`
- /// tokens (using the cl100k_base tiktoken encoding). When the full output
- /// would exceed the limit, only the first and last frame of each exception
- /// are kept with a `...` marker between them. If the truncated output is
- /// still over the limit, the string is hard-truncated to exactly `limit`
- /// tokens.
- pub fn print_stacktrace(&self, max_tokens: Option<usize>) -> String {
- let full = self.render_stacktrace(false);
-
- let Some(limit) = max_tokens else {
- return full;
- };
-
- let bpe = &*CL100K_BPE;
- let tokens = bpe.encode_with_special_tokens(&full);
-
- if tokens.len() <= limit {
- return full;
- }
-
- let truncated = self.render_stacktrace(true);
- let tokens = bpe.encode_with_special_tokens(&truncated);
-
- if tokens.len() <= limit {
- return truncated;
- }
-
- // Hard-truncate to `limit` tokens. Truncation can split a multi-byte
- // character's token sequence, producing bytes that aren't valid UTF-8
- // on decode. Drop trailing tokens until we land on a clean boundary.
- let mut tokens: Vec<_> = tokens.into_iter().take(limit).collect();
- loop {
- match bpe.decode(tokens.clone()) {
- Ok(text) => break text,
- Err(_) => {
- tokens.pop();
- }
- }
- }
- }
-
- fn render_stacktrace(&self, truncate: bool) -> String {
- let mut content = String::with_capacity(2048);
-
- for exception in &self.exception_list.0 {
- // Add exception type and value
- let type_and_value = format!(
- "{}: {}\n",
- exception.exception_type,
- exception
- .exception_message
- .chars()
- .take(300)
- .collect::<String>()
- );
-
- content.push_str(&type_and_value);
-
- let Some(stack) = &exception.stack else {
- continue;
- };
-
- let frames = stack.get_frames();
-
- if truncate && frames.len() > 2 {
- content.push_str(&Self::render_frame(&frames[0]));
- content.push_str("...\n");
- content.push_str(&Self::render_frame(frames.last().unwrap()));
- } else {
- for frame in frames {
- content.push_str(&Self::render_frame(frame));
- }
- }
- }
-
- content
- }
-
- fn render_frame(frame: &Frame) -> String {
- let mut output = String::new();
-
- if let Some(resolved_name) = &frame.resolved_name {
- output.push_str(resolved_name);
- } else {
- output.push_str(&frame.mangled_name);
- }
-
- if let Some(source) = &frame.source {
- output.push_str(&format!(" in {source}"));
- }
-
- if let Some(line) = frame.line {
- output.push_str(&format!(" line {line}"));
- }
-
- if let Some(column) = frame.column {
- output.push_str(&format!(" column {column}"));
- }
-
- output.push('\n');
- output
- }
-
- pub fn to_fingerprint_embedding_request(&self, issue: &Issue) -> EmbeddingRequest {
- EmbeddingRequest {
- team_id: issue.team_id,
- product: "error_tracking".to_string(),
- document_type: "fingerprint".to_string(),
- rendering: "type_message_and_stack".to_string(),
- document_id: self.fingerprint.clone(),
- timestamp: issue.created_at,
- content: self.print_stacktrace(Some(7000)),
- models: vec![
- EmbeddingModel::OpenAITextEmbeddingLarge,
- EmbeddingModel::OpenAITextEmbeddingSmall,
- ],
- metadata: Default::default(),
- }
- }
}
impl Stacktrace {