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.

perf(error-tracking): cache symbol set failures in memory (#67851)

Catalin Irimieeb79d7586177
diff --git a/rust/cymbal/src/core/config.rs b/rust/cymbal/src/core/config.rs
index 087f5e122373..bf1f7950d11d 100644
--- a/rust/cymbal/src/core/config.rs
+++ b/rust/cymbal/src/core/config.rs
@@ -62,6 +62,13 @@ pub struct ResolverConfig {
#[envconfig(default = "300")]
pub frame_unresolved_ttl_seconds: u64,
+ // TTL for the in-memory negative cache of symbol-set lookup failures in the `Saving` layer.
+ // Like `frame_unresolved_ttl_seconds`, this is kept short: a failure record can become
+ // resolvable the moment a user uploads the missing symbols, so a cached negative result
+ // must not outlive that upload by long.
+ #[envconfig(default = "300")]
+ pub symbol_set_negative_cache_ttl_seconds: u64,
+
// Maximum number of lines of pre and post context to get per frame
#[envconfig(default = "15")]
pub context_line_count: usize,
diff --git a/rust/cymbal/src/core/metric_consts.rs b/rust/cymbal/src/core/metric_consts.rs
index 5b211721fd39..f2b1308a6c51 100644
--- a/rust/cymbal/src/core/metric_consts.rs
+++ b/rust/cymbal/src/core/metric_consts.rs
@@ -15,6 +15,7 @@ pub const SYMBOL_SET_DB_MISSES: &str = "cymbal_symbol_set_db_misses";
pub const SYMBOL_SET_SAVED: &str = "cymbal_symbol_set_saved";
pub const SAVED_SYMBOL_SET_LOADED: &str = "cymbal_saved_symbol_set_loaded";
pub const SAVED_SYMBOL_SET_ERROR_RETURNED: &str = "cymbal_saved_symbol_set_error_returned";
+pub const SYMBOL_SET_NEGATIVE_CACHE_HIT: &str = "cymbal_symbol_set_negative_cache_hit";
pub const SYMBOL_SET_FETCH_RETRY: &str = "cymbal_symbol_set_fetch_retry";
pub const FRAME_RESOLVED: &str = "cymbal_frame_resolved";
pub const FRAME_CACHE_HITS: &str = "cymbal_frame_cache_hits";
diff --git a/rust/cymbal/src/core/resolver.rs b/rust/cymbal/src/core/resolver.rs
index f7f754d99be2..50b2ba92e9f5 100644
--- a/rust/cymbal/src/core/resolver.rs
+++ b/rust/cymbal/src/core/resolver.rs
@@ -73,6 +73,7 @@ pub fn build_catalog(
s3_client.clone(),
config.object_storage_bucket.clone(),
config.ss_prefix.clone(),
+ std::time::Duration::from_secs(config.symbol_set_negative_cache_ttl_seconds),
);
let smp_caching = Caching::new(smp_saving, ss_cache.clone());
// We want to fetch each sourcemap from the outside world exactly once,
diff --git a/rust/cymbal/src/core/symbolication/symbol/local.rs b/rust/cymbal/src/core/symbolication/symbol/local.rs
index 996fc5bd1d22..05765040c690 100644
--- a/rust/cymbal/src/core/symbolication/symbol/local.rs
+++ b/rust/cymbal/src/core/symbolication/symbol/local.rs
@@ -324,6 +324,7 @@ mod test {
client.clone(),
config.object_storage_bucket.clone(),
config.ss_prefix.clone(),
+ std::time::Duration::from_secs(config.symbol_set_negative_cache_ttl_seconds),
);
let hmp = ChunkIdFetcher::new(
diff --git a/rust/cymbal/src/core/symbolication/symbol_store/saving.rs b/rust/cymbal/src/core/symbolication/symbol_store/saving.rs
index cb02699cbf7b..10f1786aab6d 100644
--- a/rust/cymbal/src/core/symbolication/symbol_store/saving.rs
+++ b/rust/cymbal/src/core/symbolication/symbol_store/saving.rs
@@ -4,6 +4,7 @@ use async_trait::async_trait;
use bytes::Bytes;
use chrono::{DateTime, Duration, Utc};
+use moka::future::{Cache, CacheBuilder};
use sha2::{Digest, Sha512};
use sqlx::PgPool;
use tracing::{error, info, warn};
@@ -15,7 +16,7 @@ use crate::{
metric_consts::{
FRAME_RESOLUTION_RESULTS_DELETED, SAVED_SYMBOL_SET_ERROR_RETURNED, SAVED_SYMBOL_SET_LOADED,
SAVE_SYMBOL_SET, SYMBOL_SET_DB_FETCHES, SYMBOL_SET_DB_HITS, SYMBOL_SET_DB_MISSES,
- SYMBOL_SET_FETCH_RETRY, SYMBOL_SET_SAVED,
+ SYMBOL_SET_FETCH_RETRY, SYMBOL_SET_NEGATIVE_CACHE_HIT, SYMBOL_SET_SAVED,
},
symbolication::symbol_store::{chunk_id::SymbolSetKey, BlobClient},
};
@@ -24,6 +25,13 @@ use super::{Fetcher, Parser};
const MAX_REF_BYTES: usize = 2048;
+// Total byte budget for the in-memory negative cache. Refs and failure reasons are
+// event-controlled (a JS frame's ref is its source URL, and a `NoSourcemap` failure embeds that
+// URL), so the cache is weighed by the byte size of each key+value and bounded by total weight
+// rather than entry count — a flood of unique, long URLs can't grow it without bound. 64 MiB is
+// ample for the working set of recently-failed symbol sets. TTL is the primary staleness bound.
+const NEGATIVE_CACHE_MAX_WEIGHT: u64 = 64 * 1024 * 1024;
+
// We truncate the reference to resolve an issue with the maximum size in a BTRee index on Postgres
// TODO: update model to use a hash of the reference instead
fn truncate_ref(s: &str) -> &str {
@@ -46,6 +54,16 @@ pub struct Saving<F> {
pool: PgPool,
bucket: String,
prefix: String,
+ // In-memory negative cache of recently-failed lookups, keyed per (team_id, truncated
+ // lookup_ref). It holds only the serialized `failure_reason` of a *stored* failure record
+ // (never transient DB/S3/network errors), so a hit can rebuild the exact stored error
+ // without re-reading Postgres. The DB stays the source of truth; this only short-circuits
+ // the repeated negative reads for sets we already know failed recently. Keyed per
+ // individual ref (not the whole `OrChunkId`) so the chunk-id-wins priority in `fetch` is
+ // preserved, and by the *truncated* ref so the key-space matches the DB (which truncates
+ // before writing) and stays bounded against long, event-controlled URLs. The cache TTL
+ // bounds staleness after a user uploads the missing symbols.
+ negative_cache: Cache<(i32, String), String>,
}
// A record of an attempt to fetch a symbol set. If it succeeded, it will have a storage pointer
@@ -85,13 +103,24 @@ impl<F> Saving<F> {
s3_client: Arc<dyn BlobClient>,
bucket: String,
prefix: String,
+ negative_cache_ttl: std::time::Duration,
) -> Self {
+ let negative_cache = CacheBuilder::new(NEGATIVE_CACHE_MAX_WEIGHT)
+ .weigher(|(_, ref_key): &(i32, String), reason: &String| {
+ // Bound by the bytes actually held; saturate rather than wrap for huge values.
+ (ref_key.len() + reason.len())
+ .try_into()
+ .unwrap_or(u32::MAX)
+ })
+ .time_to_live(negative_cache_ttl)
+ .build();
Self {
inner,
pool,
s3_client,
bucket,
prefix,
+ negative_cache,
}
}
@@ -120,7 +149,16 @@ impl<F> Saving<F> {
};
self.s3_client.put(&self.bucket, &key, data).await?;
- if !record.save_data_if_missing(&self.pool).await? {
+ let wrote_new_data = record.save_data_if_missing(&self.pool).await?;
+ // Reaching here means real data is now present for this ref (we just wrote it, or an
+ // existing row already had it), so any negative-cache entry for it is stale — drop it
+ // so lookups stop returning the old failure before the TTL would expire it. This also
+ // clears entries a concurrent failing lookup for the same URL save key may have added
+ // while we were fetching/parsing.
+ self.negative_cache
+ .invalidate(&Self::negative_cache_key(team_id, &record.set_ref))
+ .await;
+ if !wrote_new_data {
warn!(
"Not overwriting existing symbol set data for {} after dynamic fetch",
record.set_ref
@@ -165,17 +203,26 @@ impl<F> Saving<F> {
) -> Result<(), UnhandledError> {
info!("Saving symbol set error for {}", set_ref);
let start = common_metrics::timing_guard(SAVE_SYMBOL_SET, &[]).label("data", "false");
+ let failure_reason = serde_json::to_string(&reason)?;
let mut record = SymbolSetRecord {
id: Uuid::now_v7(),
team_id,
- set_ref,
+ set_ref: set_ref.clone(),
storage_ptr: None,
- failure_reason: Some(serde_json::to_string(&reason)?),
+ failure_reason: Some(failure_reason.clone()),
created_at: Utc::now(),
content_hash: None,
last_used: Some(Utc::now()),
};
- record.save_failure(&self.pool).await?;
+ // Only prime the negative cache if the failure was actually persisted. When
+ // `save_failure` is a no-op — a row with real symbol data already exists for this ref
+ // (e.g. an upload raced ahead of us) — caching the failure would shadow that data until
+ // TTL, so we must not.
+ if record.save_failure(&self.pool).await? {
+ self.negative_cache
+ .insert(Self::negative_cache_key(team_id, &set_ref), failure_reason)
+ .await;
+ }
start.label("outcome", "success").fin();
Ok(())
}
@@ -183,6 +230,35 @@ impl<F> Saving<F> {
fn add_prefix(&self, key: String) -> String {
format!("{}/{}", self.prefix, key)
}
+
+ // Negative-cache key for a ref. Truncated to match the DB key-space (the DB truncates before
+ // writing/looking up) and to keep keys bounded against long, event-controlled URLs.
+ fn negative_cache_key(team_id: i32, set_ref: &str) -> (i32, String) {
+ (team_id, truncate_ref(set_ref).to_string())
+ }
+
+ // Probe the negative cache for a single lookup ref, rebuilding the stored error on a hit
+ // exactly as the DB recent-failure path does (deserialize the stored `failure_reason` into
+ // a `FrameError`). Called per ref, interleaved with the DB lookup in `fetch`, so a
+ // higher-priority ref's real data is always found before a lower-priority ref's cached
+ // failure — preserving the chunk-id-wins order.
+ async fn negative_cache_lookup(
+ &self,
+ team_id: i32,
+ lookup_ref: &str,
+ ) -> Result<Option<ResolveError>, UnhandledError> {
+ let Some(failure_reason) = self
+ .negative_cache
+ .get(&Self::negative_cache_key(team_id, lookup_ref))
+ .await
+ else {
+ return Ok(None);
+ };
+ metrics::counter!(SYMBOL_SET_NEGATIVE_CACHE_HIT).increment(1);
+ let error: FrameError =
+ serde_json::from_str(&failure_reason).map_err(UnhandledError::from)?;
+ Ok(Some(ResolveError::ResolutionError(error)))
+ }
}
#[async_trait]
@@ -198,6 +274,7 @@ where
async fn fetch(&self, team_id: i32, r: Self::Ref) -> Result<Self::Fetched, Self::Err> {
let lookup_refs = r.lookup_refs();
let save_ref = r.save_ref();
+
metrics::counter!(SYMBOL_SET_DB_FETCHES).increment(1);
// Try lookup keys in priority order — for an `OrChunkId::Both`, this means the chunk
@@ -207,6 +284,16 @@ where
// 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 {
+ // Consult the in-memory negative cache for this ref before the DB read. It only ever
+ // holds stored failures (never transient errors), so a hit reproduces the same error
+ // the DB recent-failure path would, without the SELECT + deserialize + log. Checked
+ // per ref inside the priority loop so a higher-priority ref's real data is always
+ // found first — a cached failure can only short-circuit once every earlier ref has
+ // missed both the cache and the DB.
+ if let Some(error) = self.negative_cache_lookup(team_id, lookup_ref).await? {
+ return Err(error);
+ }
+
info!("Fetching symbol set data for {}", lookup_ref);
let Some(mut record) = SymbolSetRecord::load(&self.pool, team_id, lookup_ref).await?
else {
@@ -249,16 +336,23 @@ where
// row without also storing the error, and if we do, we want to panic, but we
// also want to log an error
metrics::counter!(SAVED_SYMBOL_SET_ERROR_RETURNED).increment(1);
- if record.failure_reason.is_none() {
+ let Some(failure_reason) = record.failure_reason.clone() else {
error!("Found a record with no data and no error: {:?}", record);
panic!("Found a record with no data and no error");
- }
+ };
+ // Cache this known-recent failure so subsequent lookups for the same ref skip
+ // the DB read. Keyed by the individual ref we hit, preserving lookup priority.
+ self.negative_cache
+ .insert(
+ Self::negative_cache_key(team_id, lookup_ref),
+ failure_reason.clone(),
+ )
+ .await;
// TODO - this can fail due to changes in how we serialise, or changes in
// the error type - and we should handle that by deleting the symbol record
// and re-fetching, I think (we don't need to cleanup s3 since it's a failure
// case, there is no saved data).
- let error = serde_json::from_str(&record.failure_reason.unwrap())
- .map_err(UnhandledError::from)?;
+ let error = serde_json::from_str(&failure_reason).map_err(UnhandledError::from)?;
return Err(ResolveError::ResolutionError(error));
}
@@ -469,7 +563,12 @@ impl SymbolSetRecord {
Ok(false)
}
- pub async fn save_failure<'c, E>(&mut self, e: E) -> Result<(), UnhandledError>
+ // Returns whether a failure row was actually written. The upsert is a no-op (returns
+ // `false`) when a row already exists with a `storage_ptr` — i.e. real symbol data is present
+ // — because the `WHERE storage_ptr IS NULL` guard refuses to clobber it. Callers must not
+ // treat a no-op as a stored failure (e.g. must not cache it), since the DB source of truth
+ // still holds usable data for that ref.
+ pub async fn save_failure<'c, E>(&mut self, e: E) -> Result<bool, UnhandledError>
where
E: sqlx::Executor<'c, Database = sqlx::Postgres>,
{
@@ -495,9 +594,10 @@ impl SymbolSetRecord {
{
self.id = id;
metrics::counter!(SYMBOL_SET_SAVED).increment(1);
+ return Ok(true);
}
- Ok(())
+ Ok(false)
}
pub async fn delete<'c, E>(&mut self, e: E) -> Result<(), UnhandledError>
@@ -630,6 +730,7 @@ mod test {
Arc::new(client),
config.object_storage_bucket.clone(),
config.ss_prefix.clone(),
+ std::time::Duration::from_secs(config.symbol_set_negative_cache_ttl_seconds),
);
let test_url = Url::parse(&server.url(CHUNK_PATH.to_string())).unwrap();
@@ -694,6 +795,7 @@ mod test {
Arc::new(client),
config.object_storage_bucket.clone(),
config.ss_prefix.clone(),
+ std::time::Duration::from_secs(config.symbol_set_negative_cache_ttl_seconds),
);
saving_smp
@@ -738,6 +840,7 @@ mod test {
Arc::new(client),
config.object_storage_bucket.clone(),
config.ss_prefix.clone(),
+ std::time::Duration::from_secs(config.symbol_set_negative_cache_ttl_seconds),
);
let test_url = Url::parse(&server.url(CHUNK_PATH.to_string())).unwrap();
@@ -788,6 +891,7 @@ mod test {
Arc::new(client),
config.object_storage_bucket.clone(),
config.ss_prefix.clone(),
+ std::time::Duration::from_secs(config.symbol_set_negative_cache_ttl_seconds),
);
let test_url = Url::parse(&server.url(CHUNK_PATH.to_string())).unwrap();
@@ -851,6 +955,7 @@ mod test {
Arc::new(client),
config.object_storage_bucket.clone(),
config.ss_prefix.clone(),
+ std::time::Duration::from_secs(config.symbol_set_negative_cache_ttl_seconds),
);
saving_smp.lookup(0, test_url.clone()).await.unwrap_err();
@@ -863,4 +968,411 @@ mod test {
assert_eq!(record.storage_ptr.as_deref(), Some(storage_ptr.as_str()));
assert!(record.failure_reason.is_none());
}
+
+ #[sqlx::test(migrations = "./tests/test_migrations")]
+ async fn test_negative_cache_short_circuits_db(db: PgPool) {
+ let server = MockServer::start();
+
+ let mut config = ResolverConfig::init_with_defaults().unwrap();
+ config.object_storage_bucket = "test-bucket".to_string();
+ config.ss_prefix = "test-prefix".to_string();
+ config.allow_internal_ips = true;
+
+ let source_mock = server.mock(|when, then| {
+ when.method("GET").path(CHUNK_PATH);
+ then.status(404);
+ });
+
+ let client = MockS3Client::default();
+ let smp = SourcemapProvider::new(&config);
+ let saving_smp = Saving::new(
+ smp,
+ db.clone(),
+ Arc::new(client),
+ config.object_storage_bucket.clone(),
+ config.ss_prefix.clone(),
+ std::time::Duration::from_secs(config.symbol_set_negative_cache_ttl_seconds),
+ );
+
+ let test_url = Url::parse(&server.url(CHUNK_PATH.to_string())).unwrap();
+
+ // First attempt fails, persists the failure to Postgres, and primes the negative cache.
+ saving_smp.lookup(0, test_url.clone()).await.unwrap_err();
+ source_mock.assert_hits(1);
+
+ // Delete the stored failure row out from under the resolver. If the second lookup still
+ // returns the failure, it can only have come from the in-memory negative cache — proof
+ // the DB read was skipped entirely.
+ let mut record = SymbolSetRecord::load(&db, 0, test_url.as_ref())
+ .await
+ .unwrap()
+ .unwrap();
+ record.delete(&db).await.unwrap();
+ assert!(SymbolSetRecord::load(&db, 0, test_url.as_ref())
+ .await
+ .unwrap()
+ .is_none());
+
+ saving_smp.lookup(0, test_url.clone()).await.unwrap_err();
+ // Still no second upstream hit, and the DB no longer holds the row.
+ source_mock.assert_hits(1);
+ }
+
+ #[sqlx::test(migrations = "./tests/test_migrations")]
+ async fn test_transient_errors_are_not_cached(db: PgPool) {
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ use async_trait::async_trait;
+
+ use crate::{error::UnhandledError, symbolication::symbol_store::Fetcher};
+
+ // Inner fetcher that always fails with a *transient* (non-resolution) error and counts
+ // how many times it was called.
+ struct FlakyFetcher {
+ fetches: Arc<std::sync::atomic::AtomicUsize>,
+ }
+
+ #[async_trait]
+ impl Fetcher for FlakyFetcher {
+ type Ref = Url;
+ type Fetched = Bytes;
+ type Err = crate::error::ResolveError;
+
+ async fn fetch(
+ &self,
+ _team_id: i32,
+ _r: Self::Ref,
+ ) -> Result<Self::Fetched, Self::Err> {
+ self.fetches.fetch_add(1, Ordering::SeqCst);
+ Err(UnhandledError::Other("transient boom".to_string()).into())
+ }
+ }
+
+ let fetches = Arc::new(AtomicUsize::new(0));
+ let saving = Saving::new(
+ FlakyFetcher {
+ fetches: fetches.clone(),
+ },
+ db.clone(),
+ Arc::new(MockS3Client::default()),
+ "test-bucket".to_string(),
+ "test-prefix".to_string(),
+ std::time::Duration::from_secs(300),
+ );
+
+ let url = Url::parse("https://example.com/static/app.js").unwrap();
+
+ // Two fetches: a transient error must never be cached, so the inner fetcher is reached
+ // both times (the second isn't short-circuited by the negative cache). `Saveable` (the
+ // Ok type) isn't `Debug`, so match rather than `unwrap_err`.
+ assert!(saving.fetch(0, url.clone()).await.is_err());
+ assert!(saving.fetch(0, url.clone()).await.is_err());
+ assert_eq!(fetches.load(Ordering::SeqCst), 2);
+ }
+
+ #[sqlx::test(migrations = "./tests/test_migrations")]
+ async fn test_uploaded_chunk_id_data_wins_over_cached_url_failure(db: PgPool) {
+ use crate::symbolication::symbol_store::{
+ chunk_id::{ChunkIdFetcher, OrChunkId},
+ Fetcher,
+ };
+
+ // Regression: for an `OrChunkId::Both`, a cached failure under the (lower-priority) URL
+ // must never short-circuit ahead of real data uploaded under the (higher-priority)
+ // chunk id. The cache is probed per ref inside the priority loop, so the chunk-id row is
+ // found before the URL cache entry is ever consulted.
+ let mut config = ResolverConfig::init_with_defaults().unwrap();
+ config.object_storage_bucket = "test-bucket".to_string();
+ config.ss_prefix = "test-prefix".to_string();
+
+ let chunk_id = Uuid::now_v7().to_string();
+ let url = Url::parse("https://example.com/static/app.js").unwrap();
+ let storage_ptr = "symbolsets/uploaded".to_string();
+
+ // Uploaded symbol data, keyed by chunk id.
+ let mut record = SymbolSetRecord {
+ id: Uuid::now_v7(),
+ team_id: 0,
+ set_ref: chunk_id.clone(),
+ storage_ptr: Some(storage_ptr.clone()),
+ failure_reason: None,
+ created_at: Utc::now(),
+ content_hash: Some("fake-hash".to_string()),
+ last_used: Some(Utc::now()),
+ };
+ record.save(&db).await.unwrap();
+
+ // `Saving::fetch` handles saved lookup refs itself: it loads the chunk-id row and reads
+ // the blob via its OWN s3 client, without delegating to the inner ChunkIdFetcher. So the
+ // S3 expectation must live on the Saving-layer client; the ChunkIdFetcher's client is
+ // never exercised on this path.
+ let mut saving_client = MockS3Client::default();
+ saving_client
+ .expect_get()
+ .with(
+ predicate::eq(config.object_storage_bucket.clone()),
+ predicate::eq(storage_ptr.clone()),
+ )
+ .returning(|_, _| Ok(Some(Bytes::from(get_symbol_data_bytes()))));
+
+ let chunk_id_smp = ChunkIdFetcher::new(
+ SourcemapProvider::new(&config),
+ Arc::new(MockS3Client::default()),
+ db.clone(),
+ config.object_storage_bucket.clone(),
+ );
+ let saving = Saving::new(
+ chunk_id_smp,
+ db.clone(),
+ Arc::new(saving_client),
+ config.object_storage_bucket.clone(),
+ config.ss_prefix.clone(),
+ std::time::Duration::from_secs(config.symbol_set_negative_cache_ttl_seconds),
+ );
+
+ // Poison the URL key with a stored failure, as a prior capture-time miss would have.
+ let stored = crate::error::FrameError::JavaScript(crate::error::JsResolveErr::NoSourcemap(
+ url.to_string(),
+ ));
+ saving
+ .negative_cache
+ .insert(
+ (0, url.to_string()),
+ serde_json::to_string(&stored).unwrap(),
+ )
+ .await;
+
+ // The Both lookup must return the uploaded chunk-id data, not the cached URL failure.
+ let both = OrChunkId::both(url, chunk_id);
+ saving
+ .fetch(0, both)
+ .await
+ .map(|_| ())
+ .expect("chunk-id data must win over the cached URL failure");
+ }
+
+ #[sqlx::test(migrations = "./tests/test_migrations")]
+ async fn test_saving_data_invalidates_cached_failure(db: PgPool) {
+ use crate::symbolication::symbol_store::Fetcher;
+
+ // Regression: once real data is saved for a ref, a previously-cached failure for that
+ // same ref must not keep shadowing it until the TTL. `save_data` invalidates the entry.
+ let mut config = ResolverConfig::init_with_defaults().unwrap();
+ config.object_storage_bucket = "test-bucket".to_string();
+ config.ss_prefix = "test-prefix".to_string();
+
+ let url = Url::parse("https://example.com/static/app.js").unwrap();
+
+ let mut client = MockS3Client::default();
+ client
+ .expect_put()
+ .with(
+ predicate::eq(config.object_storage_bucket.clone()),
+ predicate::str::starts_with(config.ss_prefix.clone()),
+ predicate::always(),
+ )
+ .returning(|_, _, _| Ok(()))
+ .once();
+ client
+ .expect_get()
+ .with(
+ predicate::eq(config.object_storage_bucket.clone()),
+ predicate::str::starts_with(config.ss_prefix.clone()),
+ )
+ .returning(|_, _| Ok(Some(Bytes::from(get_symbol_data_bytes()))));
+
+ // The inner provider is irrelevant here: after invalidation the lookup is served from the
+ // DB data row + S3, and if it were ever reached it would just error.
+ let smp = SourcemapProvider::new(&config);
+ let saving = Saving::new(
+ smp,
+ db.clone(),
+ Arc::new(client),
+ config.object_storage_bucket.clone(),
+ config.ss_prefix.clone(),
+ std::time::Duration::from_secs(config.symbol_set_negative_cache_ttl_seconds),
+ );
+
+ // Prime a stored failure for the URL, as an earlier failed lookup would have.
+ let stored = crate::error::FrameError::JavaScript(crate::error::JsResolveErr::NoSourcemap(
+ url.to_string(),
+ ));
+ saving
+ .negative_cache
+ .insert(
+ (0, url.to_string()),
+ serde_json::to_string(&stored).unwrap(),
+ )
+ .await;
+
+ // Persist real data for the same URL. This must invalidate the negative-cache entry.
+ saving
+ .save_data(0, url.to_string(), Bytes::from(get_symbol_data_bytes()))
+ .await
+ .unwrap();
+
+ // The next fetch must return the freshly-saved data, not the stale cached failure.
+ saving
+ .fetch(0, url)
+ .await
+ .map(|_| ())
+ .expect("saved data must win over the previously-cached failure");
+ }
+
+ // Negative-cache tests. These construct `Saving` over a *lazy* Postgres pool that never
+ // connects: on a negative-cache hit `fetch` returns before any DB query, so the pool is
+ // never touched, and the assertions are DB-free. The `transient_errors_are_not_cached`
+ // and populate-from-DB behaviours require a live DB and live in the sqlx tests above.
+ mod negative_cache {
+ use std::{
+ sync::{
+ atomic::{AtomicUsize, Ordering},
+ Arc,
+ },
+ time::Duration,
+ };
+
+ use async_trait::async_trait;
+ use bytes::Bytes;
+ use reqwest::Url;
+ use sqlx::PgPool;
+
+ use crate::{
+ error::{FrameError, JsResolveErr, ResolveError},
+ symbolication::symbol_store::{
+ saving::{truncate_ref, Saving, MAX_REF_BYTES},
+ Fetcher, MockS3Client,
+ },
+ };
+
+ // A `Fetcher` that counts how many times its `fetch` runs, so a test can assert the
+ // negative cache short-circuited before reaching the inner layer.
+ struct CountingFetcher {
+ fetches: Arc<AtomicUsize>,
+ }
+
+ #[async_trait]
+ impl Fetcher for CountingFetcher {
+ type Ref = Url;
+ type Fetched = Bytes;
+ type Err = ResolveError;
+
+ async fn fetch(
+ &self,
+ _team_id: i32,
+ _r: Self::Ref,
+ ) -> Result<Self::Fetched, Self::Err> {
+ self.fetches.fetch_add(1, Ordering::SeqCst);
+ Ok(Bytes::from_static(b"unexpected"))
+ }
+ }
+
+ fn build_saving(fetches: Arc<AtomicUsize>) -> Saving<CountingFetcher> {
+ // Lazy pool: constructing it never connects, and these tests never trigger a query.
+ let pool = PgPool::connect_lazy("postgres://localhost/does-not-connect").unwrap();
+ Saving::new(
+ CountingFetcher { fetches },
+ pool,
+ Arc::new(MockS3Client::default()),
+ "test-bucket".to_string(),
+ "test-prefix".to_string(),
+ Duration::from_secs(300),
+ )
+ }
+
+ #[tokio::test]
+ async fn hit_returns_stored_error_without_touching_inner_or_db() {
+ let fetches = Arc::new(AtomicUsize::new(0));
+ let saving = build_saving(fetches.clone());
+
+ let team_id = 7;
+ let url = Url::parse("https://example.com/static/app.js").unwrap();
+ // Store the same serialized shape the DB path persists: a JSON `FrameError`.
+ let stored = FrameError::JavaScript(JsResolveErr::NoSourcemap(url.to_string()));
+ saving
+ .negative_cache
+ .insert(
+ (team_id, url.to_string()),
+ serde_json::to_string(&stored).unwrap(),
+ )
+ .await;
+
+ // `Saveable` (the Ok type) isn't `Debug`, so destructure rather than `unwrap_err`.
+ let Err(err) = saving.fetch(team_id, url.clone()).await else {
+ panic!("expected the cached failure to be returned");
+ };
+
+ // The stored failure is rebuilt exactly, not swallowed into an UnhandledError, and
+ // the inner fetcher (and thus the DB, since the pool can't connect) is never reached.
+ match err {
+ ResolveError::ResolutionError(frame_err) => assert_eq!(frame_err, stored),
+ other => panic!("expected rebuilt ResolutionError, got {other:?}"),
+ }
+ assert_eq!(fetches.load(Ordering::SeqCst), 0);
+ }
+
+ #[tokio::test]
+ async fn miss_for_a_different_team_does_not_collide() {
+ let fetches = Arc::new(AtomicUsize::new(0));
+ let saving = build_saving(fetches.clone());
+
+ let url = Url::parse("https://example.com/static/app.js").unwrap();
+ let stored = FrameError::JavaScript(JsResolveErr::NoSourcemap(url.to_string()));
+ // Seed team 1 only.
+ saving
+ .negative_cache
+ .insert(
+ (1, url.to_string()),
+ serde_json::to_string(&stored).unwrap(),
+ )
+ .await;
+
+ // A lookup for team 2 with the same ref must not hit team 1's entry — the probe
+ // misses, falls through to the (lazy, unconnected) DB, and errors trying to connect.
+ // `Saveable` (the Ok type) isn't `Debug`, so destructure rather than `unwrap_err`.
+ let Err(err) = saving.fetch(2, url).await else {
+ panic!("expected a DB connection failure on cache miss");
+ };
+ match err {
+ ResolveError::UnhandledError(_) => {} // DB connect failure — expected on a miss
+ other => panic!("expected a DB connection failure on cache miss, got {other:?}"),
+ }
+ }
+
+ #[tokio::test]
+ async fn probe_truncates_the_ref_to_match_the_db_key_space() {
+ let fetches = Arc::new(AtomicUsize::new(0));
+ let saving = build_saving(fetches.clone());
+
+ // A ref longer than the DB truncation bound. The DB writes/looks up under the
+ // truncated form, so the cache must key by the truncated form too — otherwise a
+ // populate-under-truncated / probe-under-full mismatch would silently never hit.
+ let long_url = Url::parse(&format!(
+ "https://example.com/{}",
+ "a".repeat(MAX_REF_BYTES)
+ ))
+ .unwrap();
+ let long_ref = long_url.to_string();
+ assert!(long_ref.len() > MAX_REF_BYTES);
+ let stored = FrameError::JavaScript(JsResolveErr::NoSourcemap("x".to_string()));
+ // Seed exactly as the code does: under the truncated key.
+ saving
+ .negative_cache
+ .insert(
+ (3, truncate_ref(&long_ref).to_string()),
+ serde_json::to_string(&stored).unwrap(),
+ )
+ .await;
+
+ // Probing with the full (untruncated) ref must still hit, proving the probe truncates.
+ let Err(err) = saving.fetch(3, long_url).await else {
+ panic!("expected the cached failure for the truncated ref to be returned");
+ };
+ match err {
+ ResolveError::ResolutionError(frame_err) => assert_eq!(frame_err, stored),
+ other => panic!("expected rebuilt ResolutionError, got {other:?}"),
+ }
+ assert_eq!(fetches.load(Ordering::SeqCst), 0);
+ }
+ }
}