: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
feat(cli): experimental release injection (#81171)
Aleksander Błaszkiewicz8d58ef5de6c3
diff --git a/cli/.sampo/changesets/cli-experimental-release-injection.md b/cli/.sampo/changesets/cli-experimental-release-injection.mdnew file mode 100644index 000000000000..ccdce882936a--- /dev/null+++ b/cli/.sampo/changesets/cli-experimental-release-injection.md@@ -0,0 +1,5 @@+---+cargo/posthog-cli: minor+---++Add `--release-mode` (env `POSTHOG_RELEASE_MODE`) to `inject`/`upload`/`process`. The default `symbol-set` keeps the existing behavior: the release id is stamped onto the uploaded symbol sets. The experimental `event` mode derives content-addressed chunk ids that stay stable across rebuilds and injects the release id into each JS chunk as `_posthogReleaseId`, so the SDK reports it per event and symbol sets stay release-independent. The release is still created; it just isn't bound to any chunk.diff --git a/cli/Cargo.lock b/cli/Cargo.lockindex dd8ce3f7d260..7554e7806a5f 100644--- a/cli/Cargo.lock+++ b/cli/Cargo.lock@@ -2814,6 +2814,12 @@ dependencies = ["digest",]+[[package]]+name = "sha1_smol"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"+[[package]]name = "sha2"version = "0.10.9"@@ -3583,6 +3589,7 @@ dependencies = ["getrandom 0.3.4","js-sys","serde",+ "sha1_smol","wasm-bindgen",]diff --git a/cli/Cargo.toml b/cli/Cargo.tomlindex afb937fc54a4..c31c939a1b1f 100644--- a/cli/Cargo.toml+++ b/cli/Cargo.toml@@ -50,7 +50,7 @@ serde_yaml = "0.9"colored = "3.0"regex = "1.12"tracing = "0.1.41"-uuid = { version = "1.16.0", features = ["v7"] }+uuid = { version = "1.16.0", features = ["v5", "v7"] }thiserror = "2.0.12"tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }posthog-rs = { version = "0.15.0", default-features = false, features = ["error-tracking"] }diff --git a/cli/src/api/symbol_sets.rs b/cli/src/api/symbol_sets.rsindex a9fdbc502122..38cf87cc54db 100644--- a/cli/src/api/symbol_sets.rs+++ b/cli/src/api/symbol_sets.rs@@ -38,6 +38,11 @@ pub struct SymbolSetUpload {pub release_id: Option<String>,pub data: Vec<u8>,++ /// Precomputed hash for the server's skip-identical-content check; `None` hashes `data`+ /// as-is. Set this when `data` contains bytes that vary between builds of identical code+ /// (e.g. an injected release id), so unchanged chunks still skip re-upload.+ pub content_hash: Option<String>,}/// Per-run tally of what an upload actually did. Without it a run that skipped@@ -183,6 +188,7 @@ pub fn upload_with_retry_and_concurrency(chunk_id: s.chunk_id.clone(),release_id: None,data: s.data,+ content_hash: s.content_hash,}).collect();let res = upload_inner(@@ -247,8 +253,16 @@ fn upload_inner(info!("Starting upload of batch {i}, {} symbol sets", batch.len());// Hash each payload once, across the pool — the same hash is sent in the// start request and used to confirm the upload when finishing.- let content_hashes: Vec<String> =- thread_pool.install(|| batch.par_iter().map(|u| content_hash([&u.data])).collect());+ let content_hashes: Vec<String> = thread_pool.install(|| {+ batch+ .par_iter()+ .map(|u| {+ u.content_hash+ .clone()+ .unwrap_or_else(|| content_hash([&u.data]))+ })+ .collect()+ });let start_response = start_upload(batch, &content_hashes, force, skip_on_conflict)?;let id_map: HashMap<_, _> = batch@@ -460,6 +474,7 @@ impl SymbolSetUpload {chunk_id: self.chunk_id.clone(),release_id: self.release_id.clone(),data: vec![],+ content_hash: self.content_hash.clone(),}}}diff --git a/cli/src/debug_symbols/mod.rs b/cli/src/debug_symbols/mod.rsindex d6832dd02198..d957c5c07ff9 100644--- a/cli/src/debug_symbols/mod.rs+++ b/cli/src/debug_symbols/mod.rs@@ -121,6 +121,7 @@ impl DebugSymbolFile {chunk_id: self.debug_id,release_id,data: wrapped,+ content_hash: None,})}}diff --git a/cli/src/debug_symbols/upload.rs b/cli/src/debug_symbols/upload.rsindex 769283fd9e24..dcb153a92706 100644--- a/cli/src/debug_symbols/upload.rs+++ b/cli/src/debug_symbols/upload.rs@@ -165,6 +165,7 @@ mod tests {chunk_id: chunk_id.to_string(),release_id: None,data: data.to_vec(),+ content_hash: None,};let uploads = merge_uploads_prefer_dsym(@@ -184,6 +185,7 @@ mod tests {chunk_id: uuid.to_string(),release_id: None,data: data.to_vec(),+ content_hash: None,};let uploads =diff --git a/cli/src/dsym/mod.rs b/cli/src/dsym/mod.rsindex 0c7755f1b6f2..967bb7078a45 100644--- a/cli/src/dsym/mod.rs+++ b/cli/src/dsym/mod.rs@@ -83,6 +83,7 @@ impl DsymFile {chunk_id: entry.uuid,release_id: self.release_id.clone(),data: entry.data,+ content_hash: None,}).collect()}diff --git a/cli/src/proguard/mod.rs b/cli/src/proguard/mod.rsindex ab589aa03a1a..1a7d64f005e6 100644--- a/cli/src/proguard/mod.rs+++ b/cli/src/proguard/mod.rs@@ -53,6 +53,7 @@ impl TryInto<SymbolSetUpload> for ProguardFile {chunk_id: self.map_id,release_id: self.release_id,data,+ content_hash: None,})}}diff --git a/cli/src/sourcemaps/args.rs b/cli/src/sourcemaps/args.rsindex 512a09bd66a9..a6b05f23c87e 100644--- a/cli/src/sourcemaps/args.rs+++ b/cli/src/sourcemaps/args.rs@@ -93,6 +93,15 @@ impl FileSelectionArgs {}}+/// How exceptions get associated with a release.+#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]+pub enum ReleaseMode {+ /// Bind the release to the uploaded symbol sets (the previous behavior)+ SymbolSet,+ /// EXPERIMENTAL: resolve the release per event from an id injected into each chunk+ Event,+}+#[derive(clap::Args, Clone)]pub struct ReleaseArgs {/// The project name associated with the uploaded chunks. Required to have the uploaded chunks associated withdiff --git a/cli/src/sourcemaps/constant.rs b/cli/src/sourcemaps/constant.rsindex 7126946cb6ae..4e496bea438e 100644--- a/cli/src/sourcemaps/constant.rs+++ b/cli/src/sourcemaps/constant.rs@@ -1,3 +1,21 @@+// Chunk-id-only injection. `e._posthogChunkIds[stack] = chunkId` on the global.pub const CODE_SNIPPET_TEMPLATE: &str = r#"!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._posthogChunkIds=e._posthogChunkIds||{},e._posthogChunkIds[n]="__POSTHOG_CHUNK_ID__")}catch(e){}}();"#;++// Chunk-id + release injection. Sets `e._posthogReleaseId` to the release row's id+// (first-wins, so the first loaded chunk pins the release) alongside the chunk-id map.+// The SDK only reads it when it is a non-empty string, so the placeholder is filled with+// a JSON-encoded string literal that carries its own quotes.+pub const CODE_SNIPPET_WITH_RELEASE_TEMPLATE: &str = r#"!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{};e._posthogReleaseId=e._posthogReleaseId||__POSTHOG_RELEASE_ID__;var n=(new e.Error).stack;n&&(e._posthogChunkIds=e._posthogChunkIds||{},e._posthogChunkIds[n]="__POSTHOG_CHUNK_ID__")}catch(e){}}();"#;+pub const CHUNKID_COMMENT_PREFIX: &str = "\n//# chunkId=__POSTHOG_CHUNK_ID__";pub const CHUNKID_PLACEHOLDER: &str = "__POSTHOG_CHUNK_ID__";+/// The placeholder as it appears in the snippet templates: inside a JS string literal. Snippet+/// rendering replaces it quotes-and-all with a JSON-encoded value, so the id can't break out.+pub const QUOTED_CHUNKID_PLACEHOLDER: &str = "\"__POSTHOG_CHUNK_ID__\"";+pub const RELEASE_ID_PLACEHOLDER: &str = "__POSTHOG_RELEASE_ID__";++// Fixed namespace for deriving deterministic (content-addressed) chunk ids via UUIDv5.+// Same minified bytes in, same chunk id out — across machines and rebuilds — so re-uploads+// dedupe and symbol sets stay stable without a per-build random id.+pub const CHUNK_ID_NAMESPACE: uuid::Uuid =+ uuid::Uuid::from_u128(0x0e9b3c7a5d1f42a8b6c4e2d0f8a17593);diff --git a/cli/src/sourcemaps/content.rs b/cli/src/sourcemaps/content.rsindex 517a58581c83..34de8a6c8011 100644--- a/cli/src/sourcemaps/content.rs+++ b/cli/src/sourcemaps/content.rs@@ -8,10 +8,74 @@ use std::{collections::BTreeMap, path::PathBuf};use crate::{api::symbol_sets::SymbolSetUpload,- sourcemaps::constant::{CHUNKID_COMMENT_PREFIX, CHUNKID_PLACEHOLDER, CODE_SNIPPET_TEMPLATE},+ sourcemaps::constant::{+ CHUNKID_COMMENT_PREFIX, CHUNKID_PLACEHOLDER, CODE_SNIPPET_TEMPLATE,+ CODE_SNIPPET_WITH_RELEASE_TEMPLATE, QUOTED_CHUNKID_PLACEHOLDER, RELEASE_ID_PLACEHOLDER,+ },utils::files::SourceFile,};+/// Build the injected IIFE for a chunk. Both ids are filled in as JSON-encoded string literals,+/// so quotes/backslashes in the values can't break out of the snippet — chunk ids matter too,+/// since re-injection reuses whatever the `//# chunkId=` comment carries.+fn build_code_snippet(chunk_id: &str, release_id: Option<&str>) -> Result<String> {+ let Some(release_id) = release_id else {+ return substitute_chunk_id(CODE_SNIPPET_TEMPLATE, chunk_id);+ };+ Ok(+ substitute_chunk_id(CODE_SNIPPET_WITH_RELEASE_TEMPLATE, chunk_id)?+ .replace(RELEASE_ID_PLACEHOLDER, &serde_json::to_string(release_id)?),+ )+}++/// Fill a snippet template's quoted chunk-id placeholder with the JSON-encoded id. Every site+/// that renders or searches for an injected snippet must encode the same way, or ids that+/// need escaping would fail to round-trip through detection and removal.+fn substitute_chunk_id(template: &str, chunk_id: &str) -> Result<String> {+ Ok(template.replace(+ QUOTED_CHUNKID_PLACEHOLDER,+ &serde_json::to_string(chunk_id)?,+ ))+}++struct ReleaseSnippetSpan {+ start: usize,+ end: usize,+ release_id_start: usize,+ release_id_end: usize,+}++/// Locate the release-variant snippet for `chunk_id` in `source`, if present.+fn find_release_snippet(source: &str, chunk_id: &str) -> Option<ReleaseSnippetSpan> {+ let (prefix, suffix) = CODE_SNIPPET_WITH_RELEASE_TEMPLATE+ .split_once(RELEASE_ID_PLACEHOLDER)+ .expect("release template has a release id placeholder");+ let suffix = substitute_chunk_id(suffix, chunk_id).ok()?;++ let start = source.find(prefix)?;+ let release_id_start = start + prefix.len();+ let release_id_len = source[release_id_start..].find(&suffix)?;+ // The span between prefix and suffix must be the injected release id — a short JSON+ // string literal. A distant suffix match means user code, not our snippet.+ if release_id_len > 256 {+ return None;+ }+ let release_id_end = release_id_start + release_id_len;++ Some(ReleaseSnippetSpan {+ start,+ end: release_id_end + suffix.len(),+ release_id_start,+ release_id_end,+ })+}++/// Read the release id embedded in the source's release-variant snippet, if any.+pub fn get_injected_release_id(source: &str, chunk_id: &str) -> Option<String> {+ let span = find_release_snippet(source, chunk_id)?;+ serde_json::from_str(&source[span.release_id_start..span.release_id_end]).ok()+}+#[derive(Debug, Serialize, Deserialize, PartialEq, Eq)]pub struct SourceMapContent {#[serde(skip_serializing_if = "Option::is_none")]@@ -176,12 +240,12 @@ impl MinifiedSourceFile {self.get_comment_value(&patterns)}- pub fn set_chunk_id(&mut self, chunk_id: &str) -> Result<SourceMap> {+ pub fn set_chunk_id(&mut self, chunk_id: &str, release_id: Option<&str>) -> Result<SourceMap> {let (new_source_content, source_adjustment) = {// Update source content with chunk IDlet source_content = &self.inner.content;let mut magic_source = MagicString::new(source_content);- let code_snippet = CODE_SNIPPET_TEMPLATE.replace(CHUNKID_PLACEHOLDER, chunk_id);+ let code_snippet = build_code_snippet(chunk_id, release_id)?;magic_source.prepend(&code_snippet).map_err(|err| anyhow!("Failed to prepend code snippet: {err}"))?;@@ -307,12 +371,16 @@ impl MinifiedSourceFile {.map_err(|err| anyhow!("Failed to remove chunk comment: {err}"))?;}- let code_snippet = CODE_SNIPPET_TEMPLATE.replace(CHUNKID_PLACEHOLDER, &chunk_id);+ let code_snippet = substitute_chunk_id(CODE_SNIPPET_TEMPLATE, &chunk_id)?;if let Some(code_snippet_start) = source_content.find(&code_snippet) {let code_snippet_end = code_snippet_start as i64 + code_snippet.len() as i64;magic_source.remove(code_snippet_start as i64, code_snippet_end).map_err(|err| anyhow!("Failed to remove code snippet {err}"))?;+ } else if let Some(span) = find_release_snippet(source_content, &chunk_id) {+ magic_source+ .remove(span.start as i64, span.end as i64)+ .map_err(|err| anyhow!("Failed to remove code snippet {err}"))?;}let adjustment = magic_source@@ -386,6 +454,7 @@ impl TryInto<SymbolSetUpload> for SourceMapFile {chunk_id,release_id,data,+ content_hash: None,})}}@@ -405,6 +474,36 @@ mod tests {}}+ #[test]+ fn build_code_snippet_json_encodes_ids() {+ let hostile = r#"a");window.x=1;("b"#;+ let encoded = serde_json::to_string(hostile).unwrap();++ let plain = build_code_snippet(hostile, None).unwrap();+ let with_release = build_code_snippet(hostile, Some(hostile)).unwrap();++ assert!(plain.contains(&encoded), "snippet: {plain}");+ assert_eq!(+ with_release.matches(&encoded).count(),+ 2,+ "snippet: {with_release}"+ );+ }++ #[test]+ fn get_injected_release_id_round_trips_escaped_ids() {+ // Ids that need JSON escaping must survive detection: the re-inject flow reads the+ // embedded release id back to decide whether to refresh the snippet.+ let chunk_id = r#"weird"chunk\id"#;+ let release_id = r#"rel"ease\id"#;+ let snippet = build_code_snippet(chunk_id, Some(release_id)).unwrap();++ assert_eq!(+ get_injected_release_id(&format!("{snippet}code();"), chunk_id).as_deref(),+ Some(release_id)+ );+ }+#[test]fn is_empty_true_for_all_empty_fields() {let sm = content_from(json!({diff --git a/cli/src/sourcemaps/hermes/inject.rs b/cli/src/sourcemaps/hermes/inject.rsindex ffd8e8777551..9578a2257f6a 100644--- a/cli/src/sourcemaps/hermes/inject.rs+++ b/cli/src/sourcemaps/hermes/inject.rs@@ -2,17 +2,27 @@// It's intended as an escape hatch for people rolling their own build pipeline - we expect most users to be// using the metro plugin for injecting, and then calling clone-use anyhow::Result;+use anyhow::{bail, Result};use walkdir::DirEntry;use crate::{invocation_context::context,- sourcemaps::inject::{inject_impl, InjectArgs},+ sourcemaps::{+ args::ReleaseMode,+ inject::{inject_impl, InjectArgs},+ },};pub fn inject(args: &InjectArgs) -> Result<()> {context().capture_command_invoked("hermes_inject");args.validate()?;+ // The rest of the Hermes pipeline (clone, upload, the RN SDK) has no event-mode support,+ // so accepting the flag would inject a global nothing reads while upload re-binds the+ // release anyway. Rejecting also catches a POSTHOG_RELEASE_MODE=event env var set for a+ // web build leaking into a React Native build in the same environment.+ if args.release_mode == ReleaseMode::Event {+ bail!("--release-mode=event is not supported for Hermes bundles. Remove the flag (or unset POSTHOG_RELEASE_MODE) and inject again.");+ }inject_impl(args, is_metro_bundle, None)}diff --git a/cli/src/sourcemaps/inject.rs b/cli/src/sourcemaps/inject.rsindex a413b86668be..e5885ace2d50 100644--- a/cli/src/sourcemaps/inject.rs+++ b/cli/src/sourcemaps/inject.rs@@ -6,7 +6,8 @@ use walkdir::DirEntry;use crate::{api::releases::{Release, ReleaseBuilder},sourcemaps::{- args::{FileSelectionArgs, ReleaseArgs},+ args::{FileSelectionArgs, ReleaseArgs, ReleaseMode},+ constant::CHUNK_ID_NAMESPACE,content::SourceMapFile,source_pairs::{read_pairs, SourcePair},},@@ -26,6 +27,20 @@ pub struct InjectArgs {#[clap(flatten)]pub release: ReleaseArgs,++ /// How the release is associated with exceptions. `symbol-set` (the default) stamps the+ /// release id into the sourcemap so the uploaded symbol set is bound to it: the previous+ /// behavior. EXPERIMENTAL `event` injects the release id into each chunk as+ /// `_posthogReleaseId` so the SDK emits it on every exception, and derives+ /// content-addressed chunk ids that are stable across rebuilds. Also settable via+ /// `POSTHOG_RELEASE_MODE`.+ #[arg(+ long,+ env = "POSTHOG_RELEASE_MODE",+ value_enum,+ default_value = "symbol-set"+ )]+ pub release_mode: ReleaseMode,}impl InjectArgs {@@ -43,6 +58,7 @@ pub fn inject_impl(file_selection,public_path_prefix,release,+ release_mode,} = args;info!("injecting selection: {}", file_selection);@@ -57,16 +73,33 @@ pub fn inject_impl(bail!("no source files found");}- let created_release_id = if let Some(r) = existing_release {- Some(r.id.to_string())- } else {- let cwd = std::env::current_dir()?;- get_release_for_maps(&cwd, release.clone(), pairs.iter().map(|p| &p.sourcemap))?- .as_ref()- .map(|r| r.id.to_string())- };-- pairs = inject_pairs(pairs, created_release_id)?;+ match release_mode {+ ReleaseMode::Event => {+ // The release id travels inside each chunk for the SDK to emit, rather than being+ // stamped into the sourcemap, so the release exists but nothing binds a symbol set+ // to it.+ let release_id = resolve_release_id(release.clone(), existing_release)?;+ if release_id.is_none() {+ warn!(+ "no release could be resolved, injecting chunk ids only — events will carry no release"+ );+ }+ pairs = inject_pairs(pairs, release_id.as_deref())?;+ }+ ReleaseMode::SymbolSet => {+ // Fetch or create a release over the API and stamp its id into the sourcemap,+ // binding the uploaded symbol set to it.+ let created_release_id = if let Some(r) = existing_release {+ Some(r.id.to_string())+ } else {+ let cwd = std::env::current_dir()?;+ get_release_for_maps(&cwd, release.clone(), pairs.iter().map(|p| &p.sourcemap))?+ .as_ref()+ .map(|r| r.id.to_string())+ };+ pairs = inject_pairs_legacy(pairs, created_release_id)?;+ }+ }// Write the source and sourcemaps back to diskfor pair in &pairs {@@ -76,7 +109,42 @@ pub fn inject_impl(Ok(())}+/// Event-mode injection (`--release-mode=event`): content-addressed chunk ids plus an optional+/// `_posthogReleaseId` payload.pub fn inject_pairs(+ mut pairs: Vec<SourcePair>,+ release_id: Option<&str>,+) -> 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);+ pair.add_chunk_id(chunk_id, release_id)?;+ continue;+ };++ // Already injected: the chunk id is content-addressed and the content didn't change,+ // so keep it — but refresh the embedded release id when a different release resolved,+ // or a re-run over an existing dist would keep reporting the old release on every+ // event. When no release resolves, leave the pair untouched: failing to resolve is+ // missing information (e.g. no git context), not evidence the embedded id is stale.+ let Some(release_id) = release_id else {+ continue;+ };+ if pair.get_injected_release_id().as_deref() == Some(release_id) {+ continue;+ }+ pair.remove_chunk_id(chunk_id.clone())?;+ pair.add_chunk_id(chunk_id, Some(release_id))?;+ }++ Ok(pairs)+}++/// Symbol-set-mode injection (the default): a random per-build chunk id and the created release+/// id stamped into the sourcemap. Regenerates the chunk id whenever the release id changes or is+/// missing.+pub fn inject_pairs_legacy(mut pairs: Vec<SourcePair>,created_release_id: Option<String>,) -> Result<Vec<SourcePair>> {@@ -90,7 +158,7 @@ pub fn inject_pairs(if let Some(previous_chunk_id) = pair.get_chunk_id() {pair.update_chunk_id(previous_chunk_id, chunk_id)?;} else {- pair.add_chunk_id(chunk_id)?;+ pair.add_chunk_id(chunk_id, None)?;}}}@@ -98,6 +166,43 @@ pub fn inject_pairs(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()+}++/// Resolve the release row whose id gets injected into the chunks. Reuses the release already+/// fetched upstream (the `process` command) when there is one; otherwise resolves name/version+/// from flags and git/CI metadata and fetches or creates the row. Returns `None` only when there+/// isn't enough information to identify a release at all.+fn resolve_release_id(+ release: ReleaseArgs,+ existing_release: Option<&Release>,+) -> Result<Option<String>> {+ if let Some(r) = existing_release {+ return Ok(Some(r.id.to_string()));+ }++ let cwd = std::env::current_dir()?;+ let release_args_were_provided =+ release.name.is_some() || release.version.is_some() || release.build.is_some();+ let mut builder: ReleaseBuilder = release.into();+ add_git_info_to_release_builder(&cwd, &mut builder, release_args_were_provided)?;+ if !builder.can_create() {+ return Ok(None);+ }+ Ok(Some(builder.fetch_or_create()?.id.to_string()))+}+pub fn get_release_for_maps<'a>(directory: &Path,release: ReleaseArgs,@@ -242,6 +347,15 @@ mod tests {temp_root}+ #[test]+ fn stable_chunk_id_covers_source_and_sourcemap() {+ let id = stable_chunk_id("code();", r#"{"mappings":"AAAA"}"#);++ 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"}"#));+ }+#[test]fn git_failure_is_not_fatal_when_release_fields_are_explicit() {let _env_lock = lock_env();diff --git a/cli/src/sourcemaps/plain/mod.rs b/cli/src/sourcemaps/plain/mod.rsindex 6ec74eb125a4..cfe039ef8c37 100644--- a/cli/src/sourcemaps/plain/mod.rs+++ b/cli/src/sourcemaps/plain/mod.rs@@ -2,7 +2,9 @@ use anyhow::Result;use clap::Subcommand;use crate::sourcemaps::{- args::{FileSelectionArgs, ReleaseArgs, UploadConcurrencyArgs, UploadConflictArgs},+ args::{+ FileSelectionArgs, ReleaseArgs, ReleaseMode, UploadConcurrencyArgs, UploadConflictArgs,+ },inject::InjectArgs,};@@ -47,6 +49,19 @@ pub struct ProcessArgs {#[clap(flatten)]pub upload_concurrency: UploadConcurrencyArgs,++ /// How the release is associated with exceptions. `symbol-set` (the default) stamps the+ /// release id onto the uploaded symbol sets: the previous behavior. EXPERIMENTAL `event`+ /// injects the release id into each chunk as `_posthogReleaseId` (alongside+ /// content-addressed chunk ids) so the SDK reports the release per event; symbol sets stay+ /// release-independent. Also settable via `POSTHOG_RELEASE_MODE`.+ #[arg(+ long,+ env = "POSTHOG_RELEASE_MODE",+ value_enum,+ default_value = "symbol-set"+ )]+ pub release_mode: ReleaseMode,}impl ProcessArgs {@@ -63,6 +78,7 @@ impl From<ProcessArgs> for (InjectArgs, upload::Args) {file_selection: args.file_selection.clone(),release: args.release.clone(),public_path_prefix: args.public_path_prefix.clone(),+ release_mode: args.release_mode,};let upload_args = upload::Args {file_selection: args.file_selection,@@ -73,6 +89,7 @@ impl From<ProcessArgs> for (InjectArgs, upload::Args) {release: args.release,conflict: args.conflict,upload_concurrency: args.upload_concurrency,+ release_mode: args.release_mode,};(inject_args, upload_args)diff --git a/cli/src/sourcemaps/plain/upload.rs b/cli/src/sourcemaps/plain/upload.rsindex 2b51b9c11033..b670157d98a2 100644--- a/cli/src/sourcemaps/plain/upload.rs+++ b/cli/src/sourcemaps/plain/upload.rs@@ -19,7 +19,9 @@ use crate::{},invocation_context::context,sourcemaps::{- args::{FileSelectionArgs, ReleaseArgs, UploadConcurrencyArgs, UploadConflictArgs},+ args::{+ FileSelectionArgs, ReleaseArgs, ReleaseMode, UploadConcurrencyArgs, UploadConflictArgs,+ },content::MinifiedSourceFile,inject::get_release_for_maps,plain::inject::is_javascript_file,@@ -60,6 +62,19 @@ pub struct Args {/// DEPRECATED - this flag is a no-op. Use top-level `--skip-ssl-verification` instead.#[arg(long)]pub skip_ssl_verification: bool,++ /// How the release is associated with exceptions. `symbol-set` (the default) stamps the+ /// release id onto the uploaded symbol sets: the previous behavior. EXPERIMENTAL `event`+ /// leaves symbol sets unbound; the chunks already carry the release id in their injected+ /// snippet, so the release is resolved per event rather than per symbol set. Also settable+ /// via `POSTHOG_RELEASE_MODE`.+ #[arg(+ long,+ env = "POSTHOG_RELEASE_MODE",+ value_enum,+ default_value = "symbol-set"+ )]+ pub release_mode: ReleaseMode,}pub fn upload_cmd(args: &Args) -> Result<()> {@@ -86,8 +101,12 @@ pub fn upload(args: &Args, existing_release: Option<&Release>) -> Result<()> {.collect::<Vec<_>>();info!("Found {} chunks to upload", pairs.len());- // Reuse the pre-resolved release if available, otherwise fetch or create one- let created_release_id = if let Some(r) = existing_release {+ // 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+ // would only serve to stamp it onto the symbol sets, which is the binding event mode avoids.+ let created_release_id = if args.release_mode == ReleaseMode::Event {+ None+ } else if let Some(r) = existing_release {Some(r.id.to_string())} else {let cwd = std::env::current_dir()?;@@ -132,9 +151,10 @@ pub fn upload(args: &Args, existing_release: Option<&Release>) -> Result<()> {// 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(TryInto::try_into)+ .map(|pair| pair.into_upload(release_mode)).collect::<Result<Vec<SymbolSetUpload>>>().context("While preparing files for upload")?;diff --git a/cli/src/sourcemaps/source_pairs.rs b/cli/src/sourcemaps/source_pairs.rsindex 041e685c7b2f..390cfcb89728 100644--- a/cli/src/sourcemaps/source_pairs.rs+++ b/cli/src/sourcemaps/source_pairs.rs@@ -1,6 +1,10 @@use crate::{api::symbol_sets::SymbolSetUpload,- sourcemaps::content::{MinifiedSourceFile, SourceMapFile},+ sourcemaps::{+ args::ReleaseMode,+ content::{get_injected_release_id, MinifiedSourceFile, SourceMapFile},+ },+ utils::files::content_hash,};use anyhow::{anyhow, Context, Result};use posthog_symbol_data::{write_symbol_data, SourceAndMap};@@ -33,6 +37,13 @@ impl SourcePair {self.sourcemap.get_release_id()}+ /// The release id embedded in the source's injected snippet (event release mode),+ /// as opposed to `get_release_id`, which reads the one stamped into the sourcemap.+ pub fn get_injected_release_id(&self) -> Option<String> {+ let chunk_id = self.get_chunk_id()?;+ get_injected_release_id(&self.source.inner.content, &chunk_id)+ }+pub fn remove_chunk_id(&mut self, chunk_id: String) -> Result<()> {if self.get_chunk_id().as_ref() != Some(&chunk_id) {return Err(anyhow!("Chunk ID mismatch"));@@ -49,16 +60,16 @@ impl SourcePair {new_chunk_id: String,) -> Result<()> {self.remove_chunk_id(previous_chunk_id)?;- self.add_chunk_id(new_chunk_id)?;+ self.add_chunk_id(new_chunk_id, None)?;Ok(())}- pub fn add_chunk_id(&mut self, chunk_id: String) -> Result<()> {+ pub fn add_chunk_id(&mut self, chunk_id: String, release_id: Option<&str>) -> Result<()> {if self.has_chunk_id() {return Err(anyhow!("Chunk ID already set"));}- let adjustment = self.source.set_chunk_id(&chunk_id)?;+ let adjustment = self.source.set_chunk_id(&chunk_id, release_id)?;// In cases where sourcemaps are shared across multiple chunks,// we should only apply the adjustment if the sourcemap doesn't// have a chunk ID set (since otherwise, it's already been adjusted)@@ -114,15 +125,43 @@ pub fn read_pairs(pairs}-impl TryInto<SymbolSetUpload> for SourcePair {- type Error = anyhow::Error;-- fn try_into(self) -> Result<SymbolSetUpload> {+impl SourcePair {+ /// Turn the pair into an upload payload. The payload always carries the injected artifact;+ /// only the content hash depends on the mode.+ ///+ /// In event mode the hash is computed over the pair with the injection undone (snippet and+ /// chunk-id comment removed, sourcemap adjustment reversed), because the injected bytes vary+ /// while the chunk id does not: the embedded release id changes every release, and a chunk+ /// injected before a release could be resolved carries a shorter snippet (and a differently+ /// adjusted sourcemap) than the same chunk after a later run adds the release. The server+ /// keys its skip-or-conflict decision on this hash per chunk id, so any injection-state+ /// dependence turns an unchanged chunk into a `content_hash_mismatch` rejection.+ ///+ /// 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(|| anyhow!("Chunk ID not found"))?;- let source_content = self.source.inner.content;+ let release_id = self.sourcemap.get_release_id();+ let source_content = self.source.inner.content.clone();let sourcemap_content = serde_json::to_string(&self.sourcemap.inner.content)?;++ let content_hash = match release_mode {+ ReleaseMode::Event => {+ self.remove_chunk_id(chunk_id.clone())?;+ let pristine_map = serde_json::to_string(&self.sourcemap.inner.content)?;+ // JSON serialization never contains a raw NUL, so it unambiguously separates+ // the parts (same framing as `stable_chunk_id`).+ Some(content_hash([+ self.source.inner.content.as_bytes(),+ b"\0".as_slice(),+ pristine_map.as_bytes(),+ ]))+ }+ ReleaseMode::SymbolSet => None,+ };+let data = SourceAndMap {minified_source: source_content,sourcemap: sourcemap_content,@@ -133,7 +172,8 @@ impl TryInto<SymbolSetUpload> for SourcePair {Ok(SymbolSetUpload {chunk_id,data,- release_id: self.sourcemap.get_release_id(),+ release_id,+ content_hash,})}}diff --git a/cli/tests/debug_symbols.rs b/cli/tests/debug_symbols.rsindex d0d9729efe0d..bb6951ac4784 100644--- a/cli/tests/debug_symbols.rs+++ b/cli/tests/debug_symbols.rs@@ -313,6 +313,7 @@ fn dedup_preserves_per_format_chunk_id_casing() {chunk_id: chunk_id.to_string(),release_id: None,data: data.to_vec(),+ content_hash: None,};let deduped = dedup_uploads_by_chunk_id(vec![diff --git a/cli/tests/sourcemap.rs b/cli/tests/sourcemap.rsindex 3e76bf775743..20513d23d749 100644--- a/cli/tests/sourcemap.rs+++ b/cli/tests/sourcemap.rs@@ -1,6 +1,9 @@use posthog_cli::{sourcemaps::{- content::SourceMapContent, inject::inject_pairs, plain::inject::is_javascript_file,+ args::ReleaseMode,+ content::SourceMapContent,+ inject::{inject_pairs, inject_pairs_legacy},+ plain::inject::is_javascript_file,source_pairs::SourcePair,},utils::files::FileSelection,@@ -129,7 +132,7 @@ fn test_pair_inject() {let current_pair = pairs.first_mut().expect("Failed to get first pair");let chunk_id = "00000-00000-00000";current_pair- .add_chunk_id(chunk_id.to_string())+ .add_chunk_id(chunk_id.to_string(), None).expect("Failed to set chunk ID");assert_file_eq(@@ -152,7 +155,7 @@ fn test_index_inject() {let current_pair = pairs.first_mut().expect("Failed to get first pair");let chunk_id = "00000-00000-00000";current_pair- .add_chunk_id(chunk_id.to_string())+ .add_chunk_id(chunk_id.to_string(), None).expect("Failed to set chunk ID");let bytes = serde_json::to_string(¤t_pair.sourcemap.inner.content).unwrap();@@ -177,7 +180,7 @@ fn test_index_inject_retains_extension_fields() {let chunk_id = "00000-00000-00000";current_pair- .add_chunk_id(chunk_id.to_string())+ .add_chunk_id(chunk_id.to_string(), None).expect("Failed to set chunk ID");// Extension field should be retained after flattening@@ -206,7 +209,7 @@ fn test_pair_remove() {let current_pair = pairs.first_mut().expect("Failed to get first pair");let chunk_id = "00000-00000-00000";current_pair- .add_chunk_id(chunk_id.to_string())+ .add_chunk_id(chunk_id.to_string(), None).expect("Failed to set chunk ID");current_pair@@ -222,13 +225,150 @@ fn test_pair_remove() {}#[test]-fn test_reinject_without_new_release() {+fn test_reinject_is_idempotent() {+ // A chunk that already carries a content-addressed id must survive re-injection untouched.+ // Regenerating the id on every build would orphan the already-uploaded symbol set.let case_path = get_case_path("reinject");let pairs =read_pairs(vec![case_path.clone()], vec![], vec![], &None).expect("Failed to read pairs");assert_eq!(pairs.len(), 1);+ let source_before = pairs.first().unwrap().source.inner.content.clone();+let injected_pairs = inject_pairs(pairs, None).expect("Failed to inject pairs");let first_pair = injected_pairs.first().expect("Failed to get first pair");++ assert_eq!(first_pair.source.get_chunk_id().as_deref(), Some("0"));+ assert_eq!(first_pair.source.inner.content, source_before);+}++#[test]+fn test_pair_remove_strips_release_variant_snippet() {+ // Removal must strip the release-carrying snippet too, or updating a chunk would stack+ // a second snippet on top of the old one.+ let case_path = get_case_path("inject");+ let mut pairs =+ read_pairs(vec![case_path.clone()], vec![], vec![], &None).expect("Failed to read pairs");+ let current_pair = pairs.first_mut().expect("Failed to get first pair");+ let chunk_id = "00000-00000-00000";+ current_pair+ .add_chunk_id(+ chunk_id.to_string(),+ Some("0199f7c2-1c4e-7c3a-9f8b-2d6e4a1b7c05"),+ )+ .expect("Failed to set chunk ID");++ current_pair+ .remove_chunk_id(chunk_id.to_string())+ .expect("Failed to remove chunk ID");++ assert_file_eq(&case_path, "chunk.js", ¤t_pair.source.inner.content);++ let expected_val: SourceMapContent =+ serde_json::from_str(include_str!(case!("inject/chunk.js.map"))).unwrap();+ assert_eq!(expected_val, current_pair.sourcemap.inner.content);+}++#[test]+fn test_reinject_refreshes_stale_release_id() {+ // Re-running inject over an already-injected dist with a new release must swap the+ // embedded release id while keeping the content-addressed chunk id.+ let case_path = get_case_path("inject");+ let pairs =+ read_pairs(vec![case_path.clone()], vec![], vec![], &None).expect("Failed to read pairs");+ let injected = inject_pairs(pairs, Some("release-a")).expect("Failed to inject pairs");+ let chunk_id = injected+ .first()+ .and_then(|p| p.get_chunk_id())+ .expect("chunk id");++ let refreshed = inject_pairs(injected, Some("release-b")).expect("Failed to re-inject pairs");+ let pair = refreshed.first().expect("Failed to get first pair");++ assert_eq!(pair.get_chunk_id().as_deref(), Some(chunk_id.as_str()));+ let source = &pair.source.inner.content;+ assert!(+ source.contains(r#"_posthogReleaseId||"release-b""#),+ "source: {source}"+ );+ assert!(!source.contains("release-a"), "source: {source}");+}++#[test]+fn test_reinject_without_release_keeps_embedded_release_id() {+ // A run that can't resolve a release has no information — it must not clear the+ // release id a previous run embedded.+ let case_path = get_case_path("inject");+ let pairs =+ read_pairs(vec![case_path.clone()], vec![], vec![], &None).expect("Failed to read pairs");+ let injected = inject_pairs(pairs, Some("release-a")).expect("Failed to inject pairs");+ let source_before = injected.first().unwrap().source.inner.content.clone();++ let reinjected = inject_pairs(injected, None).expect("Failed to re-inject pairs");++ assert_eq!(+ reinjected.first().unwrap().source.inner.content,+ source_before+ );+}++#[test]+fn test_reinject_adds_release_to_releaseless_chunk() {+ // A chunk injected while no release was resolvable must pick the release up on a later+ // run, keeping its content-addressed chunk id.+ let case_path = get_case_path("inject");+ let pairs =+ read_pairs(vec![case_path.clone()], vec![], vec![], &None).expect("Failed to read pairs");+ let injected = inject_pairs(pairs, None).expect("Failed to inject pairs");+ let chunk_id = injected+ .first()+ .and_then(|p| p.get_chunk_id())+ .expect("chunk id");++ let refreshed = inject_pairs(injected, Some("release-a")).expect("Failed to re-inject pairs");+ let pair = refreshed.first().expect("Failed to get first pair");++ assert_eq!(pair.get_chunk_id().as_deref(), Some(chunk_id.as_str()));+ assert!(pair+ .source+ .inner+ .content+ .contains(r#"_posthogReleaseId||"release-a""#));+}++#[test]+fn test_inject_with_release_embeds_id_in_source() {+ // Injecting with a release must embed its id into the JS chunk itself — that global is the+ // SDK's only source of the release — and must leave the release out of the sourcemap, so+ // nothing binds the uploaded symbol set to it. The SDK ignores the global unless it is a+ // non-empty string, so it has to be emitted as a quoted string literal.+ let case_path = get_case_path("inject");+ let pairs =+ read_pairs(vec![case_path.clone()], vec![], vec![], &None).expect("Failed to read pairs");+ assert_eq!(pairs.len(), 1);+ let release_id = "0199f7c2-1c4e-7c3a-9f8b-2d6e4a1b7c05";++ let injected_pairs = inject_pairs(pairs, Some(release_id)).expect("Failed to inject pairs");+ let first_pair = injected_pairs.first().expect("Failed to get first pair");++ let source = &first_pair.source.inner.content;+ assert!(+ source.contains(&format!(r#"_posthogReleaseId||"{release_id}""#)),+ "source: {source}"+ );+ assert!(first_pair.source.get_chunk_id().is_some());+ assert!(first_pair.sourcemap.get_release_id().is_none());+}++#[test]+fn test_legacy_reinject_without_new_release() {+ // Legacy path: with no release, an existing chunk carrying a stale release id is regenerated+ // and the release id is cleared from the sourcemap.+ let case_path = get_case_path("reinject");+ let pairs =+ read_pairs(vec![case_path.clone()], vec![], vec![], &None).expect("Failed to read pairs");+ assert_eq!(pairs.len(), 1);+ let injected_pairs = inject_pairs_legacy(pairs, None).expect("Failed to inject pairs");+ let first_pair = injected_pairs.first().expect("Failed to get first pair");assert_ne!(&first_pair.source.get_chunk_id().unwrap(), "0");assert_eq!(&first_pair.sourcemap.get_chunk_id().unwrap(),@@ -238,14 +378,15 @@ fn test_reinject_without_new_release() {}#[test]-fn test_reinject_with_new_release() {+fn test_legacy_reinject_with_new_release() {+ // Legacy path: a new release id regenerates the chunk id and is stamped into the sourcemap.let case_path = get_case_path("reinject");let pairs =read_pairs(vec![case_path.clone()], vec![], vec![], &None).expect("Failed to read pairs");assert_eq!(pairs.len(), 1);let release_id = uuid::Uuid::now_v7().to_string();let injected_pairs =- inject_pairs(pairs, Some(release_id.clone())).expect("Failed to inject pairs");+ inject_pairs_legacy(pairs, Some(release_id.clone())).expect("Failed to inject pairs");let first_pair = injected_pairs.first().expect("Failed to get first pair");assert_ne!(&first_pair.source.get_chunk_id().unwrap(), "0");assert_eq!(@@ -284,14 +425,55 @@ fn test_upload_set() {assert_ne!(source_chunk_id, sourcemap_chunk_id);// Convert to UploadSet- use posthog_cli::api::symbol_sets::SymbolSetUpload;- let upload_set: SymbolSetUpload = pair_with_different_ids- .try_into()+ let upload_set = pair_with_different_ids+ .into_upload(ReleaseMode::SymbolSet).expect("Failed to convert to SymbolSetUpload");// Verify that the upload set uses the source's chunk ID, not the sourcemap'sassert_eq!(upload_set.chunk_id, source_chunk_id);assert_ne!(upload_set.chunk_id, sourcemap_chunk_id);+ // Symbol-set uploads must not precompute a hash: the server stores raw-payload hashes+ // for previously uploaded chunks, and a different hash form would flag every unchanged+ // chunk as a content conflict.+ assert!(upload_set.content_hash.is_none());+}++#[test]+fn test_event_mode_content_hash_is_stable_across_release_states() {+ // The hash must not depend on which snippet variant is embedded. A chunk injected while+ // no release was resolvable, the same chunk injected with a release, and the transition+ // between the two all keep one chunk id, so they must hash identically or the server+ // rejects the later upload as a content_hash_mismatch.+ let case_path = get_case_path("inject");+ let load = || {+ read_pairs(vec![case_path.clone()], vec![], vec![], &None).expect("Failed to read pairs")+ };+ let hash_of = |pairs: Vec<SourcePair>| -> String {+ pairs+ .into_iter()+ .next()+ .expect("Failed to get first pair")+ .into_upload(ReleaseMode::Event)+ .expect("Failed to convert to SymbolSetUpload")+ .content_hash+ .expect("event mode always sets a content hash")+ };++ let releaseless = hash_of(inject_pairs(load(), None).expect("Failed to inject pairs"));+ let with_release = hash_of(+ inject_pairs(load(), Some("11111111-2222-4333-8444-555555555555"))+ .expect("Failed to inject pairs"),+ );+ let transitioned = {+ let injected = inject_pairs(load(), None).expect("Failed to inject pairs");+ hash_of(+ inject_pairs(injected, Some("99999999-8888-4777-8666-000000000000"))+ .expect("Failed to re-inject pairs"),+ )+ };++ assert_eq!(releaseless, with_release);+ assert_eq!(releaseless, transitioned);}#[test]