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.

feat(error-tracking): limit concurrent large symbol set parses in cymbal (#113136)

Hugues Pouillot0abf755775d1
diff --git a/rust/common/symbol_data/.sampo/changesets/roguish-thunderbearer-tuonetar.md b/rust/common/symbol_data/.sampo/changesets/roguish-thunderbearer-tuonetar.md
new file mode 100644
index 000000000000..b20d05cea080
--- /dev/null
+++ b/rust/common/symbol_data/.sampo/changesets/roguish-thunderbearer-tuonetar.md
@@ -0,0 +1,5 @@
+---
+cargo/posthog-symbol-data: patch
+---
+
+Include decompressed-size metadata in new symbol-data containers so servers can limit memory-heavy parsing accurately.
diff --git a/rust/common/symbol_data/src/lib.rs b/rust/common/symbol_data/src/lib.rs
index e92bf0ebdf87..2a1acf1cbd04 100644
--- a/rust/common/symbol_data/src/lib.rs
+++ b/rust/common/symbol_data/src/lib.rs
@@ -7,6 +7,7 @@ mod utils;
pub use error::Error as SymbolDataError;
// The core data type
+pub use symbol_data::known_decompressed_size as symbol_data_known_decompressed_size;
pub use symbol_data::read_as as read_symbol_data;
pub use symbol_data::read_as_with_byte_count as read_symbol_data_with_byte_count;
pub use symbol_data::write as write_symbol_data;
diff --git a/rust/common/symbol_data/src/symbol_data.rs b/rust/common/symbol_data/src/symbol_data.rs
index 7e8ea8314b81..1e0a0e24e10e 100644
--- a/rust/common/symbol_data/src/symbol_data.rs
+++ b/rust/common/symbol_data/src/symbol_data.rs
@@ -66,6 +66,9 @@ where
Compression::Zstd => {
let mut encoder = zstd::Encoder::new(Vec::new(), 3)
.map_err(|e| Error::CompressionError(e.to_string()))?;
+ encoder
+ .set_pledged_src_size(Some(raw_bytes.len() as u64))
+ .map_err(|e| Error::CompressionError(e.to_string()))?;
encoder
.write_all(&raw_bytes)
.map_err(|e| Error::CompressionError(e.to_string()))?;
@@ -91,6 +94,49 @@ where
read_as_with_byte_count(data).map(|(v, _)| v)
}
+pub fn known_decompressed_size(data: &[u8]) -> Result<Option<usize>, Error> {
+ let version = read_version(data)?;
+
+ match version {
+ V1_VERSION => {
+ assert_at_least_as_long_as(v1_header_len(), data.len())?;
+ Ok(Some(data.len() - v1_header_len()))
+ }
+ VERSION => {
+ assert_at_least_as_long_as(v2_header_len(), data.len())?;
+ let payload = &data[v2_header_len()..];
+ match Compression::try_from(data[v2_header_len() - 1])? {
+ Compression::None => Ok(Some(payload.len())),
+ Compression::Zstd => known_zstd_decompressed_size(payload),
+ }
+ }
+ other => Err(Error::WrongVersion(other, VERSION)),
+ }
+}
+
+fn known_zstd_decompressed_size(mut data: &[u8]) -> Result<Option<usize>, Error> {
+ let mut total = 0usize;
+ while !data.is_empty() {
+ let frame_len = zstd::zstd_safe::find_frame_compressed_size(data).map_err(|code| {
+ Error::CompressionError(zstd::zstd_safe::get_error_name(code).to_string())
+ })?;
+ let Some(frame_size) = zstd::zstd_safe::get_frame_content_size(data)
+ .map_err(|e| Error::CompressionError(e.to_string()))?
+ else {
+ return Ok(None);
+ };
+ let Ok(frame_size) = usize::try_from(frame_size) else {
+ return Ok(None);
+ };
+ let Some(next_total) = total.checked_add(frame_size) else {
+ return Ok(None);
+ };
+ total = next_total;
+ data = &data[frame_len..];
+ }
+ Ok(Some(total))
+}
+
/// Like `read_as`, but also returns the decompressed payload byte count.
/// This is useful for cache memory accounting when the container uses compression,
/// since the compressed size can be much smaller than the actual data in memory.
diff --git a/rust/common/symbol_data/tests/test.rs b/rust/common/symbol_data/tests/test.rs
index fa6576ab4991..a9db99db45ab 100644
--- a/rust/common/symbol_data/tests/test.rs
+++ b/rust/common/symbol_data/tests/test.rs
@@ -1,6 +1,9 @@
+use std::io::Write;
+
use posthog_symbol_data::{
- read_symbol_data, write_symbol_data, write_symbol_data_uncompressed, AppleDsym, ElfDebugInfo,
- HermesMap, ProguardMapping, SourceAndMap,
+ read_symbol_data, symbol_data_known_decompressed_size, write_symbol_data,
+ write_symbol_data_uncompressed, AppleDsym, ElfDebugInfo, HermesMap, ProguardMapping,
+ SourceAndMap,
};
const MAGIC_LEN: usize = b"posthog_error_tracking".len();
@@ -30,10 +33,54 @@ fn test_v2_compressed_header() {
assert_eq!(version, 2);
assert_eq!(bytes[COMPRESSION_OFFSET], 1); // zstd
+ let uncompressed = write_symbol_data_uncompressed(input.clone()).unwrap();
+ assert_eq!(
+ symbol_data_known_decompressed_size(&bytes).unwrap(),
+ Some(uncompressed.len() - COMPRESSION_OFFSET - 1)
+ );
+
let output = read_symbol_data::<SourceAndMap>(&bytes).unwrap();
assert_eq!(input, output);
}
+#[test]
+fn test_v2_compressed_size_includes_concatenated_frames() {
+ let first = zstd::bulk::compress(b"first", 3).unwrap();
+ let second_payload = vec![b'x'; 100_000];
+ let second = zstd::bulk::compress(&second_payload, 3).unwrap();
+
+ let mut bytes = write_symbol_data(SourceAndMap {
+ minified_source: "source".to_string(),
+ sourcemap: "map".to_string(),
+ })
+ .unwrap();
+ bytes.truncate(COMPRESSION_OFFSET + 1);
+ bytes.extend(first);
+ bytes.extend(second);
+
+ assert_eq!(
+ symbol_data_known_decompressed_size(&bytes).unwrap(),
+ Some(5 + second_payload.len())
+ );
+}
+
+#[test]
+fn test_v2_compressed_without_content_size() {
+ let mut encoder = zstd::Encoder::new(Vec::new(), 3).unwrap();
+ encoder.write_all(b"legacy payload").unwrap();
+ let compressed = encoder.finish().unwrap();
+
+ let mut bytes = write_symbol_data(SourceAndMap {
+ minified_source: "source".to_string(),
+ sourcemap: "map".to_string(),
+ })
+ .unwrap();
+ bytes.truncate(COMPRESSION_OFFSET + 1);
+ bytes.extend(compressed);
+
+ assert_eq!(symbol_data_known_decompressed_size(&bytes).unwrap(), None);
+}
+
#[test]
fn test_v2_uncompressed_header() {
let input = SourceAndMap {
diff --git a/rust/cymbal/src/core/config.rs b/rust/cymbal/src/core/config.rs
index 21897dfdbfde..8ada2a845bb5 100644
--- a/rust/cymbal/src/core/config.rs
+++ b/rust/cymbal/src/core/config.rs
@@ -102,6 +102,15 @@ pub struct ResolverConfig {
#[envconfig(default = "64")]
pub symbol_resolution_concurrency: usize,
+ // Parsing a symbol set can need many times its fetched size in memory, and the symbol
+ // store cache does not count that memory. Parses of fetched blobs at least this large
+ // share a small concurrency limit, so a few of them cannot run the pod out of memory.
+ #[envconfig(default = "10000000")]
+ pub symbol_set_large_parse_bytes: usize,
+
+ #[envconfig(default = "2")]
+ pub symbol_set_max_concurrent_large_parses: usize,
+
// Shared secret authenticating the cymbal <-> cymbal-resolution gRPC seam.
#[envconfig(default = "")]
pub internal_api_secret: String,
diff --git a/rust/cymbal/src/core/metric_consts.rs b/rust/cymbal/src/core/metric_consts.rs
index 5fe3614edcd6..8c9511399520 100644
--- a/rust/cymbal/src/core/metric_consts.rs
+++ b/rust/cymbal/src/core/metric_consts.rs
@@ -54,6 +54,8 @@ pub const SOURCEMAP_PARSE: &str = "cymbal_sourcemap_parse";
// Decompressed size of a parsed symbol set, in bytes. Labelled by `kind`
// (`sourcemap` / `hermes` / `proguard` / `apple`).
pub const SYMBOL_SET_DECOMPRESSED_BYTES: &str = "cymbal_symbol_set_decompressed_bytes";
+// Time a large symbol set parse waits for a `ParseLimiter` permit, in milliseconds.
+pub const SYMBOL_SET_LARGE_PARSE_WAIT_MS: &str = "cymbal_symbol_set_large_parse_wait_ms";
// Histogram buckets for the byte-shaped metrics above. The default
// `common_metrics` buckets are tuned for milliseconds of latency and saturate
diff --git a/rust/cymbal/src/core/resolver.rs b/rust/cymbal/src/core/resolver.rs
index 621ec1134d5e..5912b49e6ba3 100644
--- a/rust/cymbal/src/core/resolver.rs
+++ b/rust/cymbal/src/core/resolver.rs
@@ -8,7 +8,7 @@ use crate::core::error::UnhandledError;
use crate::core::symbolication::symbol::{local::LocalSymbolResolver, SymbolResolver};
use crate::core::symbolication::symbol_store::{
apple::AppleProvider,
- caching::{Caching, SymbolSetCache},
+ caching::{Caching, ParseLimiter, SymbolSetCache},
chunk_id::ChunkIdFetcher,
concurrency,
hermesmap::HermesMapProvider,
@@ -58,6 +58,10 @@ pub fn build_catalog(
let ss_cache = Arc::new(Mutex::new(SymbolSetCache::new(
config.symbol_store_cache_max_bytes,
)));
+ let parse_limiter = ParseLimiter::new(
+ config.symbol_set_large_parse_bytes,
+ config.symbol_set_max_concurrent_large_parses,
+ );
let smp = SourcemapProvider::new(config).with_chunk_id_rescue(
posthog_pool.clone(),
@@ -78,7 +82,8 @@ pub fn build_catalog(
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());
+ let smp_caching =
+ Caching::new(smp_saving, ss_cache.clone()).with_parse_limiter(parse_limiter.clone());
// We want to fetch each sourcemap from the outside world exactly once,
// and if it isn't in the cache, load/parse it from s3 exactly once too.
// Limiting the per symbol set reference concurrency to 1 ensures this.
@@ -92,7 +97,8 @@ pub fn build_catalog(
);
// Skip the saving layer for HermesMapProvider, since it'll never fetch
// something from the outside world.
- let hmp_caching = Caching::new(hmp_chunk, ss_cache.clone());
+ let hmp_caching =
+ Caching::new(hmp_chunk, ss_cache.clone()).with_parse_limiter(parse_limiter.clone());
let hmp_atmostonce = concurrency::AtMostOne::new(hmp_caching);
let pgp_chunk = ChunkIdFetcher::new(
@@ -101,7 +107,8 @@ pub fn build_catalog(
posthog_pool.clone(),
config.object_storage_bucket.clone(),
);
- let pgp_caching = Caching::new(pgp_chunk, ss_cache.clone());
+ let pgp_caching =
+ Caching::new(pgp_chunk, ss_cache.clone()).with_parse_limiter(parse_limiter.clone());
let pgp_atmostonce = concurrency::AtMostOne::new(pgp_caching);
let apple_chunk = ChunkIdFetcher::new(
@@ -110,7 +117,8 @@ pub fn build_catalog(
posthog_pool.clone(),
config.object_storage_bucket.clone(),
);
- let apple_caching = Caching::new(apple_chunk, ss_cache.clone());
+ let apple_caching =
+ Caching::new(apple_chunk, ss_cache.clone()).with_parse_limiter(parse_limiter.clone());
let apple_atmostonce = concurrency::AtMostOne::new(apple_caching);
let native_chunk = ChunkIdFetcher::new(
@@ -119,7 +127,7 @@ pub fn build_catalog(
posthog_pool.clone(),
config.object_storage_bucket.clone(),
);
- let native_caching = Caching::new(native_chunk, ss_cache);
+ let native_caching = Caching::new(native_chunk, ss_cache).with_parse_limiter(parse_limiter);
let native_atmostonce = concurrency::AtMostOne::new(native_caching);
Arc::new(Catalog::new(
diff --git a/rust/cymbal/src/core/symbolication/symbol_store/apple.rs b/rust/cymbal/src/core/symbolication/symbol_store/apple.rs
index 37e5aa24dc0e..0de740b07bc9 100644
--- a/rust/cymbal/src/core/symbolication/symbol_store/apple.rs
+++ b/rust/cymbal/src/core/symbolication/symbol_store/apple.rs
@@ -8,7 +8,7 @@ use posthog_symbol_data::{read_symbol_data_with_byte_count, AppleDsym};
use crate::{
error::{AppleError, ResolveError, UnhandledError},
metric_consts::SYMBOL_SET_DECOMPRESSED_BYTES,
- symbolication::symbol_store::{native::ParsedNativeSymbols, Fetcher, Parser},
+ symbolication::symbol_store::{native::ParsedNativeSymbols, Fetcher, ParsePermit, Parser},
};
pub struct AppleProvider {}
@@ -33,11 +33,16 @@ impl Parser for AppleProvider {
type Set = ParsedNativeSymbols;
type Err = ResolveError;
- async fn parse(&self, source: Self::Source) -> Result<ParsedNativeSymbols, ResolveError> {
+ async fn parse(
+ &self,
+ source: Self::Source,
+ permit: ParsePermit,
+ ) -> Result<ParsedNativeSymbols, ResolveError> {
// dSYM parsing is the heaviest CPU work in the system: zstd decompress, ZIP
// expansion, DWARF parse, and symcache conversion. Always offload from the tokio
// runtime.
tokio::task::spawn_blocking(move || -> Result<ParsedNativeSymbols, ResolveError> {
+ let _permit = permit;
// Try to unwrap symbol_data container first (new format),
// fall back to raw ZIP for backward compatibility with existing uploads.
// TODO(2026-09-24): Remove raw ZIP fallback once all old uploads have expired.
diff --git a/rust/cymbal/src/core/symbolication/symbol_store/caching.rs b/rust/cymbal/src/core/symbolication/symbol_store/caching.rs
index 5c66053e2092..ec23fec71051 100644
--- a/rust/cymbal/src/core/symbolication/symbol_store/caching.rs
+++ b/rust/cymbal/src/core/symbolication/symbol_store/caching.rs
@@ -2,15 +2,15 @@ use std::{any::Any, collections::HashMap, sync::Arc, time::Instant};
use async_trait::async_trait;
use bytes::Bytes;
-use tokio::sync::Mutex;
+use tokio::sync::{Mutex, Semaphore};
use tracing::info;
use crate::metric_consts::{
STORE_CACHED_BYTES, STORE_CACHE_EVICTIONS, STORE_CACHE_EVICTION_RUNS, STORE_CACHE_HITS,
- STORE_CACHE_MISSES,
+ STORE_CACHE_MISSES, SYMBOL_SET_LARGE_PARSE_WAIT_MS,
};
-use super::{chunk_id::SymbolSetCacheKey, Fetcher, Parser, Provider};
+use super::{chunk_id::SymbolSetCacheKey, Fetcher, ParsePermit, Parser, Provider};
// Parsing can transiently need many times the fetched size (e.g. ProguardCache::write), and
// none of that is held against the cache budget. We log large parses before they start, so
@@ -23,6 +23,33 @@ const LARGE_PARSED_BYTES: usize = 50_000_000;
pub struct Caching<P> {
inner: P,
cache: Arc<Mutex<SymbolSetCache>>, // This inner cache is shared across providers
+ parse_limiter: Option<ParseLimiter>,
+}
+
+// Bounds how many large symbol sets are parsed at once. A parse can need many times the
+// fetched size in transient memory, and the cache budget does not count it. Clones share
+// one set of permits, so a single limiter covers every provider it is given to.
+#[derive(Clone)]
+pub struct ParseLimiter {
+ large_parse_bytes: usize,
+ permits: Arc<Semaphore>,
+}
+
+impl ParseLimiter {
+ pub fn new(large_parse_bytes: usize, max_concurrent_large_parses: usize) -> Self {
+ Self {
+ large_parse_bytes,
+ permits: Arc::new(Semaphore::new(max_concurrent_large_parses.max(1))),
+ }
+ }
+
+ async fn acquire(&self, required: bool) -> ParsePermit {
+ if !required {
+ return ParsePermit::none();
+ }
+ // UNWRAP - we never close the semaphore
+ ParsePermit::limited(self.permits.clone().acquire_owned().await.unwrap())
+ }
}
impl<P> Caching<P>
@@ -36,7 +63,16 @@ where
P::Set: Countable + Any + Send + Sync,
{
pub fn new(inner: P, cache: Arc<Mutex<SymbolSetCache>>) -> Self {
- Self { inner, cache }
+ Self {
+ inner,
+ cache,
+ parse_limiter: None,
+ }
+ }
+
+ pub fn with_parse_limiter(mut self, parse_limiter: ParseLimiter) -> Self {
+ self.parse_limiter = Some(parse_limiter);
+ self
}
}
@@ -68,14 +104,28 @@ where
let found = self.inner.fetch(team_id, r).await?;
let fetched_bytes = found.byte_count();
let set_type = set_type_name::<P::Set>();
+
+ let wait_start = Instant::now();
+ let permit = match &self.parse_limiter {
+ Some(limiter) => {
+ let required = found.requires_parse_permit(limiter.large_parse_bytes);
+ limiter.acquire(required).await
+ }
+ None => ParsePermit::none(),
+ };
+ let wait_ms = wait_start.elapsed().as_millis() as u64;
+ if permit.is_limited() {
+ metrics::histogram!(SYMBOL_SET_LARGE_PARSE_WAIT_MS).record(wait_ms as f64);
+ }
+
if fetched_bytes >= LARGE_FETCHED_BYTES {
info!(
team_id,
- cache_key, set_type, fetched_bytes, "Parsing large symbol set"
+ cache_key, set_type, fetched_bytes, wait_ms, "Parsing large symbol set"
);
}
let parse_start = Instant::now();
- let parsed = self.inner.parse(found).await?;
+ let parsed = self.inner.parse(found, permit).await?;
let bytes = parsed.byte_count();
if fetched_bytes >= LARGE_FETCHED_BYTES || bytes >= LARGE_PARSED_BYTES {
info!(
@@ -190,6 +240,10 @@ struct CachedSymbolSet {
pub trait Countable {
fn byte_count(&self) -> usize;
+
+ fn requires_parse_permit(&self, threshold: usize) -> bool {
+ self.byte_count() >= threshold
+ }
}
impl Countable for Vec<u8> {
@@ -202,6 +256,13 @@ impl Countable for Bytes {
fn byte_count(&self) -> usize {
self.len()
}
+
+ fn requires_parse_permit(&self, threshold: usize) -> bool {
+ match posthog_symbol_data::symbol_data_known_decompressed_size(self) {
+ Ok(Some(size)) => size.max(self.len()) >= threshold,
+ Ok(None) | Err(_) => true,
+ }
+ }
}
fn set_type_name<T>() -> &'static str {
@@ -213,13 +274,15 @@ fn set_type_name<T>() -> &'static str {
mod tests {
use std::{
convert::Infallible,
+ io::{Cursor, Write},
sync::atomic::{AtomicUsize, Ordering},
- sync::Arc,
+ sync::{Arc, Condvar, Mutex as StdMutex},
};
use super::*;
use crate::symbolication::symbol_store::chunk_id::OrChunkId;
use async_trait::async_trait;
+ use posthog_symbol_data::{write_symbol_data, SourceAndMap};
use reqwest::Url;
struct FakeProvider {
@@ -249,7 +312,11 @@ mod tests {
type Set = Vec<u8>;
type Err = Infallible;
- async fn parse(&self, data: Self::Source) -> Result<Self::Set, Self::Err> {
+ async fn parse(
+ &self,
+ data: Self::Source,
+ _permit: ParsePermit,
+ ) -> Result<Self::Set, Self::Err> {
Ok(data)
}
}
@@ -280,6 +347,185 @@ mod tests {
assert_eq!(fetches.load(Ordering::SeqCst), 2);
}
+ struct SizedProvider {
+ fetched_bytes: usize,
+ in_flight: Arc<AtomicUsize>,
+ max_in_flight: Arc<AtomicUsize>,
+ }
+
+ #[async_trait]
+ impl Fetcher for SizedProvider {
+ 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> {
+ Ok(vec![0; self.fetched_bytes])
+ }
+ }
+
+ #[async_trait]
+ impl Parser for SizedProvider {
+ type Source = Vec<u8>;
+ type Set = Vec<u8>;
+ type Err = Infallible;
+
+ async fn parse(
+ &self,
+ data: Self::Source,
+ permit: ParsePermit,
+ ) -> Result<Self::Set, Self::Err> {
+ let _permit = permit;
+ let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1;
+ self.max_in_flight.fetch_max(now, Ordering::SeqCst);
+ for _ in 0..5 {
+ tokio::task::yield_now().await;
+ }
+ self.in_flight.fetch_sub(1, Ordering::SeqCst);
+ Ok(data)
+ }
+ }
+
+ struct BlockingProvider {
+ active: Arc<AtomicUsize>,
+ started: tokio::sync::mpsc::UnboundedSender<()>,
+ release: Arc<(StdMutex<bool>, Condvar)>,
+ }
+
+ #[async_trait]
+ impl Fetcher for BlockingProvider {
+ 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> {
+ Ok(vec![0])
+ }
+ }
+
+ #[async_trait]
+ impl Parser for BlockingProvider {
+ type Source = Vec<u8>;
+ type Set = Vec<u8>;
+ type Err = Infallible;
+
+ async fn parse(
+ &self,
+ data: Self::Source,
+ permit: ParsePermit,
+ ) -> Result<Self::Set, Self::Err> {
+ let active = self.active.clone();
+ let started = self.started.clone();
+ let release = self.release.clone();
+
+ Ok(tokio::task::spawn_blocking(move || {
+ let _permit = permit;
+ active.fetch_add(1, Ordering::SeqCst);
+ started.send(()).unwrap();
+
+ let (lock, condvar) = &*release;
+ let mut released = lock.lock().unwrap();
+ while !*released {
+ released = condvar.wait(released).unwrap();
+ }
+
+ active.fetch_sub(1, Ordering::SeqCst);
+ data
+ })
+ .await
+ .unwrap())
+ }
+ }
+
+ #[tokio::test(flavor = "current_thread")]
+ async fn parse_limiter_bounds_only_large_parses() {
+ for (fetched_bytes, expected_max) in [(100, 1), (99, 3)] {
+ let max_in_flight = Arc::new(AtomicUsize::new(0));
+ let provider = SizedProvider {
+ fetched_bytes,
+ in_flight: Arc::new(AtomicUsize::new(0)),
+ max_in_flight: max_in_flight.clone(),
+ };
+ let cache = Arc::new(Mutex::new(SymbolSetCache::new(1 << 20)));
+ let caching =
+ Caching::new(provider, cache).with_parse_limiter(ParseLimiter::new(100, 1));
+
+ futures::future::join_all(
+ (0..3).map(|i| caching.lookup(1, OrChunkId::<Url>::chunk_id(format!("set-{i}")))),
+ )
+ .await;
+
+ assert_eq!(
+ max_in_flight.load(Ordering::SeqCst),
+ expected_max,
+ "fetched_bytes = {fetched_bytes}"
+ );
+ }
+
+ let compressed = Bytes::from(
+ write_symbol_data(SourceAndMap {
+ minified_source: "a".repeat(100),
+ sourcemap: "b".repeat(100),
+ })
+ .unwrap(),
+ );
+ assert!(compressed.len() < 100);
+ assert!(compressed.requires_parse_permit(100));
+
+ let mut raw_zip = Cursor::new(Vec::new());
+ {
+ let mut writer = zip::ZipWriter::new(&mut raw_zip);
+ writer
+ .start_file("symbols", zip::write::SimpleFileOptions::default())
+ .unwrap();
+ writer.write_all(b"symbols").unwrap();
+ writer.finish().unwrap();
+ }
+ let raw_zip = Bytes::from(raw_zip.into_inner());
+ assert!(raw_zip.requires_parse_permit(raw_zip.len() + 1));
+ }
+
+ #[tokio::test]
+ async fn cancelled_lookup_keeps_permit_until_blocking_parse_finishes() {
+ let active = Arc::new(AtomicUsize::new(0));
+ let (started_tx, mut started_rx) = tokio::sync::mpsc::unbounded_channel();
+ let release = Arc::new((StdMutex::new(false), Condvar::new()));
+ let provider = BlockingProvider {
+ active: active.clone(),
+ started: started_tx,
+ release: release.clone(),
+ };
+ let limiter = ParseLimiter::new(1, 1);
+ let caching = Arc::new(
+ Caching::new(provider, Arc::new(Mutex::new(SymbolSetCache::new(1024))))
+ .with_parse_limiter(limiter.clone()),
+ );
+
+ let lookup = tokio::spawn({
+ let caching = caching.clone();
+ async move {
+ caching
+ .lookup(1, OrChunkId::<Url>::chunk_id("set".to_string()))
+ .await
+ }
+ });
+ started_rx.recv().await.unwrap();
+ lookup.abort();
+ assert!(lookup.await.unwrap_err().is_cancelled());
+
+ assert_eq!(active.load(Ordering::SeqCst), 1);
+ assert_eq!(limiter.permits.available_permits(), 0);
+
+ let (lock, condvar) = &*release;
+ *lock.lock().unwrap() = true;
+ condvar.notify_one();
+ let released_permit = limiter.permits.clone().acquire_owned().await.unwrap();
+
+ assert_eq!(active.load(Ordering::SeqCst), 0);
+ drop(released_permit);
+ assert_eq!(limiter.permits.available_permits(), 1);
+ }
+
#[test]
fn replacing_cache_entry_keeps_held_bytes_accurate() {
let mut cache = SymbolSetCache::new(10);
diff --git a/rust/cymbal/src/core/symbolication/symbol_store/chunk_id.rs b/rust/cymbal/src/core/symbolication/symbol_store/chunk_id.rs
index 241a256bec1f..b6936a99c089 100644
--- a/rust/cymbal/src/core/symbolication/symbol_store/chunk_id.rs
+++ b/rust/cymbal/src/core/symbolication/symbol_store/chunk_id.rs
@@ -16,7 +16,7 @@ use crate::{
symbolication::symbol_store::BlobClient,
};
-use super::{saving::SymbolSetRecord, Fetcher, Parser};
+use super::{saving::SymbolSetRecord, Fetcher, ParsePermit, Parser};
pub struct ChunkIdFetcher<Parser> {
pub inner: Parser,
@@ -165,8 +165,8 @@ where
type Set = P::Set;
type Err = P::Err;
- async fn parse(&self, data: Self::Source) -> Result<Self::Set, Self::Err> {
- self.inner.parse(data).await
+ async fn parse(&self, data: Self::Source, permit: ParsePermit) -> Result<Self::Set, Self::Err> {
+ self.inner.parse(data, permit).await
}
}
diff --git a/rust/cymbal/src/core/symbolication/symbol_store/hermesmap.rs b/rust/cymbal/src/core/symbolication/symbol_store/hermesmap.rs
index 72dad7d08359..2ed656f4a4e7 100644
--- a/rust/cymbal/src/core/symbolication/symbol_store/hermesmap.rs
+++ b/rust/cymbal/src/core/symbolication/symbol_store/hermesmap.rs
@@ -7,7 +7,7 @@ use crate::{
error::{HermesError, ResolveError, UnhandledError},
langs::hermes::HermesRef,
metric_consts::SYMBOL_SET_DECOMPRESSED_BYTES,
- symbolication::symbol_store::{caching::Countable, Fetcher, Parser},
+ symbolication::symbol_store::{caching::Countable, Fetcher, ParsePermit, Parser},
};
pub struct ParsedHermesMap {
@@ -76,10 +76,15 @@ impl Parser for HermesMapProvider {
type Set = ParsedHermesMap;
type Err = ResolveError;
- async fn parse(&self, source: Bytes) -> Result<ParsedHermesMap, Self::Err> {
+ async fn parse(
+ &self,
+ source: Bytes,
+ permit: ParsePermit,
+ ) -> Result<ParsedHermesMap, Self::Err> {
// zstd decompress + Hermes sourcemap parse are both CPU-bound; offload from the
// tokio runtime so a large bundle doesn't block other in-flight requests.
tokio::task::spawn_blocking(move || -> Result<ParsedHermesMap, ResolveError> {
+ let _permit = permit;
let (map, decompressed_bytes): (HermesMap, usize) =
read_symbol_data_with_byte_count(&source).map_err(HermesError::DataError)?;
metrics::histogram!(SYMBOL_SET_DECOMPRESSED_BYTES, "kind" => "hermes")
diff --git a/rust/cymbal/src/core/symbolication/symbol_store/mod.rs b/rust/cymbal/src/core/symbolication/symbol_store/mod.rs
index bd983deb35be..0d518caaa617 100644
--- a/rust/cymbal/src/core/symbolication/symbol_store/mod.rs
+++ b/rust/cymbal/src/core/symbolication/symbol_store/mod.rs
@@ -5,6 +5,7 @@ use async_trait::async_trait;
use chunk_id::OrChunkId;
use reqwest::Url;
use sourcemap::OwnedSourceMapCache;
+use tokio::sync::OwnedSemaphorePermit;
use crate::{
error::ResolveError,
@@ -50,12 +51,28 @@ pub trait Fetcher: Send + Sync + 'static {
async fn fetch(&self, team_id: i32, r: Self::Ref) -> Result<Self::Fetched, Self::Err>;
}
+pub struct ParsePermit(Option<OwnedSemaphorePermit>);
+
+impl ParsePermit {
+ pub fn none() -> Self {
+ Self(None)
+ }
+
+ pub fn limited(permit: OwnedSemaphorePermit) -> Self {
+ Self(Some(permit))
+ }
+
+ pub fn is_limited(&self) -> bool {
+ self.0.is_some()
+ }
+}
+
#[async_trait]
pub trait Parser: Send + Sync + 'static {
type Source;
type Set;
type Err;
- async fn parse(&self, data: Self::Source) -> Result<Self::Set, Self::Err>;
+ async fn parse(&self, data: Self::Source, permit: ParsePermit) -> Result<Self::Set, Self::Err>;
}
#[async_trait]
@@ -179,7 +196,7 @@ where
async fn lookup(&self, team_id: i32, r: Self::Ref) -> Result<Arc<Self::Set>, Self::Err> {
let fetched = self.fetch(team_id, r).await?;
- let parsed = self.parse(fetched).await?;
+ let parsed = self.parse(fetched, ParsePermit::none()).await?;
Ok(Arc::new(parsed))
}
}
diff --git a/rust/cymbal/src/core/symbolication/symbol_store/native.rs b/rust/cymbal/src/core/symbolication/symbol_store/native.rs
index 3fc692d0b221..4f04fd956c62 100644
--- a/rust/cymbal/src/core/symbolication/symbol_store/native.rs
+++ b/rust/cymbal/src/core/symbolication/symbol_store/native.rs
@@ -15,7 +15,7 @@ use posthog_symbol_data::{read_symbol_data_with_byte_count, AppleDsym, ElfDebugI
use crate::{
error::{NativeError, ResolveError, UnhandledError},
metric_consts::SYMBOL_SET_DECOMPRESSED_BYTES,
- symbolication::symbol_store::{caching::Countable, Fetcher, Parser},
+ symbolication::symbol_store::{caching::Countable, Fetcher, ParsePermit, Parser},
};
/// Manifest format for source files bundled in the symbol ZIP under `__source/`
@@ -320,11 +320,16 @@ impl Parser for NativeProvider {
type Set = ParsedNativeSymbols;
type Err = ResolveError;
- async fn parse(&self, source: Self::Source) -> Result<ParsedNativeSymbols, ResolveError> {
+ async fn parse(
+ &self,
+ source: Self::Source,
+ permit: ParsePermit,
+ ) -> Result<ParsedNativeSymbols, ResolveError> {
// Debug-info parsing is the heaviest CPU work in the system: zstd
// decompress, ZIP expansion, DWARF parse, and symcache conversion.
// Always offload from the tokio runtime.
tokio::task::spawn_blocking(move || -> Result<ParsedNativeSymbols, ResolveError> {
+ let _permit = permit;
// Slice selection invariant: CLI dSYM uploads are one single-arch
// binary per UUID (fat binaries are thinned at upload), so a
// chunk_id lookup always parses the slice it names. The arm64
diff --git a/rust/cymbal/src/core/symbolication/symbol_store/proguard.rs b/rust/cymbal/src/core/symbolication/symbol_store/proguard.rs
index 6928b4a626bb..2fa2fa25d569 100644
--- a/rust/cymbal/src/core/symbolication/symbol_store/proguard.rs
+++ b/rust/cymbal/src/core/symbolication/symbol_store/proguard.rs
@@ -7,7 +7,7 @@ use posthog_symbol_data::{read_symbol_data_with_byte_count, ProguardMapping};
use crate::{
error::{ProguardError, ResolveError, UnhandledError},
metric_consts::SYMBOL_SET_DECOMPRESSED_BYTES,
- symbolication::symbol_store::{caching::Countable, Fetcher, Parser},
+ symbolication::symbol_store::{caching::Countable, Fetcher, ParsePermit, Parser},
};
pub struct FetchedMapping {
@@ -47,10 +47,15 @@ impl Parser for ProguardProvider {
type Set = FetchedMapping;
type Err = ResolveError;
- async fn parse(&self, source: Self::Source) -> Result<FetchedMapping, ResolveError> {
+ async fn parse(
+ &self,
+ source: Self::Source,
+ permit: ParsePermit,
+ ) -> Result<FetchedMapping, ResolveError> {
// zstd decompress + ProguardCache::write are CPU-bound; offload from the tokio
// runtime so a large mapping doesn't block other in-flight requests.
tokio::task::spawn_blocking(move || -> Result<FetchedMapping, ResolveError> {
+ let _permit = permit;
let (map, decompressed_bytes): (ProguardMapping, usize) =
read_symbol_data_with_byte_count(&source).map_err(ProguardError::DataError)?;
metrics::histogram!(SYMBOL_SET_DECOMPRESSED_BYTES, "kind" => "proguard")
diff --git a/rust/cymbal/src/core/symbolication/symbol_store/saving.rs b/rust/cymbal/src/core/symbolication/symbol_store/saving.rs
index e5dbe2feefdb..57016cdefa43 100644
--- a/rust/cymbal/src/core/symbolication/symbol_store/saving.rs
+++ b/rust/cymbal/src/core/symbolication/symbol_store/saving.rs
@@ -24,7 +24,7 @@ use crate::{
symbolication::symbol_store::{chunk_id::SymbolSetKey, BlobClient},
};
-use super::{caching::Countable, Fetcher, Parser};
+use super::{caching::Countable, Fetcher, ParsePermit, Parser};
pub(crate) const MAX_REF_BYTES: usize = 2048;
@@ -127,6 +127,10 @@ impl Countable for Saveable {
fn byte_count(&self) -> usize {
self.data.len()
}
+
+ fn requires_parse_permit(&self, threshold: usize) -> bool {
+ self.data.requires_parse_permit(threshold)
+ }
}
impl<F> Saving<F> {
@@ -465,7 +469,7 @@ where
type Set = F::Set;
type Err = F::Err;
- async fn parse(&self, data: Saveable) -> Result<Self::Set, Self::Err> {
+ async fn parse(&self, data: Saveable, permit: ParsePermit) -> Result<Self::Set, Self::Err> {
let Saveable {
data: bytes,
storage_ptr,
@@ -482,7 +486,7 @@ where
None
};
- match self.inner.parse(bytes).await {
+ match self.inner.parse(bytes, permit).await {
Ok(s) => {
debug!(team_id, "parsed symbol set data");
if let (Some(bytes_to_save), Some(save_ref)) = (bytes_to_save, &save_ref) {
diff --git a/rust/cymbal/src/core/symbolication/symbol_store/sourcemap.rs b/rust/cymbal/src/core/symbolication/symbol_store/sourcemap.rs
index f900d44f034c..19f5274e47cd 100644
--- a/rust/cymbal/src/core/symbolication/symbol_store/sourcemap.rs
+++ b/rust/cymbal/src/core/symbolication/symbol_store/sourcemap.rs
@@ -31,7 +31,7 @@ use super::{
caching::Countable,
chunk_id::{load_symbol_set_data, SymbolSetLoadResult},
dart_minified_names::parse_dart_minified_names,
- BlobClient, Fetcher, Parser,
+ BlobClient, Fetcher, ParsePermit, Parser,
};
pub struct SourcemapProvider {
@@ -482,13 +482,14 @@ impl Parser for SourcemapProvider {
type Source = Bytes;
type Set = OwnedSourceMapCache;
type Err = ResolveError;
- async fn parse(&self, data: Bytes) -> Result<Self::Set, Self::Err> {
+ async fn parse(&self, data: Bytes, permit: ParsePermit) -> Result<Self::Set, Self::Err> {
let start = common_metrics::timing_guard(SOURCEMAP_PARSE, &[]);
// `read_symbol_data_with_byte_count` zstd-decompresses a potentially large blob, and
// `SourceMapCacheWriter::new` is a CPU-bound serializer. Running them on a tokio
// worker blocks the runtime; offload to a blocking thread instead.
let smc =
tokio::task::spawn_blocking(move || -> Result<OwnedSourceMapCache, ResolveError> {
+ let _permit = permit;
let (sam, decompressed_bytes): (SourceAndMap, usize) =
read_symbol_data_with_byte_count(&data).map_err(JsResolveErr::JSDataError)?;
metrics::histogram!(SYMBOL_SET_DECOMPRESSED_BYTES, "kind" => "sourcemap")
diff --git a/rust/cymbal/src/modes/resolution/README.md b/rust/cymbal/src/modes/resolution/README.md
index a578bcba1c6d..3b2a72b4cfaf 100644
--- a/rust/cymbal/src/modes/resolution/README.md
+++ b/rust/cymbal/src/modes/resolution/README.md
@@ -121,6 +121,8 @@ All variables are prefixed `CYMBAL_REMOTE_RESOLUTION_` and live on `cymbal::conf
| `INTERNAL_API_SECRET` | _empty_ | Shared secret required as `X-Internal-Api-Secret` metadata on every gRPC request. Empty configuration rejects all RPCs. |
| `MAX_CONCURRENT_REQUESTS` | `256` | Hard cap on in-flight gRPC streams. Excess returns `UNAVAILABLE` from the gRPC load-shed layer. `0` disables the cap. |
| `SYMBOL_RESOLUTION_CONCURRENCY` | `64` | Cap on concurrent symbol-resolution operations across all in-flight items. |
+| `SYMBOL_SET_LARGE_PARSE_BYTES` | `10000000` | Fetched size, in bytes, at which a symbol set parse counts as large. Large parses share the limit below, because their transient memory is not counted by the symbol store cache. |
+| `SYMBOL_SET_MAX_CONCURRENT_LARGE_PARSES` | `2` | Cap on concurrent large symbol set parses across all providers. Other large parses wait. |
| `MAX_ITEM_CONCURRENCY` | `64` | Process-wide cap on concurrently processed exception items. Excess items receive `ERROR_KIND_OVERLOADED`. |
| `SERVICE_INSTANCE_ID` | random UUID | Identifier surfaced to callers via `LoadEvent` on the Subscribe stream. |
| `SUBSCRIBE_TICK_INTERVAL_MS` | `1000` | Default `LoadEvent` heartbeat cadence when callers do not suggest one. Load events may be emitted earlier when draining changes or in-flight load crosses coarse thresholds. |
diff --git a/rust/cymbal/tests/resolve.rs b/rust/cymbal/tests/resolve.rs
index f416f357f078..3cea7fa7f02f 100644
--- a/rust/cymbal/tests/resolve.rs
+++ b/rust/cymbal/tests/resolve.rs
@@ -15,7 +15,7 @@ use cymbal::{
native::NativeProvider,
proguard::ProguardProvider,
sourcemap::{OwnedSourceMapCache, SourcemapProvider},
- Catalog, Fetcher, Parser,
+ Catalog, Fetcher, ParsePermit, Parser,
},
types::{RawExceptionProperties, Stacktrace},
};
@@ -64,8 +64,12 @@ where
type Set = P::Set;
type Err = P::Err;
- async fn parse(&self, source: Self::Source) -> Result<Self::Set, Self::Err> {
- self.inner.parse(source).await
+ async fn parse(
+ &self,
+ source: Self::Source,
+ permit: ParsePermit,
+ ) -> Result<Self::Set, Self::Err> {
+ self.inner.parse(source, permit).await
}
}