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(rust): upgrade workspace to posthog-rs 0.18.0 and on_error metric (#67600)

Eli Reisman5bbebcea1740
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 4bf3d8f915b0..ec8e3a1dcf32 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -1316,7 +1316,7 @@ dependencies = [
"moka",
"natord",
"object_store",
- "posthog-rs 0.13.3",
+ "posthog-rs",
"rayon",
"rdkafka",
"reqwest 0.12.28",
@@ -2441,7 +2441,9 @@ name = "common-posthog"
version = "0.1.0"
dependencies = [
"httpmock",
- "posthog-rs 0.17.3",
+ "metrics",
+ "metrics-util",
+ "posthog-rs",
"serde_json",
"tokio",
"tracing",
@@ -2882,7 +2884,7 @@ dependencies = [
"mockall",
"moka",
"personhog-common",
- "posthog-rs 0.17.3",
+ "posthog-rs",
"posthog-symbol-data",
"proguard",
"rand 0.8.5",
@@ -7885,33 +7887,9 @@ dependencies = [
[[package]]
name = "posthog-rs"
-version = "0.13.3"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2136b5250589588b5b514cd64b286bfb8630f2223e4f56ab1fa3858f1600ab38"
-dependencies = [
- "backtrace",
- "brotli 7.0.0",
- "chrono",
- "derive_builder",
- "flate2",
- "os_info",
- "regex",
- "reqwest 0.13.4",
- "semver",
- "serde",
- "serde_json",
- "sha1",
- "tokio",
- "tracing",
- "uuid",
- "zstd",
-]
-
-[[package]]
-name = "posthog-rs"
-version = "0.17.3"
+version = "0.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7f226e5d9495b0b870a88a53bbbd0d80acbcb66321717791a35991fcf4e890f6"
+checksum = "a5bcf2bdf6c269ff65ff9d4f360bc5f42d560afff96a589d873326594d473bd6"
dependencies = [
"backtrace",
"brotli 7.0.0",
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 66d10dc9f37b..3ced01bf3891 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -200,7 +200,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.17.3", features = ["async-client", "capture-v1"] }
+posthog-rs = { version = "0.18.0", features = ["async-client", "capture-v1"] }
redis = { version = "0.32.7", features = [
"tokio-comp",
"cluster",
diff --git a/rust/batch-import-worker/Cargo.toml b/rust/batch-import-worker/Cargo.toml
index b93c7045b9e5..6a863e1c7954 100644
--- a/rust/batch-import-worker/Cargo.toml
+++ b/rust/batch-import-worker/Cargo.toml
@@ -49,7 +49,7 @@ metrics = { workspace = true }
url = { workspace = true }
urlencoding = "2.1"
moka = { workspace = true }
-posthog-rs = { version = "0.13.3", features = ["async-client", "capture-v1"] }
+posthog-rs = { workspace = true }
[dev-dependencies]
httpmock = { workspace = true }
diff --git a/rust/batch-import-worker/src/emit/capture.rs b/rust/batch-import-worker/src/emit/capture.rs
index 0f28a41de738..909a739c2be4 100644
--- a/rust/batch-import-worker/src/emit/capture.rs
+++ b/rust/batch-import-worker/src/emit/capture.rs
@@ -160,7 +160,7 @@ impl<'a> Transaction<'a> for CaptureTransaction<'a> {
for batch in batches {
let batch_count = batch.len();
- if let Err(e) = self.client.capture_batch(batch, true).await {
+ if let Err(e) = self.client.capture_batch_immediate(batch, true).await {
// The worker is the only place that sees per-event loss attributed to a
// reason: capture counts requests, not events, and a failed import sub-batch
// can carry thousands of events. `reason` lets alerting exclude expected
@@ -747,7 +747,7 @@ mod tests {
(PosthogError::Unauthorized, "unauthorized"),
(PosthogError::Connection("x".into()), "transport"),
(PosthogError::Serialization("x".into()), "serialization"),
- // A variant capture_batch never returns still maps safely via the
+ // A variant capture_batch_immediate never returns still maps safely via the
// non_exhaustive catch-all rather than panicking.
(PosthogError::NotInitialized, "other"),
];
diff --git a/rust/common/posthog/Cargo.toml b/rust/common/posthog/Cargo.toml
index 4e7d86677cef..21231e3fb2d8 100644
--- a/rust/common/posthog/Cargo.toml
+++ b/rust/common/posthog/Cargo.toml
@@ -7,6 +7,7 @@ edition = "2021"
workspace = true
[dependencies]
+metrics = { workspace = true }
posthog-rs = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
@@ -14,3 +15,4 @@ tracing = { workspace = true }
[dev-dependencies]
httpmock = { workspace = true }
+metrics-util = { workspace = true }
diff --git a/rust/common/posthog/src/lib.rs b/rust/common/posthog/src/lib.rs
index 53bc7b129a15..8969566c28e1 100644
--- a/rust/common/posthog/src/lib.rs
+++ b/rust/common/posthog/src/lib.rs
@@ -8,6 +8,7 @@ use std::sync::{Arc, OnceLock};
use std::task::{Context, Waker};
use std::time::Instant;
+use posthog_rs::PostHogError;
use serde_json::Value;
/// Hard cap on captured exceptions per process per minute. Bounds both outage
@@ -15,6 +16,13 @@ use serde_json::Value;
/// ingests the internal project's `$exception` events, i.e. its own captures.
const MAX_CAPTURES_PER_MINUTE: u32 = 10;
+/// Terminal SDK delivery failures, counted once per `on_error` invocation.
+/// Labeled `service` (the caller passed to [`init`]), `surface` (which SDK
+/// network path failed), and `reason` (bounded failure class). Shared across
+/// every service that inits through this crate; the `service` label keeps them
+/// cleanly faceted regardless of scrape topology.
+const SDK_DELIVERY_FAILURES: &str = "posthog_sdk_delivery_failures_total";
+
static SERVICE: OnceLock<ServiceContext> = OnceLock::new();
static CAPTURE_WINDOW: RateWindow = RateWindow::new();
static CLOCK_START: OnceLock<Instant> = OnceLock::new();
@@ -69,6 +77,10 @@ pub async fn init(
.host(normalize_host(endpoint))
.error_tracking(error_tracking)
.before_send(move |event| prepare_event_for_capture(event, &context))
+ // Observe terminal SDK delivery failures. Registering a hook silences the
+ // SDK's default per-drop WARN, so the hook re-emits it alongside a metric.
+ // Observability-only: must not re-enter the SDK.
+ .on_error(move |err| report_sdk_error(service, err))
.build()
.expect("all client options have defaults");
posthog_rs::init_global(options).await?;
@@ -155,6 +167,68 @@ fn is_fatal_exception(event: &posthog_rs::Event) -> bool {
== Some("fatal")
}
+/// Emit the delivery-failure metric and a log breadcrumb for one terminal SDK
+/// failure. Wired as the client's `on_error` hook in [`init`]; runs on whichever
+/// SDK thread hit the failure, stays allocation-light, and never calls back into
+/// the SDK.
+///
+/// The `warn!` restores the signal the SDK emitted before a hook took over:
+/// registering `on_error` suppresses the SDK's own default per-drop `warn!`, so
+/// without this we would go dark on logs. `warn`, not `error`, matches that
+/// default and the severity of dropped telemetry (degraded, not fatal); it fires
+/// only on terminal failure (post-retry), so it stays bounded.
+fn report_sdk_error(service: &'static str, err: &PostHogError<'_>) {
+ let (surface, reason) = classify_sdk_error(err);
+ metrics::counter!(
+ SDK_DELIVERY_FAILURES,
+ "service" => service,
+ "surface" => surface,
+ "reason" => reason,
+ )
+ .increment(1);
+ tracing::warn!(
+ service,
+ surface,
+ reason,
+ "posthog-rs dropped telemetry after terminal delivery failure"
+ );
+}
+
+/// Map a `PostHogError` to bounded `(surface, reason)` metric labels. `surface`
+/// is the SDK network path that failed; `reason` classifies the cause. Both are
+/// `&'static str` to keep the label set low-cardinality. `PostHogError` is
+/// `#[non_exhaustive]`, hence the catch-all arm.
+fn classify_sdk_error(err: &PostHogError<'_>) -> (&'static str, &'static str) {
+ match err {
+ // A capture failure with no underlying error is the capture-v1 2xx
+ // whose per-event verdicts left events unpersisted (no transport error).
+ PostHogError::Capture(f) => (
+ "capture",
+ f.error().map_or("partial_drop", sdk_error_reason),
+ ),
+ PostHogError::FeatureFlags(f) => ("flags", sdk_error_reason(f.error())),
+ PostHogError::LocalEvaluation(f) => ("local_evaluation", sdk_error_reason(f.error())),
+ _ => ("unknown", "other"),
+ }
+}
+
+/// Bounded failure class for a `posthog_rs::Error`. Mirrors the tag split the
+/// batch-import-worker uses so `quota` (expected billing enforcement) stays
+/// separable from actionable transport/server failures in alerts.
+/// `posthog_rs::Error` is `#[non_exhaustive]`, hence the catch-all arm.
+fn sdk_error_reason(err: &posthog_rs::Error) -> &'static str {
+ match err {
+ posthog_rs::Error::BillingLimitExceeded(_) => "quota",
+ posthog_rs::Error::BadRequest(_) => "bad_request",
+ posthog_rs::Error::ServerError { .. } => "server_error",
+ posthog_rs::Error::RateLimit => "rate_limited",
+ posthog_rs::Error::Unauthorized => "unauthorized",
+ posthog_rs::Error::Connection(_) => "transport",
+ posthog_rs::Error::Serialization(_) => "serialization",
+ _ => "other",
+ }
+}
+
/// Strip a legacy capture path suffix from a configured PostHog endpoint,
/// leaving the bare host the SDK expects.
fn normalize_host(endpoint: &str) -> String {
@@ -249,4 +323,32 @@ mod tests {
assert!(!limiter.allows(1, 3));
assert!(limiter.allows(2, 3));
}
+
+ #[test]
+ fn sdk_error_reason_maps_every_variant() {
+ use posthog_rs::Error;
+ // The exact tag per variant is an alerting contract: `quota` (expected
+ // billing enforcement) MUST stay separable from actionable failures.
+ let cases: &[(Error, &str)] = &[
+ (Error::BillingLimitExceeded("x".into()), "quota"),
+ (Error::BadRequest("x".into()), "bad_request"),
+ (
+ Error::ServerError {
+ status: 503,
+ message: "x".into(),
+ },
+ "server_error",
+ ),
+ (Error::RateLimit, "rate_limited"),
+ (Error::Unauthorized, "unauthorized"),
+ (Error::Connection("x".into()), "transport"),
+ (Error::Serialization("x".into()), "serialization"),
+ // A variant outside the classified set maps safely via the
+ // non_exhaustive catch-all instead of panicking.
+ (Error::NotInitialized, "other"),
+ ];
+ for (err, expected) in cases {
+ assert_eq!(sdk_error_reason(err), *expected, "reason for {err:?}");
+ }
+ }
}
diff --git a/rust/common/posthog/tests/on_error_hook.rs b/rust/common/posthog/tests/on_error_hook.rs
new file mode 100644
index 000000000000..bb1d83a34c5b
--- /dev/null
+++ b/rust/common/posthog/tests/on_error_hook.rs
@@ -0,0 +1,71 @@
+//! End-to-end coverage for the `on_error` hook wired in `common_posthog::init`:
+//! a terminal capture failure must emit `posthog_sdk_delivery_failures_total`
+//! with the right `service`/`surface`/`reason` labels.
+//!
+//! One test per binary: `init` builds a process-global PostHog client and the
+//! DebuggingRecorder installs a process-global metrics recorder. The hook fires
+//! on the SDK's background worker thread, so a thread-local recorder would miss
+//! it — the recorder must be global.
+
+use std::collections::HashMap;
+
+use httpmock::prelude::*;
+use metrics_util::debugging::{DebugValue, DebuggingRecorder};
+
+#[tokio::test]
+async fn init_hook_emits_delivery_failure_metric_on_terminal_reject() {
+ let recorder = DebuggingRecorder::new();
+ let snapshotter = recorder.snapshotter();
+ recorder
+ .install()
+ .expect("no global recorder should be installed yet in this test binary");
+
+ // 400 is a permanent reject: the SDK does not retry it, so the hook fires
+ // after a single attempt and `flush` returns once that attempt is done.
+ let server = MockServer::start_async().await;
+ let mock = server
+ .mock_async(|when, then| {
+ when.method(POST);
+ then.status(400).body("bad request");
+ })
+ .await;
+
+ common_posthog::init("test-svc", Some("test-key"), &server.base_url())
+ .await
+ .expect("init should succeed when an api key is provided");
+
+ posthog_rs::capture(posthog_rs::Event::new_anon("test_event"));
+ posthog_rs::flush().await;
+
+ mock.assert_async().await;
+
+ let hit = snapshotter
+ .snapshot()
+ .into_vec()
+ .into_iter()
+ .find_map(|(key, _, _, value)| {
+ if key.key().name() != "posthog_sdk_delivery_failures_total" {
+ return None;
+ }
+ let labels: HashMap<String, String> = key
+ .key()
+ .labels()
+ .map(|l| (l.key().to_string(), l.value().to_string()))
+ .collect();
+ match value {
+ DebugValue::Counter(c) => Some((labels, c)),
+ _ => None,
+ }
+ });
+
+ let (labels, count) =
+ hit.expect("terminal capture reject must emit the delivery-failure metric");
+ assert_eq!(count, 1, "one terminal failure => one increment");
+ assert_eq!(labels.get("service").map(String::as_str), Some("test-svc"));
+ assert_eq!(labels.get("surface").map(String::as_str), Some("capture"));
+ assert_eq!(
+ labels.get("reason").map(String::as_str),
+ Some("bad_request"),
+ "HTTP 400 must classify as bad_request",
+ );
+}