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): leave script file paths out of the event-mode content hash (#106861)

Aleksander Błaszkiewicz69a476590377
diff --git a/cli/.sampo/changesets/event-hash-ignores-chunk-file-names.md b/cli/.sampo/changesets/event-hash-ignores-chunk-file-names.md
new file mode 100644
index 000000000000..07451d6c1f90
--- /dev/null
+++ b/cli/.sampo/changesets/event-hash-ignores-chunk-file-names.md
@@ -0,0 +1,5 @@
+---
+cargo/posthog-cli: patch
+---
+
+In event release mode, `sourcemap upload` no longer uploads unchanged chunks again when the bundler names chunks by content, as Vite does by default. Every chunk carries the release id, so every release renamed every chunk, and the content hash covered those names: the map's `file`, the `sourceMappingURL` comment and imports of other chunks. The hash now leaves out script file paths (ending in `.js`, `.mjs` or `.cjs`). Hashes stored by earlier versions include the paths, so the first upload after updating sends each chunk once more.
diff --git a/cli/src/sourcemaps/source_pairs.rs b/cli/src/sourcemaps/source_pairs.rs
index 7d55c5aa0531..502a79c02617 100644
--- a/cli/src/sourcemaps/source_pairs.rs
+++ b/cli/src/sourcemaps/source_pairs.rs
@@ -2,12 +2,14 @@ use crate::{
api::symbol_sets::SymbolSetUpload,
sourcemaps::{
args::ReleaseMode,
- content::{get_injected_release_id, MinifiedSourceFile, SourceMapFile},
+ content::{get_injected_release_id, MinifiedSourceFile, SourceMapContent, SourceMapFile},
},
utils::files::content_hash,
};
use anyhow::{anyhow, Context, Result};
use posthog_symbol_data::{write_symbol_data, SourceAndMap};
+use serde_json::Value;
+use std::borrow::Cow;
use tracing::{debug, info, warn};
use walkdir::DirEntry;
@@ -149,6 +151,82 @@ pub fn read_pairs(
pairs
}
+// The control characters keep the token from matching anything a bundler writes.
+const FILE_PATH_TOKEN: &str = "\u{1}file-path\u{1}";
+
+/// Replace every script file path in `text` with one token, for the event-mode content hash.
+/// With content-hashed file names every release renames every chunk, because each chunk carries
+/// the release id, and the names appear inside chunks: imports, `sourceMappingURL` and the map's
+/// `file`. A path is a run of path characters that ends in `.js`, `.mjs` or `.cjs` with no
+/// identifier character after it. The result depends only on `text`, so one chunk hashes the same
+/// way in every upload.
+///
+/// A stored symbol set that this lets the server keep resolves frames the same way: the hash still
+/// covers the mappings, so a path that changes length changes the hash. A function named after a
+/// run, such as `{"one.js"(){}}`, could only go stale if one chunk id covered two builds whose code
+/// differs inside a run. No chunk id does: `@posthog/rollup-plugin` derives its ids before imports
+/// become file names, and every other chunk id covers the final content.
+fn without_file_paths(text: &str) -> Cow<'_, str> {
+ let bytes = text.as_bytes();
+ let mut normalized = String::new();
+ let mut copied = 0;
+ let mut searched = 0;
+ while let Some(found) = text[searched..].find("js") {
+ let js = searched + found;
+ let end = js + 2;
+ searched = end;
+ let extension = if js >= 1 && bytes[js - 1] == b'.' {
+ js - 1
+ } else if js >= 2 && matches!(bytes[js - 1], b'm' | b'c') && bytes[js - 2] == b'.' {
+ js - 2
+ } else {
+ continue;
+ };
+ if text[end..].chars().next().is_some_and(is_identifier_char) {
+ continue;
+ }
+ // Walking back stops at what was already replaced, which keeps the scan linear.
+ let Some(start) = text[copied..extension]
+ .char_indices()
+ .rev()
+ .take_while(|(_, c)| is_path_char(*c))
+ .last()
+ .map(|(offset, _)| copied + offset)
+ else {
+ continue;
+ };
+ if normalized.is_empty() {
+ normalized.reserve(text.len());
+ }
+ normalized.push_str(&text[copied..start]);
+ normalized.push_str(FILE_PATH_TOKEN);
+ copied = end;
+ }
+ if normalized.is_empty() {
+ return Cow::Borrowed(text);
+ }
+ normalized.push_str(&text[copied..]);
+ Cow::Owned(normalized)
+}
+
+fn is_identifier_char(c: char) -> bool {
+ c.is_alphanumeric() || matches!(c, '_' | '$')
+}
+
+fn is_path_char(c: char) -> bool {
+ is_identifier_char(c) || matches!(c, '-' | '.' | '/' | '\\' | '~' | '@' | '+')
+}
+
+/// Replace the file path in the map's `file` field, the only field that names the chunk rather
+/// than its sources.
+fn without_file_path_in_file_field(map: &mut SourceMapContent) {
+ if let Some(Value::String(file)) = map.fields.get_mut("file") {
+ if let Cow::Owned(normalized) = without_file_paths(file) {
+ *file = normalized;
+ }
+ }
+}
+
impl SourcePair {
/// Turn the pair into an upload payload. The payload always carries the injected artifact;
/// only the content hash depends on the mode.
@@ -165,6 +243,9 @@ impl SourcePair {
/// hashes would make the server keep the first map and resolve later frames to the wrong
/// source positions.
///
+ /// The hash also leaves out script file paths, which change with every release when the
+ /// bundler names chunks by content (see `without_file_paths`).
+ ///
/// 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> {
@@ -187,11 +268,13 @@ impl SourcePair {
b"chunk-id-only"
};
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);
// 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(),
+ pristine_source.as_bytes(),
b"\0".as_slice(),
pristine_map.as_bytes(),
b"\0".as_slice(),
@@ -216,3 +299,70 @@ impl SourcePair {
})
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn normalize(text: &str) -> String {
+ without_file_paths(text).replace(FILE_PATH_TOKEN, "<path>")
+ }
+
+ #[test]
+ fn replaces_script_file_paths() {
+ assert_eq!(
+ normalize(
+ r#"import("./one-BrAf3own.js");const d=["assets/one-BrAf3own.js","https://cdn.example.com/a/b-X_1.mjs"];
+//# sourceMappingURL=index-C3e2Htc9.js.map"#
+ ),
+ r#"import("<path>");const d=["<path>","https:<path>"];
+//# sourceMappingURL=<path>.map"#
+ );
+ }
+
+ #[test]
+ fn replaces_directory_names_with_the_path() {
+ assert_eq!(
+ normalize(r#"import("../Bx9_a1c2/one.cjs")"#),
+ r#"import("<path>")"#
+ );
+ assert_eq!(
+ normalize(r#"require("C:\\ci\\Bx9_a1c2\\one.js")"#),
+ normalize(r#"require("C:\\ci\\Zq0_w9e8\\one.js")"#)
+ );
+ }
+
+ #[test]
+ fn leaves_other_extensions_and_bare_extensions_alone() {
+ let text = r#"["index.json","index.jsx","a.js_b",".js",x.jsonp,"js"]"#;
+ assert_eq!(normalize(text), text);
+ assert!(matches!(without_file_paths(text), Cow::Borrowed(_)));
+ }
+
+ #[test]
+ fn handles_repeated_extensions_and_multibyte_text() {
+ assert_eq!(normalize("a.jsx.js x.js.map"), "<path> <path>.map");
+ assert_eq!(normalize("é日.js 😀 é.mjs"), "<path> 😀 <path>");
+ // An emoji is not a path character, so the path starts after it.
+ assert_eq!(normalize("😀js.js"), "😀<path>");
+ }
+
+ #[test]
+ fn replaces_only_the_file_field_of_a_map() {
+ // A source can share a chunk's name, and frames resolve to it, so it stays.
+ let mut map: SourceMapContent = serde_json::from_value(serde_json::json!({
+ "version": 3,
+ "file": "assets/index.js",
+ "sources": ["../src/index.js"],
+ "mappings": "AAAA",
+ }))
+ .expect("Failed to build SourceMapContent");
+ without_file_path_in_file_field(&mut map);
+
+ assert_eq!(map.fields["file"], FILE_PATH_TOKEN);
+ assert_eq!(
+ map.fields["sources"],
+ serde_json::json!(["../src/index.js"])
+ );
+ }
+}
diff --git a/cli/tests/sourcemap.rs b/cli/tests/sourcemap.rs
index 255f05d59aad..fa30d4216266 100644
--- a/cli/tests/sourcemap.rs
+++ b/cli/tests/sourcemap.rs
@@ -10,6 +10,7 @@ use posthog_cli::{
};
use anyhow::Result;
+use posthog_symbol_data::{read_symbol_data, SourceAndMap};
use serde_json::json;
use std::{
@@ -518,13 +519,17 @@ fn test_event_mode_content_hash_tracks_the_snippet_variant() {
const BUNDLER_DEBUG_ID: &str = "11111111-2222-4333-8444-555555555555";
fn make_pair(source_content: &str, map_json: serde_json::Value) -> SourcePair {
+ make_named_pair("chunk.js", source_content, map_json)
+}
+
+fn make_named_pair(name: &str, source_content: &str, map_json: serde_json::Value) -> SourcePair {
SourcePair {
source: MinifiedSourceFile {
- inner: SourceFile::new(PathBuf::from("chunk.js"), source_content.to_string()),
+ inner: SourceFile::new(PathBuf::from(name), source_content.to_string()),
},
sourcemap: SourceMapFile {
inner: SourceFile::new(
- PathBuf::from("chunk.js.map"),
+ PathBuf::from(format!("{name}.map")),
serde_json::from_value(map_json).expect("Failed to build SourceMapContent"),
),
},
@@ -661,6 +666,126 @@ fn test_event_mode_content_hash_is_stable_across_releases_for_adopted_ids() {
assert_eq!(fresh.content_hash, transitioned.content_hash);
}
+const ENTRY_DEBUG_ID: &str = "22222222-3333-4444-8555-666666666666";
+const LAZY_DEBUG_ID: &str = "33333333-4444-4555-8666-777777777777";
+
+/// The debug ids stand in for chunk ids that stay the same across releases, like the ones
+/// `@posthog/rollup-plugin` derives.
+fn content_named_release(
+ release_id: &str,
+ entry_name: &str,
+ lazy_name: &str,
+ lazy_code: &str,
+) -> Vec<SourcePair> {
+ let chunk = |name: &str, code: &str, debug_id: &str| {
+ make_named_pair(
+ name,
+ &format!("{code}\n//# debugId={debug_id}\n//# sourceMappingURL={name}.map\n"),
+ json!({
+ "version": 3,
+ "file": name,
+ "sources": ["../src/index.js"],
+ "sourcesContent": ["import('./lazy.js')\n"],
+ "names": [],
+ "mappings": "AAAA",
+ "debugId": debug_id,
+ }),
+ )
+ };
+ inject_pairs(
+ vec![
+ chunk(
+ entry_name,
+ &format!("import(\"./{lazy_name}\");"),
+ ENTRY_DEBUG_ID,
+ ),
+ chunk(lazy_name, lazy_code, LAZY_DEBUG_ID),
+ ],
+ Some(release_id),
+ )
+ .expect("Failed to inject pairs")
+}
+
+fn event_mode_hashes(pairs: Vec<SourcePair>) -> Vec<String> {
+ pairs
+ .into_iter()
+ .map(|pair| {
+ pair.into_upload(ReleaseMode::Event)
+ .expect("Failed to convert to SymbolSetUpload")
+ .content_hash
+ .expect("event mode always sets a content hash")
+ })
+ .collect()
+}
+
+#[test]
+fn test_event_mode_content_hash_ignores_chunk_file_names() {
+ let release = |release_id, entry_name, lazy_name| {
+ content_named_release(release_id, entry_name, lazy_name, "console.log(1);")
+ };
+
+ assert_eq!(
+ event_mode_hashes(release(
+ "release-a",
+ "index-C3e2Htc9.js",
+ "lazy-BrAf3own.js"
+ )),
+ event_mode_hashes(release(
+ "release-b",
+ "index-CSi0TbGB.js",
+ "lazy-CGeNrzqs.js"
+ ))
+ );
+}
+
+#[test]
+fn test_event_mode_content_hash_still_tracks_code_changes() {
+ let before = event_mode_hashes(content_named_release(
+ "release-a",
+ "index-C3e2Htc9.js",
+ "lazy-BrAf3own.js",
+ "console.log(1);",
+ ));
+ let after = event_mode_hashes(content_named_release(
+ "release-b",
+ "index-CSi0TbGB.js",
+ "lazy-CGeNrzqs.js",
+ "console.log(2);",
+ ));
+
+ assert_eq!(
+ before[0], after[0],
+ "the entry changed only in the lazy chunk's name"
+ );
+ assert_ne!(before[1], after[1], "the lazy chunk's code changed");
+}
+
+#[test]
+fn test_event_mode_upload_keeps_the_file_names() {
+ let pair = content_named_release(
+ "release-a",
+ "index-C3e2Htc9.js",
+ "lazy-BrAf3own.js",
+ "console.log(1);",
+ )
+ .into_iter()
+ .next()
+ .unwrap();
+ let (source, map) = (
+ pair.source.inner.content.clone(),
+ serde_json::to_string(&pair.sourcemap.inner.content).unwrap(),
+ );
+
+ let upload = pair
+ .into_upload(ReleaseMode::Event)
+ .expect("Failed to convert to SymbolSetUpload");
+ let stored: SourceAndMap = read_symbol_data(&upload.data).expect("Failed to read upload");
+
+ assert!(source.contains("./lazy-BrAf3own.js"));
+ assert_eq!(stored.minified_source, source);
+ assert_eq!(stored.sourcemap, map);
+}
+
#[test]
fn test_file_selection() {
// This does not work with glob patterns