: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(cymbal): treat map_id-less java frames as pre-resolved (#76829)
Cataline304e0efd448
diff --git a/frontend/src/lib/components/Errors/utils.ts b/frontend/src/lib/components/Errors/utils.tsindex ad2ac478d637..48c5a3021cfb 100644--- a/frontend/src/lib/components/Errors/utils.ts+++ b/frontend/src/lib/components/Errors/utils.ts@@ -46,6 +46,9 @@ export function getRuntimeFromLib(lib?: string | null): ErrorTrackingRuntime {return 'flutter'case 'posthog-elixir':return 'elixir'+ // posthog-server is the current java server SDK identifier; posthog-java is the+ // tombstoned legacy SDK, kept so already-ingested events still resolve.+ case 'posthog-server':case 'posthog-java':case 'analytics-java':return 'java'diff --git a/rust/cymbal/src/core/symbolication/symbol/mod.rs b/rust/cymbal/src/core/symbolication/symbol/mod.rsindex 5283f014542f..94044582692d 100644--- a/rust/cymbal/src/core/symbolication/symbol/mod.rs+++ b/rust/cymbal/src/core/symbolication/symbol/mod.rs@@ -53,23 +53,34 @@ pub trait SymbolResolver: Send + Sync + 'static {team_id: TeamId,mut exception: Exception,) -> Result<Exception, UnhandledError> {- let resolve_java_module_and_type =- async |exception: &Exception| -> Result<(String, String), ResolveError> {- // Pick the first Java frame that carries a ProGuard mapping ref,- // not just the first frame. Wire-order normalization can move a- // ref-less framework frame to the front, so anchoring on the- // frame that actually has a `map_id` keeps class remapping- // order-independent.- let symbolset_ref = exception- .get_raw_frame()- .iter()- .find_map(|frame| match frame {- RawFrame::Java(java_frame) => java_frame.get_ref().ok(),- _ => None,- })- .ok_or(ProguardError::NoOriginalFrames)- .map_err(ResolveError::from)?;+ // Pick the first Java frame that carries a ProGuard mapping ref,+ // not just the first frame. Wire-order normalization can move a+ // ref-less framework frame to the front, so anchoring on the+ // frame that actually has a `map_id` keeps class remapping+ // order-independent.+ let symbolset_ref = exception+ .get_raw_frame()+ .iter()+ .find_map(|frame| match frame {+ RawFrame::Java(java_frame) => java_frame.get_ref().ok(),+ _ => None,+ });++ // When no frame in the stack carries a map_id, the whole exception came from an+ // unobfuscated JVM app, so `exception_type` and `module` already hold the real+ // class name and there is nothing to remap. Return early instead of attempting+ // the lookup, which would log and increment JAVA_EXCEPTION_REMAP_FAILED once per+ // event for traffic that was never obfuscated in the first place. A map_id that+ // is present but whose mapping is missing still falls through to the error arm+ // below, because that is a genuine failure.+ let Some(symbolset_ref) = symbolset_ref else {+ return Ok(exception);+ };+ let resolve_java_module_and_type =+ async |exception: &Exception,+ symbolset_ref: OrChunkId<ProguardRef>|+ -> Result<(String, String), ResolveError> {let module = exception.module.clone()@@ -88,7 +99,7 @@ pub trait SymbolResolver: Send + Sync + 'static {Ok((new_module, new_type))};- match resolve_java_module_and_type(&exception).await {+ match resolve_java_module_and_type(&exception, symbolset_ref).await {Ok((new_module, new_type)) => {exception.module = Some(new_module);exception.exception_type = new_type@@ -104,7 +115,6 @@ pub trait SymbolResolver: Send + Sync + 'static {.increment(1)}Err(ResolveError::UnhandledError(err)) => {- // Handle no original frames errorreturn Err(err);}};@@ -150,3 +160,83 @@ fn split_last_dot(s: &str) -> Result<(String, String), ResolveError> {let before = parts.next().ok_or(ProguardError::InvalidClass)?;Ok((before.to_string(), last.to_string()))}++#[cfg(test)]+mod tests {+ use crate::{+ core::types::Stacktrace,+ langs::{java::RawJavaFrame, CommonFrameMetadata},+ };++ use super::*;++ // A resolver whose class-remapping path panics, so the test below fails loudly if+ // `resolve_java_exception` attempts a lookup it was supposed to skip.+ struct NeverResolves;++ #[async_trait]+ impl SymbolResolver for NeverResolves {+ async fn resolve_raw_frame(+ &self,+ _team_id: TeamId,+ _frame: &RawFrame,+ _debug_images: &[DebugImage],+ ) -> Result<Vec<Frame>, UnhandledError> {+ unreachable!("frame resolution is not exercised here")+ }++ async fn resolve_java_class(+ &self,+ _team_id: TeamId,+ _symbolset_ref: OrChunkId<ProguardRef>,+ _class: String,+ ) -> Result<String, ResolveError> {+ panic!("must not look up a mapping when no frame carries a map_id")+ }++ async fn resolve_dart_minified_name(+ &self,+ _team_id: TeamId,+ _symbolset_ref: String,+ _minified_name: &str,+ ) -> Result<String, ResolveError> {+ unreachable!("dart resolution is not exercised here")+ }+ }++ fn java_exception(map_id: Option<&str>) -> Exception {+ Exception {+ exception_id: None,+ exception_type: "IllegalStateException".to_string(),+ exception_message: "boom".to_string(),+ mechanism: None,+ module: Some("java.lang".to_string()),+ thread_id: None,+ stack: Some(Stacktrace::Raw {+ frames: vec![RawFrame::Java(RawJavaFrame {+ filename: Some("InvoiceService.java".to_string()),+ function: "charge".to_string(),+ lineno: Some(42),+ module: "com.acme.billing.InvoiceService".to_string(),+ map_id: map_id.map(ToString::to_string),+ method_synthetic: false,+ meta: CommonFrameMetadata::default(),+ })],+ }),+ }+ }++ #[tokio::test]+ async fn unobfuscated_java_exceptions_skip_the_remap_attempt() {+ let result = NeverResolves+ .resolve_java_exception(1, java_exception(None))+ .await+ .unwrap();++ // The type and module come back untouched, and no lookup was attempted: the stub+ // resolver panics if one is, which is what keeps JAVA_EXCEPTION_REMAP_FAILED from+ // firing once per event on unobfuscated JVM traffic.+ assert_eq!(result.exception_type, "IllegalStateException");+ assert_eq!(result.module.as_deref(), Some("java.lang"));+ }+}diff --git a/rust/cymbal/src/core/types/langs/java.rs b/rust/cymbal/src/core/types/langs/java.rsindex 4bda68721d40..62fbb6557891 100644--- a/rust/cymbal/src/core/types/langs/java.rs+++ b/rust/cymbal/src/core/types/langs/java.rs@@ -17,6 +17,13 @@ use crate::{},};+// Namespace tag for the frame id construction below. It sits outside the digest on purpose:+// every other language's encoder emits a bare digest over a concatenation of fields the+// client controls, so any of them can be handed values that reproduce this construction's+// byte stream exactly. A tag inside the hash input would be part of what they can+// reproduce; a tag on the key itself is not. Changing the construction means bumping this.+const FRAME_ID_VERSION: &str = "java-v2";+#[derive(Debug, Clone, Deserialize, Serialize)]pub struct RawJavaFrame {pub filename: Option<String>, // The relative path of the file the context line is in@@ -35,6 +42,26 @@ pub struct RawJavaFrame {pub meta: CommonFrameMetadata,}+// Feed a variable-length value with its length in front, so the hash sees where the value+// ends. Concatenating raw would let bytes move across a field boundary without changing the+// digest.+fn update_len_prefixed(hasher: &mut Sha512, value: &[u8]) {+ hasher.update((value.len() as u64).to_be_bytes());+ hasher.update(value);+}++// An absent value is one byte apart from a present empty one, which a length prefix alone+// would fold together.+fn update_optional(hasher: &mut Sha512, value: Option<&str>) {+ match value {+ Some(value) => {+ hasher.update([1u8]);+ update_len_prefixed(hasher, value.as_bytes());+ }+ None => hasher.update([0u8]),+ }+}+impl RawJavaFrame {pub fn frame_id(&self) -> String {// We don't have version info for java frames, so we rely on@@ -43,14 +70,48 @@ impl RawJavaFrame {// if two frames are from two different library versions, if the// files they're in are sufficiently similar we can consider// them to be the same frame+ //+ // This id is the cache key for stored frame results, so two frames whose fields+ // differ must never encode to the same bytes. Every variable-length field is+ // length-prefixed and every optional one carries a presence byte: a flat+ // concatenation let module "a1.d" with map_id "release" hash identically to module+ // "a1.drelease" with no map_id. Project tokens ship inside client apps, so whoever+ // submits a crafted colliding frame first decides which record the other shape+ // reads. `filename: None` is therefore distinct from `Some("")`, and an absent+ // `lineno` from `Some(0)`: nothing rejects a zero line on the way in, and the two+ // resolve to frames with different `line` values.+ //+ // The mapping reference has to participate at all because a pass-through frame is+ // saved as resolved, with no linked symbol set and the longer resolved TTL, so if it+ // shared an id with the same source location captured *with* a map_id, that cached+ // record would be served to the obfuscated frame and suppress its proguard remap,+ // and a later mapping upload would not invalidate it. Proguard can renumber lines+ // even for classes it keeps, so matching file/function/line/module across the two+ // shapes is reachable.+ //+ // The tag on the front of the key gives this construction its own keyspace. Without+ // it the key is a bare digest, which leaves two ways for records of different shapes+ // to alias: a rolling deploy has old and new instances reading each other's java+ // records, and the encoders for the other languages, which hash flat concatenations+ // of client-controlled strings, can be fed values that land on a java key. It retires+ // every stored java id once and they re-resolve on next sight, which the ~30 minute+ // TTL makes cheap. Fingerprints are unaffected: this id only appears as `raw_id` in+ // the fingerprint record, never in the hash itself.let mut hasher = Sha512::new();- if let Some(filename) = &self.filename {- hasher.update(filename.as_bytes());+ update_optional(&mut hasher, self.filename.as_deref());+ update_len_prefixed(&mut hasher, self.function.as_bytes());+ // Fixed to u64 rather than usize, so the key does not depend on the pointer width of+ // the instance that wrote it.+ match self.lineno {+ Some(lineno) => {+ hasher.update([1u8]);+ hasher.update((lineno as u64).to_be_bytes());+ }+ None => hasher.update([0u8]),}- hasher.update(self.function.as_bytes());- hasher.update(self.lineno.unwrap_or_default().to_be_bytes());- hasher.update(self.module.as_bytes());- format!("{:x}", hasher.finalize())+ update_len_prefixed(&mut hasher, self.module.as_bytes());+ update_optional(&mut hasher, self.map_id.as_deref());+ format!("{FRAME_ID_VERSION}:{:x}", hasher.finalize())}pub async fn resolve_frame<C>(@@ -86,6 +147,16 @@ impl RawJavaFrame {whereC: SymbolCatalog<OrChunkId<ProguardRef>, FetchedMapping>,{+ // A frame without a map_id has no ProGuard mapping to demangle against, which is+ // the norm for unobfuscated JVM apps: server SDKs, and Android builds without+ // minification. javac keeps the real file, line and method names in the class+ // file, so the frame arrives already readable and there is nothing to resolve.+ // Short-circuit before `get_ref()` and the catalog lookup so these frames stop+ // being counted (and logged) as resolution failures.+ if self.map_id.is_none() {+ return Ok(vec![self.into()]);+ }+let r = self.get_ref()?;let map: Arc<FetchedMapping> = catalog.lookup(team_id, r.clone()).await?;let cache = map.get_cache()?;@@ -203,6 +274,67 @@ impl<'a> From<(&'a RawJavaFrame, StackFrame<'a>)> for Frame {}}+// Pass-through conversion for a frame that arrived already readable, because it carries+// no map_id and so has no ProGuard mapping to demangle against. The client-provided+// module, method, file and line are the real ones, so we surface them as-is with+// `resolved: true` and no failure. This mirrors the direct `From<&RawX> for Frame`+// conversions used by the catalog-free languages (python, go, php, ruby).+//+// INVARIANT: `resolved_name` deliberately stays `None`, even though the frame is+// resolved. `update_frame` in `modes/processing/fingerprinting/mod.rs` branches on+// `resolved_name`: when it is `Some`, it hashes source + module + resolved_name and+// returns; when it is `None`, it hashes source + module + mangled_name (+ line under V1)+// + lang. Because `mangled_name`, `source`, `module` and `lang` here are identical to+// what the previous failure path produced, leaving `resolved_name` as `None` keeps the+// mangled branch selected, so the per-frame hash contribution is byte-identical.+// Populating it would silently re-key that traffic into new issues, so that flip is+// deferred to a `FingerprintVersion` bump, which is the mechanism that exists for+// intentional regrouping.+//+// That covers per-frame hashing, but not frame *selection*, and the two differ for one+// case. `FrameSelection::InAppResolvedElseAll` (the V1 default) keeps in-app frames, and+// restricts to resolved ones only when at least one frame in the exception resolved. For a+// stack where no frame carries a map_id, every frame flips to resolved together, so the+// selected set is unchanged and the fingerprint is stable. For a *mixed* stack, where some+// frames carry a map_id and some do not (see the ref-less-frame handling in+// `resolve_java_exception`), a ref-less in-app frame used to be excluded next to a+// successfully remapped one and is now included, which does change that issue's+// fingerprint. Obfuscated-android traffic is the only shape that hits this.+//+// The success metric is not emitted here: the `RawFrame` dispatcher in+// `symbolication/resolve.rs` already counts every frame that comes back with+// `resolved: true` toward `FRAME_RESOLVED`.+impl From<&RawJavaFrame> for Frame {+ fn from(raw: &RawJavaFrame) -> Self {+ let mut f = Frame {+ frame_id: FrameId::placeholder(),+ mangled_name: raw.function.clone(),+ line: raw.lineno.map(|ln| ln as u32),+ column: None,+ source: raw.filename.clone(),+ // No map_id means no applicationId to reclassify against, so `resolved_in_app`+ // would return the raw flag anyway. The client classified this build correctly+ // because its class names were never obfuscated.+ in_app: raw.meta.in_app,+ resolved_name: None,+ lang: "java".to_string(),+ resolved: true,+ resolve_failure: None,++ junk_drawer: None,+ code_variables: None,+ synthetic: raw.meta.synthetic,+ context: None,+ suspicious: false,+ module: Some(raw.module.clone()),+ };++ add_raw_to_junk(&mut f, raw);++ f+ }+}+impl From<(&RawJavaFrame, ProguardError)> for Frame {fn from((raw, error): (&RawJavaFrame, ProguardError)) -> Self {record_frame_resolution_failure("java", error.metric_reason(), &error);@@ -236,6 +368,17 @@ impl From<(&RawJavaFrame, ProguardError)> for Frame {#[cfg(test)]mod tests {+ use sqlx::{postgres::PgConnectOptions, PgPool};++ use crate::{+ core::config::ResolverConfig,+ symbolication::symbol_store::{+ apple::AppleProvider, chunk_id::ChunkIdFetcher, hermesmap::HermesMapProvider,+ native::NativeProvider, proguard::ProguardProvider, sourcemap::SourcemapProvider,+ Catalog, MockS3Client,+ },+ };+use super::*;const PROGUARD_MAP: &str =@@ -256,6 +399,183 @@ mod tests {}}+ // A pool that never opens a connection. The pass-through path returns before any+ // query runs, so a lazy pool lets the catalog be built without a live Postgres.+ fn lazy_pool() -> PgPool {+ PgPool::connect_lazy_with(PgConnectOptions::new())+ }++ // A catalog whose S3 client has no mockall expectations set, so any attempt to fetch+ // a symbol set panics instead of returning a plausible-looking miss. That turns "the+ // pass-through path reached the symbol store" into a test failure.+ fn catalog_that_never_fetches(db: PgPool) -> Catalog {+ let mut config = ResolverConfig::init_with_defaults().unwrap();+ config.object_storage_bucket = "test-bucket".to_string();+ let client = Arc::new(MockS3Client::default());++ let bucket = config.object_storage_bucket.clone();+ let smp = ChunkIdFetcher::new(+ SourcemapProvider::new(&config),+ client.clone(),+ db.clone(),+ bucket.clone(),+ );+ let hmp = ChunkIdFetcher::new(+ HermesMapProvider {},+ client.clone(),+ db.clone(),+ bucket.clone(),+ );+ let pgp = ChunkIdFetcher::new(+ ProguardProvider {},+ client.clone(),+ db.clone(),+ bucket.clone(),+ );+ let apple =+ ChunkIdFetcher::new(AppleProvider {}, client.clone(), db.clone(), bucket.clone());+ let native = ChunkIdFetcher::new(NativeProvider {}, client.clone(), db.clone(), bucket);+ Catalog::new(smp, hmp, pgp, apple, native)+ }++ #[tokio::test]+ async fn map_id_less_frames_pass_through_without_lookup() {+ let catalog = catalog_that_never_fetches(lazy_pool());++ // An unobfuscated server-JVM stack: application classes plus a framework frame,+ // none of them carrying a map_id.+ let frames = [+ raw_frame("com.acme.billing.InvoiceService", true, None),+ raw_frame("java.lang.Thread", false, None),+ ];++ for raw in &frames {+ assert_eq!(raw.symbol_set_ref(), None);++ let resolved = raw.resolve_frame(1, &catalog).await.unwrap();+ assert_eq!(+ resolved.len(),+ 1,+ "pass-through maps 1 raw frame to 1 frame"+ );+ let f = &resolved[0];++ assert!(f.resolved, "an unobfuscated frame is already resolved");+ assert_eq!(f.resolve_failure, None);+ assert_eq!(f.resolved_name, None, "see the fingerprint invariant");+ assert_eq!(f.mangled_name, raw.function);+ assert_eq!(f.module.as_deref(), Some(raw.module.as_str()));+ assert_eq!(f.source, raw.filename);+ assert_eq!(f.line, raw.lineno.map(|l| l as u32));+ assert_eq!(f.lang, "java");+ assert_eq!(f.in_app, raw.meta.in_app);+ }+ }++ // Guards the fingerprint-neutrality claim in the `From<&RawJavaFrame>` invariant+ // comment. Every field `update_frame` reads must match what the old failure path+ // produced, so flipping these frames to resolved cannot re-key existing issues.+ // If someone populates `resolved_name` on the pass-through path, this fails.+ #[test]+ fn pass_through_is_fingerprint_identical_to_the_old_failure_frame() {+ let raw = raw_frame("com.acme.billing.InvoiceService", true, None);++ let passed_through: Frame = (&raw).into();+ let legacy: Frame = (&raw, ProguardError::NoMapId).into();++ assert_eq!(passed_through.resolved_name, None);+ assert_eq!(legacy.resolved_name, None);++ // The inputs `update_frame` hashes, in both the resolved and unresolved branches.+ assert_eq!(passed_through.source, legacy.source);+ assert_eq!(passed_through.module, legacy.module);+ assert_eq!(passed_through.mangled_name, legacy.mangled_name);+ assert_eq!(passed_through.line, legacy.line);+ assert_eq!(passed_through.lang, legacy.lang);++ // The behavior that actually changed.+ assert!(passed_through.resolved);+ assert!(!legacy.resolved);+ assert_eq!(passed_through.resolve_failure, None);+ }++ #[sqlx::test(migrations = "./tests/test_migrations")]+ async fn map_id_with_missing_mapping_still_fails(db: PgPool) {+ // A map_id is present but no symbol set was ever uploaded. That is a real+ // resolution failure and must stay one, so the short-circuit above cannot be+ // widened to swallow obfuscated frames we genuinely failed to demangle.+ let catalog = catalog_that_never_fetches(db);+ let raw = raw_frame("a1.d", false, Some("[email protected]+3"));++ let resolved = raw.resolve_frame(1, &catalog).await.unwrap();+ assert_eq!(resolved.len(), 1);+ let f = &resolved[0];+ assert!(!f.resolved);+ assert!(f.resolve_failure.is_some());+ assert_eq!(f.resolved_name, None);+ }++ #[test]+ fn map_id_changes_the_frame_id() {+ // The id is the cache key for stored frame results, so the same source location+ // captured with and without a mapping reference must not share one. Otherwise the+ // pass-through record, saved as resolved on the long TTL with no linked symbol set,+ // would be served to the obfuscated frame instead of it being remapped.+ let without = raw_frame("a1.d", false, None);+ let with = raw_frame("a1.d", false, Some("[email protected]+3"));+ assert_ne!(without.frame_id(), with.frame_id());++ // The unversioned construction every stored java id was written with. The version+ // tag has to move both frame shapes off it, or a mixed-version fleet serves records+ // written for one shape to the other until they expire.+ let mut legacy = Sha512::new();+ legacy.update(without.filename.as_ref().unwrap().as_bytes());+ legacy.update(without.function.as_bytes());+ legacy.update(without.lineno.unwrap().to_be_bytes());+ legacy.update(without.module.as_bytes());+ let legacy = format!("{:x}", legacy.finalize());+ assert_ne!(without.frame_id(), legacy);+ assert_ne!(with.frame_id(), legacy);+ }++ #[test]+ fn bytes_cannot_shift_across_field_boundaries() {+ // Concatenating the fields raw made these two frames hash the same bytes, so one+ // could plant the stored record the other reads: a crafted pass-through frame keeps+ // the real obfuscated frame from being remapped for as long as the record lives.+ let mapped = raw_frame("a1.d", false, Some("release"));+ let shifted = raw_frame("a1.drelease", false, None);+ assert_ne!(mapped.frame_id(), shifted.frame_id());++ // The same bug in the presence bytes: an absent field must not encode like a present+ // empty or zero one. Both shapes reach us from untrusted capture payloads, and they+ // pass through to frames with different `source` and `line`.+ let mut no_filename = raw_frame("a1.d", false, None);+ no_filename.filename = None;+ let mut empty_filename = raw_frame("a1.d", false, None);+ empty_filename.filename = Some(String::new());+ assert_ne!(no_filename.frame_id(), empty_filename.frame_id());++ let mut no_lineno = raw_frame("a1.d", false, None);+ no_lineno.lineno = None;+ let mut zero_lineno = raw_frame("a1.d", false, None);+ zero_lineno.lineno = Some(0);+ assert_ne!(no_lineno.frame_id(), zero_lineno.frame_id());+ }++ #[test]+ fn frame_ids_are_tagged_outside_the_digest() {+ // Frame records are keyed by raw id per team, and the other languages' encoders emit+ // a bare digest over client-controlled strings, so one of those frames can be given+ // field values that reproduce this construction's hash input. The tag has to sit on+ // the key, where they cannot reach it, which also means a java id is never a plain+ // hex digest.+ let id = raw_frame("a1.d", false, Some("[email protected]+3")).frame_id();++ assert!(id.starts_with("java-v2:"), "{id}");+ assert!(!id.chars().all(|c| c.is_ascii_hexdigit()), "{id}");+ }+#[test]fn resolved_frames_under_application_id_promote_to_in_app() {let mapping = proguard::ProguardMapping::new(PROGUARD_MAP.as_bytes());