: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(cli): upload one symbol set per chunk id (#82654)
Aleksander Błaszkiewicz751c7c08aa23
diff --git a/cli/.sampo/changesets/sourcemap-dedupe-chunk-ids.md b/cli/.sampo/changesets/sourcemap-dedupe-chunk-ids.mdnew file mode 100644index 000000000000..ec116066722f--- /dev/null+++ b/cli/.sampo/changesets/sourcemap-dedupe-chunk-ids.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: patch+---++Upload one symbol set per chunk id when processing sourcemaps. In `--release-mode event` a bundler that copies an entry point to a second name (a hashless alias beside `app-<hash>.js`) produces two byte-identical files that share a sourcemap, and so one content-addressed chunk id twice, which the bulk-start endpoint rejects as `invalid_chunk_ids`.diff --git a/cli/src/api/symbol_sets.rs b/cli/src/api/symbol_sets.rsindex 38cf87cc54db..99047d3a5423 100644--- a/cli/src/api/symbol_sets.rs+++ b/cli/src/api/symbol_sets.rs@@ -45,6 +45,24 @@ pub struct SymbolSetUpload {pub content_hash: Option<String>,}+/// Coalesce uploads that share a chunk_id, keeping the first occurrence. Bulk start rejects a+/// batch with a repeated id, before it filters out the chunks the server already has.+pub fn dedup_uploads_by_chunk_id(uploads: Vec<SymbolSetUpload>) -> Vec<SymbolSetUpload> {+ let mut seen = std::collections::HashSet::new();+ let mut deduped = Vec::with_capacity(uploads.len());+ for upload in uploads {+ if seen.insert(upload.chunk_id.clone()) {+ deduped.push(upload);+ } else {+ warn!(+ "Duplicate chunk id {} across symbol sets; keeping the first",+ upload.chunk_id+ );+ }+ }+ deduped+}+/// Per-run tally of what an upload actually did. Without it a run that skipped/// every chunk is indistinguishable from one that uploaded every chunk, since/// both just exit zero.diff --git a/cli/src/debug_symbols/mod.rs b/cli/src/debug_symbols/mod.rsindex d957c5c07ff9..3cd9b964b5a4 100644--- a/cli/src/debug_symbols/mod.rs+++ b/cli/src/debug_symbols/mod.rs@@ -463,30 +463,6 @@ pub fn package_dsym_bundles(bundles: &[PathBuf], include_source: bool) -> Vec<Syuploads}-/// Coalesce uploads that share a chunk_id, keeping the first occurrence.-///-/// ELF chunk_ids are lowercase (derived by `symbolic`) and Mach-O chunk_ids —-/// executables and dSYMs alike — are uppercase (to match what the SDKs emit),-/// so the two formats never collide; this merges the same Mach-O UUID-/// appearing both as a binary and in a dSYM bundle, or a dSYM UUID appearing-/// in more than one bundle. Casing is preserved exactly and must never be-/// normalized: the SDK matches chunk_ids case-sensitively, per format.-pub fn dedup_uploads_by_chunk_id(uploads: Vec<SymbolSetUpload>) -> Vec<SymbolSetUpload> {- let mut seen = std::collections::HashSet::new();- let mut deduped = Vec::with_capacity(uploads.len());- for upload in uploads {- if seen.insert(upload.chunk_id.clone()) {- deduped.push(upload);- } else {- warn!(- "Duplicate chunk id {} across symbol sets; keeping the first",- upload.chunk_id- );- }- }- deduped-}-/// Extract the debug id of an ELF file, e.g. for testing parity with the SDK.pub fn elf_debug_id(path: &Path) -> Result<String> {let data = std::fs::read(path)?;diff --git a/cli/src/debug_symbols/upload.rs b/cli/src/debug_symbols/upload.rsindex dcb153a92706..c4eb025ba14c 100644--- a/cli/src/debug_symbols/upload.rs+++ b/cli/src/debug_symbols/upload.rs@@ -7,9 +7,9 @@ use crate::{api::{self,releases::ReleaseBuilder,- symbol_sets::{SymbolSetUpload, MAX_FILE_SIZE},+ symbol_sets::{dedup_uploads_by_chunk_id, SymbolSetUpload, MAX_FILE_SIZE},},- debug_symbols::{dedup_uploads_by_chunk_id, discover, package_dsym_bundles, report_problems},+ debug_symbols::{discover, package_dsym_bundles, report_problems},sourcemaps::args::{pack_version, ReleaseArgs, UploadConflictArgs},utils::git::get_git_info,};@@ -151,6 +151,8 @@ fn merge_uploads_prefer_dsym(.partition(|upload| upload.data.len() <= max_file_size);preferred_dsyms.extend(native_uploads);preferred_dsyms.extend(oversized_dsyms);+ // Casing must never be normalized here: the SDK matches chunk_ids case-sensitively, per+ // format, and lowercase ELF ids never collide with uppercase Mach-O ones.dedup_uploads_by_chunk_id(preferred_dsyms)}diff --git a/cli/src/sourcemaps/plain/upload.rs b/cli/src/sourcemaps/plain/upload.rsindex b670157d98a2..657bd0739e51 100644--- a/cli/src/sourcemaps/plain/upload.rs+++ b/cli/src/sourcemaps/plain/upload.rs@@ -15,7 +15,7 @@ const WRAPPER_JS_SIZE_THRESHOLD_BYTES: usize = 2048;use crate::{api::{releases::Release,- symbol_sets::{self, SymbolSetUpload},+ symbol_sets::{self, dedup_uploads_by_chunk_id, SymbolSetUpload},},invocation_context::context,sourcemaps::{@@ -25,7 +25,7 @@ use crate::{content::MinifiedSourceFile,inject::get_release_for_maps,plain::inject::is_javascript_file,- source_pairs::read_pairs,+ source_pairs::{read_pairs, SourcePair},},utils::files::{delete_files, FileSelection},};@@ -149,14 +149,7 @@ pub fn upload(args: &Args, existing_release: Option<&Release>) -> Result<()> {}let empty_skipped = empty_pairs.len();- // Payload preparation (serialization + zstd compression) is CPU-bound,- // so spread it across cores.- let release_mode = args.release_mode;- let uploads = valid_pairs- .into_par_iter()- .map(|pair| pair.into_upload(release_mode))- .collect::<Result<Vec<SymbolSetUpload>>>()- .context("While preparing files for upload")?;+ let uploads = prepare_uploads(valid_pairs, args.release_mode)?;let file_count = uploads.len();let total_bytes: usize = uploads.iter().map(|u| u.data.len()).sum();@@ -207,6 +200,23 @@ pub fn upload(args: &Args, existing_release: Option<&Release>) -> Result<()> {Ok(())}+/// 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(+ pairs: Vec<SourcePair>,+ release_mode: ReleaseMode,+) -> Result<Vec<SymbolSetUpload>> {+ // Payload preparation (serialization + zstd compression) is CPU-bound,+ // so spread it across cores.+ let uploads = pairs+ .into_par_iter()+ .map(|pair| pair.into_upload(release_mode))+ .collect::<Result<Vec<SymbolSetUpload>>>()+ .context("While preparing files for upload")?;++ Ok(dedup_uploads_by_chunk_id(uploads))+}+fn remove_sourcemap_references(paths: Vec<PathBuf>) -> Result<()> {for path in paths {let mut source = MinifiedSourceFile::load(&path)@@ -219,3 +229,39 @@ fn remove_sourcemap_references(paths: Vec<PathBuf>) -> Result<()> {}Ok(())}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::{sourcemaps::inject::inject_pairs, utils::files::FileSelection};++ #[test]+ fn event_mode_uploads_one_payload_per_chunk_id() {+ // The hashless copy keeps the original's sourceMappingURL, so both files are identical.+ let dir = tempfile::tempdir().expect("Failed to create temp dir");+ let entry = "console.log(\"hi\");\n//# sourceMappingURL=app-BKG53LDN.js.map\n";+ std::fs::write(dir.path().join("app-BKG53LDN.js"), entry).expect("Failed to write entry");+ std::fs::write(dir.path().join("app.js"), entry).expect("Failed to write hashless copy");+ std::fs::write(+ dir.path().join("app-BKG53LDN.js.map"),+ r#"{"version":3,"sources":["app.ts"],"sourcesContent":["console.log('hi')\n"],"mappings":"AAAA,QAAQ,IAAI,IAAI","names":[]}"#,+ )+ .expect("Failed to write sourcemap");++ let selection = FileSelection::from_roots(vec![dir.path().to_path_buf()])+ .include(vec![])+ .expect("Failed to build selection")+ .exclude(vec![])+ .expect("Failed to build selection");+ let pairs = read_pairs(selection.into_iter().filter(is_javascript_file), &None);+ assert_eq!(pairs.len(), 2);++ let injected = inject_pairs(pairs, None).expect("Failed to inject pairs");+ let chunk_ids: Vec<_> = injected.iter().map(|pair| pair.get_chunk_id()).collect();+ assert_eq!(chunk_ids[0], chunk_ids[1]);++ let uploads =+ prepare_uploads(injected, ReleaseMode::Event).expect("Failed to prepare uploads");+ assert_eq!(uploads.len(), 1);+ }+}diff --git a/cli/tests/debug_symbols.rs b/cli/tests/debug_symbols.rsindex bb6951ac4784..f8a74274c286 100644--- a/cli/tests/debug_symbols.rs+++ b/cli/tests/debug_symbols.rs@@ -1,10 +1,8 @@use std::io::Read;use std::path::{Path, PathBuf};-use posthog_cli::api::symbol_sets::SymbolSetUpload;-use posthog_cli::debug_symbols::{- dedup_uploads_by_chunk_id, discover, elf_debug_id, package_dsym_bundles, report_problems,-};+use posthog_cli::api::symbol_sets::{dedup_uploads_by_chunk_id, SymbolSetUpload};+use posthog_cli::debug_symbols::{discover, elf_debug_id, package_dsym_bundles, report_problems};use posthog_cli::dsym::source_bundle::extract_source_paths_from_dwarf_bytes;use posthog_symbol_data::{read_symbol_data, AppleDsym, ElfDebugInfo};