:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(error-tracking): drop code variables for listed teams in cymbal (#110677)
Aleksander Błaszkiewiczc4981a126442
diff --git a/rust/cymbal/README.md b/rust/cymbal/README.mdindex a781ead218e5..b21c3bcb24b9 100644--- a/rust/cymbal/README.md+++ b/rust/cymbal/README.md@@ -75,6 +75,29 @@ Symbol resolution runs in resolution-mode pods via theSee the [resolution mode README](src/modes/resolution/README.md) forconfiguration and operator guidance.+## Dropping code variables (processing mode)++`ERROR_TRACKING_DROP_CODE_VARIABLES_TEAM_IDS` takes a comma-separated list of+team ids. The default is empty, which keeps code variables for every team. An+entry that is not a team id stops processing mode at startup, so a typo cannot+leave a team out of the list without an error. Use+it for a team that receives events from senders you cannot upgrade, such as+old SDK versions that attach frame locals without masking.++For a listed team, processing mode removes `code_variables` from every frame+two times:++1. On the incoming event, before it is parsed. The resolution service then+ never stores the variables, and an event that fails to parse is returned+ without them.+2. On the resolved frames. A stored frame record keeps the variables of the+ event that first resolved that frame. The frame id does not include code+ variables, so the record is reused for later events that hit the same+ frame. This pass removes those replayed variables.++The setting does not change frame records that are already in Postgres. Remove+their variables separately if they must not stay there.+## Remote resolution behaviorThe public HTTP contract stays `POST /process`: callers send an array ofdiff --git a/rust/cymbal/src/modes/processing/app_context.rs b/rust/cymbal/src/modes/processing/app_context.rsindex 1175647f3dd9..faddb7a720ca 100644--- a/rust/cymbal/src/modes/processing/app_context.rs+++ b/rust/cymbal/src/modes/processing/app_context.rs@@ -52,6 +52,7 @@ pub struct AppContext {// Team allowlist for the rate limiter: `None` = all teams, `Some(set)` = only// these. Parsed from ERROR_TRACKING_RATE_LIMITER_ENABLED_TEAM_IDS.pub rate_limiter_enabled_team_ids: Option<HashSet<i32>>,+ pub drop_code_variables_team_ids: Arc<HashSet<i32>>,// Shared `(team_id, fingerprint) -> issue_id` mapping cache. Lives on AppContext so// it persists across requests — only the stable mapping is cached, never the Issue// itself, so suppression / reopen always see current PG state (see `IssueLinker`).@@ -180,6 +181,9 @@ impl AppContext {let rate_limiter = build_rate_limiter(config).await?;let rate_limiter_enabled_team_ids =parse_team_id_allowlist(&config.error_tracking_rate_limiter_enabled_team_ids);+ let drop_code_variables_team_ids = Arc::new(parse_strict_team_id_list(+ &config.drop_code_variables_team_ids,+ )?);Ok(Self {health_registry,@@ -194,6 +198,7 @@ impl AppContext {issue_buckets_heal_gate: HealGate::new(),rate_limiter,rate_limiter_enabled_team_ids,+ drop_code_variables_team_ids,issue_cache,release_cache,remote_resolution,@@ -251,6 +256,20 @@ fn parse_team_id_allowlist(value: &str) -> Option<HashSet<i32>> {)}+/// A typo must stop startup, because a skipped entry would silently leave that team out.+fn parse_strict_team_id_list(value: &str) -> Result<HashSet<i32>, UnhandledError> {+ value+ .split(',')+ .map(str::trim)+ .filter(|entry| !entry.is_empty())+ .map(|entry| {+ entry.parse::<i32>().map_err(|_| {+ UnhandledError::Other(format!("invalid team id {entry:?} in team id list"))+ })+ })+ .collect()+}+async fn build_remote_resolution(config: &ProcessingConfig,) -> Result<(Option<RemoteResolutionContext>, Option<JoinHandle<()>>), UnhandledError> {@@ -284,3 +303,26 @@ async fn build_remote_resolution(Some(refresh_task),))}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn strict_team_id_list_parses_valid_input() {+ for (input, expected) in [("", vec![]), ("2", vec![2]), (" 2, 3 ,", vec![2, 3])] {+ assert_eq!(+ parse_strict_team_id_list(input).unwrap(),+ expected.into_iter().collect::<HashSet<i32>>(),+ "input {input:?}"+ );+ }+ }++ #[test]+ fn strict_team_id_list_rejects_a_typo() {+ for input in ["2,x3", "2;3", "two"] {+ assert!(parse_strict_team_id_list(input).is_err(), "input {input:?}");+ }+ }+}diff --git a/rust/cymbal/src/modes/processing/config.rs b/rust/cymbal/src/modes/processing/config.rsindex c7f329d2cf97..68b051e43398 100644--- a/rust/cymbal/src/modes/processing/config.rs+++ b/rust/cymbal/src/modes/processing/config.rs@@ -200,6 +200,10 @@ pub struct ProcessingConfig {#[envconfig(default = "")]pub spike_alert_enabled_team_ids: String,+ // Teams whose frame code variables are dropped, for old SDK senders we cannot upgrade.+ #[envconfig(from = "ERROR_TRACKING_DROP_CODE_VARIABLES_TEAM_IDS", default = "")]+ pub drop_code_variables_team_ids: String,+// ----------------------------------------------------------------------// Remote resolution (cymbal.resolution.v1).// ----------------------------------------------------------------------diff --git a/rust/cymbal/src/modes/processing/stages/http_pipeline.rs b/rust/cymbal/src/modes/processing/stages/http_pipeline.rsindex b860fea9df83..86286925f66e 100644--- a/rust/cymbal/src/modes/processing/stages/http_pipeline.rs+++ b/rust/cymbal/src/modes/processing/stages/http_pipeline.rs@@ -34,6 +34,17 @@ impl Stage for HttpEventPipeline {async fn process(self, batch: Batch<Self::Input>) -> StageResult<Self> {let (preprocess, postprocess) =create_pre_post_processing(batch.len(), Box::new(handle_result));+ // Strip first: pre-processing keeps this copy and returns it unchanged on failure.+ let drop_team_ids = self.app_context.drop_code_variables_team_ids.clone();+ let batch = batch.map(+ |mut event, ()| {+ if drop_team_ids.contains(&event.team_id) {+ event.drop_code_variables();+ }+ event+ },+ &mut (),+ );batch.apply_stage(preprocess).await?diff --git a/rust/cymbal/src/modes/processing/stages/resolution/mod.rs b/rust/cymbal/src/modes/processing/stages/resolution/mod.rsindex 054e99bf21a3..0811e27c0155 100644--- a/rust/cymbal/src/modes/processing/stages/resolution/mod.rs+++ b/rust/cymbal/src/modes/processing/stages/resolution/mod.rs@@ -1,4 +1,4 @@-use std::sync::Arc;+use std::{collections::HashSet, sync::Arc};use sqlx::PgPool;use tokio::sync::{OwnedSemaphorePermit, Semaphore};@@ -27,6 +27,7 @@ pub struct ResolutionStage {pub remote: RemoteResolutionContext,pub posthog_pool: PgPool,pub release_cache: ReleaseCache,+ pub drop_code_variables_team_ids: Arc<HashSet<i32>>,}#[derive(Clone)]@@ -45,6 +46,7 @@ impl From<&Arc<AppContext>> for ResolutionStage {.expect("processing app context requires remote resolution"),posthog_pool: app_context.posthog_pool.clone(),release_cache: app_context.release_cache.clone(),+ drop_code_variables_team_ids: app_context.drop_code_variables_team_ids.clone(),}}}@@ -73,6 +75,18 @@ impl Stage for ResolutionStage {// 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 drop_team_ids = self.drop_code_variables_team_ids.clone();+ let resolved = resolved.map(+ |item, ()| {+ item.map(|mut event| {+ if drop_team_ids.contains(&event.team_id()) {+ event.drop_code_variables();+ }+ event+ })+ },+ &mut (),+ );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/event.rs b/rust/cymbal/src/modes/processing/types/event.rsindex 2102b988118c..3d8f7ecccc62 100644--- a/rust/cymbal/src/modes/processing/types/event.rs+++ b/rust/cymbal/src/modes/processing/types/event.rs@@ -20,6 +20,29 @@ pub struct AnyEvent {pub others: HashMap<String, Value>,}+impl AnyEvent {+ pub fn drop_code_variables(&mut self) {+ let Some(exceptions) = self+ .properties+ .get_mut("$exception_list")+ .and_then(Value::as_array_mut)+ else {+ return;+ };+ for exception in exceptions {+ let Some(frames) = exception+ .pointer_mut("/stacktrace/frames")+ .and_then(Value::as_array_mut)+ else {+ continue;+ };+ for frame in frames.iter_mut().filter_map(Value::as_object_mut) {+ frame.remove("code_variables");+ }+ }+ }+}+pub trait PropertiesContainer: Send + Clone + 'static {fn set_properties(&mut self, new_props: Value) -> Result<(), UnhandledError>;fn attach_error(&mut self, error: String) -> Result<(), UnhandledError>;diff --git a/rust/cymbal/src/modes/processing/types/exception_event.rs b/rust/cymbal/src/modes/processing/types/exception_event.rsindex 85207105aaa9..3068fa13e321 100644--- a/rust/cymbal/src/modes/processing/types/exception_event.rs+++ b/rust/cymbal/src/modes/processing/types/exception_event.rs@@ -7,12 +7,18 @@ use uuid::Uuid;use crate::{error::EventError,fingerprinting::{Fingerprint, FingerprintRecordPart, FingerprintVersion},- frames::releases::{ReleaseInfo, ReleaseRecord},+ frames::{+ releases::{ReleaseInfo, ReleaseRecord},+ RawFrame,+ },issue_resolution::{Issue, IssueSeverity},langs::native::DebugImage,modes::processing::normalization::{normalize_legacy_tags, normalize_wire_order},recursively_sanitize_properties,- types::{event::AnyEvent, ExceptionList, ProcessedExceptionProperties, RawExceptionProperties},+ types::{+ event::AnyEvent, ExceptionList, ProcessedExceptionProperties, RawExceptionProperties,+ Stacktrace,+ },};use super::ProcessedExceptionPropertiesWire;@@ -203,6 +209,27 @@ impl<S> ExceptionEvent<S> {self.uuid}+ /// Resolved frames need this even when the event sent none: stored records replay old ones.+ pub fn drop_code_variables(&mut self) {+ for exception in self.exception_list.iter_mut() {+ match &mut exception.stack {+ Some(Stacktrace::Raw { frames }) => {+ for frame in frames.iter_mut() {+ if let RawFrame::Python(python) = frame {+ python.code_variables = None;+ }+ }+ }+ Some(Stacktrace::Resolved { frames }) => {+ for frame in frames.iter_mut() {+ frame.code_variables = None;+ }+ }+ None => {}+ }+ }+ }+pub fn team_id(&self) -> i32 {self.team_id}diff --git a/rust/cymbal/tests/common/mod.rs b/rust/cymbal/tests/common/mod.rsindex 51e33208dfde..45dc09812136 100644--- a/rust/cymbal/tests/common/mod.rs+++ b/rust/cymbal/tests/common/mod.rs@@ -434,6 +434,7 @@ pub fn remote_stage(ctx: RemoteResolutionContext) -> ResolutionStage {.connect_lazy("postgres://unused/unused").expect("lazy pool construction does not connect"),release_cache: ReleaseCache::new(0, Duration::from_secs(0)),+ drop_code_variables_team_ids: Default::default(),}}diff --git a/rust/cymbal/tests/event.rs b/rust/cymbal/tests/event.rsindex f97921a26579..b35aaa9b4415 100644--- a/rust/cymbal/tests/event.rs+++ b/rust/cymbal/tests/event.rs@@ -7,6 +7,7 @@ use cymbal::{error::UnhandledError,fingerprinting::{Fingerprint, FingerprintVersion},frames::Frame,+ modes::processing::ProcessingConfig,symbolication::symbol_store::saving::SymbolSetRecord,types::{event::AnyEvent, Exception, ExceptionList, Mechanism, ProcessedExceptionProperties,@@ -229,6 +230,28 @@ impl TestHarness {self.post_events(vec![event.clone()]).await}+ async fn post_event_with_config<T: DeserializeOwned>(+ &self,+ event: &AnyEvent,+ configure: impl FnOnce(&mut ProcessingConfig),+ ) -> (StatusCode, T) {+ utils::get_response_with_config(+ self.db.clone(),+ STORAGE_BUCKET.to_string(),+ || {+ Request::builder()+ .method("POST")+ .header("content-type", "application/json")+ .uri("/process")+ .body(Body::from(serde_json::to_vec(&vec![event]).unwrap()))+ .unwrap()+ },+ Arc::new(Self::create_s3_mock()),+ configure,+ )+ .await+ }+async fn post_raw_string(&self, json: &[u8]) -> (StatusCode, String) {utils::get_raw_response(self.db.clone(),@@ -722,6 +745,102 @@ async fn resolves_python_raw_frames(db: PgPool) {});}+fn python_event_with_code_variables() -> AnyEvent {+ let mut event = load_static_event("python");+ for frame in event.properties["$exception_list"][0]["stacktrace"]["frames"]+ .as_array_mut()+ .unwrap()+ {+ frame["code_variables"] = json!({"token": "fake-token-for-tests"});+ }+ event+}++fn frames_with_code_variables(body: &SuccessResponse) -> usize {+ let event = body+ .first_event()+ .as_ref()+ .expect("event should be returned");+ event.properties["$exception_list"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|exception| exception["stacktrace"]["frames"].as_array())+ .flatten()+ .filter(|frame| !frame["code_variables"].is_null())+ .count()+}++#[sqlx::test(migrations = "./tests/test_migrations")]+async fn drops_code_variables_replayed_from_stored_frames(db: PgPool) {+ let harness = TestHarness::new(db);++ let (status, body): (_, SuccessResponse) = harness+ .post_event_with_config(&python_event_with_code_variables(), |_| {})+ .await;+ assert!(status.is_success());+ assert!(frames_with_code_variables(&body) > 0);++ // The second event carries no code variables, so any that come back are replayed records.+ let mut event = load_static_event("python");+ event.uuid = Uuid::now_v7();+ let (status, body): (_, SuccessResponse) = harness+ .post_event_with_config(&event, |config| {+ config.drop_code_variables_team_ids = "1".to_string();+ })+ .await;+ assert!(status.is_success());+ assert_eq!(frames_with_code_variables(&body), 0);+}++#[sqlx::test(migrations = "./tests/test_migrations")]+async fn does_not_store_code_variables_for_listed_teams(db: PgPool) {+ let harness = TestHarness::new(db.clone());++ let (status, body): (_, SuccessResponse) = harness+ .post_event_with_config(&python_event_with_code_variables(), |config| {+ config.drop_code_variables_team_ids = "1".to_string();+ })+ .await;++ assert!(status.is_success());+ assert_eq!(frames_with_code_variables(&body), 0);+ let (stored, stored_with_code_variables): (i64, i64) = sqlx::query_as(+ "SELECT count(*), count(*) FILTER (WHERE contents ? 'code_variables')+ FROM posthog_errortrackingstackframe WHERE team_id = 1",+ )+ .fetch_one(&db)+ .await+ .unwrap();+ assert!(stored > 0);+ assert_eq!(stored_with_code_variables, 0);+}++#[sqlx::test(migrations = "./tests/test_migrations")]+async fn drops_code_variables_from_events_that_fail_to_parse(db: PgPool) {+ let harness = TestHarness::new(db);+ let mut event = python_event_with_code_variables();+ // A python frame without `function` does not deserialize, so the event is returned as sent.+ event.properties["$exception_list"][0]["stacktrace"]["frames"][0]+ .as_object_mut()+ .unwrap()+ .remove("function");++ let (status, body): (_, SuccessResponse) = harness+ .post_event_with_config(&event, |config| {+ config.drop_code_variables_team_ids = "1".to_string();+ })+ .await;++ assert!(status.is_success());+ let returned = body+ .first_event()+ .as_ref()+ .expect("event should be returned");+ assert!(returned.properties["$cymbal_errors"].is_array());+ assert_eq!(frames_with_code_variables(&body), 0);+}+#[sqlx::test(migrations = "./tests/test_migrations")]async fn resolves_javascript_with_sourcemaps(db: PgPool) {let harness = TestHarness::new(db.clone());