: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(error-tracking): separate symbol set lookup and save keys (#59591)
Hugues Pouillotb501ad419860
diff --git a/rust/cymbal/src/langs/js.rs b/rust/cymbal/src/langs/js.rsindex 3a4e9c9c68a1..ec38f9ab886a 100644--- a/rust/cymbal/src/langs/js.rs+++ b/rust/cymbal/src/langs/js.rs@@ -107,8 +107,7 @@ impl RawJSFrame {}pub fn symbol_set_ref(&self) -> Option<String> {- // If we have a chunk ID for a frame, no matter where the data we save comes from, we save it with that- // chunk id as the ref.+ // Prefer the chunk id in frame metadata when present; persistence derives its keys separately.self.get_ref().ok().map(|r| r.to_string())}diff --git a/rust/cymbal/src/symbol_store/caching.rs b/rust/cymbal/src/symbol_store/caching.rsindex 3c886f890438..7f6555e7fdd7 100644--- a/rust/cymbal/src/symbol_store/caching.rs+++ b/rust/cymbal/src/symbol_store/caching.rs@@ -8,7 +8,7 @@ use crate::metric_consts::{STORE_CACHE_MISSES,};-use super::{Fetcher, Parser, Provider};+use super::{chunk_id::SymbolSetCacheKey, Fetcher, Parser, Provider};// This is a type-specific symbol provider layer, designed to// wrap some inner provider and provide a type-safe caching layer@@ -20,10 +20,10 @@ pub struct Caching<P> {impl<P> Caching<P>// This where clause exists exclusively to give more obvious compiler errors in cases where// the passed P doesn't cause Provider to be implemented for this Caching<P> - for example,-// if the P's P::Ref doesn't implement ToString+// if the P's P::Ref doesn't implement SymbolSetCacheKeywhereP: Fetcher + Parser<Source = P::Fetched, Err = <P as Fetcher>::Err>,- P::Ref: ToString + Send,+ P::Ref: SymbolSetCacheKey + Send,P::Fetched: Send,P::Set: Countable + Any + Send + Sync,{@@ -36,7 +36,7 @@ whereimpl<P> Provider for Caching<P>whereP: Fetcher + Parser<Source = P::Fetched, Err = <P as Fetcher>::Err>,- P::Ref: ToString + Send,+ P::Ref: SymbolSetCacheKey + Send,P::Fetched: Send,P::Set: Countable + Any + Send + Sync,{@@ -46,7 +46,7 @@ whereasync fn lookup(&self, team_id: i32, r: Self::Ref) -> Result<Arc<Self::Set>, Self::Err> {let mut cache = self.cache.lock().await;- let cache_key = format!("{}:{}", team_id, r.to_string());+ let cache_key = format!("{}:{}", team_id, r.symbol_set_cache_key());if let Some(set) = cache.get(&cache_key) {metrics::counter!(STORE_CACHE_HITS).increment(1);return Ok(set);@@ -169,3 +169,76 @@ impl Countable for Vec<u8> {self.len()}}++#[cfg(test)]+mod tests {+ use std::{+ convert::Infallible,+ sync::atomic::{AtomicUsize, Ordering},+ sync::Arc,+ };++ use async_trait::async_trait;+ use reqwest::Url;++ use super::*;+ use crate::symbol_store::chunk_id::OrChunkId;++ struct FakeProvider {+ fetches: Arc<AtomicUsize>,+ }++ #[async_trait]+ impl Fetcher for FakeProvider {+ type Ref = OrChunkId<Url>;+ type Fetched = Vec<u8>;+ type Err = Infallible;++ async fn fetch(&self, _team_id: i32, r: Self::Ref) -> Result<Self::Fetched, Self::Err> {+ self.fetches.fetch_add(1, Ordering::SeqCst);+ let data = match r {+ OrChunkId::Inner(_) => b"inner".to_vec(),+ OrChunkId::ChunkId(_) => b"chunk-id".to_vec(),+ OrChunkId::Both { .. } => b"both".to_vec(),+ };+ Ok(data)+ }+ }++ #[async_trait]+ impl Parser for FakeProvider {+ type Source = Vec<u8>;+ type Set = Vec<u8>;+ type Err = Infallible;++ async fn parse(&self, data: Self::Source) -> Result<Self::Set, Self::Err> {+ Ok(data)+ }+ }++ #[tokio::test]+ async fn caching_does_not_share_both_and_chunk_id_keys() {+ let fetches = Arc::new(AtomicUsize::new(0));+ let provider = FakeProvider {+ fetches: fetches.clone(),+ };+ let cache = Arc::new(Mutex::new(SymbolSetCache::new(1024)));+ let caching = Caching::new(provider, cache);++ let chunk_id = "chunk-id-1".to_string();+ let url = Url::parse("https://example.com/static/chunk.js").unwrap();++ let both = caching+ .lookup(1, OrChunkId::both(url, chunk_id.clone()))+ .await+ .unwrap();+ let chunk_only = caching+ .lookup(1, OrChunkId::<Url>::chunk_id(chunk_id))+ .await+ .unwrap();++ assert_eq!(both.as_ref(), b"both");+ assert_eq!(chunk_only.as_ref(), b"chunk-id");+ assert_eq!(fetches.load(Ordering::SeqCst), 2);+ }+}diff --git a/rust/cymbal/src/symbol_store/chunk_id.rs b/rust/cymbal/src/symbol_store/chunk_id.rsindex b0e73cb0db66..a7f3ffef4293 100644--- a/rust/cymbal/src/symbol_store/chunk_id.rs+++ b/rust/cymbal/src/symbol_store/chunk_id.rs@@ -6,6 +6,7 @@ use std::{use async_trait::async_trait;use bytes::Bytes;use metrics::counter;+use sha2::{Digest, Sha512};use sqlx::PgPool;use tracing::error;@@ -89,12 +90,12 @@ pub async fn load_symbol_set_data(// use a 0 variant enum to indicate their data is only available in the presence of a chunk ID, and the underlying// fetcher simply asserts `unreachable!()`.//-// Most of the "cleverness" of this layer is actually that the `Display` implementation of `OrChunkId`-// which returns the chunk ID if it's set, rather than the inner T's display implementation, which means-// that the saving and caching layers, or any other layers above this one that rely on Fetcher::Ref: ToString-// will use the chunk ID as the symbol set key, rather than the inner T's reference - which makes things like-// deleting all saved frame resolution results for any frame with a chunk ID that were seen before the chunk id-// symbol data was uploaded, possible using the chunk id directly.+// Layers above this one use dedicated ref-derivation traits:+// - Caching and concurrency use `SymbolSetCacheKey`, which keeps the `Inner`, `ChunkId`,+// and `Both` namespaces distinct so attacker-controlled refs cannot poison each other.+// - The `Saving` persistence layer uses `SymbolSetKey`, which separates+// the lookup keys (chunk id first, then URL) from the save key (URL when present).+// See the trait's docs for why those are kept distinct.#[async_trait]impl<P> Fetcher for ChunkIdFetcher<P>where@@ -198,9 +199,12 @@ where}}-// The "cleverness" mentioned above - any time an OrChunkId is used as a symbol set reference,-// and the chunk id is set, it will be used as the key when calling ToString, rather than the-// inner T's display impl+// `Display` is the human-readable identity of a ref, used by log lines and resolved frame+// metadata. For Both, we surface the chunk id because it's the more meaningful identifier+// across frames carrying both a URL and a chunk id.+//+// The persistence and caching layers do NOT use this — see `SymbolSetKey` and+// `SymbolSetCacheKey` below for why.impl<R> Display for OrChunkId<R>whereR: Display,@@ -214,6 +218,99 @@ where}}+// `SymbolSetCacheKey` is the in-memory cache / concurrency identity. Unlike `Display`, it+// must keep `Both(id, inner)` distinct from bare `ChunkId(id)`: a `Both` lookup may fall back+// to fetching attacker-controlled URL data when the chunk id is missing, and caching that under+// the bare chunk-id key would transiently poison future chunk-id-only lookups.+pub trait SymbolSetCacheKey {+ fn symbol_set_cache_key(&self) -> String;+}++fn hashed_symbol_set_cache_key(prefix: &str, parts: &[&str]) -> String {+ let mut hasher = Sha512::new();+ for part in parts {+ hasher.update(part.len().to_be_bytes());+ hasher.update(part.as_bytes());+ }+ format!("{}:{:x}", prefix, hasher.finalize())+}++impl<R> SymbolSetCacheKey for OrChunkId<R>+where+ R: Display,+{+ fn symbol_set_cache_key(&self) -> String {+ match self {+ OrChunkId::Inner(inner) => hashed_symbol_set_cache_key("inner", &[&inner.to_string()]),+ OrChunkId::ChunkId(id) => hashed_symbol_set_cache_key("chunk-id", &[id]),+ OrChunkId::Both { inner, id } => {+ hashed_symbol_set_cache_key("both", &[id, &inner.to_string()])+ }+ }+ }+}++impl SymbolSetCacheKey for reqwest::Url {+ fn symbol_set_cache_key(&self) -> String {+ hashed_symbol_set_cache_key("inner", &[self.as_str()])+ }+}++// `SymbolSetKey` separates the DB lookup keys from the DB save key.+//+// The capture pipeline can receive a frame carrying both an attacker-controlled URL and an+// arbitrary chunk id. Persisting that fetch under the chunk id namespace would let the+// capture path squat rows that the authenticated upload API (which always keys by chunk id)+// would later want to write — letting unauthenticated capture traffic pre-empt or be+// confused with authenticated uploads.+//+// To prevent that, capture-driven writes are keyed by the URL the bytes were fetched from,+// while upload-driven writes stay keyed by chunk id. The two writers can no longer target+// the same row. Lookups still try the chunk id first (so an upload-API row keyed by chunk+// id is preferred over a capture-cached row keyed by URL), then fall back to the URL.+//+// `save_ref` is `None` for a bare `ChunkId` ref — there is no URL to fetch from, so there's+// nothing meaningful to persist, and we refuse to write a row keyed by a chunk id we never+// fetched data for.+pub trait SymbolSetKey {+ fn lookup_refs(&self) -> Vec<String>;+ fn save_ref(&self) -> Option<String>;+}++impl<R> SymbolSetKey for OrChunkId<R>+where+ R: Display,+{+ fn lookup_refs(&self) -> Vec<String> {+ match self {+ OrChunkId::Inner(inner) => vec![inner.to_string()],+ OrChunkId::ChunkId(id) => vec![id.clone()],+ OrChunkId::Both { inner, id } => vec![id.clone(), inner.to_string()],+ }+ }++ fn save_ref(&self) -> Option<String> {+ match self {+ OrChunkId::Inner(inner) => Some(inner.to_string()),+ OrChunkId::Both { inner, .. } => Some(inner.to_string()),+ OrChunkId::ChunkId(_) => None,+ }+ }+}++// `Url` standalone behaves exactly like `OrChunkId::Inner(url)` — a single self-keyed ref+// with no chunk-id alternative. Used directly by unit tests that wrap `SourcemapProvider`+// in `Saving` without an intervening `ChunkIdFetcher`.+impl SymbolSetKey for reqwest::Url {+ fn lookup_refs(&self) -> Vec<String> {+ vec![self.to_string()]+ }++ fn save_ref(&self) -> Option<String> {+ Some(self.to_string())+ }+}+impl<R> OrChunkId<R> {pub fn inner(inner: R) -> Self {Self::Inner(inner)@@ -252,7 +349,7 @@ mod test {langs::js::RawJSFrame,symbol_store::{apple::AppleProvider,- chunk_id::{ChunkIdFetcher, OrChunkId},+ chunk_id::{ChunkIdFetcher, OrChunkId, SymbolSetCacheKey},hermesmap::HermesMapProvider,proguard::ProguardProvider,saving::SymbolSetRecord,@@ -288,6 +385,20 @@ mod test {.unwrap()}+ #[test]+ fn symbol_set_cache_key_keeps_ref_namespaces_distinct() {+ let chunk_id = Uuid::now_v7().to_string();+ let url = Url::parse("https://example.com/static/chunk.js").unwrap();++ let both = OrChunkId::both(url.clone(), chunk_id.clone()).symbol_set_cache_key();+ let chunk_only = OrChunkId::<Url>::chunk_id(chunk_id).symbol_set_cache_key();+ let inner_only = OrChunkId::inner(url).symbol_set_cache_key();++ assert_ne!(both, chunk_only);+ assert_ne!(both, inner_only);+ assert_ne!(chunk_only, inner_only);+ }+fn get_example_frame() -> RawJSFrame {let event: ClickHouseEvent = serde_json::from_str(EXAMPLE_EXCEPTION).unwrap();let mut props: RawErrProps = serde_json::from_str(&event.properties.unwrap()).unwrap();diff --git a/rust/cymbal/src/symbol_store/concurrency.rs b/rust/cymbal/src/symbol_store/concurrency.rsindex 0956df465cdf..4d596efacd0b 100644--- a/rust/cymbal/src/symbol_store/concurrency.rs+++ b/rust/cymbal/src/symbol_store/concurrency.rs@@ -6,7 +6,7 @@ use std::{use async_trait::async_trait;use tokio::sync::{Mutex, OwnedMutexGuard};-use super::Provider;+use super::{chunk_id::SymbolSetCacheKey, Provider};// Limits the number of concurrent lookups// for a given symbol set to 1. Note this places@@ -64,14 +64,16 @@ impl<P> AtMostOne<P> {impl<P> Provider for AtMostOne<P>whereP: Provider,- P::Ref: ToString + Send,+ P::Ref: SymbolSetCacheKey + Send,{type Ref = P::Ref;type Set = P::Set;type Err = P::Err;async fn lookup(&self, team_id: i32, r: Self::Ref) -> Result<Arc<Self::Set>, Self::Err> {- let lock = self.acquire(format!("{}:{}", team_id, r.to_string())).await;+ let lock = self+ .acquire(format!("{}:{}", team_id, r.symbol_set_cache_key()))+ .await;let result = self.inner.lookup(team_id, r).await;drop(lock);resultdiff --git a/rust/cymbal/src/symbol_store/saving.rs b/rust/cymbal/src/symbol_store/saving.rsindex 2856f60cc5e6..06044a155c69 100644--- a/rust/cymbal/src/symbol_store/saving.rs+++ b/rust/cymbal/src/symbol_store/saving.rs@@ -17,7 +17,7 @@ use crate::{SYMBOL_SET_FETCH_RETRY, SYMBOL_SET_SAVED,},posthog_utils::{capture_symbol_set_deleted, capture_symbol_set_saved},- symbol_store::BlobClient,+ symbol_store::{chunk_id::SymbolSetKey, BlobClient},};use super::{Fetcher, Parser};@@ -67,11 +67,15 @@ pub struct SymbolSetRecord {// pass the information necessary to store the underlying data between the fetch and parse stages,// (to avoid saving data we can't parse). The payload is held as `Bytes` so it can be cheaply// cloned (refcount bump) when the parse and save paths both need a reference.+//+// `save_ref` is the DB key to insert under when persisting a fresh fetch. It is `None` when+// the original ref had no save target (a bare `OrChunkId::ChunkId`, which has no URL to+// fetch from). When `storage_ptr` is `Some`, `save_ref` is irrelevant — parse won't persist.pub struct Saveable {pub data: Bytes,pub storage_ptr: Option<String>, // This is None if we still need to save this datapub team_id: i32,- pub set_ref: String,+ pub save_ref: Option<String>,}impl<F> Saving<F> {@@ -185,28 +189,43 @@ impl<F> Saving<F> {impl<F> Fetcher for Saving<F>whereF: Fetcher<Fetched = Bytes, Err = ResolveError>,- F::Ref: ToString + Send,+ F::Ref: SymbolSetKey + Send,{type Ref = F::Ref;type Fetched = Saveable;type Err = F::Err;async fn fetch(&self, team_id: i32, r: Self::Ref) -> Result<Self::Fetched, Self::Err> {- let set_ref = r.to_string();- info!("Fetching symbol set data for {}", set_ref);+ let lookup_refs = r.lookup_refs();+ let save_ref = r.save_ref();metrics::counter!(SYMBOL_SET_DB_FETCHES).increment(1);- if let Some(mut record) = SymbolSetRecord::load(&self.pool, team_id, &set_ref).await? {- metrics::counter!(SYMBOL_SET_DB_HITS).increment(1);+ // Try lookup keys in priority order — for an `OrChunkId::Both`, this means the chunk+ // id (authoritative, upload-API namespace) wins over the URL (capture-cached). A stale+ // failure under one key falls through to the next; a fresh failure or data short-circuits.+ // `DB_HITS` is bumped at most once per fetch (on the first row found) regardless of+ // how many lookup refs we probe — multi-ref lookups must not inflate the counter.+ let mut hit_counted = false;+ for lookup_ref in &lookup_refs {+ info!("Fetching symbol set data for {}", lookup_ref);+ let Some(mut record) = SymbolSetRecord::load(&self.pool, team_id, lookup_ref).await?+ else {+ continue;+ };+ if !hit_counted {+ metrics::counter!(SYMBOL_SET_DB_HITS).increment(1);+ hit_counted = true;+ }+if let Some(storage_ptr) = record.storage_ptr.clone() {- info!("Found s3 saved symbol set data for {}", set_ref);+ info!("Found s3 saved symbol set data for {}", lookup_ref);record.set_last_used(&self.pool).await?;let data = match self.s3_client.get(&self.bucket, &storage_ptr).await {Ok(Some(data)) => data,Ok(None) => {warn!("Storage pointer points to a record that doesn't exist");record.delete(&self.pool).await?;- return Err(FrameError::MissingChunkIdData(set_ref).into());+ return Err(FrameError::MissingChunkIdData(lookup_ref.clone()).into());}// Otherwise, if we just failed to talk to s3 for some reason, treat it as an unhandled error, and dieErr(err) => return Err(err.into()),@@ -216,13 +235,15 @@ wheredata,storage_ptr: Some(storage_ptr),team_id,- set_ref,+ save_ref: save_ref.clone(),});- } else if record+ }++ if record.last_used.is_some_and(|l| Utc::now() - l < chrono::Duration::days(1)){- info!("Found recent symbol set error for {}", set_ref);+ info!("Found recent symbol set error for {}", lookup_ref);// We tried less than a day ago to get the set data, and failed, so bail out// with the stored error. We unwrap here because we should never store a "no set"// row without also storing the error, and if we do, we want to panic, but we@@ -240,7 +261,8 @@ where.map_err(UnhandledError::from)?;return Err(ResolveError::ResolutionError(error));}- info!("Found stale symbol set error for {}", set_ref);++ info!("Found stale symbol set error for {}", lookup_ref);// We last tried to get the symbol set more than a day ago, so we should try againmetrics::counter!(SYMBOL_SET_FETCH_RETRY).increment(1);}@@ -250,18 +272,22 @@ wherematch self.inner.fetch(team_id, r).await {// NOTE: We don't save the data here, because we want to save it only after parsingOk(data) => {- info!("Inner fetched symbol set data for {}", set_ref);+ info!("Inner fetched symbol set data");Ok(Saveable {data,storage_ptr: None,team_id,- set_ref,+ save_ref,})}Err(ResolveError::ResolutionError(e)) => {- // But if we failed to get any data, we save that fact- self.save_no_data(team_id, set_ref, &e).await?;- return Err(ResolveError::ResolutionError(e));+ // Only record a failure when we actually have a save key — bare chunk-id refs+ // never write to the DB (otherwise capture traffic could squat the upload-API+ // namespace with failure rows).+ if let Some(save_ref) = save_ref {+ self.save_no_data(team_id, save_ref, &e).await?;+ }+ Err(ResolveError::ResolutionError(e))}Err(e) => Err(e), // If some non-resolution error occurred, we just bail out}@@ -283,7 +309,7 @@ wheredata: bytes,storage_ptr,team_id,- set_ref,+ save_ref,} = data;// On the loaded-from-S3 path we never need to save the bytes back, so we hand them@@ -297,18 +323,22 @@ wherematch self.inner.parse(bytes).await {Ok(s) => {- info!("Parsed symbol set data for {}", set_ref);- if let Some(bytes_to_save) = bytes_to_save {- self.save_data(team_id, set_ref, bytes_to_save).await?;+ info!("Parsed symbol set data");+ if let (Some(bytes_to_save), Some(save_ref)) = (bytes_to_save, &save_ref) {+ self.save_data(team_id, save_ref.clone(), bytes_to_save)+ .await?;}Ok(s)}Err(ResolveError::ResolutionError(e)) => {- info!("Failed to parse symbol set data for {}", set_ref);+ info!("Failed to parse symbol set data");if storage_ptr.is_none() {- // Save fresh parse failures to prevent refetching for a day, but never- // replace an existing uploaded blob with a parser error.- self.save_no_data(team_id, set_ref, &e).await?;+ if let Some(save_ref) = save_ref {+ // Save fresh parse failures to prevent refetching for a day, but never+ // replace an existing uploaded blob with a parser error, and never+ // write to a namespace we don't own (bare chunk-id refs have no save key).+ self.save_no_data(team_id, save_ref, &e).await?;+ }}Err(ResolveError::ResolutionError(e))}