: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): resolve Hermes maps without scope metadata (#71998)
Catalin Irimie7fd3c5510d48
diff --git a/rust/cymbal/src/core/symbolication/symbol_store/hermesmap.rs b/rust/cymbal/src/core/symbolication/symbol_store/hermesmap.rsindex ca7f7c90cac8..72dad7d08359 100644--- a/rust/cymbal/src/core/symbolication/symbol_store/hermesmap.rs+++ b/rust/cymbal/src/core/symbolication/symbol_store/hermesmap.rs@@ -1,6 +1,7 @@use async_trait::async_trait;use bytes::Bytes;use posthog_symbol_data::{read_symbol_data_with_byte_count, HermesMap};+use serde::Deserialize;use crate::{error::{HermesError, ResolveError, UnhandledError},@@ -10,11 +11,46 @@ use crate::{};pub struct ParsedHermesMap {- pub map: sourcemap::SourceMapHermes,+ pub(crate) map: ParsedHermesSourceMap,/// Decompressed byte count from the symbol_data container, used for cache memory accounting.decompressed_bytes: usize,}+pub(crate) enum ParsedHermesSourceMap {+ WithScopes(sourcemap::SourceMapHermes),+ LocationOnly(sourcemap::SourceMap),+}++impl ParsedHermesSourceMap {+ pub fn lookup_token(&self, line: u32, column: u32) -> Option<sourcemap::Token<'_>> {+ match self {+ Self::WithScopes(map) => map.lookup_token(line, column),+ Self::LocationOnly(map) => map.lookup_token(line, column),+ }+ }++ pub fn get_original_function_name(&self, bytecode_offset: u32) -> Option<&str> {+ match self {+ Self::WithScopes(map) => map.get_original_function_name(bytecode_offset),+ Self::LocationOnly(_) => None,+ }+ }+}++#[derive(Deserialize)]+struct HermesMapMetadata {+ #[serde(default, deserialize_with = "marker_present")]+ x_hermes_function_offsets: bool,+}++fn marker_present<'de, D>(deserializer: D) -> Result<bool, D::Error>+where+ D: serde::Deserializer<'de>,+{+ serde::de::IgnoredAny::deserialize(deserializer)?;+ Ok(true)+}+impl Countable for ParsedHermesMap {fn byte_count(&self) -> usize {self.decompressed_bytes@@ -60,10 +96,84 @@ impl ParsedHermesMap {map: HermesMap,decompressed_bytes: usize,) -> Result<ParsedHermesMap, HermesError> {+ let content = map.sourcemap;+ let decoded = sourcemap::decode_slice(content.as_bytes())+ .map_err(|e| HermesError::InvalidMap(e.to_string()))?;++ let map = match decoded {+ sourcemap::DecodedMap::Hermes(map) => ParsedHermesSourceMap::WithScopes(map),+ // The CLI also accepts this Hermes marker, but rust-sourcemap classifies+ // maps without Metro's scope metadata as regular source maps.+ sourcemap::DecodedMap::Regular(map) if has_hermes_function_offsets(&content)? => {+ ParsedHermesSourceMap::LocationOnly(map)+ }+ _ => {+ return Err(HermesError::InvalidMap(+ sourcemap::Error::IncompatibleSourceMap.to_string(),+ ));+ }+ };+Ok(ParsedHermesMap {- map: sourcemap::SourceMapHermes::from_reader(map.sourcemap.as_bytes())- .map_err(|e| HermesError::InvalidMap(e.to_string()))?,+ map,decompressed_bytes,})}}++fn has_hermes_function_offsets(content: &str) -> Result<bool, HermesError> {+ let content = match content.as_bytes().first() {+ Some(b')' | b']' | b'}' | b'\'') => content+ .split_once('\n')+ .map(|(_, content)| content)+ .unwrap_or_default(),+ _ => content,+ };+ let metadata: HermesMapMetadata =+ serde_json::from_str(content).map_err(|e| HermesError::InvalidMap(e.to_string()))?;+ Ok(metadata.x_hermes_function_offsets)+}++#[cfg(test)]+mod tests {+ use posthog_symbol_data::HermesMap;++ use super::{ParsedHermesMap, ParsedHermesSourceMap};++ const OFFSETS_ONLY_MAP: &str =+ include_str!("../../../../tests/static/hermes/hermes_example.map");++ #[test]+ fn parses_offsets_only_map_for_location_resolution() {+ let parsed = ParsedHermesMap::parse(+ HermesMap {+ sourcemap: OFFSETS_ONLY_MAP.to_string(),+ },+ OFFSETS_ONLY_MAP.len(),+ )+ .unwrap();++ assert!(matches!(parsed.map, ParsedHermesSourceMap::LocationOnly(_)));+ let token = parsed.map.lookup_token(0, 1000).unwrap();+ assert_eq!(+ token.get_source(),+ Some("./build/android/index.android.bundle")+ );+ assert_eq!(token.get_src_line(), 49);+ assert_eq!(token.get_src_col(), 26);+ assert_eq!(parsed.map.get_original_function_name(1000), None);+ }++ #[test]+ fn rejects_regular_map_without_hermes_marker() {+ let result = ParsedHermesMap::parse(+ HermesMap {+ sourcemap: r#"{"version":3,"sources":["index.js"],"names":[],"mappings":"AAAA"}"#+ .to_string(),+ },+ 0,+ );++ assert!(result.is_err());+ }+}diff --git a/rust/cymbal/src/core/types/langs/hermes.rs b/rust/cymbal/src/core/types/langs/hermes.rsindex f4d5ce42caaf..c31236e8d824 100644--- a/rust/cymbal/src/core/types/langs/hermes.rs+++ b/rust/cymbal/src/core/types/langs/hermes.rs@@ -244,29 +244,85 @@ impl From<&RawHermesFrame> for Frame {#[cfg(test)]mod test {use crate::core::symbolication::resolve::Resolve;+ use async_trait::async_trait;use std::sync::Arc;use chrono::Utc;use mockall::predicate;- use posthog_symbol_data::write_symbol_data;+ use posthog_symbol_data::{write_symbol_data, HermesMap};use regex::Regex;use sqlx::PgPool;use uuid::Uuid;use crate::{core::config::ResolverConfig,+ error::ResolveError,frames::RawFrame,- langs::{hermes::RawHermesFrame, CommonFrameMetadata},+ langs::{+ hermes::{HermesRef, RawHermesFrame},+ CommonFrameMetadata,+ },symbolication::symbol_store::{- apple::AppleProvider, chunk_id::ChunkIdFetcher, hermesmap::HermesMapProvider,- native::NativeProvider, proguard::ProguardProvider, saving::SymbolSetRecord,- sourcemap::SourcemapProvider, Catalog, MockS3Client,+ apple::AppleProvider,+ chunk_id::{ChunkIdFetcher, OrChunkId},+ hermesmap::{HermesMapProvider, ParsedHermesMap},+ native::NativeProvider,+ proguard::ProguardProvider,+ saving::SymbolSetRecord,+ sourcemap::SourcemapProvider,+ Catalog, MockS3Client, SymbolCatalog,},};const HERMES_MAP: &str = include_str!("../../../../tests/static/hermes/composed_example.map");+ const OFFSETS_ONLY_MAP: &str =+ include_str!("../../../../tests/static/hermes/hermes_example.map");const RAW_STACK: &str = include_str!("../../../../tests/static/hermes/raw_stack.txt");+ struct StaticHermesCatalog(Arc<ParsedHermesMap>);++ #[async_trait]+ impl SymbolCatalog<OrChunkId<HermesRef>, ParsedHermesMap> for StaticHermesCatalog {+ async fn lookup(+ &self,+ _team_id: i32,+ _r: OrChunkId<HermesRef>,+ ) -> Result<Arc<ParsedHermesMap>, ResolveError> {+ Ok(self.0.clone())+ }+ }++ #[tokio::test]+ async fn test_offsets_only_hermes_resolution() {+ let map = ParsedHermesMap::parse(+ HermesMap {+ sourcemap: OFFSETS_ONLY_MAP.to_string(),+ },+ OFFSETS_ONLY_MAP.len(),+ )+ .unwrap();+ let catalog = StaticHermesCatalog(Arc::new(map));+ let frame = RawHermesFrame {+ column: Some(1000),+ source: "index.android.bundle".to_string(),+ fn_name: "anonymous".to_string(),+ chunk_id: Some("test-chunk".to_string()),+ meta: CommonFrameMetadata::default(),+ };++ let resolved = frame.resolve_frame(1, &catalog, 15).await.unwrap();++ assert!(resolved.resolved);+ assert_eq!(+ resolved.source.as_deref(),+ Some("./build/android/index.android.bundle")+ );+ assert_eq!(resolved.line, Some(49));+ assert_eq!(resolved.column, Some(26));+ assert_eq!(resolved.resolved_name, None);+ assert_eq!(resolved.resolve_failure, None);+ }+#[sqlx::test(migrations = "./tests/test_migrations")]async fn test_hermes_resolution(db: PgPool) {let team_id = 1;