: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
fix(error-tracking): parse untagged stacktraces from old python SDKs (#97776)
Jimmy Zhub1847cc2e971
diff --git a/rust/cymbal/src/modes/processing/normalization.rs b/rust/cymbal/src/modes/processing/normalization.rsindex 90190429a64c..9fe7f5f4b4a9 100644--- a/rust/cymbal/src/modes/processing/normalization.rs+++ b/rust/cymbal/src/modes/processing/normalization.rs@@ -19,10 +19,15 @@//! left untouched, payloads below it (or with an unparseable version) are still//! normalized. A `None` cutoff means the SDK has not flipped yet, so everything//! is normalized.+//!+//! The module also normalizes legacy untagged payloads ([`normalize_legacy_tags`]):+//! SDKs from before the stacktrace `type` and frame `platform` tags existed need+//! those tags added before typed parsing.use std::sync::OnceLock;use semver::Version;+use serde_json::Value;use crate::types::ExceptionList;@@ -261,6 +266,66 @@ pub fn legacy_wire_order(Some(legacy)}+// Keys only python frames carry on the wire. posthog-python < 3.8.0 sent frames without+// a platform tag, so any of these keys is what identifies such a frame. The list mirrors+// the serde field names of `RawPythonFrame` (core/types/langs/python.rs) — keep in sync.+const LEGACY_PYTHON_FRAME_KEYS: &[&str] = &[+ "abs_path",+ "context_line",+ "module",+ "pre_context",+ "post_context",+];++/// Tags legacy untagged payloads in place, on the raw `$exception_list` JSON before+/// typed parsing. posthog-python only added the `"type": "raw"` stacktrace tag and the+/// frame `platform` tag in 3.8.0; `Stacktrace` and `RawFrame` parse both as serde-tagged+/// enums, so an untagged payload would otherwise fail with a missing-field error and+/// never become an issue. An untagged stacktrace is tagged raw. An untagged frame in a+/// raw stacktrace is tagged python only when a python-only key identifies it — other+/// frame shapes overlap too much to classify safely, so any other untagged frame keeps+/// failing typed parsing.+///+/// This runs once, at the processing-ingest boundary (`TryFrom<AnyEvent>`). Every other+/// parse site of these types consumes cymbal-serialized JSON, which always carries the+/// tags.+pub fn normalize_legacy_tags(exception_list: &mut Value) {+ let Some(exceptions) = exception_list.as_array_mut() else {+ return;+ };+ for exception in exceptions {+ let Some(stacktrace) = exception+ .get_mut("stacktrace")+ .and_then(Value::as_object_mut)+ else {+ continue;+ };+ if !stacktrace.contains_key("type") {+ stacktrace.insert("type".to_string(), Value::String("raw".to_string()));+ }+ // Only raw stacktraces can carry untagged legacy frames. Resolved frames+ // legitimately carry keys like `module`, and must not get a platform tag.+ if stacktrace.get("type").and_then(Value::as_str) != Some("raw") {+ continue;+ }+ let Some(frames) = stacktrace.get_mut("frames").and_then(Value::as_array_mut) else {+ continue;+ };+ for frame in frames {+ let Some(frame) = frame.as_object_mut() else {+ continue;+ };+ if !frame.contains_key("platform")+ && LEGACY_PYTHON_FRAME_KEYS+ .iter()+ .any(|key| frame.contains_key(*key))+ {+ frame.insert("platform".to_string(), Value::String("python".to_string()));+ }+ }+ }+}+#[cfg(test)]mod test {use super::*;@@ -724,4 +789,81 @@ mod test {assert_eq!(parse_lenient("garbage"), None);assert_eq!(parse_lenient(""), None);}++ // The shape posthog-python < 3.8.0 emits: no "type" on the stacktrace and no+ // "platform" on the frames. Written fresh, not copied from captured data.+ const LEGACY_PYTHON_EXCEPTION_LIST: &str = r#"[+ {+ "type": "ConnectionError",+ "value": "connection refused",+ "stacktrace": {+ "frames": [+ {+ "abs_path": "/app/example/service.py",+ "context_line": " connect()",+ "filename": "example/service.py",+ "function": "start",+ "lineno": 12,+ "module": "example.service",+ "pre_context": [],+ "post_context": [],+ "in_app": true+ }+ ]+ }+ }+ ]"#;++ #[test]+ fn tags_a_legacy_python_exception_list_so_it_parses() {+ let mut value: Value = serde_json::from_str(LEGACY_PYTHON_EXCEPTION_LIST).unwrap();+ normalize_legacy_tags(&mut value);+ let list: ExceptionList = serde_json::from_value(value).unwrap();+ let Some(Stacktrace::Raw { frames }) = &list[0].stack else {+ panic!("expected a raw stacktrace");+ };+ assert!(matches!(frames.as_slice(), [RawFrame::Python(_)]));++ // Serialization must write the tags back: downstream consumers (resolution,+ // notifications) re-parse cymbal-serialized stacktraces and rely on them.+ let serialized = serde_json::to_value(&list).unwrap();+ assert_eq!(serialized[0]["stacktrace"]["type"], "raw");+ assert_eq!(+ serialized[0]["stacktrace"]["frames"][0]["platform"],+ "python"+ );+ }++ #[test]+ fn leaves_resolved_stacktrace_frames_untouched() {+ let raw = r#"[+ {+ "type": "Error",+ "value": "boom",+ "stacktrace": {+ "type": "resolved",+ "frames": [{"module": "example.service", "function": "start"}]+ }+ }+ ]"#;+ let mut value: Value = serde_json::from_str(raw).unwrap();+ normalize_legacy_tags(&mut value);+ assert_eq!(value[0]["stacktrace"]["frames"][0].get("platform"), None);+ }++ #[test]+ fn leaves_untagged_frames_without_python_markers_unclassified() {+ let raw = r#"[+ {+ "type": "Error",+ "value": "boom",+ "stacktrace": {+ "frames": [{"filename": "app.js", "function": "main", "lineno": 3, "colno": 7}]+ }+ }+ ]"#;+ let mut value: Value = serde_json::from_str(raw).unwrap();+ normalize_legacy_tags(&mut value);+ assert!(serde_json::from_value::<ExceptionList>(value).is_err());+ }}diff --git a/rust/cymbal/src/modes/processing/types/exception_event.rs b/rust/cymbal/src/modes/processing/types/exception_event.rsindex f9ac3e73680b..a2a9abd6af1c 100644--- a/rust/cymbal/src/modes/processing/types/exception_event.rs+++ b/rust/cymbal/src/modes/processing/types/exception_event.rs@@ -10,7 +10,7 @@ use crate::{frames::releases::{ReleaseInfo, ReleaseRecord},issue_resolution::{Issue, IssueSeverity},langs::native::DebugImage,- modes::processing::normalization::normalize_wire_order,+ modes::processing::normalization::{normalize_legacy_tags, normalize_wire_order},recursively_sanitize_properties,types::{event::AnyEvent, ExceptionList, ProcessedExceptionProperties, RawExceptionProperties},};@@ -615,6 +615,7 @@ impl TryFrom<AnyEvent> for ExceptionEvent<Parsed> {.and_then(|object| object.get_mut("$exception_list")){recursively_sanitize_properties(event.uuid, value, 0)?;+ normalize_legacy_tags(value);}let mut raw: RawExceptionProperties = serde_json::from_value(properties)