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.

chore(cymbal): enforce processing order with typestate (#71601)

Hugues Pouillot6e0d56bdd121
diff --git a/rust/cymbal/src/core/metric_consts.rs b/rust/cymbal/src/core/metric_consts.rs
index 0e2aced28cc0..5cecc87f4b36 100644
--- a/rust/cymbal/src/core/metric_consts.rs
+++ b/rust/cymbal/src/core/metric_consts.rs
@@ -130,7 +130,6 @@ pub const SPIKE_ALERT_STAGE: &str = "cymbal_spike_detection_time";
// Operators
pub const FRAME_RESOLVER_OPERATOR: &str = "cymbal_frame_batch_time";
pub const EXCEPTION_RESOLVER_OPERATOR: &str = "cymbal_exception_exception_resolver_operator";
-pub const PROPERTIES_RESOLVER_OPERATOR: &str = "cymbal_exception_properties_resolver_operator";
pub const LEGACY_ORDER_RESOLVER_OPERATOR: &str = "cymbal_exception_legacy_order_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";
diff --git a/rust/cymbal/src/modes/processing/stages/alerting/mod.rs b/rust/cymbal/src/modes/processing/stages/alerting/mod.rs
index ef756dc5b9cd..3defe491223e 100644
--- a/rust/cymbal/src/modes/processing/stages/alerting/mod.rs
+++ b/rust/cymbal/src/modes/processing/stages/alerting/mod.rs
@@ -5,7 +5,10 @@ mod spike_detection;
use crate::{
app_context::AppContext,
metric_consts::ALERTING_STAGE,
- stages::{alerting::spike_alert::SpikeAlertStage, pipeline::ExceptionEventPipelineItem},
+ stages::{
+ alerting::spike_alert::SpikeAlertStage,
+ pipeline::{FinalizedPipelineItem, RateCheckedPipelineItem},
+ },
types::{
batch::Batch,
stage::{Stage, StageResult},
@@ -26,8 +29,8 @@ impl From<&Arc<AppContext>> for AlertingStage {
}
impl Stage for AlertingStage {
- type Input = ExceptionEventPipelineItem;
- type Output = ExceptionEventPipelineItem;
+ type Input = RateCheckedPipelineItem;
+ type Output = FinalizedPipelineItem;
fn name(&self) -> &'static str {
ALERTING_STAGE
diff --git a/rust/cymbal/src/modes/processing/stages/alerting/spike_alert.rs b/rust/cymbal/src/modes/processing/stages/alerting/spike_alert.rs
index 32456db5c203..26cfc277459b 100644
--- a/rust/cymbal/src/modes/processing/stages/alerting/spike_alert.rs
+++ b/rust/cymbal/src/modes/processing/stages/alerting/spike_alert.rs
@@ -9,16 +9,18 @@ use crate::{
app_context::AppContext,
issue_resolution::Issue,
metric_consts::SPIKE_ALERT_STAGE,
- stages::{alerting::spike_detection::do_spike_detection, pipeline::ExceptionEventPipelineItem},
+ stages::{
+ alerting::spike_detection::do_spike_detection,
+ pipeline::{FinalizedPipelineItem, RateCheckedPipelineItem},
+ },
types::{
batch::Batch,
+ exception_event::ExceptionEvent,
stage::{Stage, StageResult},
OutputErrProps,
},
};
-use tracing::error;
-
#[derive(Clone)]
pub struct SpikeAlertStage {
context: Arc<AppContext>,
@@ -31,28 +33,23 @@ impl SpikeAlertStage {
}
impl Stage for SpikeAlertStage {
- type Input = ExceptionEventPipelineItem;
- type Output = ExceptionEventPipelineItem;
+ type Input = RateCheckedPipelineItem;
+ type Output = FinalizedPipelineItem;
fn name(&self) -> &'static str {
SPIKE_ALERT_STAGE
}
- async fn process(self, batch: Batch<ExceptionEventPipelineItem>) -> StageResult<Self> {
+ async fn process(self, batch: Batch<RateCheckedPipelineItem>) -> StageResult<Self> {
let mut issues: Vec<Issue> = Vec::new();
let mut issue_props_by_id: HashMap<Uuid, OutputErrProps> = HashMap::new();
for res in batch.inner_ref() {
let Ok(evt) = res else { continue };
- let Some(issue) = &evt.issue else {
- error!("no issue associated with event");
- continue;
- };
+ let issue = evt.issue();
// Keep one OutputErrProps per issue (they share the same stack shape)
if let Entry::Vacant(e) = issue_props_by_id.entry(issue.id) {
- if let Ok(props) = evt.to_output(issue.id) {
- e.insert(props);
- }
+ e.insert(evt.to_output());
}
issues.push(issue.clone());
}
@@ -76,6 +73,6 @@ impl Stage for SpikeAlertStage {
)
.await?;
- Ok(batch)
+ Ok(batch.map(|item, ()| item.map(ExceptionEvent::into_finalized), &mut ()))
}
}
diff --git a/rust/cymbal/src/modes/processing/stages/grouping/fingerprint.rs b/rust/cymbal/src/modes/processing/stages/grouping/fingerprint.rs
index e824d0ec20ed..f96038abab78 100644
--- a/rust/cymbal/src/modes/processing/stages/grouping/fingerprint.rs
+++ b/rust/cymbal/src/modes/processing/stages/grouping/fingerprint.rs
@@ -11,10 +11,9 @@ use crate::{
metric_consts::{FINGERPRINT_GENERATOR_OPERATOR, FINGERPRINT_LEGACY_VERSION_USED},
modes::processing::normalization::legacy_wire_order,
modes::processing::rules::grouping::evaluate_grouping_rules,
- stages::{grouping::GroupingStage, pipeline::HandledError},
+ stages::grouping::GroupingStage,
types::{
- exception_properties::ExceptionProperties,
- operator::{OperatorResult, ValueOperator},
+ exception_event::{ExceptionEvent, FingerprintData, Fingerprinted, PipelineItem, Resolved},
ExceptionList,
},
};
@@ -22,45 +21,48 @@ use crate::{
#[derive(Clone, Default)]
pub struct FingerprintGenerator;
-impl ValueOperator for FingerprintGenerator {
- type Context = GroupingStage;
- type Item = ExceptionProperties;
- type HandledError = HandledError;
- type UnhandledError = UnhandledError;
-
- fn name(&self) -> &'static str {
- FINGERPRINT_GENERATOR_OPERATOR
+impl FingerprintGenerator {
+ pub async fn execute(
+ &self,
+ item: PipelineItem<Resolved>,
+ ctx: GroupingStage,
+ ) -> Result<PipelineItem<Fingerprinted>, UnhandledError> {
+ match item {
+ Err(error) => Ok(Err(error)),
+ Ok(event) => self.generate(event, ctx).await.map(Ok),
+ }
}
- async fn execute_value(
+ async fn generate(
&self,
- mut input: ExceptionProperties,
+ mut input: ExceptionEvent<Resolved>,
ctx: GroupingStage,
- ) -> OperatorResult<Self> {
+ ) -> Result<ExceptionEvent<Fingerprinted>, UnhandledError> {
// Selection order:
// 1. Existing input fingerprint wins and is marked manual.
// 2. Matching grouping rule wins and is marked custom.
// 3. Automatic versions use the newest already-saved fingerprint, or the newest version.
// Manual and rule fingerprints intentionally do not set a fingerprint version.
- if input.fingerprint.is_some() {
- apply_manual_fingerprint(&mut input)?;
- return Ok(Ok(input));
+ if let Some(client_fingerprint) = input.client_fingerprint() {
+ let fingerprint = manual_fingerprint(client_fingerprint);
+ return Ok(input.into_fingerprinted(fingerprint));
}
// Serializing the event to JSON is only needed when the team has grouping rules, so
// defer it: `evaluate_grouping_rules` invokes this closure only when rules exist.
let matched_rule =
- evaluate_grouping_rules(&ctx.connection, input.team_id, &ctx.team_manager, || {
- Ok(serde_json::to_value(&input)?)
+ evaluate_grouping_rules(&ctx.connection, input.team_id(), &ctx.team_manager, || {
+ Ok(input.to_grouping_value())
})
.await?;
if let Some(rule) = matched_rule {
let fingerprint = Fingerprint::from_rule(rule);
- input.fingerprint = Some(fingerprint.value);
- input.fingerprint_version = None;
- input.fingerprint_record = Some(fingerprint.record);
- return Ok(Ok(input));
+ return Ok(input.into_fingerprinted(FingerprintData {
+ value: fingerprint.value,
+ version: None,
+ record: fingerprint.record,
+ }));
}
// Legacy fingerprint versions keep issues keyed before wire-order
@@ -69,37 +71,46 @@ impl ValueOperator for FingerprintGenerator {
// SDK's payloads (byte-exact, covers resolution reshaping), or a
// reconstruction by re-applying the SDK's reversal once the SDK has
// flipped and only the canonical order arrives.
- let lib = input.props.get("$lib").and_then(Value::as_str);
+ let lib = input
+ .properties()
+ .get("$lib")
+ .and_then(Value::as_str)
+ .map(str::to_string);
let legacy_list = input
- .legacy_order_resolved
- .take()
- .or_else(|| legacy_wire_order(lib, &input.exception_list));
+ .take_legacy_order_resolved()
+ .or_else(|| legacy_wire_order(lib.as_deref(), input.exception_list()));
let (version, fingerprint) =
select_automatic_fingerprint(&input, legacy_list.as_ref(), &ctx).await?;
if version.is_legacy() {
metrics::counter!(FINGERPRINT_LEGACY_VERSION_USED, "version" => version.as_str())
.increment(1);
}
- input.fingerprint = Some(fingerprint.value);
- input.fingerprint_record = Some(fingerprint.record);
- input.fingerprint_version = Some(version);
- Ok(Ok(input))
+ Ok(input.into_fingerprinted(FingerprintData {
+ value: fingerprint.value,
+ version: Some(version),
+ record: fingerprint.record,
+ }))
+ }
+
+ pub fn name(&self) -> &'static str {
+ FINGERPRINT_GENERATOR_OPERATOR
}
}
-fn apply_manual_fingerprint(input: &mut ExceptionProperties) -> Result<(), UnhandledError> {
- let Some(fp) = &input.fingerprint else {
- return Err(UnhandledError::Other("Missing manual fingerprint".into()));
- };
- input.fingerprint_version = None;
- input.fingerprint_record = Some(vec![FingerprintRecordPart::Manual]);
- if fp.len() > 64 {
+fn manual_fingerprint(value: &str) -> FingerprintData {
+ let value = if value.len() > 64 {
let mut hasher = Sha512::default();
- hasher.update(fp);
- input.fingerprint = Some(format!("{:x}", hasher.finalize()));
+ hasher.update(value);
+ format!("{:x}", hasher.finalize())
+ } else {
+ value.to_string()
+ };
+ FingerprintData {
+ value,
+ version: None,
+ record: vec![FingerprintRecordPart::Manual],
}
- Ok(())
}
// Walks versions newest-first and keeps the first fingerprint that already maps to an issue,
@@ -107,7 +118,7 @@ fn apply_manual_fingerprint(input: &mut ExceptionProperties) -> Result<(), Unhan
// pre-flip order and participate only in matching: `all()` orders them below the canonical
// versions, so they can never be the fallback that creates a new issue.
async fn select_automatic_fingerprint(
- input: &ExceptionProperties,
+ input: &ExceptionEvent<Resolved>,
legacy_list: Option<&ExceptionList>,
ctx: &GroupingStage,
) -> Result<(FingerprintVersion, Fingerprint), UnhandledError> {
@@ -117,7 +128,7 @@ async fn select_automatic_fingerprint(
let list = if version.is_legacy() {
legacy_list?
} else {
- &input.exception_list
+ input.exception_list()
};
Some((*version, version.compute(list)))
})
@@ -133,7 +144,7 @@ async fn select_automatic_fingerprint(
let mut known: HashMap<String, Uuid> = HashMap::new();
let mut uncached: Vec<String> = Vec::new();
for (_, fingerprint) in fingerprints.iter() {
- let cache_key = (input.team_id, fingerprint.value.clone());
+ let cache_key = (input.team_id(), fingerprint.value.clone());
match ctx.issue_cache.get(&cache_key).await {
Some(issue_id) => {
known.insert(fingerprint.value.clone(), issue_id);
@@ -148,17 +159,17 @@ async fn select_automatic_fingerprint(
}
// One round-trip for every candidate value the cache didn't know, instead
- // of one sequential lookup per version (the cache stores hits only, so a
- // per-version walk pays a round-trip per miss — the common case for new
- // errors). Preference order is applied to the merged cache + DB result
- // set below, so the outcome is identical to the sequential newest-first
- // walk.
+ // of one sequential lookup per version. Preference order is applied to the
+ // merged cache + DB result set below.
if !uncached.is_empty() {
for record in
- IssueFingerprintOverride::load_many(&ctx.connection, input.team_id, &uncached).await?
+ IssueFingerprintOverride::load_many(&ctx.connection, input.team_id(), &uncached).await?
{
ctx.issue_cache
- .insert((input.team_id, record.fingerprint.clone()), record.issue_id)
+ .insert(
+ (input.team_id(), record.fingerprint.clone()),
+ record.issue_id,
+ )
.await;
known.insert(record.fingerprint, record.issue_id);
}
diff --git a/rust/cymbal/src/modes/processing/stages/grouping/mod.rs b/rust/cymbal/src/modes/processing/stages/grouping/mod.rs
index 2fc8b4f8ecac..4a0fa4ac8d32 100644
--- a/rust/cymbal/src/modes/processing/stages/grouping/mod.rs
+++ b/rust/cymbal/src/modes/processing/stages/grouping/mod.rs
@@ -10,7 +10,10 @@ use crate::{
app_context::AppContext,
error::UnhandledError,
metric_consts::GROUPING_STAGE,
- stages::{grouping::fingerprint::FingerprintGenerator, pipeline::ExceptionEventPipelineItem},
+ stages::{
+ grouping::fingerprint::FingerprintGenerator,
+ pipeline::{FingerprintedPipelineItem, ResolvedPipelineItem},
+ },
teams::TeamManager,
types::{batch::Batch, operator::TeamId, stage::Stage},
};
@@ -33,8 +36,8 @@ impl From<&Arc<AppContext>> for GroupingStage {
}
impl Stage for GroupingStage {
- type Input = ExceptionEventPipelineItem;
- type Output = ExceptionEventPipelineItem;
+ type Input = ResolvedPipelineItem;
+ type Output = FingerprintedPipelineItem;
fn name(&self) -> &'static str {
GROUPING_STAGE
@@ -44,6 +47,18 @@ impl Stage for GroupingStage {
self,
batch: Batch<Self::Input>,
) -> Result<Batch<Self::Output>, UnhandledError> {
- batch.apply_operator(FingerprintGenerator, self).await
+ let operator = FingerprintGenerator;
+ let timing = common_metrics::timing_guard(operator.name(), &[]);
+ let output = batch
+ .apply_func(
+ move |item, context| {
+ let operator = operator.clone();
+ async move { operator.execute(item, context).await }
+ },
+ self,
+ )
+ .await?;
+ timing.label("outcome", "success");
+ Ok(output)
}
}
diff --git a/rust/cymbal/src/modes/processing/stages/http_pipeline.rs b/rust/cymbal/src/modes/processing/stages/http_pipeline.rs
index 1d4183f64379..3f10e45adcec 100644
--- a/rust/cymbal/src/modes/processing/stages/http_pipeline.rs
+++ b/rust/cymbal/src/modes/processing/stages/http_pipeline.rs
@@ -8,7 +8,7 @@ use crate::{
types::{
batch::Batch,
event::{AnyEvent, PropertiesContainer},
- exception_properties::ExceptionProperties,
+ exception_event::{ExceptionEvent, Finalized},
stage::{Stage, StageResult},
},
};
@@ -46,11 +46,11 @@ impl Stage for HttpEventPipeline {
fn handle_result(
mut original: AnyEvent,
- processed: Result<ExceptionProperties, HandledError>,
+ processed: Result<ExceptionEvent<Finalized>, HandledError>,
) -> Result<Option<AnyEvent>, UnhandledError> {
let item: Option<AnyEvent> = match processed {
Ok(props) => {
- original.set_properties(props)?;
+ original.set_properties(props.to_clickhouse_value())?;
Some(original)
}
Err(err) => match err {
diff --git a/rust/cymbal/src/modes/processing/stages/linking/issue.rs b/rust/cymbal/src/modes/processing/stages/linking/issue.rs
index 83c7c9da8b10..6fe5756d2a57 100644
--- a/rust/cymbal/src/modes/processing/stages/linking/issue.rs
+++ b/rust/cymbal/src/modes/processing/stages/linking/issue.rs
@@ -15,11 +15,10 @@ use crate::{
},
metric_consts::{ISSUE_CREATED, ISSUE_LINKER_OPERATOR},
modes::processing::rules::assignment::{try_assignment_rules, Assignment},
- stages::{linking::LinkingStage, pipeline::HandledError},
+ stages::linking::LinkingStage,
teams::TeamManager,
types::{
- exception_properties::ExceptionProperties,
- operator::{OperatorResult, ValueOperator},
+ exception_event::{ExceptionEvent, Fingerprinted, Linked, PipelineItem},
OutputErrProps,
},
};
@@ -29,23 +28,23 @@ pub struct IssueLinker;
impl IssueLinker {
pub async fn fetch_or_create_issue(
- input: &ExceptionProperties,
+ input: &ExceptionEvent<Fingerprinted>,
ctx: Arc<AppContext>,
) -> Result<Issue, UnhandledError> {
// Extract name and description for the issue
let name = input
- .proposed_issue_name
- .clone()
- .unwrap_or_else(|| input.exception_list[0].exception_type.clone());
+ .proposed_issue_name()
+ .map(str::to_string)
+ .unwrap_or_else(|| input.exception_list()[0].exception_type.clone());
let description = input
- .proposed_issue_description
- .clone()
- .unwrap_or_else(|| input.exception_list[0].exception_message.clone());
+ .proposed_issue_description()
+ .map(str::to_string)
+ .unwrap_or_else(|| input.exception_list()[0].exception_message.clone());
- let event_timestamp = parse_datetime_assuming_utc(&input.timestamp).unwrap_or_else(|e| {
+ let event_timestamp = parse_datetime_assuming_utc(input.timestamp()).unwrap_or_else(|e| {
warn!(
- event = input.uuid.to_string(),
+ event = input.uuid().to_string(),
"Failed to get event timestamp, using current time, error: {:?}", e
);
Utc::now()
@@ -57,27 +56,33 @@ impl IssueLinker {
}
}
-impl ValueOperator for IssueLinker {
- type Item = ExceptionProperties;
- type Context = LinkingStage;
- type HandledError = HandledError;
- type UnhandledError = UnhandledError;
-
- fn name(&self) -> &'static str {
+impl IssueLinker {
+ pub fn name(&self) -> &'static str {
ISSUE_LINKER_OPERATOR
}
- async fn execute_value(&self, input: Self::Item, ctx: LinkingStage) -> OperatorResult<Self> {
- let fingerprint = input
- .fingerprint
- .clone()
- .ok_or_else(|| UnhandledError::Other("Missing fingerprint".into()))?;
- let key = (input.team_id, fingerprint);
+ pub async fn execute(
+ &self,
+ item: PipelineItem<Fingerprinted>,
+ ctx: LinkingStage,
+ ) -> Result<PipelineItem<Linked>, UnhandledError> {
+ match item {
+ Err(error) => Ok(Err(error)),
+ Ok(input) => self.link(input, ctx).await.map(Ok),
+ }
+ }
+
+ async fn link(
+ &self,
+ input: ExceptionEvent<Fingerprinted>,
+ ctx: LinkingStage,
+ ) -> Result<ExceptionEvent<Linked>, UnhandledError> {
+ let key = (input.team_id(), input.fingerprint().value.clone());
// Wrap the (large) event in an `Arc` so the cache-loader closures capture a cheap
// refcount bump instead of a full deep clone. The loaders only ever borrow the
// event, and they don't run at all on the warm-cache path, so on the hot path this
- // is one `Arc` allocation and no `ExceptionProperties` copies.
+ // is one `Arc` allocation and no event copies.
let input = Arc::new(input);
// Two-layer cache: per-batch dedup wraps the cross-request `issue_id` cache.
@@ -102,12 +107,8 @@ impl ValueOperator for IssueLinker {
// The only `Arc` clones were captured by this call's loader closures, which have
// all completed (or been dropped when moka deduped them), so we uniquely own the
// event again and can reclaim it to write back the resolved issue.
- let mut input =
- Arc::into_inner(input).expect("input Arc uniquely held after cache resolution");
- input.issue_id = Some(issue.id);
- input.issue = Some(issue);
-
- Ok(Ok(input))
+ let input = Arc::into_inner(input).expect("input Arc uniquely held after cache resolution");
+ Ok(input.into_linked(issue))
}
}
@@ -118,14 +119,11 @@ impl ValueOperator for IssueLinker {
// - On cache hit we re-read by id (cheap PK lookup) and call `maybe_reopen` so
// suppression and reopen always see current PG state.
async fn resolve_via_id_cache(
- input: Arc<ExceptionProperties>,
+ input: Arc<ExceptionEvent<Fingerprinted>>,
ctx: &LinkingStage,
) -> Result<Issue, UnhandledError> {
- let fingerprint = input
- .fingerprint
- .clone()
- .ok_or_else(|| UnhandledError::Other("Missing fingerprint".into()))?;
- let key = (input.team_id, fingerprint.clone());
+ let fingerprint = input.fingerprint().value.clone();
+ let key = (input.team_id(), fingerprint.clone());
// `try_get_with` only returns the cached value (`Uuid`), so we stash the freshly
// resolved Issue in a slot when we run the loader ourselves. That lets us reuse it
@@ -158,7 +156,7 @@ async fn resolve_via_id_cache(
// Cache hit (or we were deduped against a concurrent caller). Refresh by id.
match load_and_maybe_reopen(
ctx.app_context.as_ref(),
- input.team_id,
+ input.team_id(),
issue_id,
&fingerprint,
&input,
@@ -183,7 +181,7 @@ async fn load_and_maybe_reopen(
team_id: i32,
issue_id: Uuid,
fingerprint: &str,
- event_properties: &ExceptionProperties,
+ event_properties: &ExceptionEvent<Fingerprinted>,
) -> Result<Option<Issue>, UnhandledError> {
let mut conn = context.posthog_pool.acquire().await?;
let Some(mut issue) = Issue::load(&mut *conn, team_id, issue_id).await? else {
@@ -196,15 +194,16 @@ async fn load_and_maybe_reopen(
// Reopened — mirror the side effects from `resolve_issue`'s fast-path reopen branch.
let event_timestamp =
- parse_datetime_assuming_utc(&event_properties.timestamp).unwrap_or_else(|e| {
+ parse_datetime_assuming_utc(event_properties.timestamp()).unwrap_or_else(|e| {
warn!(
- event = event_properties.uuid.to_string(),
+ event = event_properties.uuid().to_string(),
"Failed to get event timestamp, using current time, error: {:?}", e
);
Utc::now()
});
let assignment =
- process_assignment(&mut conn, &context.team_manager, &issue, event_properties).await?;
+ process_event_assignment(&mut conn, &context.team_manager, &issue, event_properties)
+ .await?;
// We don't carry a per-fingerprint `first_seen` through this path (we loaded by id,
// not by fingerprint), so fall back to the issue's creation time the same way
// `resolve_issue` already does when the join returns no first_seen.
@@ -216,7 +215,7 @@ async fn load_and_maybe_reopen(
issue.created_at,
)
.await?;
- let output_props: OutputErrProps = event_properties.to_output(issue.id)?;
+ let output_props: OutputErrProps = event_properties.to_output(&issue);
drop(conn);
send_issue_reopened_notification(context, &issue, assignment, output_props, &event_timestamp)
.await?;
@@ -229,13 +228,10 @@ async fn resolve_issue(
name: String,
description: String,
event_timestamp: DateTime<Utc>,
- event_properties: &ExceptionProperties,
+ event_properties: &ExceptionEvent<Fingerprinted>,
) -> Result<Issue, UnhandledError> {
- let team_id = event_properties.team_id;
- let fingerprint = event_properties
- .fingerprint
- .clone()
- .ok_or(UnhandledError::Other("Missing fingerprint".into()))?;
+ let team_id = event_properties.team_id();
+ let fingerprint = event_properties.fingerprint().value.clone();
let mut conn = context.posthog_pool.acquire().await?;
// Fast path - just fetch the issue directly, and then reopen it if needed
@@ -244,9 +240,13 @@ async fn resolve_issue(
let (mut issue, fingerprint_first_seen) = result.into_issue();
if issue.maybe_reopen(&mut *conn).await? {
let first_seen_for_state = fingerprint_first_seen.unwrap_or(issue.created_at);
- let assignment =
- process_assignment(&mut conn, &context.team_manager, &issue, event_properties)
- .await?;
+ let assignment = process_event_assignment(
+ &mut conn,
+ &context.team_manager,
+ &issue,
+ event_properties,
+ )
+ .await?;
send_fingerprint_issue_state(
context,
&issue,
@@ -255,7 +255,7 @@ async fn resolve_issue(
first_seen_for_state,
)
.await?;
- let output_props: OutputErrProps = event_properties.to_output(issue.id)?;
+ let output_props: OutputErrProps = event_properties.to_output(&issue);
drop(conn);
send_issue_reopened_notification(
context,
@@ -313,9 +313,13 @@ async fn resolve_issue(
// Since we just loaded an issue, check if it needs to be reopened
if issue.maybe_reopen(&mut *conn).await? {
let first_seen_for_state = fingerprint_first_seen.unwrap_or(issue.created_at);
- let assignment =
- process_assignment(&mut conn, &context.team_manager, &issue, event_properties)
- .await?;
+ let assignment = process_event_assignment(
+ &mut conn,
+ &context.team_manager,
+ &issue,
+ event_properties,
+ )
+ .await?;
send_fingerprint_issue_state(
context,
&issue,
@@ -327,7 +331,7 @@ async fn resolve_issue(
drop(conn);
- let output_props: OutputErrProps = event_properties.to_output(issue.id)?;
+ let output_props: OutputErrProps = event_properties.to_output(&issue);
send_issue_reopened_notification(
context,
&issue,
@@ -340,9 +344,10 @@ async fn resolve_issue(
} else {
metrics::counter!(ISSUE_CREATED).increment(1);
let assignment =
- process_assignment(&mut txn, &context.team_manager, &issue, event_properties).await?;
+ process_event_assignment(&mut txn, &context.team_manager, &issue, event_properties)
+ .await?;
- let output_props = event_properties.to_output(issue.id)?;
+ let output_props = event_properties.to_output(&issue);
send_fingerprint_issue_state(
context,
&issue,
@@ -360,7 +365,7 @@ async fn resolve_issue(
&issue,
assignment,
output_props,
- event_properties.uuid,
+ event_properties.uuid(),
&event_timestamp,
)
.await?;
@@ -369,15 +374,24 @@ async fn resolve_issue(
Ok(issue)
}
+async fn process_event_assignment(
+ conn: &mut PgConnection,
+ team_manager: &TeamManager,
+ issue: &Issue,
+ exception_props: &ExceptionEvent<Fingerprinted>,
+) -> Result<Option<Assignment>, UnhandledError> {
+ let output_props = exception_props.to_output(issue);
+ process_assignment(conn, team_manager, issue, &output_props).await
+}
+
pub async fn process_assignment(
conn: &mut PgConnection,
team_manager: &TeamManager,
issue: &Issue,
- exception_props: &ExceptionProperties,
+ output_props: &OutputErrProps,
) -> Result<Option<Assignment>, UnhandledError> {
- let output_props = exception_props.to_output(issue.id)?;
let new_assignment =
- try_assignment_rules(conn, team_manager, issue.clone(), &output_props).await?;
+ try_assignment_rules(conn, team_manager, issue.clone(), output_props).await?;
let assignment = if let Some(new_assignment) = new_assignment {
Some(new_assignment.apply(&mut *conn, issue.id).await?)
diff --git a/rust/cymbal/src/modes/processing/stages/linking/mod.rs b/rust/cymbal/src/modes/processing/stages/linking/mod.rs
index e8aeadb08e54..4d1d2ddb4230 100644
--- a/rust/cymbal/src/modes/processing/stages/linking/mod.rs
+++ b/rust/cymbal/src/modes/processing/stages/linking/mod.rs
@@ -15,7 +15,7 @@ use crate::{
linking::{
issue::IssueLinker, rule_suppression::RuleSuppression, suppression::IssueSuppression,
},
- pipeline::ExceptionEventPipelineItem,
+ pipeline::{FingerprintedPipelineItem, LinkedPipelineItem},
},
types::{
batch::Batch,
@@ -37,21 +37,28 @@ pub struct LinkingStage {
}
impl Stage for LinkingStage {
- type Input = ExceptionEventPipelineItem;
- type Output = ExceptionEventPipelineItem;
+ type Input = FingerprintedPipelineItem;
+ type Output = LinkedPipelineItem;
fn name(&self) -> &'static str {
LINKING_STAGE
}
async fn process(self, batch: Batch<Self::Input>) -> StageResult<Self> {
- batch
- .apply_operator(RuleSuppression, self.clone())
- .await?
- .apply_operator(IssueLinker, self.clone())
- .await?
- .apply_operator(IssueSuppression, self.clone())
- .await
+ let fingerprinted = batch.apply_operator(RuleSuppression, self.clone()).await?;
+ let linker = IssueLinker;
+ let timing = common_metrics::timing_guard(linker.name(), &[]);
+ let linked = fingerprinted
+ .apply_func(
+ move |item, context| {
+ let linker = linker.clone();
+ async move { linker.execute(item, context).await }
+ },
+ self.clone(),
+ )
+ .await?;
+ timing.label("outcome", "success");
+ linked.apply_operator(IssueSuppression, self.clone()).await
}
}
diff --git a/rust/cymbal/src/modes/processing/stages/linking/rule_suppression.rs b/rust/cymbal/src/modes/processing/stages/linking/rule_suppression.rs
index c7481b10bae6..1d78e66d6229 100644
--- a/rust/cymbal/src/modes/processing/stages/linking/rule_suppression.rs
+++ b/rust/cymbal/src/modes/processing/stages/linking/rule_suppression.rs
@@ -6,7 +6,7 @@ use crate::{
metric_consts::{RULE_SUPPRESSED_EVENTS, RULE_SUPPRESSION_OPERATOR},
stages::{linking::LinkingStage, pipeline::HandledError},
types::{
- exception_properties::ExceptionProperties,
+ exception_event::{ExceptionEvent, Fingerprinted},
operator::{OperatorResult, ValueOperator},
},
};
@@ -15,7 +15,7 @@ use crate::{
pub struct RuleSuppression;
impl ValueOperator for RuleSuppression {
- type Item = ExceptionProperties;
+ type Item = ExceptionEvent<Fingerprinted>;
type Context = LinkingStage;
type HandledError = HandledError;
type UnhandledError = UnhandledError;
@@ -28,7 +28,7 @@ impl ValueOperator for RuleSuppression {
let mut rules = ctx
.app_context
.team_manager
- .get_suppression_rules(&ctx.app_context.posthog_pool, input.team_id)
+ .get_suppression_rules(&ctx.app_context.posthog_pool, input.team_id())
.await?;
if rules.is_empty() {
@@ -38,13 +38,10 @@ impl ValueOperator for RuleSuppression {
rules.sort_unstable_by_key(|r| r.order_key);
// Only serialize the event once we know the team has suppression rules.
- let props_json = match serde_json::to_value(&input) {
- Ok(v) => v,
- Err(_) => return Ok(Ok(input)),
- };
+ let props_json = input.to_properties_value();
for rule in rules {
- match rule.should_suppress(&props_json, &input.uuid) {
+ match rule.should_suppress(&props_json, &input.uuid()) {
Ok(false) => continue,
Ok(true) => {
counter!(RULE_SUPPRESSED_EVENTS).increment(1);
@@ -73,7 +70,7 @@ impl ValueOperator for RuleSuppression {
ctx.app_context
.team_manager
.suppression_rules
- .invalidate(&input.team_id);
+ .invalidate(&input.team_id());
}
}
}
diff --git a/rust/cymbal/src/modes/processing/stages/linking/suppression.rs b/rust/cymbal/src/modes/processing/stages/linking/suppression.rs
index b1ffc6b968c5..cbd4f53cdc04 100644
--- a/rust/cymbal/src/modes/processing/stages/linking/suppression.rs
+++ b/rust/cymbal/src/modes/processing/stages/linking/suppression.rs
@@ -6,7 +6,7 @@ use crate::{
metric_consts::{ISSUE_SUPPRESSION_OPERATOR, SUPPRESSED_ISSUE_DROPPED_EVENTS},
stages::{linking::LinkingStage, pipeline::HandledError},
types::{
- exception_properties::ExceptionProperties,
+ exception_event::{ExceptionEvent, Linked},
operator::{OperatorResult, ValueOperator},
},
};
@@ -15,7 +15,7 @@ use crate::{
pub struct IssueSuppression;
impl ValueOperator for IssueSuppression {
- type Item = ExceptionProperties;
+ type Item = ExceptionEvent<Linked>;
type Context = LinkingStage;
type HandledError = HandledError;
type UnhandledError = UnhandledError;
@@ -25,11 +25,10 @@ impl ValueOperator for IssueSuppression {
}
async fn execute_value(&self, input: Self::Item, _: LinkingStage) -> OperatorResult<Self> {
- if let Some(issue) = input.issue.as_ref() {
- if matches!(issue.status, IssueStatus::Suppressed) {
- counter!(SUPPRESSED_ISSUE_DROPPED_EVENTS).increment(1);
- return Ok(Err(EventError::Suppressed(issue.id)));
- }
+ let issue = input.issue();
+ if matches!(issue.status, IssueStatus::Suppressed) {
+ counter!(SUPPRESSED_ISSUE_DROPPED_EVENTS).increment(1);
+ return Ok(Err(EventError::Suppressed(issue.id)));
}
Ok(Ok(input))
diff --git a/rust/cymbal/src/modes/processing/stages/pipeline.rs b/rust/cymbal/src/modes/processing/stages/pipeline.rs
index 1985b2425d43..10082b610b85 100644
--- a/rust/cymbal/src/modes/processing/stages/pipeline.rs
+++ b/rust/cymbal/src/modes/processing/stages/pipeline.rs
@@ -17,7 +17,10 @@ use crate::{
},
types::{
batch::Batch,
- exception_properties::ExceptionProperties,
+ exception_event::{
+ ExceptionEvent, Finalized, Fingerprinted, Linked, Parsed, PipelineItem, RateChecked,
+ Resolved,
+ },
stage::{Stage, StageResult},
},
};
@@ -35,11 +38,16 @@ impl ExceptionEventPipeline {
pub type EventPipelineItem = Result<ClickHouseEvent, EventError>;
pub type HandledError = EventError;
-pub type ExceptionEventPipelineItem = Result<ExceptionProperties, EventError>;
+pub type ParsedPipelineItem = PipelineItem<Parsed>;
+pub type ResolvedPipelineItem = PipelineItem<Resolved>;
+pub type FingerprintedPipelineItem = PipelineItem<Fingerprinted>;
+pub type LinkedPipelineItem = PipelineItem<Linked>;
+pub type RateCheckedPipelineItem = PipelineItem<RateChecked>;
+pub type FinalizedPipelineItem = PipelineItem<Finalized>;
impl Stage for ExceptionEventPipeline {
- type Input = ExceptionEventPipelineItem;
- type Output = ExceptionEventPipelineItem;
+ type Input = ParsedPipelineItem;
+ type Output = FinalizedPipelineItem;
fn name(&self) -> &'static str {
EXCEPTION_PROCESSING_PIPELINE
@@ -67,7 +75,7 @@ impl Stage for ExceptionEventPipeline {
}
pub fn create_pre_post_processing<
- T: TryInto<ExceptionProperties, Error = EventError> + Clone,
+ T: TryInto<ExceptionEvent<Parsed>, Error = EventError> + Clone,
O,
>(
capacity: usize,
diff --git a/rust/cymbal/src/modes/processing/stages/post_processing/mod.rs b/rust/cymbal/src/modes/processing/stages/post_processing/mod.rs
index c033e2bd52f3..53f914c49837 100644
--- a/rust/cymbal/src/modes/processing/stages/post_processing/mod.rs
+++ b/rust/cymbal/src/modes/processing/stages/post_processing/mod.rs
@@ -5,7 +5,7 @@ use tokio::sync::Mutex;
use crate::{
error::UnhandledError,
metric_consts::POST_PROCESSING_STAGE,
- stages::{pipeline::ExceptionEventPipelineItem, pre_processing::PreProcessingContext},
+ stages::{pipeline::FinalizedPipelineItem, pre_processing::PreProcessingContext},
types::{
batch::Batch,
stage::{Stage, StageResult},
@@ -13,7 +13,7 @@ use crate::{
};
pub type PostProcessingHandler<I, O> =
- Box<dyn Fn(I, ExceptionEventPipelineItem) -> Result<O, UnhandledError> + Send>;
+ Box<dyn Fn(I, FinalizedPipelineItem) -> Result<O, UnhandledError> + Send>;
pub struct PostProcessingStage<T, O> {
ctx: Arc<Mutex<PreProcessingContext<T>>>,
@@ -30,7 +30,7 @@ impl<T: Clone, O> PostProcessingStage<T, O> {
}
impl<T: Clone, O> Stage for PostProcessingStage<T, O> {
- type Input = ExceptionEventPipelineItem;
+ type Input = FinalizedPipelineItem;
type Output = O;
fn name(&self) -> &'static str {
diff --git a/rust/cymbal/src/modes/processing/stages/pre_processing/mod.rs b/rust/cymbal/src/modes/processing/stages/pre_processing/mod.rs
index 38410c114f55..33c0a3f9408b 100644
--- a/rust/cymbal/src/modes/processing/stages/pre_processing/mod.rs
+++ b/rust/cymbal/src/modes/processing/stages/pre_processing/mod.rs
@@ -5,10 +5,10 @@ use tokio::sync::Mutex;
use crate::{
error::EventError,
metric_consts::PRE_PROCESSING_STAGE,
- stages::pipeline::ExceptionEventPipelineItem,
+ stages::pipeline::ParsedPipelineItem,
types::{
batch::Batch,
- exception_properties::ExceptionProperties,
+ exception_event::{ExceptionEvent, Parsed},
stage::{Stage, StageResult},
},
};
@@ -31,19 +31,21 @@ impl<T> PreProcessingContext<T> {
}
}
-pub struct PreProcessingStage<T: TryInto<ExceptionProperties, Error = EventError> + Clone> {
+pub struct PreProcessingStage<T: TryInto<ExceptionEvent<Parsed>, Error = EventError> + Clone> {
ctx: Arc<Mutex<PreProcessingContext<T>>>,
}
-impl<T: TryInto<ExceptionProperties, Error = EventError> + Clone> PreProcessingStage<T> {
+impl<T: TryInto<ExceptionEvent<Parsed>, Error = EventError> + Clone> PreProcessingStage<T> {
pub fn new(ctx: Arc<Mutex<PreProcessingContext<T>>>) -> Self {
Self { ctx }
}
}
-impl<T: TryInto<ExceptionProperties, Error = EventError> + Clone> Stage for PreProcessingStage<T> {
+impl<T: TryInto<ExceptionEvent<Parsed>, Error = EventError> + Clone> Stage
+ for PreProcessingStage<T>
+{
type Input = T;
- type Output = ExceptionEventPipelineItem;
+ type Output = ParsedPipelineItem;
fn name(&self) -> &'static str {
PRE_PROCESSING_STAGE
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 94ae8f40af4b..7c2baa52d834 100644
--- a/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs
+++ b/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs
@@ -20,17 +20,16 @@ use crate::{
metric_consts::{
RATE_LIMITING_STAGE, RATE_LIMIT_FAIL_OPEN, RATE_LIMIT_METRIC_EMIT, RATE_LIMIT_OUTCOMES,
},
- stages::pipeline::ExceptionEventPipelineItem,
+ stages::pipeline::{LinkedPipelineItem, RateCheckedPipelineItem},
types::{
batch::Batch,
+ exception_event::{ExceptionEvent, Linked},
stage::{Stage, StageResult},
},
};
use crate::modes::processing::rules::bypass::BypassRule;
use crate::modes::processing::rules::rate_limit::RateLimitSettings;
-use crate::modes::processing::types::exception_properties::ExceptionProperties;
-
pub use limiter::{RateLimitDecision, RedisRateLimiter, ScriptRunner, RATE_LIMIT_LUA};
/// Ceiling on concurrent Redis admits per batch — bounds the pathological tail (many
@@ -91,8 +90,8 @@ impl From<&Arc<AppContext>> for RateLimitingStage {
}
impl Stage for RateLimitingStage {
- type Input = ExceptionEventPipelineItem;
- type Output = ExceptionEventPipelineItem;
+ type Input = LinkedPipelineItem;
+ type Output = RateCheckedPipelineItem;
fn name(&self) -> &'static str {
RATE_LIMITING_STAGE
@@ -100,19 +99,19 @@ impl Stage for RateLimitingStage {
async fn process(self, batch: Batch<Self::Input>) -> StageResult<Self> {
let Some(limiter) = self.ctx.rate_limiter.clone() else {
- return Ok(batch); // limiter disabled — pass everything through
+ return Ok(mark_rate_checked(batch));
};
- let mut items: Vec<ExceptionEventPipelineItem> = batch.into();
+ let mut items: Vec<LinkedPipelineItem> = batch.into();
// Teams of the surviving (Ok) events. Suppressed / failed events are
// already Err and are never charged.
let team_ids: HashSet<i32> = items
.iter()
- .filter_map(|item| item.as_ref().ok().map(|props| props.team_id))
+ .filter_map(|item| item.as_ref().ok().map(ExceptionEvent::team_id))
.collect();
if team_ids.is_empty() {
- return Ok(Batch::from(items));
+ return Ok(mark_rate_checked(Batch::from(items)));
}
let settings = self
@@ -139,10 +138,17 @@ impl Stage for RateLimitingStage {
self.emit_metrics(&outcomes).await;
- Ok(Batch::from(items))
+ Ok(mark_rate_checked(Batch::from(items)))
}
}
+fn mark_rate_checked(batch: Batch<LinkedPipelineItem>) -> Batch<RateCheckedPipelineItem> {
+ batch.map(
+ |item, ()| item.map(ExceptionEvent::into_rate_checked),
+ &mut (),
+ )
+}
+
/// Core of `process`, split out for unit tests with an in-memory `ScriptRunner`.
/// Groups surviving (`Ok`) events by (team_id, issue_id), charges each group against the
/// team's limits, and flips over-limit events to `Err` in place (length/order preserved
@@ -152,19 +158,19 @@ async fn apply_rate_limits(
limiter: &RedisRateLimiter,
settings: &HashMap<i32, RateLimitSettings>,
enabled_teams: Option<&HashSet<i32>>,
- items: &mut [ExceptionEventPipelineItem],
+ items: &mut [LinkedPipelineItem],
bypassed: &HashSet<usize>,
) -> HashMap<OutcomeKey, u32> {
// Group surviving (Ok) events by (team_id, issue_id). Vec<usize> stays in input order.
// Bypassed events are skipped so they never charge a token bucket.
- let mut groups: HashMap<(i32, Option<Uuid>), Vec<usize>> = HashMap::new();
+ let mut groups: HashMap<(i32, Uuid), Vec<usize>> = HashMap::new();
for (idx, item) in items.iter().enumerate() {
if bypassed.contains(&idx) {
continue;
}
if let Ok(props) = item {
groups
- .entry((props.team_id, props.issue_id))
+ .entry((props.team_id(), props.issue_id()))
.or_default()
.push(idx);
}
@@ -182,7 +188,7 @@ async fn apply_rate_limits(
// no settings row → team not opted in
let team_settings = settings.get(&team_id)?;
// per-issue limit needs an issue to key on
- let per_issue = issue_id.and(team_settings.per_issue());
+ let per_issue = team_settings.per_issue();
let project = team_settings.project();
if per_issue.is_none() && project.is_none() {
return None;
@@ -197,7 +203,7 @@ async fn apply_rate_limits(
|(team_id, issue_id, indices, per_issue, project)| async move {
let n = indices.len() as u32;
let decision = limiter
- .admit(team_id, issue_id, per_issue, project, n)
+ .admit(team_id, Some(issue_id), per_issue, project, n)
.await;
(team_id, issue_id, indices, per_issue, project, decision)
},
@@ -222,7 +228,7 @@ async fn apply_rate_limits(
let group = classify_group(
team_id,
- issue_id,
+ Some(issue_id),
&indices,
decision,
per_issue.is_some(),
@@ -234,7 +240,7 @@ async fn apply_rate_limits(
&mut outcomes,
team_id,
LimitKind::PerIssue,
- issue_id,
+ Some(issue_id),
allowed,
limited,
);
@@ -271,7 +277,7 @@ impl RateLimitingStage {
async fn apply_bypass(
&self,
settings: &HashMap<i32, RateLimitSettings>,
- items: &[ExceptionEventPipelineItem],
+ items: &[LinkedPipelineItem],
) -> (HashSet<usize>, HashMap<OutcomeKey, u32>) {
let enabled_teams = self.ctx.rate_limiter_enabled_team_ids.as_ref();
@@ -289,7 +295,7 @@ impl RateLimitingStage {
// Load rules once per eligible team present in the batch.
let eligible_teams: HashSet<i32> = items
.iter()
- .filter_map(|item| item.as_ref().ok().map(|p| p.team_id))
+ .filter_map(|item| item.as_ref().ok().map(ExceptionEvent::team_id))
.filter(|&team_id| is_rate_limited(team_id))
.collect();
let mut rules_by_team: HashMap<i32, Vec<BypassRule>> = HashMap::new();
@@ -461,23 +467,23 @@ fn classify_group(
/// issue id) when the per-issue limit is on, and a project row when the project limit is on.
fn tally_bypassed(
outcomes: &mut HashMap<OutcomeKey, u32>,
- props: &ExceptionProperties,
+ props: &ExceptionEvent<Linked>,
settings: &HashMap<i32, RateLimitSettings>,
) {
- let Some(team_settings) = settings.get(&props.team_id) else {
+ let Some(team_settings) = settings.get(&props.team_id()) else {
return;
};
if team_settings.project().is_some() {
*outcomes
- .entry((props.team_id, LimitKind::Project, None, Outcome::Bypassed))
+ .entry((props.team_id(), LimitKind::Project, None, Outcome::Bypassed))
.or_insert(0) += 1;
}
- if props.issue_id.is_some() && team_settings.per_issue().is_some() {
+ if team_settings.per_issue().is_some() {
*outcomes
.entry((
- props.team_id,
+ props.team_id(),
LimitKind::PerIssue,
- props.issue_id,
+ Some(props.issue_id()),
Outcome::Bypassed,
))
.or_insert(0) += 1;
@@ -520,7 +526,7 @@ struct RuleToDisable<'a> {
/// re-disabled (and its cache re-invalidated) on each match. `match_fn` is [`BypassRule::try_match`]
/// in production and a fake in tests.
fn evaluate_bypass_rules<'a>(
- items: &[ExceptionEventPipelineItem],
+ items: &[LinkedPipelineItem],
rules_by_team: &'a HashMap<i32, Vec<BypassRule>>,
settings: &HashMap<i32, RateLimitSettings>,
match_fn: impl Fn(&BypassRule, &serde_json::Value) -> Result<bool, VmError>,
@@ -536,13 +542,10 @@ fn evaluate_bypass_rules<'a>(
for (idx, item) in items.iter().enumerate() {
let Ok(props) = item else { continue };
- let Some(rules) = rules_by_team.get(&props.team_id) else {
+ let Some(rules) = rules_by_team.get(&props.team_id()) else {
continue;
};
- let props_json = match serde_json::to_value(props) {
- Ok(v) => v,
- Err(_) => continue,
- };
+ let props_json = props.to_properties_value();
for rule in rules {
if disabled_rules.contains(&rule.id) {
continue;
@@ -570,7 +573,7 @@ fn evaluate_bypass_rules<'a>(
disabled_rules.insert(rule.id);
to_disable.push(RuleToDisable {
rule,
- team_id: props.team_id,
+ team_id: props.team_id(),
error: err.to_string(),
props_json: props_json.clone(),
});
@@ -586,8 +589,11 @@ fn evaluate_bypass_rules<'a>(
#[cfg(test)]
mod tests {
use super::*;
- use crate::modes::processing::types::exception_properties::ExceptionProperties;
- use crate::modes::processing::types::ExceptionList;
+ use crate::issue_resolution::{Issue, IssueStatus};
+ use crate::modes::processing::types::{
+ exception_event::{FingerprintData, ResolvedMetadata},
+ ExceptionList,
+ };
use async_trait::async_trait;
use common_redis::CustomRedisError;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -648,20 +654,9 @@ mod tests {
}
}
- fn event(team_id: i32, issue_id: Option<Uuid>) -> ExceptionEventPipelineItem {
- Ok(ExceptionProperties {
+ fn event(team_id: i32, issue_id: Option<Uuid>) -> LinkedPipelineItem {
+ Ok(ExceptionEvent {
exception_list: ExceptionList(vec![]),
- exception_sources: None,
- exception_types: None,
- exception_messages: None,
- exception_functions: None,
- exception_handled: None,
- exception_releases: HashMap::new(),
- fingerprint: None,
- fingerprint_version: None,
- proposed_fingerprint: None,
- fingerprint_record: None,
- issue_id,
proposed_issue_name: None,
proposed_issue_description: None,
debug_images: vec![],
@@ -669,9 +664,29 @@ mod tests {
uuid: Uuid::now_v7(),
timestamp: String::new(),
team_id,
- issue: None,
- legacy_order_exception_list: None,
- legacy_order_resolved: None,
+ state: Linked {
+ metadata: ResolvedMetadata {
+ sources: vec![],
+ types: vec![],
+ messages: vec![],
+ functions: vec![],
+ handled: false,
+ releases: HashMap::new(),
+ },
+ fingerprint: FingerprintData {
+ value: "test-fingerprint".to_string(),
+ version: None,
+ record: vec![],
+ },
+ issue: Issue {
+ id: issue_id.unwrap_or_default(),
+ team_id,
+ status: IssueStatus::Active,
+ name: None,
+ description: None,
+ created_at: Utc::now(),
+ },
+ },
})
}
@@ -680,8 +695,7 @@ mod tests {
let runner = Arc::new(FakeScriptRunner::failing());
let limiter = limiter_with(runner.clone());
let issue = Uuid::now_v7();
- let mut items: Vec<ExceptionEventPipelineItem> =
- (0..5).map(|_| event(1, Some(issue))).collect();
+ let mut items: Vec<LinkedPipelineItem> = (0..5).map(|_| event(1, Some(issue))).collect();
let mut cfg = HashMap::new();
cfg.insert(1, settings(Some(1), Some(1)));
@@ -700,8 +714,7 @@ mod tests {
let runner = Arc::new(FakeScriptRunner::returning(vec![3, 1]));
let limiter = limiter_with(runner);
let issue = Uuid::now_v7();
- let mut items: Vec<ExceptionEventPipelineItem> =
- (0..5).map(|_| event(7, Some(issue))).collect();
+ let mut items: Vec<LinkedPipelineItem> = (0..5).map(|_| event(7, Some(issue))).collect();
let mut cfg = HashMap::new();
cfg.insert(7, settings(Some(100), Some(100)));
@@ -720,7 +733,7 @@ mod tests {
let runner = Arc::new(FakeScriptRunner::returning(vec![3, 1]));
let limiter = limiter_with(runner);
let (issue_a, issue_b) = (Uuid::now_v7(), Uuid::now_v7());
- let mut items: Vec<ExceptionEventPipelineItem> = (0..5)
+ let mut items: Vec<LinkedPipelineItem> = (0..5)
.map(|_| event(7, Some(issue_a)))
.chain((0..5).map(|_| event(7, Some(issue_b))))
.collect();
@@ -755,7 +768,7 @@ mod tests {
async fn skips_team_without_settings_without_touching_redis() {
let runner = Arc::new(FakeScriptRunner::returning(vec![0, 0]));
let limiter = limiter_with(runner.clone());
- let mut items: Vec<ExceptionEventPipelineItem> =
+ let mut items: Vec<LinkedPipelineItem> =
(0..3).map(|_| event(42, Some(Uuid::now_v7()))).collect();
let cfg = HashMap::new(); // team 42 has no settings row
@@ -772,8 +785,7 @@ mod tests {
let runner = Arc::new(FakeScriptRunner::returning(vec![0, 0]));
let limiter = limiter_with(runner.clone());
let issue = Uuid::now_v7();
- let mut items: Vec<ExceptionEventPipelineItem> =
- vec![event(1, Some(issue)), event(2, Some(issue))];
+ let mut items: Vec<LinkedPipelineItem> = vec![event(1, Some(issue)), event(2, Some(issue))];
let mut cfg = HashMap::new();
cfg.insert(1, settings(Some(1), Some(1)));
cfg.insert(2, settings(Some(1), Some(1)));
@@ -858,8 +870,7 @@ mod tests {
let runner = Arc::new(FakeScriptRunner::returning(vec![1, 1]));
let limiter = limiter_with(runner.clone());
let issue = Uuid::now_v7();
- let mut items: Vec<ExceptionEventPipelineItem> =
- (0..5).map(|_| event(7, Some(issue))).collect();
+ let mut items: Vec<LinkedPipelineItem> = (0..5).map(|_| event(7, Some(issue))).collect();
let mut cfg = HashMap::new();
cfg.insert(7, settings(Some(100), Some(100)));
let bypassed: HashSet<usize> = [0, 1].into_iter().collect();
diff --git a/rust/cymbal/src/modes/processing/stages/resolution/exception.rs b/rust/cymbal/src/modes/processing/stages/resolution/exception.rs
index d9dc9966f4a7..293e487de789 100644
--- a/rust/cymbal/src/modes/processing/stages/resolution/exception.rs
+++ b/rust/cymbal/src/modes/processing/stages/resolution/exception.rs
@@ -5,7 +5,7 @@ use crate::{
stages::{pipeline::HandledError, resolution::ResolutionStage},
types::{
batch::Batch,
- exception_properties::ExceptionProperties,
+ exception_event::{ExceptionEvent, Parsed},
operator::{OperatorResult, ValueOperator},
Exception, ExceptionList,
},
@@ -63,7 +63,7 @@ impl ExceptionResolver {
impl ValueOperator for ExceptionResolver {
type Context = ResolutionStage;
- type Item = ExceptionProperties;
+ type Item = ExceptionEvent<Parsed>;
type HandledError = HandledError;
type UnhandledError = UnhandledError;
@@ -73,7 +73,7 @@ impl ValueOperator for ExceptionResolver {
async fn execute_value(
&self,
- mut evt: ExceptionProperties,
+ mut evt: ExceptionEvent<Parsed>,
ctx: ResolutionStage,
) -> OperatorResult<Self> {
let team_id = evt.team_id;
diff --git a/rust/cymbal/src/modes/processing/stages/resolution/frame.rs b/rust/cymbal/src/modes/processing/stages/resolution/frame.rs
index 97c3417e011c..45238a297f63 100644
--- a/rust/cymbal/src/modes/processing/stages/resolution/frame.rs
+++ b/rust/cymbal/src/modes/processing/stages/resolution/frame.rs
@@ -8,7 +8,7 @@ use crate::{
stages::{pipeline::HandledError, resolution::ResolutionStage},
types::{
batch::Batch,
- exception_properties::ExceptionProperties,
+ exception_event::{ExceptionEvent, Parsed},
operator::{OperatorResult, ValueOperator},
Exception, ExceptionList, Stacktrace,
},
@@ -195,7 +195,7 @@ fn partition_into_units(frames: Vec<RawFrame>) -> Vec<Vec<RawFrame>> {
impl ValueOperator for FrameResolver {
type Context = ResolutionStage;
- type Item = ExceptionProperties;
+ type Item = ExceptionEvent<Parsed>;
type HandledError = HandledError;
type UnhandledError = UnhandledError;
@@ -205,7 +205,7 @@ impl ValueOperator for FrameResolver {
async fn execute_value(
&self,
- mut evt: ExceptionProperties,
+ mut evt: ExceptionEvent<Parsed>,
ctx: ResolutionStage,
) -> OperatorResult<Self> {
// Clone rather than take: `$debug_images` is serialized back onto the
diff --git a/rust/cymbal/src/modes/processing/stages/resolution/legacy.rs b/rust/cymbal/src/modes/processing/stages/resolution/legacy.rs
index cba34edc1c06..c4ef7250865b 100644
--- a/rust/cymbal/src/modes/processing/stages/resolution/legacy.rs
+++ b/rust/cymbal/src/modes/processing/stages/resolution/legacy.rs
@@ -10,7 +10,7 @@ use crate::{
resolution::{exception::ExceptionResolver, frame::FrameResolver, ResolutionStage},
},
types::{
- exception_properties::ExceptionProperties,
+ exception_event::{ExceptionEvent, Parsed},
operator::{OperatorResult, ValueOperator},
ExceptionList,
},
@@ -19,15 +19,15 @@ use crate::{
/// Resolves the legacy-order snapshot through the local exception + frame
/// resolvers, in the same order the canonical list is resolved.
async fn resolve_legacy(
- evt: &ExceptionProperties,
+ evt: &ExceptionEvent<Parsed>,
legacy: ExceptionList,
ctx: ResolutionStage,
) -> Result<ExceptionList, UnhandledError> {
- let team_id = evt.team_id;
+ let team_id = evt.team_id();
// Match the canonical pipeline order: exception resolution (java/dart
// reshaping) then frame resolution.
let legacy = ExceptionResolver::resolve_exception_list(team_id, legacy, ctx.clone()).await?;
- let debug_images = Arc::new(evt.debug_images.clone());
+ let debug_images = Arc::new(evt.debug_images().to_vec());
FrameResolver::resolve_exception_list_frames(team_id, legacy, debug_images, ctx).await
}
@@ -41,7 +41,7 @@ async fn resolve_legacy(
pub struct LegacyOrderResolver;
impl ValueOperator for LegacyOrderResolver {
- type Item = ExceptionProperties;
+ type Item = ExceptionEvent<Parsed>;
type Context = ResolutionStage;
type HandledError = HandledError;
type UnhandledError = UnhandledError;
@@ -52,10 +52,10 @@ impl ValueOperator for LegacyOrderResolver {
async fn execute_value(
&self,
- mut evt: ExceptionProperties,
+ mut evt: ExceptionEvent<Parsed>,
ctx: ResolutionStage,
) -> OperatorResult<Self> {
- let Some(legacy) = evt.legacy_order_exception_list.take() else {
+ let Some(legacy) = evt.take_legacy_order_exception_list() else {
return Ok(Ok(evt));
};
@@ -67,10 +67,10 @@ impl ValueOperator for LegacyOrderResolver {
// fingerprint just falls back to the pre-normalization behavior of
// creating a fresh issue.
match resolve_legacy(&evt, legacy, ctx).await {
- Ok(resolved) => evt.legacy_order_resolved = Some(resolved),
+ Ok(resolved) => evt.set_legacy_order_resolved(resolved),
Err(e) => {
metrics::counter!(LEGACY_ORDER_RESOLVE_FAILED).increment(1);
- debug!(event = %evt.uuid, "legacy-order resolution failed, skipping alias: {e}");
+ debug!(event = %evt.uuid(), "legacy-order resolution failed, skipping alias: {e}");
}
}
Ok(Ok(evt))
diff --git a/rust/cymbal/src/modes/processing/stages/resolution/mod.rs b/rust/cymbal/src/modes/processing/stages/resolution/mod.rs
index d0040c5e3db7..0558844d73d1 100644
--- a/rust/cymbal/src/modes/processing/stages/resolution/mod.rs
+++ b/rust/cymbal/src/modes/processing/stages/resolution/mod.rs
@@ -5,19 +5,17 @@ use tokio::sync::{OwnedSemaphorePermit, Semaphore};
pub mod exception;
pub mod frame;
pub mod legacy;
-pub mod properties;
pub mod remote;
use crate::{
app_context::AppContext,
error::UnhandledError,
metric_consts::RESOLUTION_STAGE,
- stages::pipeline::ExceptionEventPipelineItem,
+ stages::pipeline::{ParsedPipelineItem, ResolvedPipelineItem},
stages::resolution::{
exception::ExceptionResolver,
frame::FrameResolver,
legacy::LegacyOrderResolver,
- properties::PropertiesResolver,
remote::resolver::{resolve_batch, RemoteResolutionContext},
},
symbolication::symbol::SymbolResolver,
@@ -62,8 +60,8 @@ impl ResolutionStage {
}
impl Stage for ResolutionStage {
- type Input = ExceptionEventPipelineItem;
- type Output = ExceptionEventPipelineItem;
+ type Input = ParsedPipelineItem;
+ type Output = ResolvedPipelineItem;
fn name(&self) -> &'static str {
RESOLUTION_STAGE
@@ -74,26 +72,22 @@ impl Stage for ResolutionStage {
// Remote mode: the stage owns orchestration across the incoming
// batch, including deterministic rollout sampling. Sampled events
// use grouped exception-level Resolve items, and unsampled events use
- // the local exception/frame operators. PropertiesResolver still
- // runs afterwards because it operates on the resolved exception
- // list shape independently of how exception/frame resolution was
- // performed.
- return resolve_batch(batch, remote, self.clone())
+ // the local exception/frame operators. Both paths materialize the
+ // resolved event metadata before returning.
+ let resolved = resolve_batch(batch, remote, self.clone())
.await?
.apply_operator(LegacyOrderResolver, self.clone())
- .await?
- .apply_operator(PropertiesResolver, self.clone())
- .await;
+ .await?;
+ return Ok(resolved.map(|item, ()| item.map(|event| event.into_resolved()), &mut ()));
}
- batch
+ let resolved = batch
.apply_operator(ExceptionResolver, self.clone())
.await?
.apply_operator(FrameResolver, self.clone())
.await?
.apply_operator(LegacyOrderResolver, self.clone())
- .await?
- .apply_operator(PropertiesResolver, self.clone())
- .await
+ .await?;
+ Ok(resolved.map(|item, ()| item.map(|event| event.into_resolved()), &mut ()))
}
}
diff --git a/rust/cymbal/src/modes/processing/stages/resolution/properties.rs b/rust/cymbal/src/modes/processing/stages/resolution/properties.rs
deleted file mode 100644
index 7146a00cadef..000000000000
--- a/rust/cymbal/src/modes/processing/stages/resolution/properties.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-use crate::{
- error::UnhandledError,
- metric_consts::PROPERTIES_RESOLVER_OPERATOR,
- stages::{pipeline::HandledError, resolution::ResolutionStage},
- types::{
- exception_properties::ExceptionProperties,
- operator::{OperatorResult, ValueOperator},
- },
-};
-
-#[derive(Clone)]
-pub struct PropertiesResolver;
-
-impl ValueOperator for PropertiesResolver {
- type Item = ExceptionProperties;
- type Context = ResolutionStage;
- type HandledError = HandledError;
- type UnhandledError = UnhandledError;
-
- fn name(&self) -> &'static str {
- PROPERTIES_RESOLVER_OPERATOR
- }
-
- async fn execute_value(
- &self,
- mut event: ExceptionProperties,
- _: ResolutionStage,
- ) -> OperatorResult<Self> {
- // Implement property resolution logic here
- event.exception_functions = Some(event.exception_list.get_unique_functions());
- event.exception_sources = Some(event.exception_list.get_unique_sources());
- event.exception_types = Some(event.exception_list.get_unique_types());
- event.exception_messages = Some(event.exception_list.get_unique_messages());
- event.exception_releases = event.exception_list.get_release_map();
- event.exception_handled = Some(event.exception_list.get_is_handled());
- Ok(Ok(event))
- }
-}
diff --git a/rust/cymbal/src/modes/processing/stages/resolution/remote/resolver.rs b/rust/cymbal/src/modes/processing/stages/resolution/remote/resolver.rs
index 62b660837872..3ee12ce127f9 100644
--- a/rust/cymbal/src/modes/processing/stages/resolution/remote/resolver.rs
+++ b/rust/cymbal/src/modes/processing/stages/resolution/remote/resolver.rs
@@ -9,13 +9,17 @@ use tokio::sync::Semaphore;
use crate::{
error::UnhandledError,
stages::{
- pipeline::ExceptionEventPipelineItem,
+ pipeline::ParsedPipelineItem,
resolution::{
exception::ExceptionResolver, frame::FrameResolver, remote::pool::EndpointPool,
ResolutionStage,
},
},
- types::{batch::Batch, exception_properties::ExceptionProperties, Exception, ExceptionList},
+ types::{
+ batch::Batch,
+ exception_event::{ExceptionEvent, Parsed},
+ Exception, ExceptionList,
+ },
};
use super::config::RemoteResolutionConfig;
@@ -65,10 +69,10 @@ impl RemoteResolutionContext {
/// Each event passes through exactly one bucket and writes itself into the
/// output exactly once. There is no shared mutation across RPC boundaries.
pub async fn resolve_batch(
- batch: Batch<ExceptionEventPipelineItem>,
+ batch: Batch<ParsedPipelineItem>,
ctx: RemoteResolutionContext,
local_stage: ResolutionStage,
-) -> Result<Batch<ExceptionEventPipelineItem>, UnhandledError> {
+) -> Result<Batch<ParsedPipelineItem>, UnhandledError> {
let batch_len = batch.len();
let partition = partition_batch(batch, ctx.config.sample_rate)?;
@@ -86,17 +90,16 @@ pub async fn resolve_batch(
fn assemble_output(
batch_len: usize,
- errors: Vec<(usize, ExceptionEventPipelineItem)>,
- empty: Vec<(usize, ExceptionEventPipelineItem)>,
- local: Vec<(usize, ExceptionEventPipelineItem)>,
- remote: Vec<(usize, ExceptionEventPipelineItem)>,
-) -> Result<Batch<ExceptionEventPipelineItem>, UnhandledError> {
- let mut output: Vec<Option<ExceptionEventPipelineItem>> =
- (0..batch_len).map(|_| None).collect();
+ errors: Vec<(usize, ParsedPipelineItem)>,
+ empty: Vec<(usize, ParsedPipelineItem)>,
+ local: Vec<(usize, ParsedPipelineItem)>,
+ remote: Vec<(usize, ParsedPipelineItem)>,
+) -> Result<Batch<ParsedPipelineItem>, UnhandledError> {
+ let mut output: Vec<Option<ParsedPipelineItem>> = (0..batch_len).map(|_| None).collect();
for (idx, item) in errors.into_iter().chain(empty).chain(local).chain(remote) {
output[idx] = Some(item);
}
- let resolved: Vec<ExceptionEventPipelineItem> = output
+ let resolved: Vec<ParsedPipelineItem> = output
.into_iter()
.enumerate()
.map(|(idx, slot)| {
@@ -120,7 +123,7 @@ fn assemble_output(
/// batch bookkeeping.
struct RemoteEvent {
batch_index: usize,
- evt: ExceptionProperties,
+ evt: ExceptionEvent<Parsed>,
/// One serialized exception per `evt.exception_list` entry, in order.
exception_jsons: Vec<Vec<u8>>,
/// Shared across this event's exceptions on the wire. The proto carries
@@ -136,7 +139,7 @@ impl RemoteEvent {
struct RemoteEventSlot {
batch_index: usize,
- evt: ExceptionProperties,
+ evt: ExceptionEvent<Parsed>,
resolved: Vec<Option<Exception>>,
}
@@ -170,13 +173,13 @@ struct ResolvedRemoteItem {
// ─────────────────────────────────────────────────────────────────────────────
async fn resolve_local_events(
- local_events: Vec<(usize, ExceptionProperties)>,
+ local_events: Vec<(usize, ExceptionEvent<Parsed>)>,
local_stage: ResolutionStage,
-) -> Result<Vec<(usize, ExceptionEventPipelineItem)>, UnhandledError> {
+) -> Result<Vec<(usize, ParsedPipelineItem)>, UnhandledError> {
if local_events.is_empty() {
return Ok(Vec::new());
}
- let (indexes, events): (Vec<usize>, Vec<ExceptionProperties>) =
+ let (indexes, events): (Vec<usize>, Vec<ExceptionEvent<Parsed>>) =
local_events.into_iter().unzip();
let batch = Batch::from(events.into_iter().map(Ok).collect::<Vec<_>>())
.apply_operator(ExceptionResolver, local_stage.clone())
@@ -193,7 +196,7 @@ async fn resolve_local_events(
async fn resolve_remote_events(
ctx: &RemoteResolutionContext,
events: Vec<RemoteEvent>,
-) -> Result<Vec<(usize, ExceptionEventPipelineItem)>, UnhandledError> {
+) -> Result<Vec<(usize, ParsedPipelineItem)>, UnhandledError> {
if events.is_empty() {
return Ok(Vec::new());
}
@@ -248,7 +251,9 @@ async fn resolve_remote_events(
})
})
.collect::<Result<Vec<_>, _>>()?;
- event.evt.exception_list = ExceptionList::from(exceptions);
+ event
+ .evt
+ .replace_exception_list(ExceptionList::from(exceptions));
Ok((event.batch_index, Ok(event.evt)))
})
.collect()
@@ -264,7 +269,7 @@ fn build_work_items(
for event in events {
let event_slot = event_slots.len();
let item_count = event.item_count();
- let team_id = event.evt.team_id;
+ let team_id = event.evt.team_id();
let routing_keys = routing_keys_for_event(&event.evt);
for (exception_slot, exception_json) in event.exception_jsons.iter().cloned().enumerate() {
@@ -309,10 +314,13 @@ fn build_work_items(
#[cfg(test)]
mod tests {
+ use std::collections::HashMap;
+
use serde_json::json;
use uuid::Uuid;
use super::*;
+ use crate::types::event::AnyEvent;
#[test]
fn build_work_items_assigns_client_tokens_and_slots_without_batch_ids() {
@@ -411,12 +419,15 @@ mod tests {
batch_index: usize,
exceptions: Vec<serde_json::Value>,
) -> RemoteEvent {
- let mut evt: ExceptionProperties = serde_json::from_value(json!({
- "$exception_list": exceptions,
- }))
+ let evt = ExceptionEvent::<Parsed>::try_from(AnyEvent {
+ uuid: Uuid::from_u128(0xABCD_0000_0000_0000 ^ (batch_index as u128)),
+ event: "$exception".to_string(),
+ team_id,
+ timestamp: String::new(),
+ properties: json!({ "$exception_list": exceptions }),
+ others: HashMap::new(),
+ })
.expect("valid exception properties");
- evt.team_id = team_id;
- evt.uuid = Uuid::from_u128(0xABCD_0000_0000_0000 ^ (batch_index as u128));
let exception_jsons = evt
.exception_list
diff --git a/rust/cymbal/src/modes/processing/stages/resolution/remote/resolver/chunk.rs b/rust/cymbal/src/modes/processing/stages/resolution/remote/resolver/chunk.rs
index 060ae3625af4..1e1ec2c70fee 100644
--- a/rust/cymbal/src/modes/processing/stages/resolution/remote/resolver/chunk.rs
+++ b/rust/cymbal/src/modes/processing/stages/resolution/remote/resolver/chunk.rs
@@ -3,16 +3,17 @@
use crate::{
langs::native::DebugImage,
- types::{exception_properties::ExceptionProperties, Exception},
+ types::{
+ exception_event::{ExceptionEvent, Parsed},
+ Exception,
+ },
};
/// Return one routing key per exception in event order.
-pub(super) fn routing_keys_for_event(evt: &ExceptionProperties) -> Vec<String> {
+pub(super) fn routing_keys_for_event(evt: &ExceptionEvent<Parsed>) -> Vec<String> {
evt.exception_list
.iter()
- .map(|exception| {
- routing_key_for_exception(evt.team_id, exception, evt.debug_images.as_ref())
- })
+ .map(|exception| routing_key_for_exception(evt.team_id(), exception, evt.debug_images()))
.collect()
}
@@ -35,13 +36,30 @@ fn team_routing_key(team_id: i32) -> String {
#[cfg(test)]
mod tests {
+ use std::collections::HashMap;
+
use serde_json::json;
+ use uuid::Uuid;
use super::*;
+ use crate::types::event::AnyEvent;
+
+ fn event(properties: serde_json::Value) -> ExceptionEvent<Parsed> {
+ AnyEvent {
+ uuid: Uuid::now_v7(),
+ event: "$exception".to_string(),
+ team_id: 7,
+ timestamp: String::new(),
+ properties,
+ others: HashMap::new(),
+ }
+ .try_into()
+ .expect("valid exception properties")
+ }
#[test]
fn routing_key_uses_first_symbol_set_ref() {
- let mut evt: ExceptionProperties = serde_json::from_value(json!({
+ let evt = event(json!({
"$exception_list": [{
"type": "Error",
"value": "boom",
@@ -57,28 +75,24 @@ mod tests {
}]
}
}]
- }))
- .expect("valid exception properties");
- evt.team_id = 7;
+ }));
assert_eq!(routing_keys_for_event(&evt), vec!["team:7:symbol:chunk-a"]);
}
#[test]
fn routing_key_falls_back_to_team_without_symbol_set_ref() {
- let mut evt: ExceptionProperties = serde_json::from_value(json!({
+ let evt = event(json!({
"$exception_list": [{
"type": "Error",
"value": "boom"
}]
- }))
- .expect("valid exception properties");
- evt.team_id = 7;
+ }));
assert_eq!(routing_keys_for_event(&evt), vec!["team:7"]);
}
#[test]
fn routing_keys_are_per_exception() {
- let mut evt: ExceptionProperties = serde_json::from_value(json!({
+ let evt = event(json!({
"$exception_list": [{
"type": "Error",
"value": "boom-a",
@@ -111,9 +125,7 @@ mod tests {
"type": "Error",
"value": "boom-c"
}]
- }))
- .expect("valid exception properties");
- evt.team_id = 7;
+ }));
assert_eq!(
routing_keys_for_event(&evt),
diff --git a/rust/cymbal/src/modes/processing/stages/resolution/remote/resolver/partition.rs b/rust/cymbal/src/modes/processing/stages/resolution/remote/resolver/partition.rs
index 6d9dabd74df4..a51fa7065818 100644
--- a/rust/cymbal/src/modes/processing/stages/resolution/remote/resolver/partition.rs
+++ b/rust/cymbal/src/modes/processing/stages/resolution/remote/resolver/partition.rs
@@ -5,20 +5,23 @@ use sha2::{Digest, Sha256};
use crate::error::UnhandledError;
use crate::metric_consts::REMOTE_RESOLUTION_SAMPLING;
-use crate::stages::pipeline::ExceptionEventPipelineItem;
-use crate::types::{batch::Batch, exception_properties::ExceptionProperties};
+use crate::stages::pipeline::ParsedPipelineItem;
+use crate::types::{
+ batch::Batch,
+ exception_event::{ExceptionEvent, Parsed},
+};
use super::RemoteEvent;
pub(super) struct Partition {
- pub(super) errors: Vec<(usize, ExceptionEventPipelineItem)>,
- pub(super) empty: Vec<(usize, ExceptionEventPipelineItem)>,
- pub(super) local: Vec<(usize, ExceptionProperties)>,
+ pub(super) errors: Vec<(usize, ParsedPipelineItem)>,
+ pub(super) empty: Vec<(usize, ParsedPipelineItem)>,
+ pub(super) local: Vec<(usize, ExceptionEvent<Parsed>)>,
pub(super) remote: Vec<RemoteEvent>,
}
pub(super) fn partition_batch(
- batch: Batch<ExceptionEventPipelineItem>,
+ batch: Batch<ParsedPipelineItem>,
sample_rate: f64,
) -> Result<Partition, UnhandledError> {
let mut errors = Vec::new();
@@ -59,7 +62,7 @@ pub(super) fn partition_batch(
fn prepare_remote_event(
batch_index: usize,
- evt: ExceptionProperties,
+ evt: ExceptionEvent<Parsed>,
) -> Result<RemoteEvent, UnhandledError> {
let exception_jsons: Vec<Vec<u8>> = evt
.exception_list
@@ -82,7 +85,7 @@ fn prepare_remote_event(
})
}
-fn should_route_event_to_remote(evt: &ExceptionProperties, sample_rate: f64) -> bool {
+fn should_route_event_to_remote(evt: &ExceptionEvent<Parsed>, sample_rate: f64) -> bool {
if sample_rate <= 0.0 {
return false;
}
@@ -91,8 +94,8 @@ fn should_route_event_to_remote(evt: &ExceptionProperties, sample_rate: f64) ->
}
let mut hasher = Sha256::new();
- hasher.update(evt.team_id.to_be_bytes());
- hasher.update(evt.uuid.as_bytes());
+ hasher.update(evt.team_id().to_be_bytes());
+ hasher.update(evt.uuid().as_bytes());
let digest = hasher.finalize();
let bucket_bytes: [u8; 8] = digest[..8]
.try_into()
@@ -103,22 +106,32 @@ fn should_route_event_to_remote(evt: &ExceptionProperties, sample_rate: f64) ->
#[cfg(test)]
mod tests {
+ use std::collections::HashMap;
+
use serde_json::json;
use uuid::Uuid;
use super::*;
+ use crate::types::event::AnyEvent;
+
+ fn event() -> ExceptionEvent<Parsed> {
+ AnyEvent {
+ uuid: Uuid::from_u128(0x123456789abcdef),
+ event: "$exception".to_string(),
+ team_id: 123,
+ timestamp: String::new(),
+ properties: json!({
+ "$exception_list": [{ "type": "Error", "value": "boom" }]
+ }),
+ others: HashMap::new(),
+ }
+ .try_into()
+ .expect("valid exception properties")
+ }
#[test]
fn sampling_decision_is_stable_for_same_team_and_event_uuid() {
- let mut evt: ExceptionProperties = serde_json::from_value(json!({
- "$exception_list": [{
- "type": "Error",
- "value": "boom"
- }]
- }))
- .expect("valid exception properties");
- evt.team_id = 123;
- evt.uuid = Uuid::from_u128(0x123456789abcdef);
+ let evt = event();
let first = should_route_event_to_remote(&evt, 0.37);
for _ in 0..100 {
@@ -128,15 +141,7 @@ mod tests {
#[test]
fn sampling_decision_respects_rate_boundaries() {
- let mut evt: ExceptionProperties = serde_json::from_value(json!({
- "$exception_list": [{
- "type": "Error",
- "value": "boom"
- }]
- }))
- .expect("valid exception properties");
- evt.team_id = 123;
- evt.uuid = Uuid::from_u128(0x123456789abcdef);
+ let evt = event();
assert!(!should_route_event_to_remote(&evt, 0.0));
assert!(should_route_event_to_remote(&evt, 1.0));
diff --git a/rust/cymbal/src/modes/processing/types/event.rs b/rust/cymbal/src/modes/processing/types/event.rs
index 67714b143378..84c51830378f 100644
--- a/rust/cymbal/src/modes/processing/types/event.rs
+++ b/rust/cymbal/src/modes/processing/types/event.rs
@@ -5,10 +5,7 @@ use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;
-use crate::{
- error::{EventError, UnhandledError},
- types::exception_properties::ExceptionProperties,
-};
+use crate::error::{EventError, UnhandledError};
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct AnyEvent {
@@ -24,13 +21,13 @@ pub struct AnyEvent {
}
pub trait PropertiesContainer: Send + Clone + 'static {
- fn set_properties(&mut self, new_props: ExceptionProperties) -> Result<(), UnhandledError>;
+ fn set_properties(&mut self, new_props: Value) -> Result<(), UnhandledError>;
fn attach_error(&mut self, error: String) -> Result<(), UnhandledError>;
}
impl PropertiesContainer for AnyEvent {
- fn set_properties(&mut self, new_props: ExceptionProperties) -> Result<(), UnhandledError> {
- self.properties = serde_json::to_value(&new_props)?;
+ fn set_properties(&mut self, new_props: Value) -> Result<(), UnhandledError> {
+ self.properties = new_props;
Ok(())
}
@@ -73,7 +70,7 @@ impl TryFrom<ClickHouseEvent> for AnyEvent {
#[cfg(test)]
mod test {
- use crate::types::exception_properties::MAX_EXCEPTION_VALUE_LENGTH;
+ use crate::types::exception_event::{ExceptionEvent, Parsed, MAX_EXCEPTION_VALUE_LENGTH};
use super::*;
use uuid::Uuid;
@@ -119,9 +116,9 @@ mod test {
let long_value = "x".repeat(MAX_EXCEPTION_VALUE_LENGTH + 100);
let event = make_exception_event(&long_value);
let any_event = AnyEvent::try_from(event).unwrap();
- let exc_props = ExceptionProperties::try_from(any_event).unwrap();
+ let exc_props = ExceptionEvent::<Parsed>::try_from(any_event).unwrap();
let expected = format!("{}...", "x".repeat(MAX_EXCEPTION_VALUE_LENGTH));
- assert_eq!(exc_props.exception_list[0].exception_message, expected);
+ assert_eq!(exc_props.exception_list()[0].exception_message, expected);
}
}
diff --git a/rust/cymbal/src/modes/processing/types/exception_event.rs b/rust/cymbal/src/modes/processing/types/exception_event.rs
new file mode 100644
index 000000000000..3b2ed08d2345
--- /dev/null
+++ b/rust/cymbal/src/modes/processing/types/exception_event.rs
@@ -0,0 +1,548 @@
+use std::collections::HashMap;
+
+use common_types::ClickHouseEvent;
+use serde_json::{Map, Value};
+use uuid::Uuid;
+
+use crate::{
+ error::EventError,
+ fingerprinting::{FingerprintRecordPart, FingerprintVersion},
+ frames::releases::ReleaseInfo,
+ issue_resolution::Issue,
+ langs::native::DebugImage,
+ modes::processing::normalization::normalize_wire_order,
+ recursively_sanitize_properties,
+ types::{event::AnyEvent, ExceptionList, OutputErrProps, RawErrProps},
+};
+
+pub const MAX_EXCEPTION_VALUE_LENGTH: usize = 10_000;
+
+pub type PipelineItem<S> = Result<ExceptionEvent<S>, EventError>;
+
+#[derive(Debug, Clone)]
+pub struct Parsed {
+ pub(crate) client_fingerprint: Option<String>,
+ pub(crate) legacy_order_exception_list: Option<ExceptionList>,
+ pub(crate) legacy_order_resolved: Option<ExceptionList>,
+}
+
+#[derive(Debug, Clone)]
+pub struct ResolvedMetadata {
+ pub sources: Vec<String>,
+ pub types: Vec<String>,
+ pub messages: Vec<String>,
+ pub functions: Vec<String>,
+ pub handled: bool,
+ pub releases: HashMap<String, ReleaseInfo>,
+}
+
+impl ResolvedMetadata {
+ fn from_exception_list(exception_list: &ExceptionList) -> 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(),
+ releases: exception_list.get_release_map(),
+ }
+ }
+}
+
+#[derive(Debug, Clone)]
+pub struct Resolved {
+ pub(crate) metadata: ResolvedMetadata,
+ pub(crate) client_fingerprint: Option<String>,
+ pub(crate) legacy_order_resolved: Option<ExceptionList>,
+}
+
+#[derive(Debug, Clone)]
+pub struct FingerprintData {
+ pub value: String,
+ pub version: Option<FingerprintVersion>,
+ pub record: Vec<FingerprintRecordPart>,
+}
+
+#[derive(Debug, Clone)]
+pub struct Fingerprinted {
+ pub(crate) metadata: ResolvedMetadata,
+ pub(crate) fingerprint: FingerprintData,
+}
+
+#[derive(Debug, Clone)]
+pub struct Linked {
+ pub(crate) metadata: ResolvedMetadata,
+ pub(crate) fingerprint: FingerprintData,
+ pub(crate) issue: Issue,
+}
+
+#[derive(Debug, Clone)]
+pub struct RateChecked {
+ linked: Linked,
+}
+
+#[derive(Debug, Clone)]
+pub struct Finalized {
+ linked: Linked,
+}
+
+#[derive(Debug, Clone)]
+pub struct ExceptionEvent<S> {
+ pub(crate) uuid: Uuid,
+ pub(crate) team_id: i32,
+ pub(crate) timestamp: String,
+ pub(crate) exception_list: ExceptionList,
+ pub(crate) debug_images: Vec<DebugImage>,
+ pub(crate) props: HashMap<String, Value>,
+ pub(crate) proposed_issue_name: Option<String>,
+ pub(crate) proposed_issue_description: Option<String>,
+ pub(crate) state: S,
+}
+
+impl<S> ExceptionEvent<S> {
+ fn map_state<T>(self, transform: impl FnOnce(S) -> T) -> ExceptionEvent<T> {
+ ExceptionEvent {
+ uuid: self.uuid,
+ team_id: self.team_id,
+ timestamp: self.timestamp,
+ exception_list: self.exception_list,
+ debug_images: self.debug_images,
+ props: self.props,
+ proposed_issue_name: self.proposed_issue_name,
+ proposed_issue_description: self.proposed_issue_description,
+ state: transform(self.state),
+ }
+ }
+
+ pub fn uuid(&self) -> Uuid {
+ self.uuid
+ }
+
+ pub fn team_id(&self) -> i32 {
+ self.team_id
+ }
+
+ pub fn timestamp(&self) -> &str {
+ &self.timestamp
+ }
+
+ pub fn exception_list(&self) -> &ExceptionList {
+ &self.exception_list
+ }
+
+ pub fn debug_images(&self) -> &[DebugImage] {
+ &self.debug_images
+ }
+
+ pub fn properties(&self) -> &HashMap<String, Value> {
+ &self.props
+ }
+
+ pub fn proposed_issue_name(&self) -> Option<&str> {
+ self.proposed_issue_name.as_deref()
+ }
+
+ pub fn proposed_issue_description(&self) -> Option<&str> {
+ self.proposed_issue_description.as_deref()
+ }
+}
+
+impl ExceptionEvent<Parsed> {
+ pub(crate) fn replace_exception_list(&mut self, exception_list: ExceptionList) {
+ self.exception_list = exception_list;
+ }
+
+ pub(crate) fn take_legacy_order_exception_list(&mut self) -> Option<ExceptionList> {
+ self.state.legacy_order_exception_list.take()
+ }
+
+ pub(crate) fn set_legacy_order_resolved(&mut self, exception_list: ExceptionList) {
+ self.state.legacy_order_resolved = Some(exception_list);
+ }
+
+ pub(crate) fn into_resolved(self) -> ExceptionEvent<Resolved> {
+ let metadata = ResolvedMetadata::from_exception_list(&self.exception_list);
+ self.map_state(|state| Resolved {
+ metadata,
+ client_fingerprint: state.client_fingerprint,
+ legacy_order_resolved: state.legacy_order_resolved,
+ })
+ }
+}
+
+impl ExceptionEvent<Resolved> {
+ pub fn metadata(&self) -> &ResolvedMetadata {
+ &self.state.metadata
+ }
+
+ pub(crate) fn client_fingerprint(&self) -> Option<&str> {
+ self.state.client_fingerprint.as_deref()
+ }
+
+ pub(crate) fn take_legacy_order_resolved(&mut self) -> Option<ExceptionList> {
+ self.state.legacy_order_resolved.take()
+ }
+
+ pub(crate) fn into_fingerprinted(
+ self,
+ fingerprint: FingerprintData,
+ ) -> ExceptionEvent<Fingerprinted> {
+ self.map_state(|state| Fingerprinted {
+ metadata: state.metadata,
+ fingerprint,
+ })
+ }
+
+ pub fn to_grouping_value(&self) -> Value {
+ let mut map = self.base_resolved_properties(&self.state.metadata);
+ map.insert(
+ "$exception_fingerprint".into(),
+ self.state
+ .client_fingerprint
+ .as_ref()
+ .map_or(Value::Null, |value| Value::String(value.clone())),
+ );
+ map.insert("$exception_fingerprint_record".into(), Value::Null);
+ map.insert("$exception_issue_id".into(), Value::Null);
+ Value::Object(map)
+ }
+}
+
+impl ExceptionEvent<Fingerprinted> {
+ pub fn metadata(&self) -> &ResolvedMetadata {
+ &self.state.metadata
+ }
+
+ pub fn fingerprint(&self) -> &FingerprintData {
+ &self.state.fingerprint
+ }
+
+ pub(crate) fn into_linked(self, issue: Issue) -> ExceptionEvent<Linked> {
+ self.map_state(|state| Linked {
+ metadata: state.metadata,
+ fingerprint: state.fingerprint,
+ issue,
+ })
+ }
+
+ pub fn to_properties_value(&self) -> Value {
+ self.properties_with_fingerprint(&self.state.metadata, &self.state.fingerprint, None)
+ }
+
+ pub fn to_output(&self, issue: &Issue) -> OutputErrProps {
+ self.build_output(&self.state.metadata, &self.state.fingerprint, issue.id)
+ }
+}
+
+impl ExceptionEvent<Linked> {
+ pub fn metadata(&self) -> &ResolvedMetadata {
+ &self.state.metadata
+ }
+
+ pub fn fingerprint(&self) -> &FingerprintData {
+ &self.state.fingerprint
+ }
+
+ pub fn issue(&self) -> &Issue {
+ &self.state.issue
+ }
+
+ pub fn issue_id(&self) -> Uuid {
+ self.state.issue.id
+ }
+
+ pub fn to_output(&self) -> OutputErrProps {
+ self.build_output(
+ &self.state.metadata,
+ &self.state.fingerprint,
+ self.state.issue.id,
+ )
+ }
+
+ pub fn to_properties_value(&self) -> Value {
+ self.properties_with_fingerprint(
+ &self.state.metadata,
+ &self.state.fingerprint,
+ Some(self.state.issue.id),
+ )
+ }
+
+ pub(crate) fn into_rate_checked(self) -> ExceptionEvent<RateChecked> {
+ self.map_state(|linked| RateChecked { linked })
+ }
+}
+
+impl ExceptionEvent<RateChecked> {
+ pub fn metadata(&self) -> &ResolvedMetadata {
+ &self.state.linked.metadata
+ }
+
+ pub fn fingerprint(&self) -> &FingerprintData {
+ &self.state.linked.fingerprint
+ }
+
+ pub fn issue(&self) -> &Issue {
+ &self.state.linked.issue
+ }
+
+ pub fn issue_id(&self) -> Uuid {
+ self.state.linked.issue.id
+ }
+
+ pub fn to_output(&self) -> OutputErrProps {
+ self.build_output(
+ &self.state.linked.metadata,
+ &self.state.linked.fingerprint,
+ self.state.linked.issue.id,
+ )
+ }
+
+ pub(crate) fn into_finalized(self) -> ExceptionEvent<Finalized> {
+ self.map_state(|state| Finalized {
+ linked: state.linked,
+ })
+ }
+}
+
+impl ExceptionEvent<Finalized> {
+ pub fn metadata(&self) -> &ResolvedMetadata {
+ &self.state.linked.metadata
+ }
+
+ pub fn fingerprint(&self) -> &FingerprintData {
+ &self.state.linked.fingerprint
+ }
+
+ pub fn issue(&self) -> &Issue {
+ &self.state.linked.issue
+ }
+
+ pub fn issue_id(&self) -> Uuid {
+ self.state.linked.issue.id
+ }
+
+ pub fn to_output(&self) -> OutputErrProps {
+ self.build_output(
+ &self.state.linked.metadata,
+ &self.state.linked.fingerprint,
+ self.state.linked.issue.id,
+ )
+ }
+
+ pub fn to_clickhouse_value(&self) -> Value {
+ let mut value = serde_json::to_value(self.to_output())
+ .expect("final exception properties are serializable");
+ let map = value
+ .as_object_mut()
+ .expect("serialized exception properties are an object");
+ if let Some(name) = &self.proposed_issue_name {
+ map.insert("$issue_name".into(), Value::String(name.clone()));
+ }
+ if let Some(description) = &self.proposed_issue_description {
+ map.insert(
+ "$issue_description".into(),
+ Value::String(description.clone()),
+ );
+ }
+ if !self.debug_images.is_empty() {
+ map.insert(
+ "$debug_images".into(),
+ serde_json::to_value(&self.debug_images)
+ .expect("debug image properties are serializable"),
+ );
+ }
+ value
+ }
+}
+
+impl<S> ExceptionEvent<S> {
+ fn base_resolved_properties(&self, metadata: &ResolvedMetadata) -> Map<String, Value> {
+ let mut map: Map<String, Value> = self.props.clone().into_iter().collect();
+ map.insert(
+ "$exception_list".into(),
+ serde_json::to_value(&self.exception_list).expect("exception list is serializable"),
+ );
+ map.insert(
+ "$exception_sources".into(),
+ serde_json::to_value(&metadata.sources).expect("exception sources are serializable"),
+ );
+ map.insert(
+ "$exception_types".into(),
+ serde_json::to_value(&metadata.types).expect("exception types are serializable"),
+ );
+ map.insert(
+ "$exception_values".into(),
+ serde_json::to_value(&metadata.messages).expect("exception messages are serializable"),
+ );
+ map.insert(
+ "$exception_functions".into(),
+ serde_json::to_value(&metadata.functions)
+ .expect("exception functions are serializable"),
+ );
+ map.insert("$exception_handled".into(), Value::Bool(metadata.handled));
+ if !metadata.releases.is_empty() {
+ map.insert(
+ "$exception_releases".into(),
+ serde_json::to_value(&metadata.releases)
+ .expect("exception releases are serializable"),
+ );
+ }
+ if let Some(name) = &self.proposed_issue_name {
+ map.insert("$issue_name".into(), Value::String(name.clone()));
+ }
+ if let Some(description) = &self.proposed_issue_description {
+ map.insert(
+ "$issue_description".into(),
+ Value::String(description.clone()),
+ );
+ }
+ if !self.debug_images.is_empty() {
+ map.insert(
+ "$debug_images".into(),
+ serde_json::to_value(&self.debug_images)
+ .expect("debug image properties are serializable"),
+ );
+ }
+ map
+ }
+
+ fn properties_with_fingerprint(
+ &self,
+ metadata: &ResolvedMetadata,
+ fingerprint: &FingerprintData,
+ issue_id: Option<Uuid>,
+ ) -> Value {
+ let mut map = self.base_resolved_properties(metadata);
+ map.insert(
+ "$exception_fingerprint".into(),
+ Value::String(fingerprint.value.clone()),
+ );
+ if let Some(version) = fingerprint.version {
+ map.insert(
+ "$exception_fingerprint_version".into(),
+ serde_json::to_value(version).expect("fingerprint version is serializable"),
+ );
+ }
+ map.insert(
+ "$exception_fingerprint_record".into(),
+ serde_json::to_value(&fingerprint.record).expect("fingerprint record is serializable"),
+ );
+ map.insert(
+ "$exception_issue_id".into(),
+ issue_id.map_or(Value::Null, |id| Value::String(id.to_string())),
+ );
+ Value::Object(map)
+ }
+
+ fn build_output(
+ &self,
+ metadata: &ResolvedMetadata,
+ fingerprint: &FingerprintData,
+ issue_id: Uuid,
+ ) -> OutputErrProps {
+ OutputErrProps {
+ exception_list: self.exception_list.clone(),
+ fingerprint: fingerprint.value.clone(),
+ fingerprint_version: fingerprint.version,
+ fingerprint_record: fingerprint.record.clone(),
+ issue_id,
+ other: self.props.clone(),
+ handled: metadata.handled,
+ releases: metadata.releases.clone(),
+ types: metadata.types.clone(),
+ values: metadata.messages.clone(),
+ sources: metadata.sources.clone(),
+ functions: metadata.functions.clone(),
+ }
+ }
+}
+
+impl TryFrom<AnyEvent> for ExceptionEvent<Parsed> {
+ type Error = EventError;
+
+ fn try_from(event: AnyEvent) -> Result<Self, Self::Error> {
+ if event.event != "$exception" {
+ return Err(EventError::WrongEventType(event.event.clone(), event.uuid));
+ }
+
+ let mut properties = event.properties;
+ if let Some(value) = properties
+ .as_object_mut()
+ .and_then(|object| object.get_mut("$exception_list"))
+ {
+ recursively_sanitize_properties(event.uuid, value, 0)?;
+ }
+
+ let mut raw: RawErrProps = serde_json::from_value(properties)
+ .map_err(|error| EventError::InvalidProperties(event.uuid, error.to_string()))?;
+ if raw.exception_list.is_empty() {
+ return Err(EventError::EmptyExceptionList(event.uuid));
+ }
+
+ for exception in raw.exception_list.iter_mut() {
+ if exception.exception_message.len() > MAX_EXCEPTION_VALUE_LENGTH {
+ let truncate_at = exception
+ .exception_message
+ .char_indices()
+ .take_while(|(index, _)| *index < MAX_EXCEPTION_VALUE_LENGTH)
+ .last()
+ .map(|(index, character)| index + character.len_utf8())
+ .unwrap_or(0);
+ exception.exception_message.truncate(truncate_at);
+ exception.exception_message.push_str("...");
+ }
+ exception.exception_id = Some(Uuid::now_v7().to_string());
+ }
+
+ for key in [
+ "$exception_sources",
+ "$exception_types",
+ "$exception_values",
+ "$exception_functions",
+ "$exception_releases",
+ "$exception_fingerprint_version",
+ "$exception_proposed_fingerprint",
+ "$exception_fingerprint_record",
+ "$exception_issue_id",
+ ] {
+ raw.other.remove(key);
+ }
+
+ let lib = raw.other.get("$lib").and_then(Value::as_str);
+ let lib_version = raw.other.get("$lib_version").and_then(Value::as_str);
+ let legacy_order_exception_list =
+ normalize_wire_order(&mut raw.exception_list, lib, lib_version);
+
+ Ok(ExceptionEvent {
+ uuid: event.uuid,
+ team_id: event.team_id,
+ timestamp: event.timestamp,
+ exception_list: raw.exception_list,
+ debug_images: raw.debug_images,
+ props: raw.other,
+ proposed_issue_name: raw.issue_name,
+ proposed_issue_description: raw.issue_description,
+ state: Parsed {
+ client_fingerprint: raw.fingerprint,
+ legacy_order_exception_list,
+ legacy_order_resolved: None,
+ },
+ })
+ }
+}
+
+impl TryFrom<ClickHouseEvent> for ExceptionEvent<Parsed> {
+ type Error = EventError;
+
+ fn try_from(event: ClickHouseEvent) -> Result<Self, Self::Error> {
+ AnyEvent::try_from(event)?.try_into()
+ }
+}
+
+impl TryFrom<Result<ClickHouseEvent, EventError>> for ExceptionEvent<Parsed> {
+ type Error = EventError;
+
+ fn try_from(event: Result<ClickHouseEvent, EventError>) -> Result<Self, Self::Error> {
+ event?.try_into()
+ }
+}
diff --git a/rust/cymbal/src/modes/processing/types/exception_properties.rs b/rust/cymbal/src/modes/processing/types/exception_properties.rs
deleted file mode 100644
index 8f1529efca34..000000000000
--- a/rust/cymbal/src/modes/processing/types/exception_properties.rs
+++ /dev/null
@@ -1,230 +0,0 @@
-use std::collections::HashMap;
-
-use common_types::ClickHouseEvent;
-use serde::{Deserialize, Serialize};
-use serde_json::Value;
-use uuid::Uuid;
-
-use crate::{
- error::{EventError, UnhandledError},
- fingerprinting::{FingerprintRecordPart, FingerprintVersion},
- frames::releases::ReleaseInfo,
- issue_resolution::Issue,
- langs::native::DebugImage,
- modes::processing::normalization::normalize_wire_order,
- recursively_sanitize_properties,
- types::{event::AnyEvent, ExceptionList, OutputErrProps},
-};
-
-pub const MAX_EXCEPTION_VALUE_LENGTH: usize = 10_000;
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ExceptionProperties {
- #[serde(rename = "$exception_list")]
- pub exception_list: ExceptionList,
-
- #[serde(rename = "$exception_sources")]
- pub exception_sources: Option<Vec<String>>,
- #[serde(rename = "$exception_types")]
- pub exception_types: Option<Vec<String>>,
- #[serde(rename = "$exception_values")]
- pub exception_messages: Option<Vec<String>>,
- #[serde(rename = "$exception_functions")]
- pub exception_functions: Option<Vec<String>>,
- #[serde(rename = "$exception_handled")]
- pub exception_handled: Option<bool>,
-
- #[serde(
- rename = "$exception_releases",
- skip_serializing_if = "HashMap::is_empty",
- default
- )]
- pub exception_releases: HashMap<String, ReleaseInfo>,
-
- #[serde(rename = "$exception_fingerprint")]
- pub fingerprint: Option<String>,
- #[serde(
- rename = "$exception_fingerprint_version",
- skip_serializing_if = "Option::is_none"
- )]
- pub fingerprint_version: Option<FingerprintVersion>,
- // Deprecated: accepted for old events but no longer emitted.
- #[serde(rename = "$exception_proposed_fingerprint", skip_serializing)]
- pub proposed_fingerprint: Option<String>,
- #[serde(rename = "$exception_fingerprint_record")]
- pub fingerprint_record: Option<Vec<FingerprintRecordPart>>,
-
- #[serde(rename = "$exception_issue_id")]
- pub issue_id: Option<Uuid>,
- #[serde(rename = "$issue_name", skip_serializing_if = "Option::is_none")]
- pub proposed_issue_name: Option<String>,
- #[serde(rename = "$issue_description", skip_serializing_if = "Option::is_none")]
- pub proposed_issue_description: Option<String>,
-
- #[serde(
- rename = "$debug_images",
- default,
- skip_serializing_if = "Vec::is_empty"
- )]
- pub debug_images: Vec<DebugImage>,
-
- #[serde(flatten)]
- pub props: HashMap<String, Value>,
-
- // Metadata used for ingestion
- #[serde(skip)]
- pub uuid: Uuid,
-
- #[serde(skip)]
- pub timestamp: String,
-
- #[serde(skip)]
- pub team_id: i32,
-
- #[serde(skip)]
- pub issue: Option<Issue>,
-
- // The raw exception list in its original (pre-normalization) wire order,
- // set only when wire-order normalization reversed frames and/or the list at
- // ingest. Resolution resolves it alongside the canonical list (cache-warm,
- // so cheap) so grouping can compute the legacy-order fingerprint for issue
- // continuity. Cleared once resolution has produced the resolved copy below.
- #[serde(skip)]
- pub legacy_order_exception_list: Option<ExceptionList>,
-
- // The resolved exception list in legacy wire order, populated by the
- // resolution stage when `legacy_order_exception_list` was set. The grouping
- // stage fingerprints it and clears it.
- #[serde(skip)]
- pub legacy_order_resolved: Option<ExceptionList>,
-}
-
-impl ExceptionProperties {
- pub fn to_output(&self, issue_id: Uuid) -> Result<OutputErrProps, UnhandledError> {
- // Extract metadata from exception list
- let types = self
- .exception_types
- .clone()
- .ok_or_else(|| UnhandledError::Other("Missing exception types".into()))?;
- let values = self
- .exception_messages
- .clone()
- .ok_or_else(|| UnhandledError::Other("Missing exception messages".into()))?;
- let sources = self
- .exception_sources
- .clone()
- .ok_or_else(|| UnhandledError::Other("Missing exception sources".into()))?;
- let functions = self
- .exception_functions
- .clone()
- .ok_or_else(|| UnhandledError::Other("Missing exception functions".into()))?;
- let releases = self.exception_releases.clone();
- let handled = self
- .exception_handled
- .ok_or_else(|| UnhandledError::Other("Missing exception handled status".into()))?;
- let fingerprint = self
- .fingerprint
- .clone()
- .ok_or_else(|| UnhandledError::Other("Missing fingerprint".into()))?;
- Ok(OutputErrProps {
- exception_list: self.exception_list.clone(),
- fingerprint,
- fingerprint_version: self.fingerprint_version,
- fingerprint_record: self.fingerprint_record.clone().unwrap_or_default(),
- issue_id,
- other: self.props.clone(),
- handled,
- releases,
- types,
- values,
- sources,
- functions,
- })
- }
-}
-
-impl TryFrom<AnyEvent> for ExceptionProperties {
- type Error = EventError;
-
- fn try_from(event: AnyEvent) -> Result<Self, Self::Error> {
- if event.event != "$exception" {
- return Err(EventError::WrongEventType(event.event.clone(), event.uuid));
- }
-
- // `event.properties` is already a `serde_json::Value`; running it back through
- // `from_value` only deep-rebuilds the tree. Take ownership directly instead.
- let mut properties = event.properties;
-
- if let Some(v) = properties
- .as_object_mut()
- .and_then(|o| o.get_mut("$exception_list"))
- {
- // We PG sanitize the exception list, because the strings in it can end up in PG kind of arbitrarily.
- // TODO - the prep stage has already sanitized the properties, so maybe we don't need to do this again?
- recursively_sanitize_properties(event.uuid, v, 0)?;
- }
-
- let mut evt: ExceptionProperties = match serde_json::from_value(properties) {
- Ok(r) => r,
- Err(e) => {
- return Err(EventError::InvalidProperties(event.uuid, e.to_string()));
- }
- };
-
- if evt.exception_list.is_empty() {
- return Err(EventError::EmptyExceptionList(event.uuid));
- }
-
- for exception in evt.exception_list.iter_mut() {
- if exception.exception_message.len() > MAX_EXCEPTION_VALUE_LENGTH {
- let truncate_at = exception
- .exception_message
- .char_indices()
- .take_while(|(i, _)| *i < MAX_EXCEPTION_VALUE_LENGTH)
- .last()
- .map(|(i, c)| i + c.len_utf8())
- .unwrap_or(0);
- exception.exception_message.truncate(truncate_at);
- exception.exception_message.push_str("...");
- }
- exception.exception_id = Some(Uuid::now_v7().to_string());
- }
-
- // Normalize incoming wire order (frames / exception list) per $lib so
- // fingerprinting and resolution downstream see canonical order. Runs
- // after exception ids are assigned so the legacy snapshot shares ids
- // with the canonical list. Reading $lib/$lib_version from `props` — the
- // flatten catch-all where non-exception event properties land.
- let lib = evt.props.get("$lib").and_then(Value::as_str);
- let lib_version = evt.props.get("$lib_version").and_then(Value::as_str);
- evt.legacy_order_exception_list =
- normalize_wire_order(&mut evt.exception_list, lib, lib_version);
-
- // Set metadata fields that are skipped during deserialization
- evt.uuid = event.uuid;
- evt.timestamp = event.timestamp;
- evt.team_id = event.team_id;
-
- Ok(evt)
- }
-}
-
-impl TryFrom<ClickHouseEvent> for ExceptionProperties {
- type Error = EventError;
-
- fn try_from(event: ClickHouseEvent) -> Result<Self, Self::Error> {
- let any_evt = AnyEvent::try_from(event)?;
- ExceptionProperties::try_from(any_evt)
- }
-}
-
-impl TryFrom<Result<ClickHouseEvent, EventError>> for ExceptionProperties {
- type Error = EventError;
-
- fn try_from(event: Result<ClickHouseEvent, EventError>) -> Result<Self, Self::Error> {
- match event {
- Ok(evt) => ExceptionProperties::try_from(evt),
- Err(e) => Err(e),
- }
- }
-}
diff --git a/rust/cymbal/src/modes/processing/types/mod.rs b/rust/cymbal/src/modes/processing/types/mod.rs
index d5a8edea1fe9..47288a32caf6 100644
--- a/rust/cymbal/src/modes/processing/types/mod.rs
+++ b/rust/cymbal/src/modes/processing/types/mod.rs
@@ -14,7 +14,7 @@ use crate::metric_consts::POSTHOG_SDK_EXCEPTION_RESOLVED;
pub mod batch;
pub mod event;
-pub mod exception_properties;
+pub mod exception_event;
pub mod operator;
pub mod stage;
diff --git a/rust/cymbal/tests/assignment_rules.rs b/rust/cymbal/tests/assignment_rules.rs
index 13e9d304e2a0..c61cf55b1f90 100644
--- a/rust/cymbal/tests/assignment_rules.rs
+++ b/rust/cymbal/tests/assignment_rules.rs
@@ -1,3 +1,5 @@
+use std::collections::HashMap;
+
use chrono::Utc;
use cymbal::{
issue_resolution::{Issue, IssueStatus},
@@ -5,7 +7,7 @@ use cymbal::{
modes::processing::ProcessingConfig,
stages::linking::issue::process_assignment,
teams::TeamManager,
- types::exception_properties::ExceptionProperties,
+ types::OutputErrProps,
};
use serde_json::{json, Value as JsonValue};
use sqlx::PgPool;
@@ -42,21 +44,12 @@ fn get_test_rule() -> AssignmentRule {
}
}
-fn test_props() -> ExceptionProperties {
- // process_assignment calls to_output(), which requires the materialized
- // search fields to be present, so seed them (empty, since exception_list is empty).
- serde_json::from_value(json!({
- "$exception_list": [],
- "$exception_types": [],
- "$exception_values": [],
- "$exception_sources": [],
- "$exception_functions": [],
- "$exception_handled": false,
- "$exception_fingerprint": "test value",
- "$exception_proposed_fingerprint": "test value",
- "test_value": "test_value",
- }))
- .unwrap()
+fn test_props() -> OutputErrProps {
+ OutputErrProps {
+ fingerprint: "test value".to_string(),
+ other: HashMap::from([("test_value".to_string(), json!("test_value"))]),
+ ..Default::default()
+ }
}
fn test_issue() -> Issue {
diff --git a/rust/cymbal/tests/common/mod.rs b/rust/cymbal/tests/common/mod.rs
index 43cd5b4562fe..56e5a05fa989 100644
--- a/rust/cymbal/tests/common/mod.rs
+++ b/rust/cymbal/tests/common/mod.rs
@@ -19,7 +19,7 @@ use async_trait::async_trait;
use cymbal::error::{ResolveError, UnhandledError};
use cymbal::frames::{Frame, RawFrame};
use cymbal::langs::native::DebugImage;
-use cymbal::stages::pipeline::ExceptionEventPipelineItem;
+use cymbal::stages::pipeline::ParsedPipelineItem;
use cymbal::stages::resolution::{
remote::{
config::RemoteResolutionConfig, pool::EndpointPool, resolver::RemoteResolutionContext,
@@ -30,8 +30,12 @@ use cymbal::symbolication::symbol::SymbolResolver;
use cymbal::symbolication::symbol_store::chunk_id::OrChunkId;
use cymbal::symbolication::symbol_store::proguard::ProguardRef;
use cymbal::types::{
- batch::Batch, exception_properties::ExceptionProperties, operator::TeamId, stage::Stage,
- Exception, ExceptionList, Stacktrace,
+ batch::Batch,
+ event::AnyEvent,
+ exception_event::{ExceptionEvent, Parsed, Resolved},
+ operator::TeamId,
+ stage::Stage,
+ Exception, Stacktrace,
};
use cymbal_proto::cymbal::resolution::v1::cymbal_resolution_server::{
CymbalResolution, CymbalResolutionServer,
@@ -461,16 +465,25 @@ pub fn local_stage() -> ResolutionStage {
pub async fn process_one(
stage: ResolutionStage,
- evt: ExceptionProperties,
-) -> Result<ExceptionProperties, UnhandledError> {
- let batch: Batch<ExceptionEventPipelineItem> = Batch::from(vec![Ok(evt)]);
+ evt: ExceptionEvent<Parsed>,
+) -> Result<ExceptionEvent<Resolved>, UnhandledError> {
+ let batch: Batch<ParsedPipelineItem> = Batch::from(vec![Ok(evt)]);
let result = stage.process(batch).await?;
let mut items: Vec<_> = result.into_iter().collect();
assert_eq!(items.len(), 1, "single-event batch must produce one output");
Ok(items.remove(0).expect("event must not be EventError"))
}
-pub fn build_event(num_exceptions: usize) -> ExceptionProperties {
+pub fn build_event(num_exceptions: usize) -> ExceptionEvent<Parsed> {
+ build_event_with(num_exceptions, 7, Uuid::now_v7(), Vec::new())
+}
+
+pub fn build_event_with(
+ num_exceptions: usize,
+ team_id: i32,
+ uuid: Uuid,
+ debug_images: Vec<DebugImage>,
+) -> ExceptionEvent<Parsed> {
let exceptions: Vec<Exception> = (0..num_exceptions)
.map(|i| Exception {
exception_id: None,
@@ -482,28 +495,17 @@ pub fn build_event(num_exceptions: usize) -> ExceptionProperties {
stack: Some(Stacktrace::Raw { frames: vec![] }),
})
.collect();
- ExceptionProperties {
- exception_list: ExceptionList::from(exceptions),
- exception_sources: None,
- exception_types: None,
- exception_messages: None,
- exception_functions: None,
- exception_handled: None,
- exception_releases: Default::default(),
- fingerprint: None,
- fingerprint_version: None,
- proposed_fingerprint: None,
- fingerprint_record: None,
- issue_id: None,
- proposed_issue_name: None,
- proposed_issue_description: None,
- debug_images: Vec::new(),
- props: Default::default(),
- uuid: Uuid::now_v7(),
+ AnyEvent {
+ uuid,
+ event: "$exception".to_string(),
+ properties: serde_json::json!({
+ "$exception_list": exceptions,
+ "$debug_images": debug_images,
+ }),
timestamp: String::new(),
- team_id: 7,
- issue: None,
- legacy_order_exception_list: None,
- legacy_order_resolved: None,
+ team_id,
+ others: Default::default(),
}
+ .try_into()
+ .expect("test event is valid")
}
diff --git a/rust/cymbal/tests/event.rs b/rust/cymbal/tests/event.rs
index 79e554744a6e..c84b07abb696 100644
--- a/rust/cymbal/tests/event.rs
+++ b/rust/cymbal/tests/event.rs
@@ -8,10 +8,7 @@ use cymbal::{
fingerprinting::{Fingerprint, FingerprintVersion},
frames::Frame,
symbolication::symbol_store::saving::SymbolSetRecord,
- types::{
- event::AnyEvent, exception_properties::ExceptionProperties, Exception, ExceptionList,
- Mechanism, Stacktrace,
- },
+ types::{event::AnyEvent, Exception, ExceptionList, Mechanism, OutputErrProps, Stacktrace},
};
use insta::assert_json_snapshot;
use mockall::predicate;
@@ -143,7 +140,7 @@ fn frame_at(mut frame: Frame, source: &str, line: u32, column: u32) -> Frame {
struct SuccessResponse(Vec<Option<AnyEvent>>);
impl SuccessResponse {
- fn take_properties(self) -> ExceptionProperties {
+ fn take_properties(self) -> OutputErrProps {
let event = self.0.first().expect("Should have at least one event");
serde_json::from_value(event.as_ref().unwrap().properties.clone())
.expect("Should deserialize properties")
@@ -335,9 +332,8 @@ async fn insert_symbol_set_record(db: &PgPool, team_id: i32, chunk_id: &str) {
// Helper to extract exception list from response
fn extract_exception_list(response: &SuccessResponse) -> ExceptionList {
let event = response.first_event();
- let props: ExceptionProperties =
- serde_json::from_value(event.as_ref().unwrap().properties.clone())
- .expect("Should deserialize properties");
+ let props: OutputErrProps = serde_json::from_value(event.as_ref().unwrap().properties.clone())
+ .expect("Should deserialize properties");
props.exception_list
}
@@ -393,14 +389,42 @@ async fn creates_issue_with_fingerprint(db: PgPool) {
let (status, body): (_, SuccessResponse) = harness.post_event(&input).await;
assert!(status.is_success(), "Expected success, got {:?}", status);
- let event: ExceptionProperties = body.take_properties();
- assert!(event.fingerprint.is_some());
- assert_eq!(event.exception_types.unwrap(), vec!["Error".to_string()]);
- assert_eq!(
- event.exception_messages.unwrap(),
- vec!["test error message".to_string()]
+ let event: OutputErrProps = body.take_properties();
+ assert!(!event.fingerprint.is_empty());
+ assert_eq!(event.types, vec!["Error".to_string()]);
+ assert_eq!(event.values, vec!["test error message".to_string()]);
+ assert_eq!(harness.get_issue_id().await, event.issue_id);
+}
+
+#[sqlx::test(migrations = "./tests/test_migrations")]
+async fn processed_properties_wire_shape_is_stable(db: PgPool) {
+ let harness = TestHarness::new(db);
+ let mut input = make_event_with_options(
+ vec![make_exception("TypeError", "cannot read property")],
+ Some("wire-contract"),
+ Some(false),
);
- assert_eq!(harness.get_issue_id().await, event.issue_id.unwrap());
+ input.properties["$issue_name"] = json!("Custom issue name");
+ input.properties["$issue_description"] = json!("Custom issue description");
+ input.properties["$debug_images"] = json!([{
+ "debug_id": "67e9247c-814e-392b-a027-dbde6748fcbf",
+ "image_addr": "0x100000000",
+ "image_vmaddr": "0x0",
+ "image_size": 4096,
+ "code_file": "ExampleApp",
+ "type": "macho",
+ "arch": "arm64"
+ }]);
+ input.properties["custom_property"] = json!({"nested": true});
+
+ let (status, body): (_, SuccessResponse) = harness.post_event(&input).await;
+
+ assert!(status.is_success());
+ let properties = &body.first_event().as_ref().unwrap().properties;
+ assert_json_snapshot!("processed_properties_wire_shape", properties, {
+ ".$exception_list[].id" => "REDACTED",
+ ".$exception_issue_id" => "REDACTED",
+ });
}
#[sqlx::test(migrations = "./tests/test_migrations")]
@@ -416,7 +440,7 @@ async fn uses_client_fingerprint_override(db: PgPool) {
let event = body.take_properties();
assert!(status.is_success());
- assert_eq!(event.fingerprint.unwrap(), "custom-fingerprint".to_string());
+ assert_eq!(event.fingerprint, "custom-fingerprint".to_string());
}
#[sqlx::test(migrations = "./tests/test_migrations")]
@@ -444,7 +468,7 @@ async fn suppressed_issue_returns_suppressed_response(db: PgPool) {
let (_, created): (_, SuccessResponse) = harness.post_event(&input).await;
let body = created.take_properties();
- let issue_id = body.issue_id.unwrap();
+ let issue_id = body.issue_id;
harness.suppress_issue(issue_id).await;
let (status, body): (_, SuccessResponse) = harness.post_event(&input).await;
@@ -487,32 +511,18 @@ async fn extracts_metadata_from_exceptions(db: PgPool) {
assert!(status.is_success());
let event = body.take_properties();
- assert_eq!(event.exception_types.unwrap(), vec!["TypeError"]);
+ assert_eq!(event.types, vec!["TypeError"]);
assert_eq!(
- event.exception_messages.unwrap(),
+ event.values,
vec!["Cannot read property 'foo' of undefined"]
);
- assert!(event.exception_handled.unwrap());
+ assert!(event.handled);
assert!(event
- .exception_sources
- .clone()
- .unwrap()
+ .sources
.contains(&"src/components/Button.tsx".to_string()));
- assert!(event
- .exception_sources
- .clone()
- .unwrap()
- .contains(&"src/App.tsx".to_string()));
- assert!(event
- .exception_functions
- .clone()
- .unwrap()
- .contains(&"handleClick".to_string()));
- assert!(event
- .exception_functions
- .clone()
- .unwrap()
- .contains(&"onClick".to_string()));
+ assert!(event.sources.contains(&"src/App.tsx".to_string()));
+ assert!(event.functions.contains(&"handleClick".to_string()));
+ assert!(event.functions.contains(&"onClick".to_string()));
}
// Frame resolution tests
@@ -652,7 +662,7 @@ fn resolved_stack_event(source: &str) -> AnyEvent {
}
fn automatic_fingerprint(version: FingerprintVersion, event: &AnyEvent) -> Fingerprint {
- let props: ExceptionProperties = serde_json::from_value(event.properties.clone())
+ let props: OutputErrProps = serde_json::from_value(event.properties.clone())
.expect("event properties should deserialize");
version.compute(&props.exception_list)
}
diff --git a/rust/cymbal/tests/remote_resolution.rs b/rust/cymbal/tests/remote_resolution.rs
index 7dec212a14ec..f798a53c83af 100644
--- a/rust/cymbal/tests/remote_resolution.rs
+++ b/rust/cymbal/tests/remote_resolution.rs
@@ -14,8 +14,8 @@ use std::time::Duration;
use async_trait::async_trait;
use common::{
- build_event, local_stage, make_ctx, make_ctx_with_sample_rate, process_one, remote_stage,
- spawn_recording_stub_server, spawn_stub_server, ServerBehavior,
+ build_event, build_event_with, local_stage, make_ctx, make_ctx_with_sample_rate, process_one,
+ remote_stage, spawn_recording_stub_server, spawn_stub_server, ServerBehavior,
};
use cymbal::error::{ResolveError, UnhandledError};
@@ -26,7 +26,8 @@ use cymbal::symbolication::symbol::SymbolResolver;
use cymbal::symbolication::symbol_store::chunk_id::OrChunkId;
use cymbal::symbolication::symbol_store::proguard::ProguardRef;
use cymbal::types::batch::Batch;
-use cymbal::types::exception_properties::ExceptionProperties;
+use cymbal::types::event::AnyEvent;
+use cymbal::types::exception_event::{ExceptionEvent, Parsed};
use cymbal::types::operator::TeamId;
use cymbal::types::stage::Stage;
use cymbal::types::Stacktrace;
@@ -84,31 +85,43 @@ fn remote_stage_with_resolver(
}
}
-fn build_dart_event() -> ExceptionProperties {
- let mut evt: ExceptionProperties = serde_json::from_value(json!({
- "$exception_list": [{
- "type": "minified:Foo",
- "value": "boom",
- "stacktrace": {
- "type": "raw",
- "frames": [{
- "platform": "web:javascript",
- "filename": "https://example.com/app.js",
- "function": "a",
- "lineno": 1,
- "colno": 2,
- "chunk_id": "chunk-a"
- }]
- }
- }]
- }))
- .expect("valid exception properties");
- evt.team_id = 7;
- evt.uuid = Uuid::from_u128(42);
- evt
+fn parsed_event(uuid: Uuid, properties: serde_json::Value) -> ExceptionEvent<Parsed> {
+ AnyEvent {
+ uuid,
+ event: "$exception".to_string(),
+ team_id: 7,
+ timestamp: String::new(),
+ properties,
+ others: Default::default(),
+ }
+ .try_into()
+ .expect("valid exception properties")
+}
+
+fn build_dart_event(uuid: Uuid) -> ExceptionEvent<Parsed> {
+ parsed_event(
+ uuid,
+ json!({
+ "$exception_list": [{
+ "type": "minified:Foo",
+ "value": "boom",
+ "stacktrace": {
+ "type": "raw",
+ "frames": [{
+ "platform": "web:javascript",
+ "filename": "https://example.com/app.js",
+ "function": "a",
+ "lineno": 1,
+ "colno": 2,
+ "chunk_id": "chunk-a"
+ }]
+ }
+ }]
+ }),
+ )
}
-fn build_event_with_symbol_refs(uuid: Uuid, symbol_refs: &[&str]) -> ExceptionProperties {
+fn build_event_with_symbol_refs(uuid: Uuid, symbol_refs: &[&str]) -> ExceptionEvent<Parsed> {
let exceptions: Vec<serde_json::Value> = symbol_refs
.iter()
.enumerate()
@@ -130,13 +143,12 @@ fn build_event_with_symbol_refs(uuid: Uuid, symbol_refs: &[&str]) -> ExceptionPr
})
})
.collect();
- let mut evt: ExceptionProperties = serde_json::from_value(json!({
- "$exception_list": exceptions
- }))
- .expect("valid exception properties");
- evt.team_id = 7;
- evt.uuid = uuid;
- evt
+ parsed_event(
+ uuid,
+ json!({
+ "$exception_list": exceptions
+ }),
+ )
}
fn sampling_bucket(team_id: i32, uuid: Uuid) -> f64 {
@@ -166,11 +178,11 @@ async fn happy_path_preserves_batch_event_and_exception_order() {
let ctx = make_ctx(&[addr], 0, Duration::from_secs(5)).await;
let evt_a = build_event(3);
let evt_b = build_event(2);
- let expected_uuids = [evt_a.uuid, evt_b.uuid];
+ let expected_uuids = [evt_a.uuid(), evt_b.uuid()];
let expected_types: Vec<Vec<_>> = [&evt_a, &evt_b]
.into_iter()
.map(|evt| {
- evt.exception_list
+ evt.exception_list()
.iter()
.map(|e| e.exception_type.clone())
.collect()
@@ -187,12 +199,12 @@ async fn happy_path_preserves_batch_event_and_exception_order() {
.collect();
assert_eq!(resolved.len(), 2);
- assert_eq!(resolved[0].uuid, expected_uuids[0]);
- assert_eq!(resolved[1].uuid, expected_uuids[1]);
+ assert_eq!(resolved[0].uuid(), expected_uuids[0]);
+ assert_eq!(resolved[1].uuid(), expected_uuids[1]);
let resolved_types: Vec<Vec<_>> = resolved
.iter()
.map(|evt| {
- evt.exception_list
+ evt.exception_list()
.iter()
.map(|e| e.exception_type.clone())
.collect()
@@ -202,7 +214,7 @@ async fn happy_path_preserves_batch_event_and_exception_order() {
for (resolved_evt, expected_evt_types) in resolved.iter().zip(expected_types.iter()) {
let mut expected_properties = expected_evt_types.clone();
expected_properties.sort();
- let mut resolved_properties = resolved_evt.exception_types.clone().unwrap_or_default();
+ let mut resolved_properties = resolved_evt.metadata().types.clone();
resolved_properties.sort();
assert_eq!(resolved_properties, expected_properties);
}
@@ -213,7 +225,7 @@ async fn local_mode_ignores_remote_pool_when_remote_is_disabled() {
let (_addr, hits) = spawn_stub_server(ServerBehavior::AlwaysInvalidArgument).await;
let evt = build_event(3);
let original_types: Vec<_> = evt
- .exception_list
+ .exception_list()
.iter()
.map(|e| e.exception_type.clone())
.collect();
@@ -222,16 +234,16 @@ async fn local_mode_ignores_remote_pool_when_remote_is_disabled() {
.await
.expect("no unhandled error");
- assert_eq!(resolved.exception_list.len(), 3);
+ assert_eq!(resolved.exception_list().len(), 3);
let resolved_types: Vec<_> = resolved
- .exception_list
+ .exception_list()
.iter()
.map(|e| e.exception_type.clone())
.collect();
assert_eq!(resolved_types, original_types);
let mut expected_properties = original_types.clone();
expected_properties.sort();
- let mut resolved_properties = resolved.exception_types.unwrap_or_default();
+ let mut resolved_properties = resolved.metadata().types.clone();
resolved_properties.sort();
assert_eq!(resolved_properties, expected_properties);
assert!(
@@ -256,12 +268,12 @@ async fn sample_rate_zero_routes_eligible_events_locally_without_remote_calls()
);
assert!(matches!(
resolved
- .exception_list
+ .exception_list()
.first()
.and_then(|e| e.stack.as_ref()),
Some(Stacktrace::Resolved { .. })
));
- assert_eq!(resolved.exception_types, Some(vec!["Boom0".to_string()]));
+ assert_eq!(resolved.metadata().types, vec!["Boom0".to_string()]);
}
#[tokio::test]
@@ -380,16 +392,20 @@ async fn accepted_outcomes_release_routing_slots_before_terminal_completion() {
async fn metadata_encodes_debug_images_json() {
let (addr, _streams, items) = spawn_recording_stub_server(ServerBehavior::Happy).await;
let ctx = make_ctx(&[addr], 0, Duration::from_secs(5)).await;
- let mut evt = build_event(1);
- evt.debug_images = vec![DebugImage {
- debug_id: "ABCDEF".to_string(),
- image_addr: "0x100000000".to_string(),
- image_vmaddr: Some("0x100000000".to_string()),
- image_size: Some(4096),
- code_file: Some("Example.app/Example".to_string()),
- image_type: Some("macho".to_string()),
- arch: Some("arm64".to_string()),
- }];
+ let evt = build_event_with(
+ 1,
+ 7,
+ Uuid::now_v7(),
+ vec![DebugImage {
+ debug_id: "ABCDEF".to_string(),
+ image_addr: "0x100000000".to_string(),
+ image_vmaddr: Some("0x100000000".to_string()),
+ image_size: Some(4096),
+ code_file: Some("Example.app/Example".to_string()),
+ image_type: Some("macho".to_string()),
+ arch: Some("arm64".to_string()),
+ }],
+ );
let result = remote_stage(ctx)
.process(Batch::from(vec![Ok(evt)]))
@@ -424,7 +440,7 @@ async fn per_item_overloaded_outcomes_reroute_independently() {
.into_iter()
.map(|item| item.expect("event must not be EventError"))
.collect();
- assert_eq!(resolved[0].exception_list.len(), 2);
+ assert_eq!(resolved[0].exception_list().len(), 2);
assert_eq!(good_items.lock().unwrap().len(), 2);
assert!(
overloaded_items.lock().unwrap().len() <= 2,
@@ -440,8 +456,7 @@ async fn mixed_sampled_remote_and_unsampled_local_events_preserve_output_orderin
let local_uuid = uuid_for_sampling_decision(7, sample_rate, false);
let ctx = make_ctx_with_sample_rate(&[addr], 0, Duration::from_secs(5), sample_rate).await;
let resolver = Arc::new(CountingResolver::default());
- let mut local_evt = build_dart_event();
- local_evt.uuid = local_uuid;
+ let local_evt = build_dart_event(local_uuid);
let remote_evt = build_event_with_symbol_refs(remote_uuid, &["remote-bundle"]);
let result = remote_stage_with_resolver(ctx, resolver.clone())
@@ -457,21 +472,22 @@ async fn mixed_sampled_remote_and_unsampled_local_events_preserve_output_orderin
.collect();
assert_eq!(resolved.len(), 2);
- assert_eq!(resolved[0].uuid, local_uuid);
- assert_eq!(resolved[1].uuid, remote_uuid);
+ assert_eq!(resolved[0].uuid(), local_uuid);
+ assert_eq!(resolved[1].uuid(), remote_uuid);
assert_eq!(hits.lock().unwrap().len(), 1);
assert_eq!(resolver.dart_name_calls.load(Ordering::SeqCst), 1);
- assert_eq!(resolved[0].exception_list[0].exception_type, "ResolvedDart");
- assert_eq!(resolved[1].exception_list[0].exception_type, "Boom0");
+ assert_eq!(
+ resolved[0].exception_list()[0].exception_type,
+ "ResolvedDart"
+ );
+ assert_eq!(resolved[1].exception_list()[0].exception_type, "Boom0");
}
#[tokio::test]
async fn partial_sample_rate_is_deterministic_for_same_event() {
let (addr, hits) = spawn_stub_server(ServerBehavior::Happy).await;
let ctx = make_ctx_with_sample_rate(&[addr], 0, Duration::from_secs(5), 0.5).await;
- let mut evt = build_event(1);
- evt.team_id = 77;
- evt.uuid = Uuid::from_u128(0x1234);
+ let evt = build_event_with(1, 77, Uuid::from_u128(0x1234), Vec::new());
for _ in 0..8 {
let _resolved = process_one(remote_stage(ctx.clone()), evt.clone())
@@ -494,7 +510,7 @@ async fn sampled_remote_failure_does_not_fall_back_to_local_resolution() {
let err = process_one(
remote_stage_with_resolver(ctx, resolver.clone()),
- build_dart_event(),
+ build_dart_event(Uuid::from_u128(42)),
)
.await
.expect_err("sampled remote failure must surface");
@@ -513,7 +529,7 @@ async fn unsampled_events_run_local_exception_frame_and_properties_resolvers() {
let resolved = process_one(
remote_stage_with_resolver(ctx, resolver.clone()),
- build_dart_event(),
+ build_dart_event(Uuid::from_u128(42)),
)
.await
.expect("unsampled event should resolve locally");
@@ -521,15 +537,12 @@ async fn unsampled_events_run_local_exception_frame_and_properties_resolvers() {
assert!(hits.lock().unwrap().is_empty());
assert_eq!(resolver.dart_name_calls.load(Ordering::SeqCst), 1);
assert_eq!(resolver.raw_frame_calls.load(Ordering::SeqCst), 1);
- assert_eq!(resolved.exception_list[0].exception_type, "ResolvedDart");
+ assert_eq!(resolved.exception_list()[0].exception_type, "ResolvedDart");
assert!(matches!(
- resolved.exception_list[0].stack.as_ref(),
+ resolved.exception_list()[0].stack.as_ref(),
Some(Stacktrace::Resolved { .. })
));
- assert_eq!(
- resolved.exception_types,
- Some(vec!["ResolvedDart".to_string()])
- );
+ assert_eq!(resolved.metadata().types, vec!["ResolvedDart".to_string()]);
}
#[tokio::test]
@@ -546,7 +559,7 @@ async fn transport_unavailable_retries_against_another_endpoint() {
let resolved = process_one(remote_stage(ctx), evt)
.await
.expect("stage succeeded");
- assert_eq!(resolved.exception_list.len(), 1);
+ assert_eq!(resolved.exception_list().len(), 1);
assert!(
bad_hits.lock().unwrap().is_empty(),
@@ -569,7 +582,7 @@ async fn per_item_retry_outcome_triggers_caller_side_reroute() {
let resolved = process_one(remote_stage(ctx), evt)
.await
.expect("stage succeeded");
- assert_eq!(resolved.exception_list.len(), 1);
+ assert_eq!(resolved.exception_list().len(), 1);
assert_eq!(good_items.lock().unwrap().len(), 1);
assert!(retry_items.lock().unwrap().len() <= 1);
}
diff --git a/rust/cymbal/tests/remote_resolution_hardening.rs b/rust/cymbal/tests/remote_resolution_hardening.rs
index 976ff9963f89..73ff0777fce1 100644
--- a/rust/cymbal/tests/remote_resolution_hardening.rs
+++ b/rust/cymbal/tests/remote_resolution_hardening.rs
@@ -31,7 +31,7 @@ async fn connection_refused_endpoint_is_classified_as_retryable() {
let resolved = process_one(remote_stage(ctx), evt)
.await
.expect("connection refused must not surface as terminal");
- assert_eq!(resolved.exception_list.len(), 1);
+ assert_eq!(resolved.exception_list().len(), 1);
assert_eq!(good_items.lock().unwrap().len(), 1);
}
@@ -55,7 +55,7 @@ async fn stream_interruption_reroutes_in_flight_items() {
let resolved = process_one(remote_stage(ctx), build_event(2))
.await
.expect("interrupted stream must reroute remaining items");
- assert_eq!(resolved.exception_list.len(), 2);
+ assert_eq!(resolved.exception_list().len(), 2);
assert_eq!(interrupted_items.lock().unwrap().len(), 1);
assert_eq!(good_items.lock().unwrap().len(), 1);
return;
@@ -113,23 +113,23 @@ async fn accounting_preserves_order_and_team_id_on_resolved_payloads() {
let evt = build_event(5);
let original_types: Vec<String> = evt
- .exception_list
+ .exception_list()
.iter()
.map(|e| e.exception_type.clone())
.collect();
- let original_team_id = evt.team_id;
+ let original_team_id = evt.team_id();
let resolved = process_one(remote_stage(ctx), evt)
.await
.expect("happy path");
let resolved_types: Vec<String> = resolved
- .exception_list
+ .exception_list()
.iter()
.map(|e| e.exception_type.clone())
.collect();
assert_eq!(resolved_types, original_types, "slots must be preserved");
- assert_eq!(resolved.team_id, original_team_id);
+ assert_eq!(resolved.team_id(), original_team_id);
}
#[tokio::test]
@@ -156,7 +156,7 @@ async fn endpoint_refresh_closes_draining_mux_and_reroutes_in_flight_item() {
.await
.expect("join remote resolution")
.expect("drained mux should reroute item");
- assert_eq!(resolved.exception_list.len(), 1);
+ assert_eq!(resolved.exception_list().len(), 1);
assert_eq!(old_items.lock().unwrap().len(), 1);
assert_eq!(new_items.lock().unwrap().len(), 1);
assert_eq!(pool.endpoints().await, vec![new_addr]);
diff --git a/rust/cymbal/tests/remote_resolution_parity.rs b/rust/cymbal/tests/remote_resolution_parity.rs
index 646763ce8996..7281ce8f11d0 100644
--- a/rust/cymbal/tests/remote_resolution_parity.rs
+++ b/rust/cymbal/tests/remote_resolution_parity.rs
@@ -30,6 +30,7 @@ use cymbal::symbolication::symbol::SymbolResolver;
use cymbal::symbolication::symbol_store::chunk_id::OrChunkId;
use cymbal::symbolication::symbol_store::proguard::ProguardRef;
use cymbal::types::batch::Batch;
+use cymbal::types::exception_event::{ExceptionEvent, Parsed, Resolved};
use cymbal::types::operator::TeamId;
use cymbal::types::stage::Stage;
use cymbal_proto::cymbal::resolution::v1::cymbal_resolution_server::CymbalResolutionServer;
@@ -131,10 +132,9 @@ fn remote_stage(
async fn run_stage(
stage: ResolutionStage,
- evt: cymbal::types::exception_properties::ExceptionProperties,
-) -> cymbal::types::exception_properties::ExceptionProperties {
- let batch: Batch<cymbal::stages::pipeline::ExceptionEventPipelineItem> =
- Batch::from(vec![Ok(evt)]);
+ evt: ExceptionEvent<Parsed>,
+) -> ExceptionEvent<Resolved> {
+ let batch: Batch<cymbal::stages::pipeline::ParsedPipelineItem> = Batch::from(vec![Ok(evt)]);
let result = stage.process(batch).await.expect("stage processed");
let mut items: Vec<_> = result.into_iter().collect();
assert_eq!(items.len(), 1, "single-event batch must produce one output");
@@ -155,30 +155,17 @@ async fn local_and_remote_stages_produce_identical_exception_list_for_empty_stac
// Exception's #[serde(skip_serializing_if = "Option::is_none")] fields and
// the difference in how `Stacktrace::Raw` vs `Stacktrace::Resolved`
// serialize.
- let local_json = serde_json::to_value(&local_out.exception_list).unwrap();
- let remote_json = serde_json::to_value(&remote_out.exception_list).unwrap();
+ let local_json = serde_json::to_value(local_out.exception_list()).unwrap();
+ let remote_json = serde_json::to_value(remote_out.exception_list()).unwrap();
assert_eq!(local_json, remote_json, "exception_list parity");
- // Properties derived by PropertiesResolver should also match in both
- // paths, since they're computed from the (parity-checked) exception_list.
+ // Derived properties should also match in both paths, since they're
+ // computed from the parity-checked exception list.
// `unique_by` preserves exception_list order, so compare directly.
- assert_eq!(local_out.exception_types, remote_out.exception_types);
- assert_eq!(local_out.exception_messages, remote_out.exception_messages);
- assert_eq!(local_out.exception_handled, remote_out.exception_handled);
-}
-
-#[tokio::test]
-async fn parity_holds_for_empty_exception_list() {
- let resolver: Arc<dyn SymbolResolver> = Arc::new(FakeResolver);
- let addr = spawn_cymbal_resolution_with_resolver(resolver.clone()).await;
- let ctx = make_ctx(&[addr], 0, Duration::from_secs(5)).await;
-
- let evt = build_event(0);
- let local_out = run_stage(local_stage(resolver.clone()), evt.clone()).await;
- let remote_out = run_stage(remote_stage(resolver, ctx), evt).await;
-
- assert_eq!(local_out.exception_list.len(), 0);
- assert_eq!(remote_out.exception_list.len(), 0);
- assert_eq!(local_out.exception_types, remote_out.exception_types);
- assert_eq!(local_out.exception_messages, remote_out.exception_messages);
+ assert_eq!(local_out.metadata().types, remote_out.metadata().types);
+ assert_eq!(
+ local_out.metadata().messages,
+ remote_out.metadata().messages
+ );
+ assert_eq!(local_out.metadata().handled, remote_out.metadata().handled);
}
diff --git a/rust/cymbal/tests/snapshots/event__processed_properties_wire_shape.snap b/rust/cymbal/tests/snapshots/event__processed_properties_wire_shape.snap
new file mode 100644
index 000000000000..f3ac14987719
--- /dev/null
+++ b/rust/cymbal/tests/snapshots/event__processed_properties_wire_shape.snap
@@ -0,0 +1,45 @@
+---
+source: cymbal/tests/event.rs
+expression: properties
+---
+{
+ "$debug_images": [
+ {
+ "arch": "arm64",
+ "code_file": "ExampleApp",
+ "debug_id": "67e9247c-814e-392b-a027-dbde6748fcbf",
+ "image_addr": "0x100000000",
+ "image_size": 4096,
+ "image_vmaddr": "0x0",
+ "type": "macho"
+ }
+ ],
+ "$exception_fingerprint": "wire-contract",
+ "$exception_fingerprint_record": [
+ {
+ "type": "manual"
+ }
+ ],
+ "$exception_functions": [],
+ "$exception_handled": false,
+ "$exception_issue_id": "REDACTED",
+ "$exception_list": [
+ {
+ "id": "REDACTED",
+ "type": "TypeError",
+ "value": "cannot read property"
+ }
+ ],
+ "$exception_sources": [],
+ "$exception_types": [
+ "TypeError"
+ ],
+ "$exception_values": [
+ "cannot read property"
+ ],
+ "$issue_description": "Custom issue description",
+ "$issue_name": "Custom issue name",
+ "custom_property": {
+ "nested": true
+ }
+}