: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): handle indexed sourcemaps in cli (#62457)
Hugues Pouillot08df2e2c495b
diff --git a/cli/.sampo/changesets/sullen-firebringer-tapio.md b/cli/.sampo/changesets/sullen-firebringer-tapio.mdnew file mode 100644index 000000000000..ad706874a5ef--- /dev/null+++ b/cli/.sampo/changesets/sullen-firebringer-tapio.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: patch+---++Handle indexed sourcemaps during uploaddiff --git a/cli/src/sourcemaps/content.rs b/cli/src/sourcemaps/content.rsindex 700af387b36a..9dfd966de704 100644--- a/cli/src/sourcemaps/content.rs+++ b/cli/src/sourcemaps/content.rs@@ -26,26 +26,42 @@ impl SourceMapContent {/// True when the sourcemap carries no symbolication payload — empty `mappings`,/// no `sources`, and no `names`. Such maps upload successfully but are useless/// for stack trace resolution, and usually indicate a bundler misconfiguration.+ ///+ /// Handles both source map flavors:+ /// - Plain maps: checks `mappings`, `sources`, `names` directly.+ /// - Indexed maps (Source Map Revision 3 "Index Map"): walks `sections[].map`+ /// and reports empty only if every nested section is itself empty. Turbopack,+ /// Metro, and webpack's ConcatSource all emit this format, and a shallow check+ /// would skip large, valid maps that happen to have empty top-level fields.pub fn is_empty(&self) -> bool {- let mappings_empty = self- .fields- .get("mappings")- .and_then(|v| v.as_str())- .is_none_or(str::is_empty);- let sources_empty = self- .fields- .get("sources")- .and_then(|v| v.as_array())- .is_none_or(Vec::is_empty);- let names_empty = self- .fields- .get("names")- .and_then(|v| v.as_array())- .is_none_or(Vec::is_empty);- mappings_empty && sources_empty && names_empty+ let get = |k: &str| self.fields.get(k);+ is_map_empty(get)}}+fn is_map_empty<'a>(get: impl Fn(&str) -> Option<&'a Value>) -> bool {+ let mappings_empty = get("mappings")+ .and_then(Value::as_str)+ .is_none_or(str::is_empty);+ let sources_empty = get("sources")+ .and_then(Value::as_array)+ .is_none_or(Vec::is_empty);+ let names_empty = get("names")+ .and_then(Value::as_array)+ .is_none_or(Vec::is_empty);+ let sections_empty = get("sections")+ .and_then(Value::as_array)+ .is_none_or(|s| s.iter().all(is_section_empty));+ mappings_empty && sources_empty && names_empty && sections_empty+}++fn is_section_empty(section: &Value) -> bool {+ let Some(map) = section.get("map").and_then(Value::as_object) else {+ return true;+ };+ is_map_empty(|k| map.get(k))+}+#[derive(Debug)]pub struct SourceMapFile {pub inner: SourceFile<SourceMapContent>,@@ -404,4 +420,71 @@ mod tests {}));assert!(!sm.is_empty());}++ #[test]+ fn is_empty_true_for_indexed_map_with_empty_sections_array() {+ // Turbopack emits this shape for thin App Router page wrappers.+ let sm = content_from(json!({+ "version": 3,+ "sources": [],+ "sections": [],+ }));+ assert!(sm.is_empty());+ }++ #[test]+ fn is_empty_false_for_indexed_map_with_non_empty_section() {+ // Turbopack's `[turbopack]_runtime.js.map` shape: top-level fields are+ // empty/absent but real mappings live under `sections[].map`.+ let sm = content_from(json!({+ "version": 3,+ "sources": [],+ "sections": [+ {+ "offset": { "line": 17, "column": 0 },+ "map": {+ "version": 3,+ "sources": ["turbopack:///[turbopack]/runtime-utils.ts"],+ "mappings": "AAAA,SAAS",+ "names": [],+ }+ }+ ],+ }));+ assert!(!sm.is_empty());+ }++ #[test]+ fn is_empty_true_when_every_section_is_empty() {+ let sm = content_from(json!({+ "version": 3,+ "sections": [+ { "offset": { "line": 0, "column": 0 }, "map": { "version": 3, "sources": [], "mappings": "", "names": [] } },+ { "offset": { "line": 5, "column": 0 }, "map": { "version": 3, "sources": [], "mappings": "", "names": [] } },+ ],+ }));+ assert!(sm.is_empty());+ }++ #[test]+ fn is_empty_false_for_nested_indexed_map() {+ // Indexed maps can technically contain indexed maps. Rare but legal.+ let sm = content_from(json!({+ "version": 3,+ "sections": [+ {+ "offset": { "line": 0, "column": 0 },+ "map": {+ "version": 3,+ "sections": [+ { "offset": { "line": 0, "column": 0 }, "map": {+ "version": 3, "sources": ["a.ts"], "mappings": "AAAA", "names": []+ }}+ ]+ }+ }+ ],+ }));+ assert!(!sm.is_empty());+ }}diff --git a/cli/src/sourcemaps/plain/upload.rs b/cli/src/sourcemaps/plain/upload.rsindex d057d74066d9..11cf24c133e8 100644--- a/cli/src/sourcemaps/plain/upload.rs+++ b/cli/src/sourcemaps/plain/upload.rs@@ -2,7 +2,14 @@ use std::time::Instant;use anyhow::{Context, Result};use serde_json::json;-use tracing::{info, warn};+use tracing::{debug, info, warn};++/// Sibling-JS size below which an empty sourcemap is treated as a harmless+/// bundler-generated wrapper (e.g. Turbopack App Router page entries,+/// webpack re-export shims). Observed wrapper files in the wild are+/// under 1 KiB; 2 KiB leaves comfortable headroom for tools that inject+/// extra glue (PostHog chunk-id IIFE, etc.) without misclassifying real code.+const WRAPPER_JS_SIZE_THRESHOLD_BYTES: usize = 2048;use crate::{api::{@@ -92,11 +99,24 @@ pub fn upload(args: &Args, existing_release: Option<&Release>) -> Result<()> {let (empty_pairs, valid_pairs): (Vec<_>, Vec<_>) = pairs.into_iter().partition(|pair| pair.sourcemap.is_empty());+ let mut empty_skipped_wrapper = 0usize;+ let mut empty_skipped_suspect = 0usize;for pair in &empty_pairs {- warn!(- "Skipping {}: sourcemap is empty (no mappings/sources/names) — likely a bundler misconfiguration",- pair.sourcemap.inner.path.display()- );+ let js_size = pair.source.inner.content.len();+ let map_path = pair.sourcemap.inner.path.display();+ if js_size < WRAPPER_JS_SIZE_THRESHOLD_BYTES {+ empty_skipped_wrapper += 1;+ debug!(+ "Skipping {}: sourcemap is empty and sibling JS is {} bytes — bundler-generated wrapper, nothing to symbolicate",+ map_path, js_size+ );+ } else {+ empty_skipped_suspect += 1;+ warn!(+ "Skipping {}: sourcemap is empty but sibling JS is {} bytes — likely a bundler misconfiguration. Check your bundler's source-map setting (e.g. webpack `devtool`, Next.js `productionBrowserSourceMaps`, server compiler config).",+ map_path, js_size+ );+ }}let empty_skipped = empty_pairs.len();@@ -115,6 +135,8 @@ pub fn upload(args: &Args, existing_release: Option<&Release>) -> Result<()> {("file_count", json!(file_count)),("total_bytes", json!(total_bytes)),("empty_skipped", json!(empty_skipped)),+ ("empty_skipped_wrapper", json!(empty_skipped_wrapper)),+ ("empty_skipped_suspect", json!(empty_skipped_suspect)),],);diff --git a/cli/src/utils/git.rs b/cli/src/utils/git.rsindex 7c63fed72185..1f8d4e2f8417 100644--- a/cli/src/utils/git.rs+++ b/cli/src/utils/git.rs@@ -15,11 +15,7 @@ pub struct GitInfo {}pub fn get_git_info(dir: Option<PathBuf>) -> Result<Option<GitInfo>> {- if let Some(info) = get_git_info_from_github() {- return Ok(Some(info));- }-- if let Some(info) = get_git_info_from_vercel() {+ if let Some(info) = get_git_info_from_env(get_env_variable) {return Ok(Some(info));}@@ -41,13 +37,22 @@ pub fn get_git_info(dir: Option<PathBuf>) -> Result<Option<GitInfo>> {}))}-fn get_git_info_from_github() -> Option<GitInfo> {- get_env_variable("GITHUB_ACTIONS")?;+#[doc(hidden)]+pub fn get_git_info_from_env(get_env: impl Fn(&str) -> Option<String>) -> Option<GitInfo> {+ if let Some(info) = get_git_info_from_github(&get_env) {+ return Some(info);+ }++ get_git_info_from_vercel(&get_env)+}++fn get_git_info_from_github(get_env: &impl Fn(&str) -> Option<String>) -> Option<GitInfo> {+ get_env("GITHUB_ACTIONS")?;- let branch = get_env_variable("GITHUB_REF_NAME")?;- let commit_id = get_env_variable("GITHUB_SHA")?;- let repository = get_env_variable("GITHUB_REPOSITORY")?;- let server_url = get_env_variable("GITHUB_SERVER_URL")?;+ let branch = get_env("GITHUB_REF_NAME")?;+ let commit_id = get_env("GITHUB_SHA")?;+ let repository = get_env("GITHUB_REPOSITORY")?;+ let server_url = get_env("GITHUB_SERVER_URL")?;let repo_name = repository.split('/').next_back().map(|s| s.to_string());let remote_url = Some(format!("{server_url}/{repository}.git"));@@ -60,14 +65,14 @@ fn get_git_info_from_github() -> Option<GitInfo> {})}-fn get_git_info_from_vercel() -> Option<GitInfo> {- get_env_variable("VERCEL")?;+fn get_git_info_from_vercel(get_env: &impl Fn(&str) -> Option<String>) -> Option<GitInfo> {+ get_env("VERCEL")?;- let branch = get_env_variable("VERCEL_GIT_COMMIT_REF")?;- let commit_id = get_env_variable("VERCEL_GIT_COMMIT_SHA")?;- let repo_slug = get_env_variable("VERCEL_GIT_REPO_SLUG")?;+ let branch = get_env("VERCEL_GIT_COMMIT_REF")?;+ let commit_id = get_env("VERCEL_GIT_COMMIT_SHA")?;+ let repo_slug = get_env("VERCEL_GIT_REPO_SLUG")?;- let remote_url = build_vercel_remote_url(&repo_slug);+ let remote_url = build_vercel_remote_url(&repo_slug, get_env);Some(GitInfo {remote_url,@@ -77,9 +82,12 @@ fn get_git_info_from_vercel() -> Option<GitInfo> {})}-fn build_vercel_remote_url(repo_slug: &String) -> Option<String> {- let provider = get_env_variable("VERCEL_GIT_PROVIDER")?;- let owner = get_env_variable("VERCEL_GIT_REPO_OWNER")?;+fn build_vercel_remote_url(+ repo_slug: &str,+ get_env: &impl Fn(&str) -> Option<String>,+) -> Option<String> {+ let provider = get_env("VERCEL_GIT_PROVIDER")?;+ let owner = get_env("VERCEL_GIT_REPO_OWNER")?;let base_url = match provider.as_str() {"github" => "https://github.com",diff --git a/cli/tests/git.rs b/cli/tests/git.rsindex 6db79f3ca831..803f36a37423 100644--- a/cli/tests/git.rs+++ b/cli/tests/git.rs@@ -1,8 +1,17 @@-use posthog_cli::utils::git::{get_git_info, get_remote_url, get_repo_name};+use posthog_cli::utils::git::{get_git_info_from_env, get_remote_url, get_repo_name};+use std::collections::HashMap;use std::fs;use std::path::PathBuf;use uuid::Uuid;+fn env_from<const N: usize>(values: [(&str, &str); N]) -> impl Fn(&str) -> Option<String> {+ let env = values+ .into_iter()+ .map(|(key, value)| (key.to_string(), value.to_string()))+ .collect::<HashMap<_, _>>();+ move |key| env.get(key).cloned()+}+fn make_git_dir_with_config(config_content: &str) -> PathBuf {let temp_root = std::env::temp_dir().join(format!("posthog_cli_git_test_{}", Uuid::now_v7()));let git_dir = temp_root.join(".git");@@ -86,16 +95,15 @@ fn test_get_repo_infos_ssh_without_dot_git() {#[test]fn test_get_git_info_from_vercel_env() {- std::env::set_var("VERCEL", "1");- std::env::set_var("VERCEL_GIT_PROVIDER", "github");- std::env::set_var("VERCEL_GIT_REPO_OWNER", "PostHog");- std::env::set_var("VERCEL_GIT_REPO_SLUG", "posthog");- std::env::set_var("VERCEL_GIT_COMMIT_REF", "main");- std::env::set_var("VERCEL_GIT_COMMIT_SHA", "abc123def456");-- let info = get_git_info(None)- .expect("should not error")- .expect("should return info");+ let info = get_git_info_from_env(env_from([+ ("VERCEL", "1"),+ ("VERCEL_GIT_PROVIDER", "github"),+ ("VERCEL_GIT_REPO_OWNER", "PostHog"),+ ("VERCEL_GIT_REPO_SLUG", "posthog"),+ ("VERCEL_GIT_COMMIT_REF", "main"),+ ("VERCEL_GIT_COMMIT_SHA", "abc123def456"),+ ]))+ .expect("should return info");assert_eq!(info.branch, "main");assert_eq!(info.commit_id, "abc123def456");@@ -104,26 +112,18 @@ fn test_get_git_info_from_vercel_env() {info.remote_url.as_deref(),Some("https://github.com/PostHog/posthog.git"));-- std::env::remove_var("VERCEL");- std::env::remove_var("VERCEL_GIT_PROVIDER");- std::env::remove_var("VERCEL_GIT_REPO_OWNER");- std::env::remove_var("VERCEL_GIT_REPO_SLUG");- std::env::remove_var("VERCEL_GIT_COMMIT_REF");- std::env::remove_var("VERCEL_GIT_COMMIT_SHA");}#[test]fn test_get_git_info_from_github_env() {- std::env::set_var("GITHUB_ACTIONS", "true");- std::env::set_var("GITHUB_SHA", "abc123def456");- std::env::set_var("GITHUB_REF_NAME", "main");- std::env::set_var("GITHUB_REPOSITORY", "PostHog/posthog");- std::env::set_var("GITHUB_SERVER_URL", "https://github.com");-- let info = get_git_info(None)- .expect("should not error")- .expect("should return info");+ let info = get_git_info_from_env(env_from([+ ("GITHUB_ACTIONS", "true"),+ ("GITHUB_SHA", "abc123def456"),+ ("GITHUB_REF_NAME", "main"),+ ("GITHUB_REPOSITORY", "PostHog/posthog"),+ ("GITHUB_SERVER_URL", "https://github.com"),+ ]))+ .expect("should return info");assert_eq!(info.branch, "main");assert_eq!(info.commit_id, "abc123def456");@@ -132,10 +132,25 @@ fn test_get_git_info_from_github_env() {info.remote_url.as_deref(),Some("https://github.com/PostHog/posthog.git"));+}++#[test]+fn test_get_git_info_prefers_github_env_over_vercel_env() {+ let info = get_git_info_from_env(env_from([+ ("GITHUB_ACTIONS", "true"),+ ("GITHUB_SHA", "github-sha"),+ ("GITHUB_REF_NAME", "github-branch"),+ ("GITHUB_REPOSITORY", "PostHog/posthog"),+ ("GITHUB_SERVER_URL", "https://github.com"),+ ("VERCEL", "1"),+ ("VERCEL_GIT_PROVIDER", "github"),+ ("VERCEL_GIT_REPO_OWNER", "PostHog"),+ ("VERCEL_GIT_REPO_SLUG", "posthog"),+ ("VERCEL_GIT_COMMIT_REF", "vercel-branch"),+ ("VERCEL_GIT_COMMIT_SHA", "vercel-sha"),+ ]))+ .expect("should return info");- std::env::remove_var("GITHUB_ACTIONS");- std::env::remove_var("GITHUB_SHA");- std::env::remove_var("GITHUB_REF_NAME");- std::env::remove_var("GITHUB_REPOSITORY");- std::env::remove_var("GITHUB_SERVER_URL");+ assert_eq!(info.branch, "github-branch");+ assert_eq!(info.commit_id, "github-sha");}