:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(cymbal): skip no-op stack frame rewrites (#94995)
José Sequeirac17afc78cf45
diff --git a/rust/cymbal/.sqlx/query-375af07f86a416378421012dd2db070d3749e8b524017814c69d3224bfd03327.json b/rust/cymbal/.sqlx/query-375af07f86a416378421012dd2db070d3749e8b524017814c69d3224bfd03327.jsonnew file mode 100644index 000000000000..d348714677c7--- /dev/null+++ b/rust/cymbal/.sqlx/query-375af07f86a416378421012dd2db070d3749e8b524017814c69d3224bfd03327.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE posthog_errortrackingstackframe\n SET created_at = $3\n WHERE raw_id = $1 AND team_id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Int4",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "375af07f86a416378421012dd2db070d3749e8b524017814c69d3224bfd03327"+}diff --git a/rust/cymbal/.sqlx/query-0eb06c157aeb1daeb4a0731a577e8be163da4904f4f5222988f4e697f6daeede.json b/rust/cymbal/.sqlx/query-7eb514f26fb17e7502338ff834e6f3caf8988cea1a31d7e615c29c062776a81d.jsonsimilarity index 56%rename from rust/cymbal/.sqlx/query-0eb06c157aeb1daeb4a0731a577e8be163da4904f4f5222988f4e697f6daeede.jsonrename to rust/cymbal/.sqlx/query-7eb514f26fb17e7502338ff834e6f3caf8988cea1a31d7e615c29c062776a81d.jsonindex 55009c4f5d1b..454503be4ab7 100644--- a/rust/cymbal/.sqlx/query-0eb06c157aeb1daeb4a0731a577e8be163da4904f4f5222988f4e697f6daeede.json+++ b/rust/cymbal/.sqlx/query-7eb514f26fb17e7502338ff834e6f3caf8988cea1a31d7e615c29c062776a81d.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO posthog_errortrackingstackframe (raw_id, part, team_id, created_at, symbol_set_id, contents, resolved, id, context)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)\n ON CONFLICT (raw_id, team_id, part) DO UPDATE SET\n created_at = $4,\n symbol_set_id = $5,\n contents = $6,\n resolved = $7,\n context = $9\n ",+ "query": "\n INSERT INTO posthog_errortrackingstackframe (raw_id, part, team_id, created_at, symbol_set_id, contents, resolved, id, context)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)\n ON CONFLICT (raw_id, team_id, part) DO UPDATE SET\n created_at = $4,\n symbol_set_id = $5,\n contents = $6,\n resolved = $7,\n context = $9\n WHERE posthog_errortrackingstackframe.symbol_set_id IS DISTINCT FROM $5\n OR posthog_errortrackingstackframe.contents IS DISTINCT FROM $6\n OR posthog_errortrackingstackframe.resolved IS DISTINCT FROM $7\n OR posthog_errortrackingstackframe.context IS DISTINCT FROM $9\n OR posthog_errortrackingstackframe.created_at < COALESCE($10, 'infinity'::timestamptz)\n ","describe": {"columns": [],"parameters": {@@ -13,10 +13,11 @@"Jsonb","Bool","Uuid",- "Jsonb"+ "Jsonb",+ "Timestamptz"]},"nullable": []},- "hash": "0eb06c157aeb1daeb4a0731a577e8be163da4904f4f5222988f4e697f6daeede"+ "hash": "7eb514f26fb17e7502338ff834e6f3caf8988cea1a31d7e615c29c062776a81d"}diff --git a/rust/cymbal/src/core/config.rs b/rust/cymbal/src/core/config.rsindex 075454e8018b..21897dfdbfde 100644--- a/rust/cymbal/src/core/config.rs+++ b/rust/cymbal/src/core/config.rs@@ -67,6 +67,12 @@ pub struct ResolverConfig {#[envconfig(default = "300")]pub frame_unresolved_ttl_seconds: u64,+ // When enabled, a re-resolution that produced an unchanged frame snapshot refreshes+ // created_at with a timestamp-only UPDATE instead of rewriting every row's full+ // contents, and skips the write entirely when no row needs a freshness refresh yet.+ #[envconfig(default = "false")]+ pub skip_unchanged_frame_rewrites: bool,+// 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 resultdiff --git a/rust/cymbal/src/core/symbolication/symbol/local.rs b/rust/cymbal/src/core/symbolication/symbol/local.rsindex b538c849a162..796bc48e18b8 100644--- a/rust/cymbal/src/core/symbolication/symbol/local.rs+++ b/rust/cymbal/src/core/symbolication/symbol/local.rs@@ -4,6 +4,7 @@ use std::{};use async_trait::async_trait;+use chrono::Utc;use common_types::error_tracking::RawFrameId;use moka::{@@ -25,7 +26,8 @@ use crate::{},symbolication::resolve::Resolve,symbolication::symbol::records::{- classify_frame_snapshot, ErrorTrackingStackFrame, FrameResultTtlPolicy,+ classify_frame_snapshot, unchanged_snapshot_needs_refresh, ErrorTrackingStackFrame,+ FrameResultTtlPolicy,},symbolication::symbol::SymbolResolver,symbolication::symbol_store::{@@ -55,6 +57,7 @@ pub struct LocalSymbolResolver {ttl_policy: FrameResultTtlPolicy,// Lines of pre/post source context to attach per resolved frame.context_lines: usize,+ skip_unchanged_rewrites: bool,}impl Expiry<RawFrameId, Vec<ErrorTrackingStackFrame>> for FrameResultTtlPolicy {@@ -121,6 +124,7 @@ impl LocalSymbolResolver {release_id_cache,ttl_policy,context_lines: config.context_line_count,+ skip_unchanged_rewrites: config.skip_unchanged_frame_rewrites,}}@@ -202,23 +206,81 @@ impl LocalSymbolResolver {}let write_outcome = classify_frame_snapshot(&stored.records, &records);+ let persisted = self.skip_unchanged_rewrites+ && write_outcome == FrameWriteOutcome::Unchanged+ && self+ .persist_unchanged_snapshot(&raw_id, &stored.records, records.len() as u64)+ .await?;++ if !persisted {+ let refresh_if_older_than = self+ .skip_unchanged_rewrites+ .then(|| Utc::now() - self.ttl_policy.refresh_age(&raw_id, &stored.records));+ for record in &records {+ let rows_affected = match record+ .save_with_refresh_guard(&self.pool, refresh_if_older_than)+ .await+ {+ Ok(rows_affected) => rows_affected,+ Err(error) => {+ record_frame_write(FrameWriteOutcome::Error, 0);+ return Err(error);+ }+ };+ record_frame_write(write_outcome, rows_affected);+ }+ }+for record in &records {- let rows_affected = match record.save(&self.pool).await {+ if record.contents.suspicious {+ metrics::counter!(SUSPICIOUS_FRAMES_DETECTED, "frame_type" => "resolved")+ .increment(1);+ }+ }+ Ok(records)+ }++ // Persists an unchanged snapshot without rewriting the rows: skips outright while+ // every stored row is still well inside its TTL, and otherwise refreshes+ // created_at alone. Returns false when the refresh touched fewer rows than the+ // snapshot holds (a concurrent delete, such as symbol-set cleanup), so the caller+ // falls back to the full upsert and restores the rows. Any error also fails open+ // through the caller's normal save path semantics.+ async fn persist_unchanged_snapshot(+ &self,+ raw_id: &RawFrameId,+ stored: &[ErrorTrackingStackFrame],+ part_count: u64,+ ) -> Result<bool, UnhandledError> {+ // The per-part upsert loop is not transactional, so a racing writer can+ // leave a multi-part snapshot half written. A timestamp-only refresh+ // spanning every part would mark that mixed snapshot fresh for a full+ // TTL. A single-part save is atomic, so only single-part snapshots take+ // the timestamp-only path.+ if part_count != 1 {+ return Ok(false);+ }++ let now = Utc::now();+ if !unchanged_snapshot_needs_refresh(&self.ttl_policy, raw_id, stored, now) {+ record_frame_write(FrameWriteOutcome::Skipped, 0);+ return Ok(true);+ }++ let rows_affected =+ match ErrorTrackingStackFrame::refresh_created_at(&self.pool, raw_id, now).await {Ok(rows_affected) => rows_affected,Err(error) => {record_frame_write(FrameWriteOutcome::Error, 0);return Err(error);}};- record_frame_write(write_outcome, rows_affected);-- let r_frame = &record.contents;- if r_frame.suspicious {- metrics::counter!(SUSPICIOUS_FRAMES_DETECTED, "frame_type" => "resolved")- .increment(1);- }+ if rows_affected < part_count {+ return Ok(false);}- Ok(records)++ record_frame_write(FrameWriteOutcome::Refreshed, rows_affected);+ Ok(true)}}@@ -315,6 +377,7 @@ mod test {use common_types::ClickHouseEvent;use httpmock::MockServer;use mockall::predicate;+ use posthog_symbol_data::{write_symbol_data, SourceAndMap};use sqlx::PgPool;use symbolic::sourcemapcache::SourceMapCacheWriter;use uuid::Uuid;@@ -554,6 +617,72 @@ mod test {assert_eq!(resolved_2, resolved_3);}+ // With the flag on, a re-resolution that produces an identical snapshot must keep+ // the stored row fresh (or every pod re-resolves the frame on each cache miss)+ // while keeping a single, content-identical row.+ #[sqlx::test(migrations = "./tests/test_migrations")]+ pub async fn unchanged_reresolution_keeps_row_fresh_without_reinserting(pool: PgPool) {+ // The second resolve reloads the symbol set from storage, so the mock must+ // return the persisted format (write_symbol_data), not the sourcemapcache+ // bytes expect_puts_and_gets serves.+ let stored_payload = Bytes::from(+ write_symbol_data(SourceAndMap {+ minified_source: String::from_utf8(MINIFIED.to_vec()).unwrap(),+ sourcemap: String::from_utf8(MAP.to_vec()).unwrap(),+ })+ .unwrap(),+ );+ let (mut config, catalog, server) = setup_test_context(pool.clone(), move |c, mut cl| {+ cl.expect_put()+ .with(+ predicate::eq(c.object_storage_bucket.clone()),+ predicate::str::starts_with(c.ss_prefix.clone()),+ predicate::always(),+ )+ .returning(|_, _, _| Ok(()))+ .times(1);+ cl.expect_get()+ .with(+ predicate::eq(c.object_storage_bucket.clone()),+ predicate::str::starts_with(c.ss_prefix.clone()),+ )+ .returning(move |_, _| Ok(Some(stored_payload.clone())))+ .times(1);+ cl+ })+ .await;+ config.skip_unchanged_frame_rewrites = true;+ // A zero TTL makes the stored row stale immediately, forcing the second+ // resolve down the re-resolution path.+ config.frame_resolved_ttl_seconds = 0;+ let resolver = LocalSymbolResolver::new(&config, Arc::new(catalog), pool.clone());++ let frame = get_test_frame(&server);+ let resolved_1 = resolver.resolve_raw_frame(0, &frame, &[]).await.unwrap();++ let (id_1, created_1): (Uuid, chrono::DateTime<chrono::Utc>) =+ sqlx::query_as("SELECT id, created_at FROM posthog_errortrackingstackframe")+ .fetch_one(&pool)+ .await+ .unwrap();++ resolver.cache.invalidate_all();+ resolver.cache.run_pending_tasks().await;++ let frame = get_test_frame(&server);+ let resolved_2 = resolver.resolve_raw_frame(0, &frame, &[]).await.unwrap();+ assert_eq!(resolved_1, resolved_2);++ let rows: Vec<(Uuid, chrono::DateTime<chrono::Utc>)> =+ sqlx::query_as("SELECT id, created_at FROM posthog_errortrackingstackframe")+ .fetch_all(&pool)+ .await+ .unwrap();+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].0, id_1);+ assert!(rows[0].1 > created_1);+ }+async fn insert_release(pool: &PgPool, team_id: i32, days_ago: i32) -> Uuid {let id = Uuid::new_v4();sqlx::query(diff --git a/rust/cymbal/src/core/symbolication/symbol/records.rs b/rust/cymbal/src/core/symbolication/symbol/records.rsindex 75563cacd28c..ae507664489a 100644--- a/rust/cymbal/src/core/symbolication/symbol/records.rs+++ b/rust/cymbal/src/core/symbolication/symbol/records.rs@@ -43,6 +43,19 @@ impl FrameResultTtlPolicy {base_ttl + self.jitter_for(id, base_ttl)}+ // Age past which an unchanged snapshot must still write, so created_at keeps the+ // rows inside the freshness window `load_snapshot` checks. Half the TTL leaves a+ // full half-window of slack before a skipped write could turn the rows stale. The+ // TTL carries the per-frame jitter from `stable_jitter_hash`, so refresh+ // boundaries do not synchronize across frames.+ pub(crate) fn refresh_age(+ &self,+ id: &RawFrameId,+ records: &[ErrorTrackingStackFrame],+ ) -> Duration {+ self.ttl_for_records(id, records) / 2+ }+fn jitter_for(&self, id: &RawFrameId, base_ttl: Duration) -> Duration {if base_ttl <= Duration::zero() {return Duration::zero();@@ -88,6 +101,22 @@ pub(crate) struct StoredFrameSnapshot {pub fresh: bool,}+// Decides whether an unchanged snapshot still needs a created_at refresh. Any row+// past the refresh age must write: a row whose created_at never refreshes goes+// permanently stale, and cymbal then re-resolves that frame on every cache miss+// forever, which costs far more than the write it saved.+pub(crate) fn unchanged_snapshot_needs_refresh(+ policy: &FrameResultTtlPolicy,+ id: &RawFrameId,+ records: &[ErrorTrackingStackFrame],+ now: DateTime<Utc>,+) -> bool {+ let refresh_age = policy.refresh_age(id, records);+ records+ .iter()+ .any(|record| record.created_at <= now - refresh_age)+}+pub(crate) fn classify_frame_snapshot(existing: &[ErrorTrackingStackFrame],current: &[ErrorTrackingStackFrame],@@ -130,6 +159,22 @@ impl ErrorTrackingStackFrame {}pub async fn save<'c, E>(&self, e: E) -> Result<u64, UnhandledError>+ where+ E: Executor<'c, Database = sqlx::Postgres>,+ {+ self.save_with_refresh_guard(e, None).await+ }++ // Racing writers load the same stale snapshot and would each rewrite identical+ // content. With a threshold, the conflict update becomes a server-side no-op+ // (no new tuple version, rows_affected 0) unless the row's content differs or+ // its created_at is older than the threshold. `None` keeps the update+ // unconditional.+ pub(crate) async fn save_with_refresh_guard<'c, E>(+ &self,+ e: E,+ refresh_if_older_than: Option<DateTime<Utc>>,+ ) -> Result<u64, UnhandledError>whereE: Executor<'c, Database = sqlx::Postgres>,{@@ -148,6 +193,11 @@ impl ErrorTrackingStackFrame {contents = $6,resolved = $7,context = $9+ WHERE posthog_errortrackingstackframe.symbol_set_id IS DISTINCT FROM $5+ OR posthog_errortrackingstackframe.contents IS DISTINCT FROM $6+ OR posthog_errortrackingstackframe.resolved IS DISTINCT FROM $7+ OR posthog_errortrackingstackframe.context IS DISTINCT FROM $9+ OR posthog_errortrackingstackframe.created_at < COALESCE($10, 'infinity'::timestamptz)"#,self.id.hash_id,self.id.part,@@ -158,6 +208,36 @@ impl ErrorTrackingStackFrame {self.resolved,Uuid::now_v7(),context,+ refresh_if_older_than,+ )+ .execute(e)+ .await?;+ Ok(result.rows_affected())+ }++ // Bumps created_at on every part of a raw frame without rewriting the row+ // contents, so an unchanged re-resolution refreshes freshness without the fat+ // JSON rewrite (a smaller tuple WAL record and no re-TOAST of `contents`).+ // Returns the number of rows updated; a count below the loaded part count means+ // the rows changed under us (for example symbol-set cleanup deleted them) and+ // the caller must fall back to the full upsert.+ pub(crate) async fn refresh_created_at<'c, E>(+ e: E,+ id: &RawFrameId,+ created_at: DateTime<Utc>,+ ) -> Result<u64, UnhandledError>+ where+ E: Executor<'c, Database = sqlx::Postgres>,+ {+ let result = sqlx::query!(+ r#"+ UPDATE posthog_errortrackingstackframe+ SET created_at = $3+ WHERE raw_id = $1 AND team_id = $2+ "#,+ id.hash_id,+ id.team_id,+ created_at,).execute(e).await?;@@ -306,6 +386,118 @@ mod tests {assert_eq!(parts, (0..8).collect::<Vec<i32>>());}+ // A refresh that misses a part, or fails to move created_at, leaves the snapshot+ // permanently stale and cymbal re-resolves the frame on every cache miss forever.+ #[sqlx::test(migrations = "./tests/test_migrations")]+ async fn refresh_created_at_restores_freshness_without_rewriting_contents(pool: sqlx::PgPool) {+ let raw_id = RawFrameId::new("raw-frame-id".to_string(), 0);+ let policy = FrameResultTtlPolicy::new(Duration::minutes(30), Duration::minutes(30));+ for part in 0..2 {+ let id = FrameId::new(raw_id.hash_id.clone(), raw_id.team_id, part);+ let frame = frame_with_part(id.clone(), part);+ let mut record = ErrorTrackingStackFrame::new(id, None, frame, true, None);+ record.created_at = Utc::now() - Duration::hours(2);+ record.save(&pool).await.unwrap();+ }++ let stale = ErrorTrackingStackFrame::load_snapshot(&pool, &raw_id, policy)+ .await+ .unwrap();+ assert!(!stale.fresh);++ let rows = ErrorTrackingStackFrame::refresh_created_at(&pool, &raw_id, Utc::now())+ .await+ .unwrap();+ assert_eq!(rows, 2);++ let refreshed = ErrorTrackingStackFrame::load_snapshot(&pool, &raw_id, policy)+ .await+ .unwrap();+ assert!(refreshed.fresh);+ assert_eq!(+ classify_frame_snapshot(&stale.records, &refreshed.records),+ FrameWriteOutcome::Unchanged+ );+ }++ // Without the guard, every racing writer that loaded the same stale snapshot+ // rewrites an identical row, creating a dead tuple and index churn per race.+ #[sqlx::test(migrations = "./tests/test_migrations")]+ async fn guarded_save_suppresses_noop_conflict_rewrites(pool: sqlx::PgPool) {+ let id = FrameId::new("raw-frame-id".to_string(), 0, 0);+ let frame = frame_with_part(id.clone(), 0);+ let record = ErrorTrackingStackFrame::new(id, None, frame, true, None);+ assert_eq!(record.save(&pool).await.unwrap(), 1);++ let threshold = Some(Utc::now() - Duration::minutes(10));++ let mut duplicate = record.clone();+ duplicate.created_at = Utc::now();+ assert_eq!(+ duplicate+ .save_with_refresh_guard(&pool, threshold)+ .await+ .unwrap(),+ 0,+ "identical content on a fresh row is a server-side no-op"+ );++ assert_eq!(+ duplicate+ .save_with_refresh_guard(&pool, Some(Utc::now() + Duration::seconds(1)))+ .await+ .unwrap(),+ 1,+ "identical content still refreshes a row older than the threshold"+ );++ let mut changed = record.clone();+ changed.resolved = false;+ assert_eq!(+ changed+ .save_with_refresh_guard(&pool, threshold)+ .await+ .unwrap(),+ 1,+ "changed content always writes"+ );++ assert_eq!(+ record.save(&pool).await.unwrap(),+ 1,+ "an unguarded save keeps the unconditional update"+ );+ }++ #[test]+ fn unchanged_snapshot_refreshes_only_past_half_ttl() {+ let policy = FrameResultTtlPolicy::new(Duration::seconds(1000), Duration::seconds(1000));+ let id = FrameId::new("raw-frame-id".to_string(), 1, 0);+ let frame = frame_with_part(id.clone(), 0);+ let mut record = ErrorTrackingStackFrame::new(id.clone(), None, frame, true, None);+ let raw_id = RawFrameId::new(id.hash_id.clone(), id.team_id);+ let now = Utc::now();++ // The jittered TTL falls in [1000s, 1100s], so the refresh boundary falls in+ // [500s, 550s]. Ages on either side of that band decide the same way for any+ // jitter value.+ record.created_at = now - Duration::seconds(499);+ assert!(!unchanged_snapshot_needs_refresh(+ &policy,+ &raw_id,+ std::slice::from_ref(&record),+ now,+ ));++ record.created_at = now - Duration::seconds(551);+ assert!(unchanged_snapshot_needs_refresh(+ &policy,+ &raw_id,+ std::slice::from_ref(&record),+ now,+ ));+ }+#[test]fn durable_snapshot_classification_covers_every_persisted_field() {use crate::core::write_attribution::FrameWriteOutcome;diff --git a/rust/cymbal/src/core/write_attribution.rs b/rust/cymbal/src/core/write_attribution.rsindex ca96c1083450..6f137e41f2e4 100644--- a/rust/cymbal/src/core/write_attribution.rs+++ b/rust/cymbal/src/core/write_attribution.rs@@ -5,6 +5,11 @@ pub(crate) enum FrameWriteOutcome {Insert,Changed,Unchanged,+ // An unchanged snapshot persisted as a created_at-only UPDATE, one statement+ // for every part of the raw frame, instead of a full per-part upsert.+ Refreshed,+ // An unchanged snapshot that needed no freshness refresh, so no query ran.+ Skipped,Error,}@@ -14,9 +19,18 @@ impl FrameWriteOutcome {Self::Insert => "insert",Self::Changed => "changed",Self::Unchanged => "unchanged",+ Self::Refreshed => "refreshed",+ Self::Skipped => "skipped",Self::Error => "error",}}++ const fn mutation(self) -> PostgresMutation {+ match self {+ Self::Refreshed => PostgresMutation::Update,+ _ => PostgresMutation::Upsert,+ }+ }}#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -93,7 +107,7 @@ pub(crate) fn record_frame_write(outcome: FrameWriteOutcome, rows_affected: u64)record_rows_affected("stack_frame","frame_snapshot",- PostgresMutation::Upsert,+ outcome.mutation(),rows_affected,);}@@ -155,9 +169,15 @@ mod tests {FrameWriteOutcome::Insert,FrameWriteOutcome::Changed,FrameWriteOutcome::Unchanged,+ FrameWriteOutcome::Refreshed,+ FrameWriteOutcome::Skipped,FrameWriteOutcome::Error,] {- record_frame_write(outcome, u64::from(outcome != FrameWriteOutcome::Error));+ let rows_affected = u64::from(!matches!(+ outcome,+ FrameWriteOutcome::Skipped | FrameWriteOutcome::Error+ ));+ record_frame_write(outcome, rows_affected);}for purpose in [@@ -200,8 +220,8 @@ mod tests {.filter(|(key, _, _, _)| key.key().name() == POSTGRES_ROWS_AFFECTED).collect::<Vec<_>>();- assert_eq!(attempts.len(), 19);- assert_eq!(rows.len(), 6);+ assert_eq!(attempts.len(), 21);+ assert_eq!(rows.len(), 7);let allowed_label_keys = HashSet::from(["table", "purpose", "outcome"]);let allowed_tables = HashSet::from(["stack_frame", "symbol_set"]);@@ -217,6 +237,7 @@ mod tests {"insert","changed","unchanged",+ "refreshed","written","skipped","error",