: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): capture service exceptions in cymbal services (#63356)
Catalin Irimie899049b801cb
diff --git a/rust/cymbal-resolution/src/service/resolve.rs b/rust/cymbal-resolution/src/service/resolve.rsindex 5412a04fdff1..b38767cac0b6 100644--- a/rust/cymbal-resolution/src/service/resolve.rs+++ b/rust/cymbal-resolution/src/service/resolve.rs@@ -1,5 +1,8 @@+use std::sync::Arc;use std::time::{Duration, Instant};+use serde_json::json;+use tokio::sync::mpsc;use tonic::{Status, Streaming};use tracing::{debug, warn};@@ -288,21 +291,21 @@ async fn resolve_one_exception(.symbol_resolver.resolve_java_exception(team_id, exception).await- .map_err(to_unhandled)?+ .map_err(|err| capture_unhandled(team_id, err))?} else if ExceptionResolver::is_dart_exception(&exception) {let _permit = acquire_permit(&stage).await?;stage.symbol_resolver.resolve_dart_exception(team_id, exception).await- .map_err(to_unhandled)?+ .map_err(|err| capture_unhandled(team_id, err))?} else {exception};FrameResolver::resolve_exception_frames(team_id, exception, &debug_images, stage).await- .map_err(to_unhandled)+ .map_err(|err| capture_unhandled(team_id, err))}async fn acquire_permit(@@ -314,7 +317,9 @@ async fn acquire_permit(.map_err(|_| ResolveOneError::Overloaded)}-fn to_unhandled(err: UnhandledError) -> ResolveOneError {+fn capture_unhandled(team_id: i32, err: UnhandledError) -> ResolveOneError {+ let err = Arc::new(err);+ common_posthog::capture_exception(err.clone(), [("team_id", json!(team_id))]);ResolveOneError::Unhandled(err.to_string())}diff --git a/rust/cymbal/src/router/event.rs b/rust/cymbal/src/router/event.rsindex 3603fa488497..c5871107176e 100644--- a/rust/cymbal/src/router/event.rs+++ b/rust/cymbal/src/router/event.rs@@ -48,16 +48,10 @@ fn get_request_id(headers: &HeaderMap) -> String {}pub enum ProcessEventsError {- Unhandled(UnhandledError),+ Unhandled(Arc<UnhandledError>),Backpressure,}-impl From<UnhandledError> for ProcessEventsError {- fn from(value: UnhandledError) -> Self {- Self::Unhandled(value)- }-}-impl IntoResponse for ProcessEventsError {fn into_response(self) -> axum::response::Response {match self {@@ -216,5 +210,19 @@ pub async fn process_events(}}- output.map_err(ProcessEventsError::from)+ match output {+ Ok(batch) => Ok(batch),+ Err(err) => {+ let err = Arc::new(err);+ common_posthog::capture_exception(+ err.clone(),+ [+ ("request_id", json!(request_id)),+ ("batch_event_count", json!(batch_event_count)),+ ("team_count", json!(team_count)),+ ],+ );+ Err(ProcessEventsError::Unhandled(err))+ }+ }}diff --git a/rust/cymbal/tests/posthog_capture.rs b/rust/cymbal/tests/posthog_capture.rsnew file mode 100644index 000000000000..58879fd96fe1--- /dev/null+++ b/rust/cymbal/tests/posthog_capture.rs@@ -0,0 +1,111 @@+use std::sync::Arc;+use std::time::Duration;++use axum::{body::Body, http::Request};+use common_redis::MockRedisClient;+use cymbal::{app_context::AppContext, config::Config, router::get_router};+use httpmock::prelude::*;+use mockall::predicate;+use serde_json::json;+use sqlx::PgPool;+use tower::ServiceExt;+use uuid::Uuid;++mod utils;+use utils::MockS3Client;++const STORAGE_BUCKET: &str = "test-bucket";++// One test per binary: common_posthog::init configures a process-wide global+// client, so a second init with a different mock server would be ignored.+#[sqlx::test(migrations = "./tests/test_migrations")]+async fn pipeline_failure_is_captured_as_posthog_exception(db: PgPool) {+ let posthog = MockServer::start_async().await;+ let capture = posthog+ .mock_async(|when, then| {+ when.method(POST)+ .path("/i/v0/e/")+ .body_contains("\"$exception\"")+ .body_contains("UnhandledError")+ .body_contains("\"service\":\"cymbal-test\"")+ .body_contains("\"request_id\"");+ then.status(200).body("{\"status\": 1}");+ })+ .await;+ // Catch-all so an unexpected payload shape fails the specific assertion+ // below instead of surfacing as a connection-level SDK error.+ let fallback = posthog+ .mock_async(|when, then| {+ when.path_contains("/");+ then.status(200).body("{\"status\": 1}");+ })+ .await;++ common_posthog::init("cymbal-test", Some("test-api-key"), &posthog.base_url())+ .await+ .expect("posthog init");++ let mut config = Config::init_with_defaults().unwrap();+ config.object_storage_bucket = STORAGE_BUCKET.to_string();++ let mut s3_client = MockS3Client::new();+ s3_client+ .expect_ping_bucket()+ .with(predicate::eq(STORAGE_BUCKET.to_string()))+ .returning(|_| Ok(()));++ let app_ctx = AppContext::new(+ &config,+ Arc::new(s3_client),+ db.clone(),+ Arc::new(MockRedisClient::new()),+ )+ .await+ .unwrap();+ let router = get_router(Arc::new(app_ctx));++ // With the pool closed, the pipeline's first database access fails with+ // an UnhandledError — the capture funnel under test.+ db.close().await;++ let event = json!([{+ "uuid": Uuid::now_v7(),+ "event": "$exception",+ "team_id": 1,+ "timestamp": "2024-01-01T00:00:00Z",+ "properties": {+ "$exception_list": [{"type": "Error", "value": "boom"}],+ "$exception_handled": false,+ },+ }]);++ let response = router+ .oneshot(+ Request::builder()+ .method("POST")+ .header("content-type", "application/json")+ .uri("/process")+ .body(Body::from(serde_json::to_vec(&event).unwrap()))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(+ response.status(),+ reqwest::StatusCode::INTERNAL_SERVER_ERROR+ );++ // The capture is fire-and-forget; wait for it to reach the mock server.+ for _ in 0..100 {+ if capture.hits_async().await > 0 {+ break;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ assert_eq!(+ capture.hits_async().await,+ 1,+ "expected a matching $exception capture; total capture requests seen: {}",+ fallback.hits_async().await+ );+}