Skip to content

: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.

fix(cli): upload native debug ID sourcemaps (#111778)

Hugues Pouillot7c55058c01ae
diff --git a/cli/.sampo/changesets/mighty-forgemaster-erika.md b/cli/.sampo/changesets/mighty-forgemaster-erika.md
new file mode 100644
index 000000000000..bd00330b27dc
--- /dev/null
+++ b/cli/.sampo/changesets/mighty-forgemaster-erika.md
@@ -0,0 +1,5 @@
+---
+cargo/posthog-cli: patch
+---
+
+Upload native bundler debug IDs without rewriting source files, and skip files without uploadable IDs instead of failing CI
diff --git a/cli/src/sourcemaps/plain/upload.rs b/cli/src/sourcemaps/plain/upload.rs
index b0f75a15e19a..9e398160062f 100644
--- a/cli/src/sourcemaps/plain/upload.rs
+++ b/cli/src/sourcemaps/plain/upload.rs
@@ -21,6 +21,7 @@ const WRAPPER_JS_SIZE_THRESHOLD_BYTES: usize = 2048;
/// Cap on the suspect paths named in the summary line. They share one line, and an
/// oversized line kills the process on a non-blocking stderr pipe (see `FileSelectionArgs`).
const MAX_LISTED_SUSPECT_PATHS: usize = 3;
+const MAX_LISTED_UNIDENTIFIED_PATHS: usize = 3;
use crate::{
api::{
@@ -121,6 +122,8 @@ pub fn upload_pairs(
);
}
+ pairs = select_uploadable_pairs(pairs);
+
// Fingerprinting re-serializes and hashes every pair, which is not free for large
// maps - skip it when nothing gets cleaned up.
let cleanup_targets = if args.delete_after {
@@ -132,6 +135,10 @@ pub fn upload_pairs(
Vec::new()
};
info!("Found {} chunks to upload", pairs.len());
+ if pairs.is_empty() {
+ warn!("No source map pairs with uploadable IDs were found; nothing to upload");
+ return Ok(());
+ }
// Reuse the pre-resolved release if available, otherwise fetch or create one. Skipped entirely
// in event mode: inject already put the release id inside the chunks, and resolving one here
@@ -276,6 +283,38 @@ pub fn upload_pairs(
Ok(())
}
+fn select_uploadable_pairs(pairs: Vec<SourcePair>) -> Vec<SourcePair> {
+ let (uploadable, skipped): (Vec<_>, Vec<_>) = pairs
+ .into_iter()
+ .partition(|pair| pair.has_chunk_id() || pair.get_debug_id().is_some());
+ if !skipped.is_empty() {
+ let listed_paths = skipped
+ .iter()
+ .take(MAX_LISTED_UNIDENTIFIED_PATHS)
+ .map(|pair| pair.source.inner.path.display().to_string())
+ .collect::<Vec<_>>();
+ let unlisted = skipped.len() - listed_paths.len();
+ let rest = if unlisted > 0 {
+ format!(" and {unlisted} more (set RUST_LOG=debug to list them all)")
+ } else {
+ String::new()
+ };
+ warn!(
+ "Skipping {} source map pairs without a PostHog chunk ID or native debug ID: {}{}",
+ skipped.len(),
+ listed_paths.join(", "),
+ rest
+ );
+ for pair in skipped {
+ debug!(
+ "Skipping {}: no PostHog chunk ID or native debug ID",
+ pair.source.inner.path.display()
+ );
+ }
+ }
+ uploadable
+}
+
/// Build the upload payloads for `pairs`, at most one per chunk id. Event mode derives the id
/// from content, so a hashless alias copied beside `app-<hash>.js` collides with its original.
fn prepare_uploads(
@@ -284,13 +323,21 @@ fn prepare_uploads(
) -> Result<Vec<SymbolSetUpload>> {
// Payload preparation (serialization + zstd compression) is CPU-bound,
// so spread it across cores.
- let uploads = pairs
+ let mut uploads = pairs
.into_par_iter()
- .map(|pair| pair.into_upload(release_mode))
- .collect::<Result<Vec<SymbolSetUpload>>>()
+ .map(|pair| {
+ let source_carries_native_debug_id =
+ !pair.has_chunk_id() && pair.source.get_debug_id().is_some();
+ pair.into_upload(release_mode)
+ .map(|upload| (source_carries_native_debug_id, upload))
+ })
+ .collect::<Result<Vec<_>>>()
.context("While preparing files for upload")?;
- Ok(dedup_uploads_by_chunk_id(uploads))
+ uploads.sort_by_key(|(source_carries_native_debug_id, _)| !source_carries_native_debug_id);
+ Ok(dedup_uploads_by_chunk_id(
+ uploads.into_iter().map(|(_, upload)| upload).collect(),
+ ))
}
fn canonical_selection_roots(paths: &[PathBuf]) -> Vec<PathBuf> {
@@ -545,6 +592,14 @@ fn restore_staged(staged: &Path, path: &Path) -> Result<()> {
mod tests {
use super::*;
use crate::{sourcemaps::inject::inject_pairs, utils::files::FileSelection};
+ use clap::Parser;
+ use posthog_symbol_data::{read_symbol_data, SourceAndMap};
+
+ #[derive(Parser)]
+ struct UploadCli {
+ #[command(flatten)]
+ args: Args,
+ }
const MAP_JSON: &str = r#"{"version":3,"sources":["a.ts"],"names":[],"mappings":""}"#;
@@ -778,4 +833,146 @@ mod tests {
prepare_uploads(injected, ReleaseMode::Event).expect("Failed to prepare uploads");
assert_eq!(uploads.len(), 1);
}
+
+ #[test]
+ fn event_mode_uploads_native_debug_ids_without_rewriting_files() {
+ let dir = tempfile::tempdir().expect("Failed to create temp dir");
+ let debug_id = "11111111-2222-4333-8444-555555555555";
+ let source = format!(
+ "console.log('hi');\n//# debugId={debug_id}\n//# sourceMappingURL=app.js.map\n"
+ );
+ let sourcemap = format!(
+ r#"{{"version":3,"sources":["app.ts"],"sourcesContent":["console.log('hi')\n"],"mappings":"AAAA,QAAQ,IAAI,IAAI","names":[],"debugId":"{debug_id}"}}"#
+ );
+ let source_path = dir.path().join("app.js");
+ let map_path = dir.path().join("app.js.map");
+ std::fs::write(&source_path, &source).expect("Failed to write entry");
+ std::fs::write(&map_path, &sourcemap).expect("Failed to write sourcemap");
+ let (runtime_path, runtime_map_path) = write_pair(dir.path(), "runtime");
+ let runtime = std::fs::read_to_string(&runtime_path).unwrap();
+ let runtime_map = std::fs::read_to_string(&runtime_map_path).unwrap();
+
+ let pairs = select_uploadable_pairs(read_dir_pairs(dir.path()));
+ assert_eq!(pairs.len(), 1);
+ let uploads = prepare_uploads(pairs, ReleaseMode::Event)
+ .expect("Failed to prepare native debug ID upload");
+
+ assert_eq!(uploads.len(), 1);
+ assert_eq!(uploads[0].chunk_id, debug_id);
+ let stored: SourceAndMap =
+ read_symbol_data(&uploads[0].data).expect("Failed to read upload payload");
+ assert_eq!(stored.minified_source, source);
+ assert_eq!(
+ serde_json::from_str::<serde_json::Value>(&stored.sourcemap)
+ .expect("Failed to parse uploaded sourcemap")["debugId"],
+ debug_id
+ );
+ assert_eq!(std::fs::read_to_string(source_path).unwrap(), source);
+ assert_eq!(std::fs::read_to_string(map_path).unwrap(), sourcemap);
+ assert_eq!(std::fs::read_to_string(runtime_path).unwrap(), runtime);
+ assert_eq!(
+ std::fs::read_to_string(runtime_map_path).unwrap(),
+ runtime_map
+ );
+ }
+
+ #[test]
+ fn native_debug_id_dedup_prefers_the_source_that_carries_the_id() {
+ let dir = tempfile::tempdir().expect("Failed to create temp dir");
+ let debug_id = "11111111-2222-4333-8444-555555555555";
+ let alias = "console.log('alias');\n//# sourceMappingURL=shared.js.map\n";
+ let instrumented = format!(
+ "console.log('instrumented');\n//# debugId={debug_id}\n//# sourceMappingURL=shared.js.map\n"
+ );
+ std::fs::write(dir.path().join("a-alias.js"), alias).expect("Failed to write alias");
+ std::fs::write(dir.path().join("z-instrumented.js"), &instrumented)
+ .expect("Failed to write instrumented source");
+ std::fs::write(
+ dir.path().join("shared.js.map"),
+ format!(
+ r#"{{"version":3,"sources":["app.ts"],"mappings":"AAAA","debugId":"{debug_id}"}}"#
+ ),
+ )
+ .expect("Failed to write shared sourcemap");
+ let mut pairs = read_dir_pairs(dir.path());
+ pairs.sort_by_key(|pair| pair.source.inner.path.clone());
+
+ let uploads = prepare_uploads(pairs, ReleaseMode::Event)
+ .expect("Failed to prepare native debug ID uploads");
+
+ assert_eq!(uploads.len(), 1);
+ assert_eq!(uploads[0].chunk_id, debug_id);
+ let stored: SourceAndMap =
+ read_symbol_data(&uploads[0].data).expect("Failed to read upload payload");
+ assert_eq!(stored.minified_source, instrumented);
+ }
+
+ #[test]
+ fn native_debug_ids_are_uploadable_without_an_opt_in() {
+ let dir = tempfile::tempdir().expect("Failed to create temp dir");
+ let debug_id = "11111111-2222-4333-8444-555555555555";
+ let (source_path, map_path) = write_pair(dir.path(), "webpack");
+ std::fs::write(
+ source_path,
+ format!(
+ "console.log(1);\n//# debugId={debug_id}\n//# sourceMappingURL=webpack.js.map\n"
+ ),
+ )
+ .expect("Failed to add a source debug ID");
+ std::fs::write(
+ map_path,
+ format!(
+ r#"{{"version":3,"sources":["app.ts"],"mappings":"AAAA","debugId":"{debug_id}"}}"#
+ ),
+ )
+ .expect("Failed to add a map debug ID");
+
+ let pairs = select_uploadable_pairs(read_dir_pairs(dir.path()));
+ let uploads = prepare_uploads(pairs, ReleaseMode::Event)
+ .expect("The native debug ID should be uploadable automatically");
+
+ assert_eq!(uploads.len(), 1);
+ assert_eq!(uploads[0].chunk_id, debug_id);
+ }
+
+ #[test]
+ fn sourcemap_only_native_debug_ids_are_uploadable() {
+ let dir = tempfile::tempdir().expect("Failed to create temp dir");
+ let debug_id = "11111111-2222-4333-8444-555555555555";
+ let (_, map_path) = write_pair(dir.path(), "mapped");
+ std::fs::write(
+ map_path,
+ format!(
+ r#"{{"version":3,"sources":["app.ts"],"mappings":"AAAA","debugId":"{debug_id}"}}"#
+ ),
+ )
+ .expect("Failed to add a map-only debug ID");
+
+ let pairs = select_uploadable_pairs(read_dir_pairs(dir.path()));
+ let uploads = prepare_uploads(pairs, ReleaseMode::Event)
+ .expect("The sourcemap debug ID should be uploadable automatically");
+
+ assert_eq!(uploads.len(), 1);
+ assert_eq!(uploads[0].chunk_id, debug_id);
+ }
+
+ #[test]
+ fn upload_without_native_or_injected_ids_is_a_successful_noop() {
+ let dir = tempfile::tempdir().expect("Failed to create temp dir");
+ let (source_path, map_path) = write_pair(dir.path(), "app");
+ let source = std::fs::read_to_string(&source_path).unwrap();
+ let sourcemap = std::fs::read_to_string(&map_path).unwrap();
+ let args = UploadCli::try_parse_from([
+ "test",
+ "--directory",
+ dir.path().to_str().expect("Temp path is not UTF-8"),
+ ])
+ .expect("Upload args should parse")
+ .args;
+
+ upload(&args, None).expect("Missing IDs must not fail a CI upload");
+
+ assert_eq!(std::fs::read_to_string(source_path).unwrap(), source);
+ assert_eq!(std::fs::read_to_string(map_path).unwrap(), sourcemap);
+ }
}
diff --git a/cli/src/sourcemaps/source_pairs.rs b/cli/src/sourcemaps/source_pairs.rs
index 502a79c02617..8a395ce20c16 100644
--- a/cli/src/sourcemaps/source_pairs.rs
+++ b/cli/src/sourcemaps/source_pairs.rs
@@ -249,9 +249,10 @@ impl SourcePair {
/// In symbol-set mode no hash is set and the upload layer hashes the raw payload, matching
/// the hashes the server already stores for previous uploads.
pub fn into_upload(mut self, release_mode: ReleaseMode) -> Result<SymbolSetUpload> {
- let chunk_id = self.get_chunk_id().ok_or_else(|| {
+ let injected_chunk_id = self.get_chunk_id();
+ let chunk_id = injected_chunk_id.clone().or_else(|| self.get_debug_id()).ok_or_else(|| {
anyhow!(
- "Chunk ID not found in {}. Run 'sourcemap inject' before 'sourcemap upload', or use 'sourcemap process' to do both.",
+ "Chunk ID or debug ID not found in {}. Run 'sourcemap inject' before 'sourcemap upload', enable native debug IDs in the bundler, or use 'sourcemap process' to do both.",
self.source.inner.path.display()
)
})?;
@@ -261,13 +262,18 @@ impl SourcePair {
let content_hash = match release_mode {
ReleaseMode::Event => {
- // Read the variant before the removal, which erases the evidence.
- let snippet_variant: &[u8] = if self.source.has_release_snippet(&chunk_id) {
- b"with-release"
+ let identity_variant: &[u8] = if injected_chunk_id.is_some() {
+ // Read the variant before the removal, which erases the evidence.
+ let snippet_variant: &[u8] = if self.source.has_release_snippet(&chunk_id) {
+ b"with-release"
+ } else {
+ b"chunk-id-only"
+ };
+ self.remove_chunk_id(chunk_id.clone())?;
+ snippet_variant
} else {
- b"chunk-id-only"
+ b"native-debug-id"
};
- self.remove_chunk_id(chunk_id.clone())?;
without_file_path_in_file_field(&mut self.sourcemap.inner.content);
let pristine_map = serde_json::to_string(&self.sourcemap.inner.content)?;
let pristine_source = without_file_paths(&self.source.inner.content);
@@ -278,7 +284,7 @@ impl SourcePair {
b"\0".as_slice(),
pristine_map.as_bytes(),
b"\0".as_slice(),
- snippet_variant,
+ identity_variant,
]))
}
ReleaseMode::SymbolSet => None,