: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 sourcemaps from chunk id comments (#58335)
Catalin Irimied9d1c8d579aa
diff --git a/rust/cymbal/src/app_context.rs b/rust/cymbal/src/app_context.rsindex 668bc9eea388..7cf4f6efc715 100644--- a/rust/cymbal/src/app_context.rs+++ b/rust/cymbal/src/app_context.rs@@ -115,7 +115,11 @@ impl AppContext {config.symbol_store_cache_max_bytes,)));- let smp = SourcemapProvider::new(config);+ let smp = SourcemapProvider::new(config).with_chunk_id_rescue(+ posthog_pool.clone(),+ s3_client.clone(),+ config.object_storage_bucket.clone(),+ );let smp_chunk = ChunkIdFetcher::new(smp,s3_client.clone(),diff --git a/rust/cymbal/src/metric_consts.rs b/rust/cymbal/src/metric_consts.rsindex cacb6ad648ec..0ca13b69407d 100644--- a/rust/cymbal/src/metric_consts.rs+++ b/rust/cymbal/src/metric_consts.rs@@ -32,6 +32,7 @@ pub const ISSUE_REOPENED: &str = "cymbal_issue_reopened";pub const FRAME_RESOLUTION_RESULTS_DELETED: &str = "cymbal_frame_resolution_results_deleted";pub const CHUNK_ID_NOT_FOUND: &str = "cymbal_chunk_id_not_found";pub const CHUNK_ID_FAILURE_FETCHED: &str = "cymbal_chunk_id_failure_fetched";+pub const CHUNK_ID_RESCUED_FROM_BODY: &str = "cymbal_chunk_id_rescued_from_body";pub const SUPPRESSED_ISSUE_DROPPED_EVENTS: &str = "cymbal_suppressed_issue_drop";pub const ASSIGNMENT_RULES_PROCESSING_TIME: &str = "cymbal_assignment_rules_processing_time";pub const ANCILLARY_CACHE: &str = "cymbal_ancillary_cache";diff --git a/rust/cymbal/src/symbol_store/chunk_id.rs b/rust/cymbal/src/symbol_store/chunk_id.rsindex 306c82f055b0..509796f42454 100644--- a/rust/cymbal/src/symbol_store/chunk_id.rs+++ b/rust/cymbal/src/symbol_store/chunk_id.rs@@ -40,6 +40,42 @@ pub enum OrChunkId<R> {Both { inner: R, id: String },}+pub enum SymbolSetLoadResult {+ Data(Vec<u8>),+ Missing,+ Failed(String),+ MissingStoragePtr(String),+ MissingBlob(SymbolSetRecord),+}++pub async fn load_symbol_set_data(+ pool: &PgPool,+ client: &dyn BlobClient,+ bucket: &str,+ team_id: i32,+ set_ref: &str,+) -> Result<SymbolSetLoadResult, UnhandledError> {+ let Some(mut record) = SymbolSetRecord::load(pool, team_id, set_ref).await? else {+ return Ok(SymbolSetLoadResult::Missing);+ };++ if let Some(failure_reason) = record.failure_reason {+ return Ok(SymbolSetLoadResult::Failed(failure_reason));+ }++ let Some(storage_ptr) = record.storage_ptr.clone() else {+ return Ok(SymbolSetLoadResult::MissingStoragePtr(record.set_ref));+ };++ record.set_last_used(pool).await?;++ // Otherwise, if we just failed to talk to s3 for some reason, treat it as an unhandled error and die+ match client.get(bucket, &storage_ptr).await? {+ Some(data) => Ok(SymbolSetLoadResult::Data(data)),+ None => Ok(SymbolSetLoadResult::MissingBlob(record)),+ }+}+// This is more-or-less a read-only version of the saving layer - it never writes symbol sets, although// it will modify records to indicate an error if the underlying parser fails. For symbol sets we dynamically// fetch (like js sourcemaps), it's main function is to strip the `OrChunkId` from the ref and pass the@@ -79,43 +115,38 @@ whereOrChunkId::Both { inner, id } => (id, Some(inner)),};- let Some(mut record) = SymbolSetRecord::load(&self.pool, team_id, &id).await? else {- counter!(CHUNK_ID_NOT_FOUND).increment(1);- let Some(inner) = inner else {- return Err(FrameError::MissingChunkIdData(id).into());- };- // We have a chunk id, but it's not saved - fetch with the inner, knowing the OrChunkId's- // `Display` implementation will use the chunk id as the set reference everywhere else- return self.inner.fetch(team_id, inner).await;- };-- // If we failed to parse this chunk's data in the past, we should not try again.- // Note that in situations where we're running beneath a `Saving` layer, we'll- // never reach this point, but we still handle the case for correctness sake- if let Some(failure_reason) = &record.failure_reason {- counter!(CHUNK_ID_FAILURE_FETCHED).increment(1);- let error: FrameError =- serde_json::from_str(failure_reason).map_err(UnhandledError::from)?;- return Err(error.into());- }-- let Some(storage_ptr) = record.storage_ptr.clone() else {- // It's never valid to have no failure reason and no storage pointer - if we hit this case, just panic- error!("No storage pointer found for chunk id {}", id);- panic!("No storage pointer found for chunk id {id}");- };-- record.set_last_used(&self.pool).await?;-- match self.client.get(&self.bucket, &storage_ptr).await {- Ok(Some(data)) => Ok(data),- Ok(None) => {+ match load_symbol_set_data(&self.pool, self.client.as_ref(), &self.bucket, team_id, &id)+ .await?+ {+ SymbolSetLoadResult::Data(data) => Ok(data),+ SymbolSetLoadResult::Missing => {+ counter!(CHUNK_ID_NOT_FOUND).increment(1);+ let Some(inner) = inner else {+ return Err(FrameError::MissingChunkIdData(id).into());+ };+ // We have a chunk id, but it's not saved - fetch with the inner, knowing the OrChunkId's+ // `Display` implementation will use the chunk id as the set reference everywhere else+ self.inner.fetch(team_id, inner).await+ }+ SymbolSetLoadResult::Failed(failure_reason) => {+ // If we failed to parse this chunk's data in the past, we should not try again.+ // Note that in situations where we're running beneath a `Saving` layer, we'll+ // never reach this point, but we still handle the case for correctness sake+ counter!(CHUNK_ID_FAILURE_FETCHED).increment(1);+ let error: FrameError =+ serde_json::from_str(&failure_reason).map_err(UnhandledError::from)?;+ Err(error.into())+ }+ SymbolSetLoadResult::MissingStoragePtr(set_ref) => {+ // It's never valid to have no failure reason and no storage pointer - if we hit this case, just panic+ error!("No storage pointer found for chunk id {}", set_ref);+ panic!("No storage pointer found for chunk id {set_ref}");+ }+ SymbolSetLoadResult::MissingBlob(mut record) => {// If the chunk ID points to a record that doesn't exist, delete the record and treat it as a frame errorrecord.delete(&self.pool).await?;- return Err(FrameError::MissingChunkIdData(record.set_ref).into());+ Err(FrameError::MissingChunkIdData(record.set_ref).into())}- // Otherwise, if we just failed to talk to s3 for some reason, treat it as an unhandled error and die- Err(err) => Err(err.into()),}}}diff --git a/rust/cymbal/src/symbol_store/sourcemap.rs b/rust/cymbal/src/symbol_store/sourcemap.rsindex 027eb126573a..a44906e4db3c 100644--- a/rust/cymbal/src/symbol_store/sourcemap.rs+++ b/rust/cymbal/src/symbol_store/sourcemap.rs@@ -4,6 +4,7 @@ use async_trait::async_trait;use base64::Engine;use posthog_symbol_data::{read_symbol_data_with_byte_count, write_symbol_data, SourceAndMap};use reqwest::Url;+use sqlx::PgPool;use symbolic::sourcemapcache::{SourceMapCache, SourceMapCacheWriter};use tracing::{info, warn};@@ -11,15 +12,28 @@ use crate::{config::Config,error::{JsResolveErr, ResolveError},metric_consts::{- SOURCEMAP_BODY_FETCHES, SOURCEMAP_BODY_REF_FOUND, SOURCEMAP_FETCH, SOURCEMAP_HEADER_FOUND,- SOURCEMAP_NOT_FOUND, SOURCEMAP_PARSE,+ CHUNK_ID_RESCUED_FROM_BODY, SOURCEMAP_BODY_FETCHES, SOURCEMAP_BODY_REF_FOUND,+ SOURCEMAP_FETCH, SOURCEMAP_HEADER_FOUND, SOURCEMAP_NOT_FOUND, SOURCEMAP_PARSE,},};-use super::{caching::Countable, dart_minified_names::parse_dart_minified_names, Fetcher, Parser};+use super::{+ caching::Countable,+ chunk_id::{load_symbol_set_data, SymbolSetLoadResult},+ dart_minified_names::parse_dart_minified_names,+ BlobClient, Fetcher, Parser,+};pub struct SourcemapProvider {pub client: reqwest::Client,+ pub chunk_id_rescue: Option<ChunkIdRescue>,+}++#[derive(Clone)]+pub struct ChunkIdRescue {+ pub pool: PgPool,+ pub blob_client: Arc<dyn BlobClient>,+ pub bucket: String,}// Sigh. Later we can be smarter here to only do the parse once, but it involves@@ -119,7 +133,24 @@ impl SourcemapProvider {let client = client.build().unwrap();- Self { client }+ Self {+ client,+ chunk_id_rescue: None,+ }+ }++ pub fn with_chunk_id_rescue(+ mut self,+ pool: PgPool,+ blob_client: Arc<dyn BlobClient>,+ bucket: String,+ ) -> Self {+ self.chunk_id_rescue = Some(ChunkIdRescue {+ pool,+ blob_client,+ bucket,+ });+ self}}@@ -140,13 +171,25 @@ impl Fetcher for SourcemapProvider {type Ref = Url;type Fetched = Vec<u8>;type Err = ResolveError;- async fn fetch(&self, _: i32, r: Url) -> Result<Vec<u8>, Self::Err> {+ async fn fetch(&self, team_id: i32, r: Url) -> Result<Vec<u8>, Self::Err> {let start = common_metrics::timing_guard(SOURCEMAP_FETCH, &[]);- let (smu, minified_source) = find_sourcemap_url(&self.client, r).await?;+ let peek = find_sourcemap_url(&self.client, r).await?;let start = start.label("found_url", "true");- let sourcemap = match smu {+ if let Some(rescue) = &self.chunk_id_rescue {+ if let Some(chunk_id) = peek.chunk_id_from_body.as_deref() {+ if let Some(data) = try_chunk_id_rescue(rescue, team_id, chunk_id).await? {+ start+ .label("found_data", "true")+ .label("rescued", "true")+ .fin();+ return Ok(data);+ }+ }+ }++ let sourcemap = match peek.sourcemap_url {SourceMappingUrl::Url(sourcemap_url) => {fetch_source_map(&self.client, sourcemap_url.clone()).await?}@@ -157,7 +200,7 @@ impl Fetcher for SourcemapProvider {assert_is_sourcemap(&sourcemap)?;let sam = SourceAndMap {- minified_source,+ minified_source: peek.body,sourcemap,};let data = write_symbol_data(sam).map_err(JsResolveErr::JSDataError)?;@@ -168,6 +211,46 @@ impl Fetcher for SourcemapProvider {}}+async fn try_chunk_id_rescue(+ rescue: &ChunkIdRescue,+ team_id: i32,+ chunk_id: &str,+) -> Result<Option<Vec<u8>>, ResolveError> {+ match load_symbol_set_data(+ &rescue.pool,+ rescue.blob_client.as_ref(),+ &rescue.bucket,+ team_id,+ chunk_id,+ )+ .await+ .map_err(ResolveError::UnhandledError)?+ {+ SymbolSetLoadResult::Data(data) => {+ metrics::counter!(CHUNK_ID_RESCUED_FROM_BODY).increment(1);+ info!(+ "Rescued URL-fetched JS frame via uploaded symbol set for chunk id {}",+ chunk_id+ );+ Ok(Some(data))+ }+ SymbolSetLoadResult::MissingBlob(mut record) => {+ warn!(+ "Symbol set record for chunk id {} points to a missing S3 object",+ record.set_ref+ );+ record+ .delete(&rescue.pool)+ .await+ .map_err(ResolveError::UnhandledError)?;+ Ok(None)+ }+ SymbolSetLoadResult::Missing+ | SymbolSetLoadResult::Failed(_)+ | SymbolSetLoadResult::MissingStoragePtr(_) => Ok(None),+ }+}+#[async_trait]impl Parser for SourcemapProvider {type Source = Vec<u8>;@@ -185,10 +268,33 @@ impl Parser for SourcemapProvider {}}+struct JsSourcePeek {+ body: String,+ sourcemap_url: SourceMappingUrl,+ chunk_id_from_body: Option<String>,+}++const CHUNK_ID_COMMENT_PREFIXES: &[&str] = &["//# chunkId=", "//@ chunkId="];++fn extract_chunk_id_from_body(body: &str) -> Option<String> {+ for line in body.lines().rev().take(32) {+ let trimmed = line.trim();+ for prefix in CHUNK_ID_COMMENT_PREFIXES {+ if let Some(rest) = trimmed.strip_prefix(prefix) {+ let id = rest.trim();+ if !id.is_empty() {+ return Some(id.to_string());+ }+ }+ }+ }+ None+}+async fn find_sourcemap_url(client: &reqwest::Client,start: Url,-) -> Result<(SourceMappingUrl, String), ResolveError> {+) -> Result<JsSourcePeek, ResolveError> {info!("Fetching script source from {}", start);// If this request fails, we cannot resolve the frame, and hand this error to the frames@@ -214,6 +320,8 @@ async fn find_sourcemap_url(// We always need the bodylet body = res.text().await.map_err(JsResolveErr::from)?;+ let chunk_id_from_body = extract_chunk_id_from_body(&body);+if let Some(header_url) = header_url {info!("Found sourcemap header: {:?}", header_url);metrics::counter!(SOURCEMAP_HEADER_FOUND).increment(1);@@ -233,7 +341,11 @@ async fn find_sourcemap_url(final_url.set_path(url);final_url};- return Ok((url.into(), body));+ return Ok(JsSourcePeek {+ body,+ sourcemap_url: url.into(),+ chunk_id_from_body,+ });}// If we didn't find a header, we have to check the body@@ -247,7 +359,11 @@ async fn find_sourcemap_url(// If we can parse this as a data URL, we can just use thatif let Some(data) = maybe_as_data_url(final_url.as_ref(), found, data_url_to_json_str)?{- return Ok((SourceMappingUrl::Data(data), body));+ return Ok(JsSourcePeek {+ body,+ sourcemap_url: SourceMappingUrl::Data(data),+ chunk_id_from_body,+ });}// If the found url has a scheme, we can just parse it@@ -273,7 +389,11 @@ async fn find_sourcemap_url(final_url.set_path(found);final_url};- return Ok((url.into(), body));+ return Ok(JsSourcePeek {+ body,+ sourcemap_url: url.into(),+ chunk_id_from_body,+ });}}@@ -285,7 +405,11 @@ async fn find_sourcemap_url(test_url.set_path(&(test_url.path().to_owned() + ".map"));if let Ok(res) = client.head(test_url.clone()).send().await {if res.status().is_success() {- return Ok((res.url().clone().into(), body));+ return Ok(JsSourcePeek {+ body,+ sourcemap_url: res.url().clone().into(),+ chunk_id_from_body,+ });}}@@ -442,10 +566,10 @@ mod test {let client = reqwest::Client::new();let url = server.url("/static/chunk-PGUQKT6S.js").parse().unwrap();- let (res, _) = find_sourcemap_url(&client, url).await.unwrap();+ let peek = find_sourcemap_url(&client, url).await.unwrap();- let SourceMappingUrl::Url(res) = res else {- panic!("Expected URL, got {res:?}");+ let SourceMappingUrl::Url(res) = peek.sourcemap_url else {+ panic!("Expected URL, got something else");};// We're doing relative-URL resolution here, so we have to account for that@@ -533,10 +657,10 @@ mod test {.url("/static/inline_sourcemap_example.js").parse().unwrap();- let (res, _) = find_sourcemap_url(&client, url).await.unwrap();+ let peek = find_sourcemap_url(&client, url).await.unwrap();- let SourceMappingUrl::Data(res) = res else {- panic!("Expected Data, got {res:?}");+ let SourceMappingUrl::Data(res) = peek.sourcemap_url else {+ panic!("Expected Data, got something else");};let expected = include_str!("../../tests/static/inline_sourcemap_example.js.map");@@ -545,4 +669,194 @@ mod test {mock.assert_hits(1);}++ #[test]+ fn extract_chunk_id_from_body_handles_known_prefixes() {+ let canonical =+ "/* code */\n//# sourceMappingURL=foo.map\n//# chunkId=019dfdfb-2ec9-7d71-84a2-6c269108158f\n";+ assert_eq!(+ extract_chunk_id_from_body(canonical),+ Some("019dfdfb-2ec9-7d71-84a2-6c269108158f".to_string())+ );++ assert_eq!(+ extract_chunk_id_from_body("//@ chunkId=abc-123\n"),+ Some("abc-123".to_string())+ );++ assert_eq!(extract_chunk_id_from_body("just some code"), None);+ assert_eq!(extract_chunk_id_from_body("//# chunkId=\n"), None);+ }++ #[sqlx::test(migrations = "./tests/test_migrations")]+ async fn chunk_id_rescue_short_circuits_when_map_url_is_404(db: PgPool) {+ use crate::symbol_store::{saving::SymbolSetRecord, MockS3Client};+ use chrono::Utc;+ use mockall::predicate;+ use uuid::Uuid;++ const RESCUE_BUCKET: &str = "test-bucket";++ let chunk_id = "019dfdfb-2ec9-7d71-84a2-6c269108158f".to_string();+ let map_path = "/static/chunk.js.map";+ let js_path = "/static/chunk.js";++ let server = MockServer::start();+ let body = format!(+ "console.log('hello');\n//# sourceMappingURL={map_path}\n//# chunkId={chunk_id}\n"+ );+ let js_mock = server.mock(|when, then| {+ when.method("GET").path(js_path);+ then.status(200).body(body);+ });+ let map_mock = server.mock(|when, then| {+ when.method("GET").path(map_path);+ then.status(404);+ });++ let storage_key = format!("symbolsets/{}", Uuid::now_v7());+ SymbolSetRecord {+ id: Uuid::now_v7(),+ team_id: 1,+ set_ref: chunk_id.clone(),+ storage_ptr: Some(storage_key.clone()),+ failure_reason: None,+ created_at: Utc::now(),+ content_hash: Some("fake-hash".to_string()),+ last_used: Some(Utc::now()),+ }+ .save(&db)+ .await+ .unwrap();++ let saved_payload = write_symbol_data(SourceAndMap {+ minified_source: String::from_utf8(MINIFIED.to_vec()).unwrap(),+ sourcemap: String::from_utf8(MAP.to_vec()).unwrap(),+ })+ .unwrap();+ let saved_payload_for_mock = saved_payload.clone();++ let mut s3 = MockS3Client::default();+ s3.expect_get()+ .with(+ predicate::eq(RESCUE_BUCKET),+ predicate::eq(storage_key.clone()),+ )+ .returning(move |_, _| Ok(Some(saved_payload_for_mock.clone())));+ let s3: Arc<dyn BlobClient> = Arc::new(s3);++ let mut config = Config::init_with_defaults().unwrap();+ config.allow_internal_ips = true;+ let provider = SourcemapProvider::new(&config).with_chunk_id_rescue(+ db.clone(),+ s3,+ RESCUE_BUCKET.to_string(),+ );++ let url = server.url(js_path).parse().unwrap();+ let got = provider.fetch(1, url).await.unwrap();++ assert_eq!(got, saved_payload, "rescue should return saved S3 bytes");+ js_mock.assert_hits(1);+ map_mock.assert_hits(0);+ }++ #[sqlx::test(migrations = "./tests/test_migrations")]+ async fn chunk_id_rescue_falls_through_when_no_db_record(db: PgPool) {+ use crate::symbol_store::MockS3Client;++ const RESCUE_BUCKET: &str = "test-bucket";++ let server = MockServer::start();+ let js_mock = server.mock(|when, then| {+ when.method("GET").path("/static/chunk-PGUQKT6S.js");+ then.status(200).body(MINIFIED);+ });+ let map_mock = server.mock(|when, then| {+ when.method("GET").path("/static/chunk-PGUQKT6S.js.map");+ then.status(200).body(MAP);+ });++ let s3: Arc<dyn BlobClient> = Arc::new(MockS3Client::default());++ let mut config = Config::init_with_defaults().unwrap();+ config.allow_internal_ips = true;+ let provider = SourcemapProvider::new(&config).with_chunk_id_rescue(+ db.clone(),+ s3,+ RESCUE_BUCKET.to_string(),+ );++ let url = server.url("/static/chunk-PGUQKT6S.js").parse().unwrap();+ provider.fetch(1, url).await.unwrap();++ js_mock.assert_hits(1);+ map_mock.assert_hits(1);+ }++ #[sqlx::test(migrations = "./tests/test_migrations")]+ async fn chunk_id_rescue_deletes_stale_record_when_blob_is_missing(db: PgPool) {+ use crate::symbol_store::{saving::SymbolSetRecord, MockS3Client};+ use chrono::Utc;+ use mockall::predicate;+ use uuid::Uuid;++ const RESCUE_BUCKET: &str = "test-bucket";++ let chunk_id = "019dfdfb-2ec9-7d71-84a2-6c269108158f".to_string();+ let storage_key = format!("symbolsets/{}", Uuid::now_v7());++ SymbolSetRecord {+ id: Uuid::now_v7(),+ team_id: 1,+ set_ref: chunk_id.clone(),+ storage_ptr: Some(storage_key.clone()),+ failure_reason: None,+ created_at: Utc::now(),+ content_hash: Some("fake-hash".to_string()),+ last_used: Some(Utc::now()),+ }+ .save(&db)+ .await+ .unwrap();++ let server = MockServer::start();+ let body =+ format!("console.log('hello');\n//# sourceMappingURL=/static/chunk.js.map\n//# chunkId={chunk_id}\n");+ let js_mock = server.mock(|when, then| {+ when.method("GET").path("/static/chunk.js");+ then.status(200).body(body);+ });+ let map_mock = server.mock(|when, then| {+ when.method("GET").path("/static/chunk.js.map");+ then.status(200).body(MAP);+ });++ let mut s3 = MockS3Client::default();+ s3.expect_get()+ .with(+ predicate::eq(RESCUE_BUCKET),+ predicate::eq(storage_key.clone()),+ )+ .returning(|_, _| Ok(None));+ let s3: Arc<dyn BlobClient> = Arc::new(s3);++ let mut config = Config::init_with_defaults().unwrap();+ config.allow_internal_ips = true;+ let provider = SourcemapProvider::new(&config).with_chunk_id_rescue(+ db.clone(),+ s3,+ RESCUE_BUCKET.to_string(),+ );++ let url = server.url("/static/chunk.js").parse().unwrap();+ provider.fetch(1, url).await.unwrap();++ assert!(SymbolSetRecord::load(&db, 1, &chunk_id)+ .await+ .unwrap()+ .is_none());+ js_mock.assert_hits(1);+ map_mock.assert_hits(1);+ }}