: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): only hash source and overwrite changed symbol sets in event release mode (#83056)
Aleksander Błaszkiewicz617ed9c912a4
diff --git a/cli/.sampo/changesets/event-mode-force-overwrite.md b/cli/.sampo/changesets/event-mode-force-overwrite.mdnew file mode 100644index 000000000000..38c8b2c346db--- /dev/null+++ b/cli/.sampo/changesets/event-mode-force-overwrite.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: patch+---++Derive the `--release-mode event` chunk id from the minified source alone, and overwrite a symbol set whose content changed instead of failing. Bundlers embed the original file in `sourcesContent`, so a comment-only edit rewrote the sourcemap and, with the map folded into the id, minted a new chunk for code that never changed. The content hash still covers source and map, so that edit re-uploads the chunk under its existing id. Chunk ids injected by earlier versions change once on the next build, which re-uploads those chunks under their new ids. `--skip-on-conflict` is now ignored in this mode, with a warning: every chunk carries the release id in its injected snippet, so every chunk conflicts on every release, and skipping them all would leave the previous release id in place.diff --git a/cli/src/sourcemaps/args.rs b/cli/src/sourcemaps/args.rsindex a6b05f23c87e..72e0380f883c 100644--- a/cli/src/sourcemaps/args.rs+++ b/cli/src/sourcemaps/args.rs@@ -131,16 +131,55 @@ pub struct ReleaseArgs {#[derive(clap::Args, Clone, Default)]pub struct UploadConflictArgs {- /// Allow overwriting an existing symbol set whose content has changed. [default: false]+ /// Allow overwriting an existing symbol set whose content has changed. Always on with+ /// `--release-mode=event`. [default: false]#[arg(long, default_value_t = false, conflicts_with = "skip_on_conflict")]pub force: bool,/// Skip symbol sets that already exist with different content instead of failing.- /// Existing symbol sets are left unchanged. [default: false]+ /// Existing symbol sets are left unchanged. Ignored with `--release-mode=event`. [default: false]#[arg(long, default_value_t = false, conflicts_with = "force")]pub skip_on_conflict: bool,}+/// How the server should treat a symbol set that already exists under the chunk id being uploaded+/// with different content.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct ConflictBehavior {+ /// Overwrite the stored symbol set.+ pub force: bool,+ /// Leave the stored symbol set alone and carry on rather than failing the run.+ pub skip_on_conflict: bool,+}++impl UploadConflictArgs {+ /// Resolve what to do about changed content, given the release mode.+ ///+ /// Event mode always overwrites, and neither flag changes that. A chunk's id and its uploaded+ /// bytes move independently there: the id is derived from the pristine minified source and so+ /// survives a new release, while the injected snippet inside the payload carries the release id+ /// and changes with every release. Every chunk therefore conflicts on every release after the+ /// first, so honoring `--skip-on-conflict` would skip all of them and leave the server serving+ /// the previous release's id forever.+ pub fn resolve(&self, release_mode: ReleaseMode) -> ConflictBehavior {+ match release_mode {+ ReleaseMode::Event => ConflictBehavior {+ force: true,+ skip_on_conflict: false,+ },+ ReleaseMode::SymbolSet => ConflictBehavior {+ force: self.force,+ skip_on_conflict: self.skip_on_conflict,+ },+ }+ }++ /// Whether the run asked to skip conflicts but the release mode cannot honor it.+ pub fn skip_on_conflict_ignored(&self, release_mode: ReleaseMode) -> bool {+ self.skip_on_conflict && release_mode == ReleaseMode::Event+ }+}+/// Pack version and build into a single string for release uniqueness./// Releases are keyed on (name, version), so "1.0+42" and "1.0+43" are/// distinct releases. The UI splits on "+" to display them separately.@@ -227,6 +266,58 @@ mod tests {}}+ #[test]+ fn event_mode_always_overwrites() {+ let cases = [+ // (force, skip_on_conflict, release_mode, expected force, expected skip)+ (false, false, ReleaseMode::Event, true, false),+ // Skipping every chunk would strand the server on the previous release id.+ (false, true, ReleaseMode::Event, true, false),+ (true, false, ReleaseMode::Event, true, false),+ (false, false, ReleaseMode::SymbolSet, false, false),+ (false, true, ReleaseMode::SymbolSet, false, true),+ (true, false, ReleaseMode::SymbolSet, true, false),+ ];++ for (force, skip_on_conflict, release_mode, expected_force, expected_skip) in cases {+ let conflict = UploadConflictArgs {+ force,+ skip_on_conflict,+ };+ assert_eq!(+ conflict.resolve(release_mode),+ ConflictBehavior {+ force: expected_force,+ skip_on_conflict: expected_skip,+ },+ "force={force} skip_on_conflict={skip_on_conflict} release_mode={release_mode:?}"+ );+ }+ }++ #[test]+ fn skip_on_conflict_is_reported_as_ignored_only_in_event_mode() {+ let cases = [+ // (skip_on_conflict, release_mode, expected)+ (true, ReleaseMode::Event, true),+ (false, ReleaseMode::Event, false),+ (true, ReleaseMode::SymbolSet, false),+ (false, ReleaseMode::SymbolSet, false),+ ];++ for (skip_on_conflict, release_mode, expected) in cases {+ let conflict = UploadConflictArgs {+ force: false,+ skip_on_conflict,+ };+ assert_eq!(+ conflict.skip_on_conflict_ignored(release_mode),+ expected,+ "skip_on_conflict={skip_on_conflict} release_mode={release_mode:?}"+ );+ }+ }+#[test]fn upload_concurrency_defaults_to_ten() {let parsed = parse_concurrency(&["test"], None).unwrap();diff --git a/cli/src/sourcemaps/inject.rs b/cli/src/sourcemaps/inject.rsindex e5885ace2d50..939f6504371a 100644--- a/cli/src/sourcemaps/inject.rs+++ b/cli/src/sourcemaps/inject.rs@@ -117,8 +117,7 @@ pub fn inject_pairs() -> Result<Vec<SourcePair>> {for pair in &mut pairs {let Some(chunk_id) = pair.get_chunk_id() else {- let sourcemap_json = serde_json::to_string(&pair.sourcemap.inner.content)?;- let chunk_id = stable_chunk_id(&pair.source.inner.content, &sourcemap_json);+ let chunk_id = stable_chunk_id(&pair.source.inner.content);pair.add_chunk_id(chunk_id, release_id)?;continue;};@@ -166,18 +165,17 @@ pub fn inject_pairs_legacy(Ok(pairs)}-/// Deterministically derive a chunk id from the pristine minified source and its sourcemap-/// (UUIDv5). Identical builds produce identical ids on every machine and rebuild, so uploads-/// dedupe — no per-build random id. The sourcemap is part of the identity on purpose: a-/// map-only change (e.g. enabling `sourcesContent`) mints a new chunk instead of conflicting-/// with the symbol set already stored under the old id.-fn stable_chunk_id(source_content: &str, sourcemap_content: &str) -> String {- let mut name = Vec::with_capacity(source_content.len() + sourcemap_content.len() + 1);- name.extend_from_slice(source_content.as_bytes());- // JSON serialization never contains a raw NUL, so it unambiguously separates the parts.- name.push(0);- name.extend_from_slice(sourcemap_content.as_bytes());- uuid::Uuid::new_v5(&CHUNK_ID_NAMESPACE, &name).to_string()+/// Deterministically derive a chunk id from the pristine minified source (UUIDv5). Identical+/// builds produce identical ids on every machine and rebuild, so uploads dedupe instead of+/// minting a per-build random id.+///+/// The sourcemap is deliberately not part of the identity. It carries `sourcesContent`, so a+/// comment-only edit rewrites the map while the minified code stays byte-identical, and folding+/// the map in would mint a new chunk for code that never changed. The map still reaches the+/// server, because the upload hashes the payload it sends: a map-only change is a content+/// change, and event mode overwrites the stored symbol set with the newer map.+fn stable_chunk_id(source_content: &str) -> String {+ uuid::Uuid::new_v5(&CHUNK_ID_NAMESPACE, source_content.as_bytes()).to_string()}/// Resolve the release row whose id gets injected into the chunks. Reuses the release already@@ -267,6 +265,7 @@ mod tests {};use super::*;+ use crate::sourcemaps::plain::inject::is_javascript_file;static ENV_LOCK: Mutex<()> = Mutex::new(());@@ -347,13 +346,50 @@ mod tests {temp_root}+ fn chunk_id_for(sourcemap: &str) -> String {+ let dir = tempfile::tempdir().expect("failed to create temporary directory");+ fs::write(+ dir.path().join("app.js"),+ "console.log(1);\n//# sourceMappingURL=app.js.map\n",+ )+ .expect("failed to write source");+ fs::write(dir.path().join("app.js.map"), sourcemap).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);++ inject_pairs(pairs, None)+ .expect("failed to inject pairs")+ .first()+ .and_then(SourcePair::get_chunk_id)+ .expect("injected pair carries a chunk id")+ }++ #[test]+ fn map_only_changes_keep_the_chunk_id() {+ // Bundlers embed the original file in `sourcesContent`, so editing a comment rewrites+ // the map while the minified code stays byte-identical. Folding the map into the id+ // would mint a new chunk on every such edit and orphan the symbol set already stored.+ let one = chunk_id_for(+ r#"{"version":3,"sources":["app.ts"],"sourcesContent":["// one\nconsole.log(1)\n"],"mappings":"AAAA","names":[]}"#,+ );+ let two = chunk_id_for(+ r#"{"version":3,"sources":["app.ts"],"sourcesContent":["// two\nconsole.log(1)\n"],"mappings":"AAAA","names":[]}"#,+ );++ assert_eq!(one, two);+ }+#[test]- fn stable_chunk_id_covers_source_and_sourcemap() {- let id = stable_chunk_id("code();", r#"{"mappings":"AAAA"}"#);+ fn stable_chunk_id_tracks_the_minified_source() {+ let id = stable_chunk_id("code();");- assert_eq!(id, stable_chunk_id("code();", r#"{"mappings":"AAAA"}"#));- assert_ne!(id, stable_chunk_id("code();", r#"{"mappings":"BBBB"}"#));- assert_ne!(id, stable_chunk_id("other();", r#"{"mappings":"AAAA"}"#));+ assert_eq!(id, stable_chunk_id("code();"));+ assert_ne!(id, stable_chunk_id("other();"));}#[test]diff --git a/cli/src/sourcemaps/plain/upload.rs b/cli/src/sourcemaps/plain/upload.rsindex 657bd0739e51..9071ace0e738 100644--- a/cli/src/sourcemaps/plain/upload.rs+++ b/cli/src/sourcemaps/plain/upload.rs@@ -84,6 +84,12 @@ pub fn upload_cmd(args: &Args) -> Result<()> {}pub fn upload(args: &Args, existing_release: Option<&Release>) -> Result<()> {+ if args.conflict.skip_on_conflict_ignored(args.release_mode) {+ warn!(+ "--skip-on-conflict is ignored with --release-mode=event. Every chunk's content changes with each release, so skipping conflicts would leave the previous release id in place. Overwriting instead."+ );+ }+let selection = FileSelection::try_from(args.file_selection.clone())?;let mut pairs = read_pairs(@@ -165,13 +171,15 @@ pub fn upload(args: &Args, existing_release: Option<&Release>) -> Result<()> {],);+ let conflict = args.conflict.resolve(args.release_mode);+let started_at = Instant::now();let (summary, upload_result) = symbol_sets::upload_with_retry_and_concurrency(uploads,args.batch_size,args.release.skip_release_on_fail,- args.conflict.force,- args.conflict.skip_on_conflict,+ conflict.force,+ conflict.skip_on_conflict,args.upload_concurrency.concurrency,);let duration_ms = started_at.elapsed().as_millis();