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): resolve event-level release in cymbal (#75254)

Aleksander Błaszkiewicz97194a819565
diff --git a/rust/cymbal/.sqlx/query-14e4503d0bcc1f5191f43c94ef499b3871d8bd81f554481cc59a6d4cfc3c1ef4.json b/rust/cymbal/.sqlx/query-14e4503d0bcc1f5191f43c94ef499b3871d8bd81f554481cc59a6d4cfc3c1ef4.json
new file mode 100644
index 000000000000..51460a2aea8f
--- /dev/null
+++ b/rust/cymbal/.sqlx/query-14e4503d0bcc1f5191f43c94ef499b3871d8bd81f554481cc59a6d4cfc3c1ef4.json
@@ -0,0 +1,59 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, team_id, hash_id, created_at, version, project, metadata\n FROM posthog_errortrackingrelease\n WHERE id = $1 AND team_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "team_id",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 2,
+ "name": "hash_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "version",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "project",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "metadata",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Int4"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "14e4503d0bcc1f5191f43c94ef499b3871d8bd81f554481cc59a6d4cfc3c1ef4"
+}
diff --git a/rust/cymbal/.sqlx/query-15ae3c40f2b589c586bb1da303fee2bc51ef8874660ae712bf7d419bc971a76f.json b/rust/cymbal/.sqlx/query-15ae3c40f2b589c586bb1da303fee2bc51ef8874660ae712bf7d419bc971a76f.json
new file mode 100644
index 000000000000..5155488f89a4
--- /dev/null
+++ b/rust/cymbal/.sqlx/query-15ae3c40f2b589c586bb1da303fee2bc51ef8874660ae712bf7d419bc971a76f.json
@@ -0,0 +1,59 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT id, team_id, hash_id, created_at, version, project, metadata\n FROM posthog_errortrackingrelease\n WHERE hash_id = $1 AND team_id = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "team_id",
+ "type_info": "Int4"
+ },
+ {
+ "ordinal": 2,
+ "name": "hash_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 4,
+ "name": "version",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "project",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "metadata",
+ "type_info": "Jsonb"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Int4"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "15ae3c40f2b589c586bb1da303fee2bc51ef8874660ae712bf7d419bc971a76f"
+}
diff --git a/rust/cymbal/src/core/metric_consts.rs b/rust/cymbal/src/core/metric_consts.rs
index 0944638a0b10..5a2e0f45d462 100644
--- a/rust/cymbal/src/core/metric_consts.rs
+++ b/rust/cymbal/src/core/metric_consts.rs
@@ -128,6 +128,8 @@ pub const SPIKE_ALERT_STAGE: &str = "cymbal_spike_detection_time";
// Operators
pub const LEGACY_ORDER_RESOLVER_OPERATOR: &str = "cymbal_exception_legacy_order_resolver_operator";
+pub const EVENT_RELEASE_RESOLVER_OPERATOR: &str =
+ "cymbal_exception_event_release_resolver_operator";
pub const LEGACY_ORDER_RESOLVE_FAILED: &str = "cymbal_exception_legacy_order_resolve_failed";
pub const FINGERPRINT_LEGACY_VERSION_USED: &str = "cymbal_fingerprint_legacy_version_used";
pub const ISSUE_LINKER_OPERATOR: &str = "cymbal_exception_issue_linker_operator";
diff --git a/rust/cymbal/src/core/types/frames/mod.rs b/rust/cymbal/src/core/types/frames/mod.rs
index ae87fdde8055..5b06b43a60f4 100644
--- a/rust/cymbal/src/core/types/frames/mod.rs
+++ b/rust/cymbal/src/core/types/frames/mod.rs
@@ -39,6 +39,8 @@ pub(crate) fn record_frame_resolution_failure(
tracing::debug!(lang = lang, reason = reason, error = %err, "frame resolution failed");
}
+pub mod releases;
+
// We consume a huge variety of differently shaped stack frames, which we have special-case
// transformation for, to produce a single, unified representation of a frame.
#[derive(Debug, Deserialize, Serialize, Clone)]
diff --git a/rust/cymbal/src/core/types/frames/releases.rs b/rust/cymbal/src/core/types/frames/releases.rs
new file mode 100644
index 000000000000..ae99af412d0e
--- /dev/null
+++ b/rust/cymbal/src/core/types/frames/releases.rs
@@ -0,0 +1,230 @@
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+use sha2::{Digest, Sha512};
+use sqlx::Executor;
+use uuid::Uuid;
+
+/// The release API does not bound what a row can hold (`version`/`project`/`metadata` are
+/// unbounded TextField/JSONField columns), but every one of these fields is embedded into every
+/// matching exception event, so a single oversized row would be amplified across the whole event
+/// stream after capture's per-event size limit has already been enforced. Clamping at fetch keeps
+/// events bounded and cache entries small enough for an entry-count budget. 8 KiB of metadata is
+/// ~25x what the CLI writes (a git object), and 255 chars fits any semver, commit SHA, or bundle
+/// identifier many times over.
+pub const MAX_RELEASE_METADATA_BYTES: usize = 8 * 1024;
+pub const MAX_RELEASE_TEXT_CHARS: usize = 255;
+
+#[derive(Debug, Clone, Eq, PartialEq)]
+pub struct ReleaseRecord {
+ pub id: Uuid,
+ pub team_id: i32,
+ pub hash_id: String,
+ pub created_at: DateTime<Utc>,
+ pub version: String,
+ pub project: String,
+ pub metadata: Option<Value>,
+}
+
+// The info, as written to clickhouse at the exception level. The scalar fields are a
+// point-in-time snapshot; `id` references the release row so consumers can re-fetch the
+// current values if the release is later edited via the API.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ReleaseInfo {
+ id: Uuid,
+ version: String,
+ project: String,
+ timestamp: DateTime<Utc>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ metadata: Option<Value>,
+}
+
+impl ReleaseRecord {
+ pub async fn for_id<'c, E>(e: E, id: Uuid, team_id: i32) -> Result<Option<Self>, sqlx::Error>
+ where
+ E: Executor<'c, Database = sqlx::Postgres>,
+ {
+ let row = sqlx::query_as!(
+ Self,
+ r#"
+ SELECT id, team_id, hash_id, created_at, version, project, metadata
+ FROM posthog_errortrackingrelease
+ WHERE id = $1 AND team_id = $2
+ "#,
+ id,
+ team_id
+ )
+ .fetch_optional(e)
+ .await?;
+
+ Ok(row.map(Self::clamped))
+ }
+
+ pub async fn for_hash<'c, E>(
+ e: E,
+ hash_id: &str,
+ team_id: i32,
+ ) -> Result<Option<Self>, sqlx::Error>
+ where
+ E: Executor<'c, Database = sqlx::Postgres>,
+ {
+ let row = sqlx::query_as!(
+ Self,
+ r#"
+ SELECT id, team_id, hash_id, created_at, version, project, metadata
+ FROM posthog_errortrackingrelease
+ WHERE hash_id = $1 AND team_id = $2
+ "#,
+ hash_id,
+ team_id
+ )
+ .fetch_optional(e)
+ .await?;
+
+ Ok(row.map(Self::clamped))
+ }
+
+ pub fn to_info(&self) -> ReleaseInfo {
+ ReleaseInfo {
+ id: self.id,
+ project: self.project.clone(),
+ version: self.version.clone(),
+ timestamp: self.created_at,
+ metadata: self.metadata.clone(),
+ }
+ }
+
+ /// Bounds every field this record can carry into an event: `metadata` over the cap the API
+ /// enforces on new writes is dropped, `version`/`project` are truncated. The `id` survives,
+ /// so consumers can still fetch the full release.
+ fn clamped(mut self) -> Self {
+ let oversized = self.metadata.as_ref().is_some_and(|metadata| {
+ serde_json::to_string(metadata).map_or(true, |s| s.len() > MAX_RELEASE_METADATA_BYTES)
+ });
+ if oversized {
+ self.metadata = None;
+ }
+ truncate_chars(&mut self.version, MAX_RELEASE_TEXT_CHARS);
+ truncate_chars(&mut self.project, MAX_RELEASE_TEXT_CHARS);
+ self
+ }
+}
+
+fn truncate_chars(value: &mut String, max_chars: usize) {
+ if let Some((byte_index, _)) = value.char_indices().nth(max_chars) {
+ value.truncate(byte_index);
+ }
+}
+
+/// Reconstruct the release `hash_id` the CLI wrote for a mobile build, from the app metadata the
+/// SDK sends on every event. Mobile events carry no injected `$release_id`, so this is how their
+/// release is resolved. It must stay byte-for-byte identical to the CLI, which keys releases on
+/// `content_hash([name, version])` where `name` is the bundle identifier and `version` is
+/// `pack_version(short_version, build)`:
+/// - packing lives in `cli/src/sourcemaps/args.rs::pack_version`
+/// - hashing lives in `cli/src/utils/files/content.rs::content_hash` (SHA-512 over the name bytes
+/// followed by the version bytes, with no separator)
+pub fn mobile_release_hash_id(
+ namespace: &str,
+ version: Option<&str>,
+ build: Option<&str>,
+) -> Option<String> {
+ let packed = pack_version(version, build)?;
+ Some(release_hash_id(namespace, &packed))
+}
+
+fn pack_version(version: Option<&str>, build: Option<&str>) -> Option<String> {
+ match (version, build) {
+ (Some(v), Some(b)) => Some(format!("{v}+{b}")),
+ (Some(v), None) => Some(v.to_string()),
+ (None, Some(b)) => Some(b.to_string()),
+ (None, None) => None,
+ }
+}
+
+fn release_hash_id(name: &str, version: &str) -> String {
+ let mut hasher = Sha512::new();
+ hasher.update(name.as_bytes());
+ hasher.update(version.as_bytes());
+ format!("{:x}", hasher.finalize())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ /// Golden vectors pinning the release `hash_id`: `content_hash([name, pack_version(version,
+ /// build)])`. Identical to the CLI's `release_hash_id_golden_vectors` test in
+ /// `cli/src/sourcemaps/args.rs`. The CLI computes this hash when it creates a release and cymbal
+ /// reconstructs it from a mobile event's app metadata, so these literals must stay the same on
+ /// both sides or mobile releases silently stop resolving. Keep the two tests in sync.
+ #[test]
+ fn release_hash_id_golden_vectors() {
+ // (name, version, build, expected hash_id)
+ let cases: [(&str, Option<&str>, Option<&str>, &str); 4] = [
+ (
+ "com.posthog.iosraw",
+ Some("1.0"),
+ Some("1"),
+ "75605cac5268ba4bdc57b4c8336f6686802e88236ae4026418a18cabcde854d1015f18734489b8ec4c71c68773a027e5b880f7278b8ba6864a5334d76ef9eba6",
+ ),
+ (
+ "com.example.app",
+ Some("1.0"),
+ Some("42"),
+ "5a7f7b504d81759fa4e15f8b3bbc77c694a9dc222cfcd06c801fae9619076e97909edf651087106af331aea76463449f015ccc41ccacbf19148329b1c2c35aa7",
+ ),
+ (
+ "com.example.app",
+ Some("2.3"),
+ None,
+ "09aeeb69b914985562d4aa39d13033abf0f90c753ef90b0148cb06b8aeadca7dd1dd853fa24c7cc51d18cf251bb7348eae58906347a217a98d74ba7ca5673b66",
+ ),
+ (
+ "com.example.app",
+ None,
+ Some("99"),
+ "5e925a3f2e9349f64ab88eede466b641a7332dc79d6f1901d931fb659704a0475fa77a3ca25c0a60b2919547de8d94117fbcc52448e83aa72787a3fe35f725ae",
+ ),
+ ];
+
+ for (name, version, build, expected) in cases {
+ assert_eq!(
+ mobile_release_hash_id(name, version, build).as_deref(),
+ Some(expected),
+ "release hash_id drift for {name} {version:?}+{build:?}"
+ );
+ }
+ }
+
+ fn record(metadata: Option<Value>) -> ReleaseRecord {
+ ReleaseRecord {
+ id: Uuid::nil(),
+ team_id: 1,
+ hash_id: "hash".to_string(),
+ created_at: Utc::now(),
+ version: "1.0".to_string(),
+ project: "com.app".to_string(),
+ metadata,
+ }
+ }
+
+ #[test]
+ fn oversized_fields_are_clamped_but_sane_fields_survive() {
+ // The API does not bound these fields, and each is embedded into every matching event;
+ // without the clamp one oversized release row would inflate the whole event stream.
+ let mut big = record(Some(json!({"git": {"commit_id": "x".repeat(100_000)}})));
+ big.version = "v".repeat(10_000);
+ big.project = "é".repeat(10_000);
+ let clamped = big.clamped();
+ assert_eq!(clamped.metadata, None);
+ assert_eq!(clamped.version.chars().count(), MAX_RELEASE_TEXT_CHARS);
+ assert_eq!(clamped.project.chars().count(), MAX_RELEASE_TEXT_CHARS);
+
+ let small_value = json!({"git": {"commit_id": "abc123"}});
+ let small = record(Some(small_value.clone())).clamped();
+ assert_eq!(small.metadata, Some(small_value));
+ assert_eq!(small.version, "1.0");
+ }
+}
diff --git a/rust/cymbal/src/modes/processing/app_context.rs b/rust/cymbal/src/modes/processing/app_context.rs
index 47b2f1411746..2caa87c82676 100644
--- a/rust/cymbal/src/modes/processing/app_context.rs
+++ b/rust/cymbal/src/modes/processing/app_context.rs
@@ -14,6 +14,7 @@ use crate::{
error::UnhandledError,
modes::processing::config::{init_global_state, ProcessingConfig},
stages::rate_limiting::RedisRateLimiter,
+ stages::resolution::event_release::ReleaseCache,
stages::resolution::remote::{
dns::TokioDnsResolver, pool::EndpointPool, resolver::RemoteResolutionContext,
RemoteResolutionConfig,
@@ -53,6 +54,10 @@ pub struct AppContext {
// itself, so suppression / reopen always see current PG state (see `IssueLinker`).
// moka caches are cheap to clone (internally Arc'd).
pub issue_cache: Cache<(TeamId, String), Uuid>,
+ // Caches event-level release resolution (`$release_id` and the mobile app-metadata hash) so a
+ // per-event lookup doesn't re-hit Postgres for the same release, including the negative result
+ // for apps that never bound one. Lives here so it survives across batches.
+ pub release_cache: ReleaseCache,
}
impl Drop for AppContext {
@@ -161,6 +166,11 @@ impl AppContext {
.time_to_live(Duration::from_secs(config.issue_cache_ttl_seconds))
.build();
+ let release_cache = ReleaseCache::new(
+ config.release_cache_max_entries,
+ Duration::from_secs(config.release_cache_ttl_seconds),
+ );
+
let (remote_resolution, remote_resolution_refresh_task) =
build_remote_resolution(config).await?;
@@ -181,6 +191,7 @@ impl AppContext {
rate_limiter,
rate_limiter_enabled_team_ids,
issue_cache,
+ release_cache,
remote_resolution,
remote_resolution_refresh_task,
})
diff --git a/rust/cymbal/src/modes/processing/config.rs b/rust/cymbal/src/modes/processing/config.rs
index fc5fdfc80336..2332cc4c21fe 100644
--- a/rust/cymbal/src/modes/processing/config.rs
+++ b/rust/cymbal/src/modes/processing/config.rs
@@ -79,6 +79,19 @@ pub struct ProcessingConfig {
#[envconfig(default = "100000")]
pub issue_cache_capacity: u64,
+ // Event-level release resolution runs once per exception event. A release row is immutable
+ // once the CLI creates it, so a positive hit never goes stale; the TTL exists to let a
+ // negative result (app metadata that matches no release yet) expire after a dSYM upload
+ // creates the release, without re-querying Postgres on every event in the meantime.
+ #[envconfig(default = "300")]
+ pub release_cache_ttl_seconds: u64,
+
+ // An entry-count bound is a real memory bound: cached records clamp metadata to
+ // MAX_RELEASE_METADATA_BYTES at fetch, so a full cache tops out around
+ // max_entries * 8 KiB per lookup kind.
+ #[envconfig(default = "10000")]
+ pub release_cache_max_entries: u64,
+
// Maximum number of in-flight futures for a single `Batch::apply_func` call.
// This is a per-call-site limit, not a global pipeline-wide concurrency cap.
#[envconfig(default = "64")]
diff --git a/rust/cymbal/src/modes/processing/stages/pipeline.rs b/rust/cymbal/src/modes/processing/stages/pipeline.rs
index 10082b610b85..67e6d705ba29 100644
--- a/rust/cymbal/src/modes/processing/stages/pipeline.rs
+++ b/rust/cymbal/src/modes/processing/stages/pipeline.rs
@@ -55,7 +55,7 @@ impl Stage for ExceptionEventPipeline {
async fn process(self, batch: Batch<Self::Input>) -> StageResult<Self> {
batch
- // Resolve stack traces
+ // Resolve stack traces and the event-level release
.apply_stage(ResolutionStage::from(&self.app_context))
.await?
// Group events by fingerprint
diff --git a/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs b/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs
index fc6e1a500a2c..86ea65cd36f4 100644
--- a/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs
+++ b/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs
@@ -671,6 +671,7 @@ mod tests {
messages: vec![],
functions: vec![],
handled: false,
+ release: None,
},
fingerprint: SelectedFingerprint::manual("test-fingerprint".to_string()),
issue: Issue {
diff --git a/rust/cymbal/src/modes/processing/stages/resolution/event_release.rs b/rust/cymbal/src/modes/processing/stages/resolution/event_release.rs
new file mode 100644
index 000000000000..6a43756a7eb2
--- /dev/null
+++ b/rust/cymbal/src/modes/processing/stages/resolution/event_release.rs
@@ -0,0 +1,214 @@
+use std::{collections::HashMap, sync::Arc, time::Duration};
+
+use moka::future::{Cache, CacheBuilder};
+use serde_json::Value;
+use sqlx::{Executor, Postgres};
+use uuid::Uuid;
+
+use crate::{
+ error::UnhandledError,
+ frames::releases::{mobile_release_hash_id, ReleaseRecord},
+ metric_consts::{ANCILLARY_CACHE, EVENT_RELEASE_RESOLVER_OPERATOR},
+ stages::{pipeline::HandledError, resolution::ResolutionStage},
+ types::{
+ exception_event::{ExceptionEvent, Parsed},
+ operator::{OperatorResult, TeamId, ValueOperator},
+ },
+};
+
+/// Per-worker cache for event-level release resolution. Both lookups run once per exception event
+/// on the ingestion hot path, so without this a mobile app that never bound a release re-queries
+/// Postgres on every event it sends (the common negative case). The CLI never mutates a release
+/// after creating it, but the public API can update or delete one, so a positive hit can go stale;
+/// the TTL bounds that staleness, and also how long a miss lingers after a later dSYM upload
+/// creates the release. Caching the negative result too is what removes the per-event query.
+///
+/// The two lookups key on different things — a release-row id for web builds, a reconstructed
+/// content hash for mobile builds — so they get separate caches. `try_get_with` coalesces
+/// concurrent misses for the same key, so a cold cache under load issues one query per key rather
+/// than one per event. moka caches are internally Arc'd, so cloning this into each per-batch
+/// `ResolutionStage` is cheap.
+///
+/// An entry-count budget is a real memory bound here because every cached record is small:
+/// `metadata` is clamped to `MAX_RELEASE_METADATA_BYTES` at fetch, and negative entries (`None`)
+/// are near-empty.
+#[derive(Clone)]
+pub struct ReleaseCache {
+ by_id: Cache<(TeamId, Uuid), Option<ReleaseRecord>>,
+ by_hash: Cache<(TeamId, String), Option<ReleaseRecord>>,
+}
+
+impl ReleaseCache {
+ /// `max_entries` bounds each of the two caches independently, so the pair can hold twice that.
+ pub fn new(max_entries: u64, ttl: Duration) -> Self {
+ Self {
+ by_id: CacheBuilder::new(max_entries).time_to_live(ttl).build(),
+ by_hash: CacheBuilder::new(max_entries).time_to_live(ttl).build(),
+ }
+ }
+
+ async fn for_id<'c, E>(
+ &self,
+ e: E,
+ id: Uuid,
+ team_id: TeamId,
+ ) -> Result<Option<ReleaseRecord>, UnhandledError>
+ where
+ E: Executor<'c, Database = Postgres>,
+ {
+ let mut cache_miss = false;
+ let record = self
+ .by_id
+ .try_get_with((team_id, id), async {
+ cache_miss = true;
+ ReleaseRecord::for_id(e, id, team_id).await
+ })
+ .await
+ .map_err(|e: Arc<sqlx::Error>| UnhandledError::Other(e.to_string()))?;
+
+ record_cache_outcome("release_by_id", cache_miss);
+ Ok(record)
+ }
+
+ async fn for_hash<'c, E>(
+ &self,
+ e: E,
+ hash_id: &str,
+ team_id: TeamId,
+ ) -> Result<Option<ReleaseRecord>, UnhandledError>
+ where
+ E: Executor<'c, Database = Postgres>,
+ {
+ let mut cache_miss = false;
+ let record = self
+ .by_hash
+ .try_get_with((team_id, hash_id.to_string()), async {
+ cache_miss = true;
+ ReleaseRecord::for_hash(e, hash_id, team_id).await
+ })
+ .await
+ .map_err(|e: Arc<sqlx::Error>| UnhandledError::Other(e.to_string()))?;
+
+ record_cache_outcome("release_by_hash", cache_miss);
+ Ok(record)
+ }
+}
+
+fn record_cache_outcome(cache_type: &'static str, cache_miss: bool) {
+ let outcome = if cache_miss { "miss" } else { "hit" };
+ metrics::counter!(ANCILLARY_CACHE, "type" => cache_type, "outcome" => outcome).increment(1);
+}
+
+/// Resolves the event-level release without going through the per-frame symbol-set join, so the
+/// release is independent of which chunks resolved the stack. Runs inside `ResolutionStage` after
+/// `resolve_batch`, so a future fallback for legacy events (which carry neither `$release_id` nor
+/// app metadata) can read the resolved frames' symbol sets.
+///
+/// Two sources, in order of preference:
+/// 1. `$release_id` — web builds inject the release row's id, which the SDK emits verbatim. Direct
+/// foreign-key lookup.
+/// 2. app metadata — mobile SDKs inject nothing, but every event already carries `$app_namespace`,
+/// `$app_version`, and `$app_build`, which the CLI hashed into the release when it uploaded the
+/// dSYMs. We reconstruct that hash and look the release up by it.
+///
+/// When neither resolves, the event release stays unset and `$exception_release` is omitted;
+/// there is no per-frame fallback yet.
+#[derive(Clone, Default)]
+pub struct EventReleaseResolver;
+
+impl ValueOperator for EventReleaseResolver {
+ type Context = ResolutionStage;
+ type Item = ExceptionEvent<Parsed>;
+ type HandledError = HandledError;
+ type UnhandledError = UnhandledError;
+
+ fn name(&self) -> &'static str {
+ EVENT_RELEASE_RESOLVER_OPERATOR
+ }
+
+ async fn execute_value(
+ &self,
+ mut evt: ExceptionEvent<Parsed>,
+ ctx: ResolutionStage,
+ ) -> OperatorResult<Self> {
+ let release_id = evt
+ .properties()
+ .get("$release_id")
+ .and_then(Value::as_str)
+ .and_then(|id| Uuid::parse_str(id).ok());
+
+ if let Some(release_id) = release_id {
+ let record = ctx
+ .release_cache
+ .for_id(&ctx.posthog_pool, release_id, evt.team_id())
+ .await?;
+ evt.set_event_release(record);
+ } else if let Some(hash_id) = mobile_release_hash_from_props(evt.properties()) {
+ let record = ctx
+ .release_cache
+ .for_hash(&ctx.posthog_pool, &hash_id, evt.team_id())
+ .await?;
+ evt.set_event_release(record);
+ }
+
+ Ok(Ok(evt))
+ }
+}
+
+/// Rebuild the release `hash_id` from a mobile event's app metadata. Returns `None` for events that
+/// aren't from a mobile SDK (no `$app_namespace`) or lack any version info to key on.
+///
+/// `$app_build` arrives as a JSON number when the SDK parsed `CFBundleVersion` as an integer, so
+/// accept a number or a string and render it the same way the CLI saw the raw plist value.
+fn mobile_release_hash_from_props(props: &HashMap<String, Value>) -> Option<String> {
+ let namespace = props.get("$app_namespace").and_then(Value::as_str)?;
+ let version = props.get("$app_version").and_then(Value::as_str);
+ let build = props.get("$app_build").and_then(scalar_to_string);
+ mobile_release_hash_id(namespace, version, build.as_deref())
+}
+
+fn scalar_to_string(value: &Value) -> Option<String> {
+ match value {
+ Value::String(s) => Some(s.clone()),
+ Value::Number(n) => Some(n.to_string()),
+ _ => None,
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ fn props(value: Value) -> HashMap<String, Value> {
+ value
+ .as_object()
+ .unwrap()
+ .iter()
+ .map(|(k, v)| (k.clone(), v.clone()))
+ .collect()
+ }
+
+ #[test]
+ fn numeric_and_string_build_hash_identically() {
+ // The iOS SDK parses a numeric CFBundleVersion into an Int, so `$app_build` arrives as a JSON
+ // number. It must hash the same as its string form, since the CLI hashed the raw plist string.
+ let from_number = mobile_release_hash_from_props(&props(json!({
+ "$app_namespace": "com.app", "$app_version": "1.0", "$app_build": 1
+ })));
+ let from_string = mobile_release_hash_from_props(&props(json!({
+ "$app_namespace": "com.app", "$app_version": "1.0", "$app_build": "1"
+ })));
+ assert!(from_number.is_some());
+ assert_eq!(from_number, from_string);
+ }
+
+ #[test]
+ fn non_mobile_event_yields_no_hash() {
+ // No `$app_namespace` means it isn't a mobile SDK event, so there's nothing to resolve.
+ assert_eq!(
+ mobile_release_hash_from_props(&props(json!({"$app_version": "1.0"}))),
+ None
+ );
+ }
+}
diff --git a/rust/cymbal/src/modes/processing/stages/resolution/mod.rs b/rust/cymbal/src/modes/processing/stages/resolution/mod.rs
index 2e2a63bfbea3..054e99bf21a3 100644
--- a/rust/cymbal/src/modes/processing/stages/resolution/mod.rs
+++ b/rust/cymbal/src/modes/processing/stages/resolution/mod.rs
@@ -1,7 +1,9 @@
use std::sync::Arc;
+use sqlx::PgPool;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
+pub mod event_release;
pub mod exception;
pub mod frame;
pub mod remote;
@@ -11,6 +13,7 @@ use crate::{
error::UnhandledError,
metric_consts::RESOLUTION_STAGE,
stages::pipeline::{ParsedPipelineItem, ResolvedPipelineItem},
+ stages::resolution::event_release::{EventReleaseResolver, ReleaseCache},
stages::resolution::remote::resolver::{resolve_batch, RemoteResolutionContext},
symbolication::symbol::SymbolResolver,
types::{
@@ -22,6 +25,8 @@ use crate::{
#[derive(Clone)]
pub struct ResolutionStage {
pub remote: RemoteResolutionContext,
+ pub posthog_pool: PgPool,
+ pub release_cache: ReleaseCache,
}
#[derive(Clone)]
@@ -38,6 +43,8 @@ impl From<&Arc<AppContext>> for ResolutionStage {
.remote_resolution
.clone()
.expect("processing app context requires remote resolution"),
+ posthog_pool: app_context.posthog_pool.clone(),
+ release_cache: app_context.release_cache.clone(),
}
}
}
@@ -63,7 +70,10 @@ impl Stage for ResolutionStage {
}
async fn process(self, batch: Batch<Self::Input>) -> StageResult<Self> {
- let resolved = resolve_batch(batch, self.remote).await?;
+ // Release resolution runs after resolve_batch so it can later fall back to the resolved
+ // frames' symbol sets for legacy events.
+ let resolved = resolve_batch(batch, self.remote.clone()).await?;
+ let resolved = resolved.apply_operator(EventReleaseResolver, self).await?;
Ok(resolved.map(|item, ()| item.map(|event| event.into_resolved()), &mut ()))
}
}
diff --git a/rust/cymbal/src/modes/processing/types/exception_event.rs b/rust/cymbal/src/modes/processing/types/exception_event.rs
index 45e6a8c12eb7..f1d494bf7fcf 100644
--- a/rust/cymbal/src/modes/processing/types/exception_event.rs
+++ b/rust/cymbal/src/modes/processing/types/exception_event.rs
@@ -7,6 +7,7 @@ use uuid::Uuid;
use crate::{
error::EventError,
fingerprinting::{Fingerprint, FingerprintRecordPart, FingerprintVersion},
+ frames::releases::{ReleaseInfo, ReleaseRecord},
issue_resolution::Issue,
langs::native::DebugImage,
modes::processing::normalization::normalize_wire_order,
@@ -25,6 +26,9 @@ pub struct Parsed {
pub(crate) client_fingerprint: Option<String>,
pub(crate) legacy_order_exception_list: Option<ExceptionList>,
pub(crate) legacy_order_resolved: Option<ExceptionList>,
+ /// The release resolved from the event's `$release_id` or mobile app metadata, if any. Set by
+ /// `EventReleaseResolver` and emitted as `$exception_release` at `into_resolved`.
+ pub(crate) event_release: Option<ReleaseRecord>,
}
#[derive(Debug, Clone)]
@@ -34,16 +38,23 @@ pub struct ResolvedMetadata {
pub messages: Vec<String>,
pub functions: Vec<String>,
pub handled: bool,
+ /// The single release the event resolves to, from its `$release_id` or mobile app metadata.
+ /// Emitted as `$exception_release`.
+ pub release: Option<ReleaseInfo>,
}
impl ResolvedMetadata {
- fn from_exception_list(exception_list: &ExceptionList) -> Self {
+ fn from_exception_list(
+ exception_list: &ExceptionList,
+ event_release: Option<&ReleaseRecord>,
+ ) -> Self {
Self {
sources: exception_list.get_unique_sources(),
types: exception_list.get_unique_types(),
messages: exception_list.get_unique_messages(),
functions: exception_list.get_unique_functions(),
handled: exception_list.get_is_handled(),
+ release: event_release.map(ReleaseRecord::to_info),
}
}
}
@@ -202,8 +213,15 @@ impl ExceptionEvent<Parsed> {
self.state.legacy_order_resolved = Some(exception_list);
}
+ pub(crate) fn set_event_release(&mut self, release: Option<ReleaseRecord>) {
+ self.state.event_release = release;
+ }
+
pub(crate) fn into_resolved(self) -> ExceptionEvent<Resolved> {
- let metadata = ResolvedMetadata::from_exception_list(&self.exception_list);
+ let metadata = ResolvedMetadata::from_exception_list(
+ &self.exception_list,
+ self.state.event_release.as_ref(),
+ );
self.map_state(|state| Resolved {
metadata,
client_fingerprint: state.client_fingerprint,
@@ -353,6 +371,12 @@ impl ExceptionEvent<Finalized> {
serde_json::to_value(metadata.functions).expect("exception functions are serializable"),
);
map.insert("$exception_handled".into(), Value::Bool(metadata.handled));
+ if let Some(release) = metadata.release {
+ map.insert(
+ "$exception_release".into(),
+ serde_json::to_value(release).expect("exception release is serializable"),
+ );
+ }
map.insert(
"$exception_fingerprint".into(),
Value::String(fingerprint.value),
@@ -413,6 +437,12 @@ impl<S> ExceptionEvent<S> {
.expect("exception functions are serializable"),
);
map.insert("$exception_handled".into(), Value::Bool(metadata.handled));
+ if let Some(release) = &metadata.release {
+ map.insert(
+ "$exception_release".into(),
+ serde_json::to_value(release).expect("exception release is serializable"),
+ );
+ }
if let Some(name) = &self.proposed_issue_name {
map.insert("$issue_name".into(), Value::String(name.clone()));
}
@@ -474,6 +504,7 @@ impl<S> ExceptionEvent<S> {
issue_id,
other: self.props.clone(),
handled: metadata.handled,
+ release: metadata.release.clone(),
types: metadata.types.clone(),
values: metadata.messages.clone(),
sources: metadata.sources.clone(),
@@ -524,6 +555,7 @@ impl TryFrom<AnyEvent> for ExceptionEvent<Parsed> {
"$exception_types",
"$exception_values",
"$exception_functions",
+ "$exception_release",
"$exception_fingerprint_version",
"$exception_proposed_fingerprint",
"$exception_fingerprint_record",
@@ -550,6 +582,7 @@ impl TryFrom<AnyEvent> for ExceptionEvent<Parsed> {
client_fingerprint: raw.fingerprint,
legacy_order_exception_list,
legacy_order_resolved: None,
+ event_release: None,
},
})
}
@@ -600,6 +633,7 @@ mod tests {
messages: vec!["boom".to_string()],
functions: vec![],
handled: false,
+ release: None,
},
client_fingerprint: Some("client-fingerprint".to_string()),
legacy_order_resolved: None,
@@ -677,4 +711,65 @@ mod tests {
assert_eq!(rate_limit["$exception_issue_id"], issue.id.to_string());
assert_eq!(rate_limit["passthrough"], true);
}
+
+ fn release_record(hash_id: &str) -> ReleaseRecord {
+ ReleaseRecord {
+ id: Uuid::now_v7(),
+ team_id: 42,
+ hash_id: hash_id.to_string(),
+ created_at: chrono::DateTime::from_timestamp(0, 0).unwrap(),
+ version: "1.2.3".to_string(),
+ project: "my-app".to_string(),
+ metadata: None,
+ }
+ }
+
+ #[test]
+ fn event_release_populates_the_singular_release() {
+ // The event-level release (from `$release_id` or mobile app metadata) is the sole source of
+ // `$exception_release`; it does not depend on any frame carrying a release.
+ let metadata = ResolvedMetadata::from_exception_list(
+ &ExceptionList::default(),
+ Some(&release_record("hash-abc")),
+ );
+ assert!(metadata.release.is_some());
+ }
+
+ #[test]
+ fn missing_event_release_leaves_the_release_unset() {
+ // Without an event-level release there is nothing to emit; there is no per-frame fallback.
+ let metadata = ResolvedMetadata::from_exception_list(&ExceptionList::default(), None);
+ assert!(metadata.release.is_none());
+ }
+
+ #[test]
+ fn exception_release_emitted_only_when_a_release_resolves() {
+ let issue = Issue {
+ id: Uuid::now_v7(),
+ team_id: 42,
+ status: crate::issue_resolution::IssueStatus::Active,
+ name: None,
+ description: None,
+ created_at: chrono::Utc::now(),
+ };
+ let record = release_record("hash-abc");
+ let expected = serde_json::to_value(record.to_info()).unwrap();
+
+ // A resolved release surfaces as `$exception_release` on both the grouping-rule projection
+ // and the derived wire form.
+ let mut resolved = resolved_event();
+ resolved.state.metadata.release = Some(record.to_info());
+ let grouping = resolved.grouping_rule_properties();
+ assert_eq!(grouping["$exception_release"], expected);
+ let fingerprinted =
+ resolved.into_fingerprinted(SelectedFingerprint::manual("fp".to_string()));
+ let wire = serde_json::to_value(fingerprinted.processed_properties(&issue)).unwrap();
+ assert_eq!(wire["$exception_release"], expected);
+
+ // No release resolved: the property is omitted.
+ let mut resolved = resolved_event();
+ resolved.state.metadata.release = None;
+ let grouping = resolved.grouping_rule_properties();
+ assert!(grouping.get("$exception_release").is_none());
+ }
}
diff --git a/rust/cymbal/src/modes/processing/types/mod.rs b/rust/cymbal/src/modes/processing/types/mod.rs
index a4fef225a359..05a4caca9fe0 100644
--- a/rust/cymbal/src/modes/processing/types/mod.rs
+++ b/rust/cymbal/src/modes/processing/types/mod.rs
@@ -7,6 +7,7 @@ use std::ops::{Deref, DerefMut};
use uuid::Uuid;
use crate::fingerprinting::{FingerprintRecordPart, FingerprintVersion};
+use crate::frames::releases::ReleaseInfo;
use crate::frames::{Frame, RawFrame};
use crate::langs::native::DebugImage;
use crate::metric_consts::POSTHOG_SDK_EXCEPTION_RESOLVED;
@@ -149,6 +150,13 @@ struct ProcessedExceptionPropertiesWire {
other: HashMap<String, Value>,
#[serde(rename = "$exception_handled")]
handled: bool,
+ // The single release an event resolves to, from its `$release_id` or mobile app metadata.
+ #[serde(
+ rename = "$exception_release",
+ skip_serializing_if = "Option::is_none",
+ default
+ )]
+ release: Option<ReleaseInfo>,
#[serde(rename = "$exception_types")]
types: Vec<String>,
#[serde(rename = "$exception_values")]
diff --git a/rust/cymbal/tests/common/mod.rs b/rust/cymbal/tests/common/mod.rs
index 5ab9dd917ca6..6fa923d4740d 100644
--- a/rust/cymbal/tests/common/mod.rs
+++ b/rust/cymbal/tests/common/mod.rs
@@ -21,6 +21,7 @@ use cymbal::frames::{Frame, RawFrame};
use cymbal::langs::native::DebugImage;
use cymbal::stages::pipeline::ParsedPipelineItem;
use cymbal::stages::resolution::{
+ event_release::ReleaseCache,
remote::{
config::RemoteResolutionConfig, pool::EndpointPool, resolver::RemoteResolutionContext,
},
@@ -424,7 +425,15 @@ impl SymbolResolver for NoopResolver {
}
pub fn remote_stage(ctx: RemoteResolutionContext) -> ResolutionStage {
- ResolutionStage { remote: ctx }
+ ResolutionStage {
+ remote: ctx,
+ // Never connected: fixture events carry no release identifiers, so the release
+ // resolver never issues a query.
+ posthog_pool: sqlx::postgres::PgPoolOptions::new()
+ .connect_lazy("postgres://unused/unused")
+ .expect("lazy pool construction does not connect"),
+ release_cache: ReleaseCache::new(0, Duration::from_secs(0)),
+ }
}
pub async fn process_one(
diff --git a/rust/cymbal/tests/remote_resolution.rs b/rust/cymbal/tests/remote_resolution.rs
index 7bf6e3a4168e..ddbab0ed5c5f 100644
--- a/rust/cymbal/tests/remote_resolution.rs
+++ b/rust/cymbal/tests/remote_resolution.rs
@@ -76,7 +76,7 @@ fn remote_stage_with_resolver(
ctx: cymbal::stages::resolution::remote::resolver::RemoteResolutionContext,
_resolver: Arc<CountingResolver>,
) -> ResolutionStage {
- ResolutionStage { remote: ctx }
+ remote_stage(ctx)
}
fn parsed_event(uuid: Uuid, properties: serde_json::Value) -> ExceptionEvent<Parsed> {