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: enable Rust panic autocapture (#66779)

Catalin Irimie9d977b219326
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 5c6a91d61e2d..67a06619742f 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -1310,7 +1310,7 @@ dependencies = [
"moka",
"natord",
"object_store",
- "posthog-rs",
+ "posthog-rs 0.13.3",
"rayon",
"rdkafka",
"reqwest 0.12.28",
@@ -2422,7 +2422,8 @@ dependencies = [
name = "common-posthog"
version = "0.1.0"
dependencies = [
- "posthog-rs",
+ "httpmock",
+ "posthog-rs 0.17.3",
"serde_json",
"tokio",
"tracing",
@@ -2863,7 +2864,7 @@ dependencies = [
"mockall",
"moka",
"personhog-common",
- "posthog-rs",
+ "posthog-rs 0.17.3",
"posthog-symbol-data",
"proguard",
"rand 0.8.5",
@@ -7867,6 +7868,31 @@ dependencies = [
"zstd",
]
+[[package]]
+name = "posthog-rs"
+version = "0.17.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f226e5d9495b0b870a88a53bbbd0d80acbcb66321717791a35991fcf4e890f6"
+dependencies = [
+ "backtrace",
+ "brotli 7.0.0",
+ "chrono",
+ "derive_builder",
+ "findshlibs",
+ "flate2",
+ "os_info",
+ "regex",
+ "reqwest 0.13.4",
+ "semver",
+ "serde",
+ "serde_json",
+ "sha1",
+ "tokio",
+ "tracing",
+ "uuid",
+ "zstd",
+]
+
[[package]]
name = "posthog-symbol-data"
version = "0.5.0"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 6effcce51a3c..527ee9571e70 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -186,7 +186,7 @@ aws-smithy-runtime-api = { version = "1.11.5", features = ["client"] }
aws-smithy-http-client = { version = "1.1.11", features = ["rustls-aws-lc"] }
mockall = "0.13.0"
moka = { version = "0.12.15", features = ["sync", "future"] }
-posthog-rs = { version = "0.13.3", features = ["async-client", "capture-v1"] }
+posthog-rs = { version = "0.17.3", features = ["async-client", "capture-v1"] }
redis = { version = "0.32.7", features = [
"tokio-comp",
"cluster",
diff --git a/rust/common/posthog/Cargo.toml b/rust/common/posthog/Cargo.toml
index 604e5fb121fd..4e7d86677cef 100644
--- a/rust/common/posthog/Cargo.toml
+++ b/rust/common/posthog/Cargo.toml
@@ -11,3 +11,6 @@ posthog-rs = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
tracing = { workspace = true }
+
+[dev-dependencies]
+httpmock = { workspace = true }
diff --git a/rust/common/posthog/src/lib.rs b/rust/common/posthog/src/lib.rs
index e52c30795559..53bc7b129a15 100644
--- a/rust/common/posthog/src/lib.rs
+++ b/rust/common/posthog/src/lib.rs
@@ -19,6 +19,7 @@ static SERVICE: OnceLock<ServiceContext> = OnceLock::new();
static CAPTURE_WINDOW: RateWindow = RateWindow::new();
static CLOCK_START: OnceLock<Instant> = OnceLock::new();
+#[derive(Clone)]
struct ServiceContext {
service: &'static str,
pod: Option<String>,
@@ -40,16 +41,15 @@ pub async fn init(
api_key: Option<&str>,
endpoint: &str,
) -> Result<(), posthog_rs::Error> {
- // A second init call keeps the first service identity.
- drop(
- SERVICE.set(ServiceContext {
+ let context = SERVICE
+ .get_or_init(|| ServiceContext {
service,
pod: std::env::var("POD_NAME")
.or_else(|_| std::env::var("HOSTNAME"))
.ok(),
region: std::env::var("POSTHOG_REGION").ok(),
- }),
- );
+ })
+ .clone();
let Some(api_key) = api_key else {
posthog_rs::disable_global();
@@ -60,6 +60,7 @@ pub async fn init(
// Exclude this crate's own frames from in-app classification so captured
// stacks lead with the real service call site, not the shared wrapper.
let error_tracking = posthog_rs::ErrorTrackingOptionsBuilder::default()
+ .capture_panics(true)
.in_app_exclude_paths(vec!["common_posthog::".to_string()])
.build()
.expect("all error tracking options have defaults");
@@ -67,6 +68,7 @@ pub async fn init(
.api_key(api_key.to_string())
.host(normalize_host(endpoint))
.error_tracking(error_tracking)
+ .before_send(move |event| prepare_event_for_capture(event, &context))
.build()
.expect("all client options have defaults");
posthog_rs::init_global(options).await?;
@@ -98,15 +100,6 @@ pub fn capture_exception<E>(
// Strings and pre-built JSON values always serialize.
let prop_err = "string and JSON property values always serialize";
let mut options = posthog_rs::CaptureExceptionOptions::new();
- if let Some(ctx) = SERVICE.get() {
- options = options.property("service", ctx.service).expect(prop_err);
- if let Some(pod) = &ctx.pod {
- options = options.property("pod", pod.as_str()).expect(prop_err);
- }
- if let Some(region) = &ctx.region {
- options = options.property("region", region.as_str()).expect(prop_err);
- }
- }
for (key, value) in properties {
options = options.property(key, value).expect(prop_err);
}
@@ -128,6 +121,40 @@ pub fn capture_exception<E>(
}
}
+fn prepare_event_for_capture(
+ mut event: posthog_rs::Event,
+ context: &ServiceContext,
+) -> Option<posthog_rs::Event> {
+ if is_fatal_exception(&event)
+ && !CAPTURE_WINDOW.allows(clock_window_minutes(), MAX_CAPTURES_PER_MINUTE)
+ {
+ return None;
+ }
+
+ let prop_err = "string property values always serialize";
+ event
+ .insert_prop("service", context.service)
+ .expect(prop_err);
+ if let Some(pod) = &context.pod {
+ event.insert_prop("pod", pod.as_str()).expect(prop_err);
+ }
+ if let Some(region) = &context.region {
+ event
+ .insert_prop("region", region.as_str())
+ .expect(prop_err);
+ }
+ Some(event)
+}
+
+fn is_fatal_exception(event: &posthog_rs::Event) -> bool {
+ event.event_name() == "$exception"
+ && event
+ .properties()
+ .get("$exception_level")
+ .and_then(Value::as_str)
+ == Some("fatal")
+}
+
/// Strip a legacy capture path suffix from a configured PostHog endpoint,
/// leaving the bare host the SDK expects.
fn normalize_host(endpoint: &str) -> String {
diff --git a/rust/common/posthog/tests/panic_capture.rs b/rust/common/posthog/tests/panic_capture.rs
new file mode 100644
index 000000000000..3a02c35cd1ba
--- /dev/null
+++ b/rust/common/posthog/tests/panic_capture.rs
@@ -0,0 +1,119 @@
+use std::sync::Arc;
+use std::time::Duration;
+
+use httpmock::prelude::*;
+use serde_json::json;
+
+#[derive(Debug)]
+struct TestError;
+
+impl std::fmt::Display for TestError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("handled telemetry test")
+ }
+}
+
+impl std::error::Error for TestError {}
+
+fn is_internal_panic_exception(req: &HttpMockRequest) -> bool {
+ let Some(body) = req.body.as_deref() else {
+ return false;
+ };
+ let Ok(body) = serde_json::from_slice::<serde_json::Value>(body) else {
+ return false;
+ };
+
+ body.pointer("/batch/0/event").and_then(|v| v.as_str()) == Some("$exception")
+ && body
+ .pointer("/batch/0/properties/$exception_list/0/type")
+ .and_then(|v| v.as_str())
+ == Some("Panic")
+ && body
+ .pointer("/batch/0/properties/$exception_list/0/value")
+ .and_then(|v| v.as_str())
+ == Some("panic telemetry test")
+ && body
+ .pointer("/batch/0/properties/$exception_level")
+ .and_then(|v| v.as_str())
+ == Some("fatal")
+ && body
+ .pointer("/batch/0/properties/service")
+ .and_then(|v| v.as_str())
+ == Some("panic-test")
+}
+
+fn is_internal_handled_exception(req: &HttpMockRequest) -> bool {
+ let Some(body) = req.body.as_deref() else {
+ return false;
+ };
+ let Ok(body) = serde_json::from_slice::<serde_json::Value>(body) else {
+ return false;
+ };
+
+ body.pointer("/batch/0/event").and_then(|v| v.as_str()) == Some("$exception")
+ && body
+ .pointer("/batch/0/properties/$exception_list/0/type")
+ .and_then(|v| v.as_str())
+ .is_some_and(|value| value.ends_with("TestError"))
+ && body
+ .pointer("/batch/0/properties/$exception_list/0/value")
+ .and_then(|v| v.as_str())
+ == Some("handled telemetry test")
+ && body
+ .pointer("/batch/0/properties/service")
+ .and_then(|v| v.as_str())
+ == Some("panic-test")
+ && body
+ .pointer("/batch/0/properties/request_id")
+ .and_then(|v| v.as_str())
+ == Some("req-1")
+}
+
+#[tokio::test]
+async fn init_enables_panic_capture() {
+ let posthog = MockServer::start_async().await;
+ let capture = posthog
+ .mock_async(|when, then| {
+ when.method(POST)
+ .path("/i/v1/analytics/events")
+ .matches(is_internal_panic_exception);
+ then.status(200).body("{\"results\":{}}");
+ })
+ .await;
+ let handled_capture = posthog
+ .mock_async(|when, then| {
+ when.method(POST)
+ .path("/i/v1/analytics/events")
+ .matches(is_internal_handled_exception);
+ then.status(200).body("{\"results\":{}}");
+ })
+ .await;
+ std::panic::set_hook(Box::new(|_| {}));
+ common_posthog::init("panic-test", Some("test-api-key"), &posthog.base_url())
+ .await
+ .expect("posthog init");
+
+ common_posthog::capture_exception(Arc::new(TestError), [("request_id", json!("req-1"))]);
+ posthog_rs::flush().await;
+ for _ in 0..100 {
+ if handled_capture.hits_async().await > 0 {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ handled_capture.assert_async().await;
+
+ let panic = std::panic::catch_unwind(|| {
+ panic!("panic telemetry test");
+ });
+ assert!(panic.is_err());
+ drop(std::panic::take_hook());
+
+ for _ in 0..100 {
+ if capture.hits_async().await > 0 {
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(50)).await;
+ }
+ capture.assert_async().await;
+}
diff --git a/rust/cymbal/src/core/analytics.rs b/rust/cymbal/src/core/analytics.rs
index ed382421b4b6..238073d05c07 100644
--- a/rust/cymbal/src/core/analytics.rs
+++ b/rust/cymbal/src/core/analytics.rs
@@ -2,7 +2,6 @@
//! lifecycle). Issue-lifecycle captures live in `crate::modes::processing::analytics`.
use posthog_rs::Event;
-use tracing::error;
const SYMBOL_SET_SAVED: &str = "error_tracking_symbol_set_saved";
const SYMBOL_SET_DELETED: &str = "error_tracking_symbol_set_deleted";
@@ -13,7 +12,7 @@ pub fn capture_symbol_set_saved(team_id: i32, set_ref: &str, storage_ptr: &str,
event.insert_prop("set_ref", set_ref).unwrap();
event.insert_prop("storage_ptr", storage_ptr).unwrap();
event.insert_prop("was_retry", was_retry).unwrap();
- spawning_capture(SYMBOL_SET_SAVED, event);
+ capture_event(event);
}
pub fn capture_symbol_set_deleted(team_id: i32, set_ref: &str, storage_ptr: Option<&str>) {
@@ -23,17 +22,12 @@ pub fn capture_symbol_set_deleted(team_id: i32, set_ref: &str, storage_ptr: Opti
if let Some(ptr) = storage_ptr {
event.insert_prop("storage_ptr", ptr).unwrap();
}
- spawning_capture(SYMBOL_SET_DELETED, event);
+ capture_event(event);
}
-pub fn spawning_capture(event_name: &'static str, event: Event) {
+pub(crate) fn capture_event(event: Event) {
if posthog_rs::global_is_disabled() {
return;
}
-
- tokio::spawn(async move {
- if let Err(e) = posthog_rs::capture(event).await {
- error!(event = event_name, error = ?e, "Error capturing PostHog event");
- }
- });
+ posthog_rs::capture(event);
}
diff --git a/rust/cymbal/src/modes/notifications/analytics.rs b/rust/cymbal/src/modes/notifications/analytics.rs
index 6b2a9b898403..cede6dc30be3 100644
--- a/rust/cymbal/src/modes/notifications/analytics.rs
+++ b/rust/cymbal/src/modes/notifications/analytics.rs
@@ -1,7 +1,7 @@
use posthog_rs::Event;
use uuid::Uuid;
-use crate::core::analytics::spawning_capture;
+use crate::core::analytics::capture_event;
const ISSUE_CREATED: &str = "error_tracking_issue_created";
const ISSUE_REOPENED: &str = "error_tracking_issue_reopened";
@@ -13,12 +13,12 @@ pub fn capture_issue_created(team_id: i32, issue_id: Uuid, sentry_integration: b
event
.insert_prop("sentry_integration", sentry_integration)
.unwrap();
- spawning_capture(ISSUE_CREATED, event);
+ capture_event(event);
}
pub fn capture_issue_reopened(team_id: i32, issue_id: Uuid) {
let mut event = Event::new_anon(ISSUE_REOPENED);
event.insert_prop("team_id", team_id).unwrap();
event.insert_prop("issue_id", issue_id.to_string()).unwrap();
- spawning_capture(ISSUE_REOPENED, event);
+ capture_event(event);
}