:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(cymbal): normalize exception wire order per lib and version (#68189)
Catalin Irimiedb8dad24ce08
diff --git a/rust/.sqlx/query-83e72043b76cb774ebeb80aa6af6bfc861f3d19907ae63684c32325bd020fcda.json b/rust/.sqlx/query-83e72043b76cb774ebeb80aa6af6bfc861f3d19907ae63684c32325bd020fcda.jsonnew file mode 100644index 000000000000..91e4bd6cfec6--- /dev/null+++ b/rust/.sqlx/query-83e72043b76cb774ebeb80aa6af6bfc861f3d19907ae63684c32325bd020fcda.json@@ -0,0 +1,47 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, team_id, issue_id, fingerprint, version FROM posthog_errortrackingissuefingerprintv2\n WHERE team_id = $1 AND fingerprint = ANY($2)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "team_id",+ "type_info": "Int4"+ },+ {+ "ordinal": 2,+ "name": "issue_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "fingerprint",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "version",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Int4",+ "TextArray"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false+ ]+ },+ "hash": "83e72043b76cb774ebeb80aa6af6bfc861f3d19907ae63684c32325bd020fcda"+}diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 387b46e6a8ef..852bc24a4b66 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2871,6 +2871,7 @@ dependencies = ["regex","reqwest 0.12.28","rustls 0.23.37",+ "semver","serde","serde_json","sha2",diff --git a/rust/cymbal/Cargo.toml b/rust/cymbal/Cargo.tomlindex ec6fa635136b..b10bfd947bef 100644--- a/rust/cymbal/Cargo.toml+++ b/rust/cymbal/Cargo.toml@@ -34,6 +34,7 @@ zip = "4.0"proguard = "5.6.2"reqwest = { workspace = true }sha2 = "0.10.8"+semver = "1.0"aws-config = { workspace = true }aws-sdk-s3 = { workspace = true }uuid = { workspace = true }diff --git a/rust/cymbal/src/core/metric_consts.rs b/rust/cymbal/src/core/metric_consts.rsindex e7c6c099cd21..5b211721fd39 100644--- a/rust/cymbal/src/core/metric_consts.rs+++ b/rust/cymbal/src/core/metric_consts.rs@@ -123,6 +123,9 @@ pub const SPIKE_ALERT_STAGE: &str = "cymbal_spike_detection_time";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";pub const ISSUE_LINKER_OPERATOR: &str = "cymbal_exception_issue_linker_operator";pub const ISSUE_SUPPRESSION_OPERATOR: &str = "cymbal_exception_issue_suppression_operator";pub const RULE_SUPPRESSION_OPERATOR: &str = "cymbal_exception_rule_suppression_operator";diff --git a/rust/cymbal/src/core/symbolication/symbol/mod.rs b/rust/cymbal/src/core/symbolication/symbol/mod.rsindex dce35aab88ba..810697ada5b3 100644--- a/rust/cymbal/src/core/symbolication/symbol/mod.rs+++ b/rust/cymbal/src/core/symbolication/symbol/mod.rs@@ -43,32 +43,37 @@ pub trait SymbolResolver: Send + Sync + 'static {) -> Result<Exception, UnhandledError> {let resolve_java_module_and_type =async |exception: &Exception| -> Result<(String, String), ResolveError> {- if let RawFrame::Java(java_frame) = exception+ // Pick the first Java frame that carries a ProGuard mapping ref,+ // not just the first frame. Wire-order normalization can move a+ // ref-less framework frame to the front, so anchoring on the+ // frame that actually has a `map_id` keeps class remapping+ // order-independent.+ let symbolset_ref = exception.get_raw_frame()- .first()+ .iter()+ .find_map(|frame| match frame {+ RawFrame::Java(java_frame) => java_frame.get_ref().ok(),+ _ => None,+ }).ok_or(ProguardError::NoOriginalFrames)- .map_err(ResolveError::from)?- {- let module = exception- .module- .clone()- .ok_or(ProguardError::NoModuleProvided)- .map_err(ResolveError::from)?;-- let exc_type = exception.exception_type.clone();-- let class = format!("{}.{}", module, exc_type);- let symbolset_ref = java_frame.get_ref()?;-- let new_class = self- .resolve_java_class(team_id, symbolset_ref, class)- .await?;-- let (new_module, new_type) = split_last_dot(new_class.as_str())?;- Ok((new_module, new_type))- } else {- Err(ProguardError::NoOriginalFrames.into())- }+ .map_err(ResolveError::from)?;++ let module = exception+ .module+ .clone()+ .ok_or(ProguardError::NoModuleProvided)+ .map_err(ResolveError::from)?;++ let exc_type = exception.exception_type.clone();++ let class = format!("{}.{}", module, exc_type);++ let new_class = self+ .resolve_java_class(team_id, symbolset_ref, class)+ .await?;++ let (new_module, new_type) = split_last_dot(new_class.as_str())?;+ Ok((new_module, new_type))};match resolve_java_module_and_type(&exception).await {diff --git a/rust/cymbal/src/modes/processing/fingerprinting/mod.rs b/rust/cymbal/src/modes/processing/fingerprinting/mod.rsindex 3330127198f5..a8de6ae548f5 100644--- a/rust/cymbal/src/modes/processing/fingerprinting/mod.rs+++ b/rust/cymbal/src/modes/processing/fingerprinting/mod.rs@@ -82,6 +82,13 @@ impl Fingerprint {#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum FingerprintVersion {+ // Legacy-order twins of V1/V2: the same strategies computed over the pre-flip wire order+ // of SDKs whose ordering the pipeline normalizes (see `normalization::legacy_wire_order`).+ // They exist so issues keyed before wire-order normalization stay addressable; being+ // non-newest, they can never create issues — they only match existing ones. Delete them+ // once legacy-keyed traffic decays (watch `$exception_fingerprint_version`).+ V1Legacy,+ V2Legacy,// The historical algorithm — bit-for-bit (guarded by tests/fingerprint_golden.rs).V1,// Normalizing strategy: hashes all frames of every chain entry, drops unresolved@@ -94,24 +101,45 @@ impl FingerprintVersion {// All registered versions, ascending. Order is meaningful: selection keeps the newest// already-used fingerprint, and new issues are created under the last (newest) entry.pub fn all() -> &'static [FingerprintVersion] {- &[FingerprintVersion::V1, FingerprintVersion::V2]+ // Each legacy twin sits immediately below its canonical version, so the+ // newest-first selection walk prefers V2, then V2's legacy order, then+ // V1, then V1's — an event matching both a V2-era legacy row and an+ // older V1 row stays on the newer issue. The last entry (the new-issue+ // fallback) must never be a legacy version.+ &[+ FingerprintVersion::V1Legacy,+ FingerprintVersion::V1,+ FingerprintVersion::V2Legacy,+ FingerprintVersion::V2,+ ]}pub fn as_str(&self) -> &'static str {match self {+ FingerprintVersion::V1Legacy => "v1_legacy",+ FingerprintVersion::V2Legacy => "v2_legacy",FingerprintVersion::V1 => "v1",FingerprintVersion::V2 => "v2",}}+ // Legacy versions hash the reconstructed pre-flip order instead of the canonical list;+ // the grouping stage supplies the right list per version.+ pub fn is_legacy(&self) -> bool {+ matches!(+ self,+ FingerprintVersion::V1Legacy | FingerprintVersion::V2Legacy+ )+ }+pub fn compute(&self, exception_list: &ExceptionList) -> Fingerprint {self.strategy().from_exception_list(exception_list)}pub fn strategy(&self) -> FingerprintStrategy {match self {- FingerprintVersion::V1 => FingerprintStrategy::default(),- FingerprintVersion::V2 => FingerprintStrategy {+ FingerprintVersion::V1 | FingerprintVersion::V1Legacy => FingerprintStrategy::default(),+ FingerprintVersion::V2 | FingerprintVersion::V2Legacy => FingerprintStrategy {frame_selection: FrameSelection::AllFrames,// `Last` scores better offline (holdout F1 0.55 vs 0.40) but SDKs disagree on// chain order — current SDKs put the root cause last, the legacy python SDK putdiff --git a/rust/cymbal/src/modes/processing/issue_resolution.rs b/rust/cymbal/src/modes/processing/issue_resolution.rsindex f9aebb3be30b..6a5039fa80d4 100644--- a/rust/cymbal/src/modes/processing/issue_resolution.rs+++ b/rust/cymbal/src/modes/processing/issue_resolution.rs@@ -308,6 +308,29 @@ impl IssueFingerprintOverride {Ok(res)}+ // Batch variant of `load` for fingerprint-version selection: one round-trip+ // for all candidate values instead of one per version.+ pub async fn load_many<'c, E>(+ executor: E,+ team_id: i32,+ fingerprints: &[String],+ ) -> Result<Vec<Self>, UnhandledError>+ where+ E: sqlx::Executor<'c, Database = sqlx::Postgres>,+ {+ let res = sqlx::query_as!(+ IssueFingerprintOverride,+ r#"+ SELECT id, team_id, issue_id, fingerprint, version FROM posthog_errortrackingissuefingerprintv2+ WHERE team_id = $1 AND fingerprint = ANY($2)+ "#,+ team_id,+ fingerprints+ ).fetch_all(executor).await?;++ Ok(res)+ }+pub async fn create_or_load<'c, E>(executor: E,team_id: i32,diff --git a/rust/cymbal/src/modes/processing/mod.rs b/rust/cymbal/src/modes/processing/mod.rsindex 0f3d70df24a6..c3f64e281a0c 100644--- a/rust/cymbal/src/modes/processing/mod.rs+++ b/rust/cymbal/src/modes/processing/mod.rs@@ -13,6 +13,7 @@ pub mod app_context;pub mod config;pub mod fingerprinting;pub mod issue_resolution;+pub mod normalization;pub mod router;pub mod rules;pub mod server;diff --git a/rust/cymbal/src/modes/processing/normalization.rs b/rust/cymbal/src/modes/processing/normalization.rsnew file mode 100644index 000000000000..f51124883a94--- /dev/null+++ b/rust/cymbal/src/modes/processing/normalization.rs@@ -0,0 +1,498 @@+//! Wire-order normalization for incoming exception payloads.+//!+//! Different PostHog SDKs historically disagreed on the order of two things:+//!+//! - `stacktrace.frames`: the canonical wire order is bottom-up, i.e.+//! `frames[0]` is the entry point (e.g. `main`) and the last frame is the+//! crash site. Some SDKs send crash-first (crash site first, entry point+//! last) and need their frames reversed at ingest.+//! - `$exception_list`: the canonical wire order is caught/outermost exception+//! first, root cause last. One SDK sends the list root-cause-first and needs+//! the list reversed.+//!+//! The cross-SDK standardization effort (sdk-specs#11) is flipping SDKs to emit+//! the canonical order directly. Until an SDK ships that flip, cymbal+//! normalizes its payloads here, keyed on `$lib` and gated on `$lib_version`.+//!+//! To retire normalization for an SDK once it ships the canonical order, set+//! that entry's cutoff to `Some(version)`: payloads at or above the cutoff are+//! left untouched, payloads below it (or with an unparseable version) are still+//! normalized. A `None` cutoff means the SDK has not flipped yet, so everything+//! is normalized.++use std::sync::OnceLock;++use semver::Version;++use crate::types::ExceptionList;++/// Which parts of a payload a given `$lib` needs reversed to reach canonical+/// wire order.+#[derive(Debug, Clone, Copy)]+struct WireOrderFix {+ /// Reverse each exception's `stacktrace.frames` (crash-first -> bottom-up).+ reverse_frames: bool,+ /// Reverse `$exception_list` (root-cause-first -> outermost-first).+ reverse_exception_list: bool,+}++impl WireOrderFix {+ const FRAMES: Self = Self {+ reverse_frames: true,+ reverse_exception_list: false,+ };+ const EXCEPTION_LIST: Self = Self {+ reverse_frames: false,+ reverse_exception_list: true,+ };+}++/// A single SDK's normalization rule.+struct LibRule {+ /// The `$lib` value this rule matches.+ lib: &'static str,+ /// What to reverse.+ fix: WireOrderFix,+ /// The version at which the SDK started emitting canonical order. `None`+ /// means it has not flipped yet, so always normalize. `Some(v)` means+ /// normalize only for versions strictly below `v`.+ canonical_since: Option<Version>,+}++/// The normalization table, keyed on `$lib`.+///+/// All cutoffs are `None` today: no SDK has shipped the canonical-order flip+/// yet. When an SDK ships it, change its `canonical_since` to the release+/// version and leave everything else alone — legacy payloads keep normalizing,+/// new payloads pass through.+///+/// Built lazily because `semver::Version` is not `const`-constructible; cached+/// for the process lifetime since this is consulted for every ingested event.+fn lib_rules() -> &'static [LibRule] {+ static RULES: OnceLock<Vec<LibRule>> = OnceLock::new();+ RULES.get_or_init(|| {+ // Crash-first frames: entry point last, crash site first on the wire.+ let crash_first_frames = [+ "posthog-android",+ "posthog-flutter",+ "posthog-php",+ "posthog-go",+ "posthog-rs",+ "posthog-elixir",+ // Java: `posthog-server` is the current java server SDK identifier+ // (module in the posthog-android repo, shares the android coercer);+ // `posthog-java` is the tombstoned legacy SDK, included defensively.+ // Both are crash-first.+ "posthog-java",+ "posthog-server",+ ];++ let mut rules: Vec<LibRule> = crash_first_frames+ .into_iter()+ .map(|lib| LibRule {+ lib,+ fix: WireOrderFix::FRAMES,+ canonical_since: None,+ })+ .collect();++ // Root-cause-first `$exception_list`: python sends chained exceptions with+ // the root cause first. Its frames are already canonical (bottom-up).+ rules.push(LibRule {+ lib: "posthog-python",+ fix: WireOrderFix::EXCEPTION_LIST,+ canonical_since: None,+ });++ rules+ })+}++/// Parses a `$lib_version` leniently. `semver` rejects things like a bare+/// `1.2` or a leading `v`, both of which SDKs emit, so we coerce common shapes+/// before parsing. An unparseable version is treated as "old" by the caller+/// (i.e. normalization still applies), so `None` here is a normalize signal.+fn parse_lenient(version: &str) -> Option<Version> {+ let trimmed = version.trim().trim_start_matches(['v', 'V']);+ if let Ok(v) = Version::parse(trimmed) {+ return Some(v);+ }++ // Split off any pre-release/build metadata, then pad the numeric core to+ // three components so `1` and `1.2` parse.+ let core = trimmed.split(['-', '+']).next().unwrap_or(trimmed);+ let mut parts: Vec<&str> = core.split('.').collect();+ if parts.is_empty() || parts.len() > 3 {+ return None;+ }+ while parts.len() < 3 {+ parts.push("0");+ }+ if parts+ .iter()+ .any(|p| p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()))+ {+ return None;+ }+ Version::parse(&parts.join(".")).ok()+}++/// Decides whether a payload from `lib_version` still needs normalizing, given+/// the version at which its SDK started emitting canonical order.+///+/// - `None` cutoff: the SDK has not flipped yet, so always normalize.+/// - `Some(cutoff)`: normalize only versions strictly below the cutoff. A+/// version at/above the cutoff is left alone; an unparseable version is+/// treated as old, so it still normalizes.+///+/// The cutoff path deliberately does no work for post-flip payloads. It does+/// not need to: a flipped SDK's canonical events fingerprint identically to the+/// pre-flip legacy events this normalizer already reorders. While the cutoff is+/// `None` (the normalization window), those legacy events are aliased so the+/// canonical fingerprint already maps to the pre-flip issue, so the first+/// post-flip canonical event hits the fast `load_by_fingerprint` path and joins+/// the same issue with no split.+fn should_normalize(canonical_since: Option<&Version>, lib_version: Option<&str>) -> bool {+ let Some(cutoff) = canonical_since else {+ return true;+ };+ match lib_version.and_then(parse_lenient) {+ Some(v) => v < *cutoff,+ None => true,+ }+}++/// Returns the fix to apply for `lib`/`lib_version`, or `None` if the payload+/// already carries canonical order (or the SDK is unknown).+fn fix_for(lib: &str, lib_version: Option<&str>) -> Option<WireOrderFix> {+ let rule = lib_rules().iter().find(|r| r.lib == lib)?;+ should_normalize(rule.canonical_since.as_ref(), lib_version).then_some(rule.fix)+}++/// Normalizes `exception_list` to canonical wire order in place, keyed on+/// `$lib`/`$lib_version`. Returns the pre-normalization (legacy-order) list when+/// a reversal was applied, so the caller can compute the legacy fingerprint for+/// issue continuity, or `None` when nothing changed.+///+/// This must run before fingerprinting/resolution: fingerprints are computed+/// over stored frame/exception order, so normalizing here keeps grouping+/// consistent across SDKs.+///+/// Note on the no-in-app fingerprint fallback: when an exception has no in-app+/// frames, fingerprinting hashes `frames.first()`. After normalization that is+/// the entry frame rather than the crash site — but that is already how+/// natively-canonical SDKs (web, node, ...) fingerprint such stacks today, so+/// this brings crash-first SDKs into line rather than introducing new+/// divergence. Improving that fallback (e.g. keying on the crash-site frame) is+/// a cross-SDK fingerprinting change out of scope for wire-order normalization.+pub fn normalize_wire_order(+ exception_list: &mut ExceptionList,+ lib: Option<&str>,+ lib_version: Option<&str>,+) -> Option<ExceptionList> {+ let fix = fix_for(lib?, lib_version)?;++ // Snapshot only once we know a reversal is coming — the common (canonical)+ // path pays no clone.+ let legacy = exception_list.clone();+ apply_fix(exception_list, fix);+ Some(legacy)+}++fn apply_fix(exception_list: &mut ExceptionList, fix: WireOrderFix) {+ if fix.reverse_exception_list {+ exception_list.reverse();+ }++ if fix.reverse_frames {+ for exception in exception_list.iter_mut() {+ if let Some(stack) = exception.stack.as_mut() {+ match stack {+ crate::types::Stacktrace::Raw { frames } => frames.reverse(),+ crate::types::Stacktrace::Resolved { frames } => frames.reverse(),+ }+ }+ }+ }+}++/// Reconstructs `lib`'s legacy wire order from a canonical-order list,+/// regardless of `$lib_version` or cutoff — each fix is its own inverse, so+/// applying it to a canonical list recovers the pre-flip order.+///+/// This is how legacy fingerprint versions keep pre-normalization issues+/// addressable after an SDK ships the flip: the cutoff stops the reordering,+/// but must not stop legacy hashing. Reconstruction is exact except where+/// resolution reshaped the list (inline expansion, remapping) — those hashes+/// can only be reproduced from the pre-flip snapshot, which post-flip events+/// no longer carry.+pub fn legacy_wire_order(+ lib: Option<&str>,+ exception_list: &ExceptionList,+) -> Option<ExceptionList> {+ let lib = lib?;+ let rule = lib_rules().iter().find(|r| r.lib == lib)?;+ let mut legacy = exception_list.clone();+ apply_fix(&mut legacy, rule.fix);+ Some(legacy)+}++#[cfg(test)]+mod test {+ use super::*;+ use crate::frames::RawFrame;+ use crate::types::{Exception, Stacktrace};++ fn py_frame(function: &str) -> RawFrame {+ // Deserialize a minimal python frame so we don't have to hand-build the+ // full raw-frame struct; only the function name matters for ordering.+ let json = serde_json::json!({+ "platform": "python",+ "function": function,+ "filename": "app.py",+ "in_app": true,+ });+ serde_json::from_value(json).expect("valid python frame")+ }++ fn frame_names(exception: &Exception) -> Vec<String> {+ match exception.stack.as_ref().unwrap() {+ Stacktrace::Raw { frames } => frames+ .iter()+ .map(|f| match f {+ RawFrame::Python(p) => p.function.clone(),+ _ => panic!("expected python frame"),+ })+ .collect(),+ _ => panic!("expected raw stacktrace"),+ }+ }++ fn exception_with_frames(exc_type: &str, functions: &[&str]) -> Exception {+ Exception {+ exception_id: None,+ exception_type: exc_type.to_string(),+ exception_message: String::new(),+ mechanism: None,+ module: None,+ thread_id: None,+ stack: Some(Stacktrace::Raw {+ frames: functions.iter().map(|f| py_frame(f)).collect(),+ }),+ }+ }++ #[test]+ fn legacy_wire_order_reconstructs_pre_flip_order() {+ // Frames: reconstruction re-applies the reversal, independent of+ // `$lib_version` — this is what keeps legacy fingerprint versions+ // computable after an SDK ships the flip and its cutoff is set.+ let canonical: ExceptionList =+ vec![exception_with_frames("Boom", &["main", "boom"])].into();+ let legacy = legacy_wire_order(Some("posthog-go"), &canonical).expect("go is in the table");+ assert_eq!(frame_names(&legacy[0]), vec!["boom", "main"]);++ // Exception list: python's fix reverses the list, not the frames.+ let canonical: ExceptionList = vec![+ exception_with_frames("Outer", &["main", "wrap"]),+ exception_with_frames("RootCause", &["main", "boom"]),+ ]+ .into();+ let legacy =+ legacy_wire_order(Some("posthog-python"), &canonical).expect("python is in the table");+ assert_eq!(legacy[0].exception_type, "RootCause");+ assert_eq!(frame_names(&legacy[0]), vec!["main", "boom"]);++ // Natively-canonical SDKs have no legacy order.+ assert!(legacy_wire_order(Some("posthog-node"), &canonical).is_none());+ assert!(legacy_wire_order(None, &canonical).is_none());+ }++ #[test]+ fn java_server_libs_both_normalize() {+ // Java server SDK sends crash-first frames under both the current+ // (`posthog-server`) and legacy tombstoned (`posthog-java`) identifiers.+ for lib in ["posthog-java", "posthog-server"] {+ let mut list: ExceptionList =+ vec![exception_with_frames("Boom", &["main", "boom"])].into();+ let legacy = normalize_wire_order(&mut list, Some(lib), Some("1.0.0"));+ assert!(legacy.is_some(), "{lib} should normalize");+ assert_eq!(frame_names(&list[0]), vec!["boom", "main"]);+ }+ }++ #[test]+ fn crash_first_lib_reverses_frames_only() {+ // posthog-go sends crash-first frames; the list order is left alone.+ let mut list: ExceptionList = vec![+ exception_with_frames("Outer", &["main", "handler", "boom"]),+ exception_with_frames("Inner", &["a", "b"]),+ ]+ .into();++ let legacy = normalize_wire_order(&mut list, Some("posthog-go"), Some("1.2.3"));++ assert!(legacy.is_some());+ assert_eq!(frame_names(&list[0]), vec!["boom", "handler", "main"]);+ assert_eq!(frame_names(&list[1]), vec!["b", "a"]);+ // List order unchanged.+ assert_eq!(list[0].exception_type, "Outer");+ assert_eq!(list[1].exception_type, "Inner");+ // The returned legacy snapshot preserves the original (pre-reversal) order.+ let legacy = legacy.unwrap();+ assert_eq!(frame_names(&legacy[0]), vec!["main", "handler", "boom"]);+ }++ #[test]+ fn python_reverses_exception_list_only() {+ // posthog-python sends the list root-cause-first; frames stay put.+ let mut list: ExceptionList = vec![+ exception_with_frames("RootCause", &["main", "boom"]),+ exception_with_frames("Wrapper", &["main", "wrap"]),+ ]+ .into();++ let legacy = normalize_wire_order(&mut list, Some("posthog-python"), Some("3.0.0"));++ assert!(legacy.is_some());+ // List reversed: outermost (Wrapper) now first.+ assert_eq!(list[0].exception_type, "Wrapper");+ assert_eq!(list[1].exception_type, "RootCause");+ // Frames unchanged.+ assert_eq!(frame_names(&list[0]), vec!["main", "wrap"]);+ }++ #[test]+ fn canonical_lib_is_untouched() {+ // web already sends canonical order; nothing should change.+ let mut list: ExceptionList =+ vec![exception_with_frames("Error", &["main", "boom"])].into();++ let legacy = normalize_wire_order(&mut list, Some("web"), Some("1.170.1"));++ assert!(legacy.is_none());+ assert_eq!(frame_names(&list[0]), vec!["main", "boom"]);+ }++ #[test]+ fn unknown_lib_is_untouched() {+ let mut list: ExceptionList =+ vec![exception_with_frames("Error", &["main", "boom"])].into();+ assert!(normalize_wire_order(&mut list, Some("posthog-martian"), None).is_none());+ assert_eq!(frame_names(&list[0]), vec!["main", "boom"]);+ }++ #[test]+ fn missing_lib_is_untouched() {+ let mut list: ExceptionList =+ vec![exception_with_frames("Error", &["main", "boom"])].into();+ assert!(normalize_wire_order(&mut list, None, Some("1.0.0")).is_none());+ assert_eq!(frame_names(&list[0]), vec!["main", "boom"]);+ }++ #[test]+ fn version_cutoff_skips_new_and_normalizes_old() {+ // Exercise the version gate directly (the shipped table is all-`None`+ // today, so no live rule has a cutoff yet).+ let cutoff = Version::parse("2.0.0").unwrap();+ let since = Some(&cutoff);++ // At/above cutoff: canonical order already, don't normalize.+ assert!(!should_normalize(since, Some("2.0.0")));+ assert!(!should_normalize(since, Some("2.5.1")));+ // Below cutoff: still legacy order, normalize.+ assert!(should_normalize(since, Some("1.9.9")));+ // Unparseable or missing version -> treat as old -> normalize.+ assert!(should_normalize(since, Some("not-a-version")));+ assert!(should_normalize(since, None));+ // No cutoff -> SDK hasn't flipped -> always normalize.+ assert!(should_normalize(None, Some("99.0.0")));+ }++ #[test]+ fn normalized_crash_first_matches_native_canonical_fingerprint() {+ use crate::fingerprinting::Fingerprint;+ use crate::frames::Frame;+ use common_types::error_tracking::FrameId;++ let resolved = |name: &str| Frame {+ frame_id: FrameId::new(String::new(), 1, 0),+ mangled_name: name.to_string(),+ line: Some(1),+ column: None,+ source: Some(format!("{name}.rs")),+ in_app: true,+ resolved_name: Some(name.to_string()),+ lang: "rust".to_string(),+ resolved: true,+ resolve_failure: None,+ synthetic: false,+ suspicious: false,+ junk_drawer: None,+ code_variables: None,+ context: None,+ release: None,+ module: None,+ };++ let exception = |frames: Vec<Frame>| Exception {+ exception_id: None,+ exception_type: "Boom".to_string(),+ exception_message: "boom".to_string(),+ mechanism: None,+ module: None,+ thread_id: None,+ stack: Some(Stacktrace::Resolved { frames }),+ };++ // A crash-first SDK sends [crash, mid, entry]; a canonical SDK sends the+ // reverse. After normalization the crash-first payload must fingerprint+ // identically to the canonical one, so both group into one issue.+ let canonical: ExceptionList = vec![exception(vec![+ resolved("entry"),+ resolved("mid"),+ resolved("crash"),+ ])]+ .into();+ let mut crash_first: ExceptionList = vec![exception(vec![+ resolved("crash"),+ resolved("mid"),+ resolved("entry"),+ ])]+ .into();++ let canonical_fp = Fingerprint::from_exception_list(&canonical).value;+ let pre_norm_fp = Fingerprint::from_exception_list(&crash_first).value;+ assert_ne!(+ canonical_fp, pre_norm_fp,+ "crash-first order should fingerprint differently before normalization"+ );++ assert!(normalize_wire_order(&mut crash_first, Some("posthog-rs"), None).is_some());+ let post_norm_fp = Fingerprint::from_exception_list(&crash_first).value;+ assert_eq!(+ canonical_fp, post_norm_fp,+ "normalized crash-first order should match canonical fingerprint"+ );+ }++ #[test]+ fn lenient_version_parsing() {+ assert_eq!(+ parse_lenient("1.2.3"),+ Some(Version::parse("1.2.3").unwrap())+ );+ assert_eq!(parse_lenient("1.2"), Some(Version::parse("1.2.0").unwrap()));+ assert_eq!(parse_lenient("1"), Some(Version::parse("1.0.0").unwrap()));+ assert_eq!(+ parse_lenient("v1.2.3"),+ Some(Version::parse("1.2.3").unwrap())+ );+ assert_eq!(+ parse_lenient("1.2.3-beta.1"),+ Some(Version::parse("1.2.3-beta.1").unwrap())+ );+ assert_eq!(parse_lenient("garbage"), None);+ assert_eq!(parse_lenient(""), None);+ }+}diff --git a/rust/cymbal/src/modes/processing/stages/grouping/fingerprint.rs b/rust/cymbal/src/modes/processing/stages/grouping/fingerprint.rsindex c8c516241eba..e824d0ec20ed 100644--- a/rust/cymbal/src/modes/processing/stages/grouping/fingerprint.rs+++ b/rust/cymbal/src/modes/processing/stages/grouping/fingerprint.rs@@ -1,15 +1,21 @@+use std::collections::HashMap;++use serde_json::Value;use sha2::{Digest, Sha512};+use uuid::Uuid;use crate::{error::UnhandledError,fingerprinting::{Fingerprint, FingerprintRecordPart, FingerprintVersion},issue_resolution::IssueFingerprintOverride,- metric_consts::FINGERPRINT_GENERATOR_OPERATOR,+ 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},types::{exception_properties::ExceptionProperties,operator::{OperatorResult, ValueOperator},+ ExceptionList,},};@@ -57,7 +63,23 @@ impl ValueOperator for FingerprintGenerator {return Ok(Ok(input));}- let (version, fingerprint) = select_automatic_fingerprint(&input, &ctx).await?;+ // Legacy fingerprint versions keep issues keyed before wire-order+ // normalization addressable. They hash the event's pre-flip order:+ // the re-resolved snapshot while normalization still reorders this+ // 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 legacy_list = input+ .legacy_order_resolved+ .take()+ .or_else(|| legacy_wire_order(lib, &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);@@ -80,46 +102,73 @@ fn apply_manual_fingerprint(input: &mut ExceptionProperties) -> Result<(), UnhanOk(())}+// Walks versions newest-first and keeps the first fingerprint that already maps to an issue,+// falling back to the newest (canonical) version for new issues. Legacy versions hash the+// 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,+ legacy_list: Option<&ExceptionList>,ctx: &GroupingStage,) -> Result<(FingerprintVersion, Fingerprint), UnhandledError> {let fingerprints = FingerprintVersion::all().iter()- .map(|version| (*version, version.compute(&input.exception_list)))+ .filter_map(|version| {+ let list = if version.is_legacy() {+ legacy_list?+ } else {+ &input.exception_list+ };+ Some((*version, version.compute(list)))+ }).collect::<Vec<_>>();let newest = fingerprints.last().cloned().ok_or_else(|| UnhandledError::Other("No fingerprint algorithms registered".into()))?;- for (version, fingerprint) in fingerprints.into_iter().rev() {- if fingerprint_exists(ctx, input.team_id, &fingerprint.value).await? {- return Ok((version, fingerprint));+ // Cache pass: collect known hits without short-circuiting — a cached hit+ // for an older version must not outrank a newer version whose row exists+ // in Postgres but is not in this worker's cache.+ 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());+ match ctx.issue_cache.get(&cache_key).await {+ Some(issue_id) => {+ known.insert(fingerprint.value.clone(), issue_id);+ }+ None => uncached.push(fingerprint.value.clone()),}}- Ok(newest)-}+ // Hot path: the newest version is a known hit, so nothing can outrank it.+ if known.contains_key(&newest.1.value) {+ return Ok(newest);+ }-async fn fingerprint_exists(- ctx: &GroupingStage,- team_id: i32,- fingerprint: &str,-) -> Result<bool, UnhandledError> {- let cache_key = (team_id, fingerprint.to_string());- if ctx.issue_cache.get(&cache_key).await.is_some() {- return Ok(true);+ // 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.+ if !uncached.is_empty() {+ for record in+ IssueFingerprintOverride::load_many(&ctx.connection, input.team_id, &uncached).await?+ {+ ctx.issue_cache+ .insert((input.team_id, record.fingerprint.clone()), record.issue_id)+ .await;+ known.insert(record.fingerprint, record.issue_id);+ }}- let Some(override_record) =- IssueFingerprintOverride::load(&ctx.connection, team_id, fingerprint).await?- else {- return Ok(false);- };+ for (version, fingerprint) in fingerprints.into_iter().rev() {+ if known.contains_key(&fingerprint.value) {+ return Ok((version, fingerprint));+ }+ }- ctx.issue_cache- .insert(cache_key, override_record.issue_id)- .await;- Ok(true)+ Ok(newest)}diff --git a/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs b/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rsindex ea531899dbe6..94ae8f40af4b 100644--- a/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs+++ b/rust/cymbal/src/modes/processing/stages/rate_limiting/mod.rs@@ -670,6 +670,8 @@ mod tests {timestamp: String::new(),team_id,issue: None,+ legacy_order_exception_list: None,+ legacy_order_resolved: None,})}diff --git a/rust/cymbal/src/modes/processing/stages/resolution/exception.rs b/rust/cymbal/src/modes/processing/stages/resolution/exception.rsindex b079bb490f99..d9dc9966f4a7 100644--- a/rust/cymbal/src/modes/processing/stages/resolution/exception.rs+++ b/rust/cymbal/src/modes/processing/stages/resolution/exception.rs@@ -30,36 +30,25 @@ impl ExceptionResolver {// Checking if the exception is a Dart exceptionexc.exception_type.starts_with("minified:")}-}--impl ValueOperator for ExceptionResolver {- type Context = ResolutionStage;- type Item = ExceptionProperties;- type HandledError = HandledError;- type UnhandledError = UnhandledError;-- fn name(&self) -> &'static str {- EXCEPTION_RESOLVER_OPERATOR- }- async fn execute_value(- &self,- mut evt: ExceptionProperties,+ pub async fn resolve_exception_list(+ team_id: i32,+ list: ExceptionList,ctx: ResolutionStage,- ) -> OperatorResult<Self> {- evt.exception_list = Batch::from(evt.exception_list.0)+ ) -> Result<ExceptionList, UnhandledError> {+ let resolved = Batch::from(list.0).apply_func(move |exc, ctx| async move {let ctx = ctx.clone();if ExceptionResolver::is_java_exception(&exc) {let _permit = ctx.acquire_symbol_resolution_permit().await?;ctx.symbol_resolver- .resolve_java_exception(evt.team_id, exc)+ .resolve_java_exception(team_id, exc).await} else if ExceptionResolver::is_dart_exception(&exc) {let _permit = ctx.acquire_symbol_resolution_permit().await?;ctx.symbol_resolver- .resolve_dart_exception(evt.team_id, exc)+ .resolve_dart_exception(team_id, exc).await} else {Ok(exc)@@ -67,8 +56,33 @@ impl ValueOperator for ExceptionResolver {},ctx,)- .await- .map(|v| ExceptionList::from(Vec::from(v)))?;+ .await?;+ Ok(ExceptionList::from(Vec::from(resolved)))+ }+}++impl ValueOperator for ExceptionResolver {+ type Context = ResolutionStage;+ type Item = ExceptionProperties;+ type HandledError = HandledError;+ type UnhandledError = UnhandledError;++ fn name(&self) -> &'static str {+ EXCEPTION_RESOLVER_OPERATOR+ }++ async fn execute_value(+ &self,+ mut evt: ExceptionProperties,+ ctx: ResolutionStage,+ ) -> OperatorResult<Self> {+ let team_id = evt.team_id;+ evt.exception_list = ExceptionResolver::resolve_exception_list(+ team_id,+ std::mem::take(&mut evt.exception_list),+ ctx,+ )+ .await?;Ok(Ok(evt))}diff --git a/rust/cymbal/src/modes/processing/stages/resolution/legacy.rs b/rust/cymbal/src/modes/processing/stages/resolution/legacy.rsnew file mode 100644index 000000000000..cba34edc1c06--- /dev/null+++ b/rust/cymbal/src/modes/processing/stages/resolution/legacy.rs@@ -0,0 +1,78 @@+use std::sync::Arc;++use tracing::debug;++use crate::{+ error::UnhandledError,+ metric_consts::{LEGACY_ORDER_RESOLVER_OPERATOR, LEGACY_ORDER_RESOLVE_FAILED},+ stages::{+ pipeline::HandledError,+ resolution::{exception::ExceptionResolver, frame::FrameResolver, ResolutionStage},+ },+ types::{+ exception_properties::ExceptionProperties,+ operator::{OperatorResult, ValueOperator},+ ExceptionList,+ },+};++/// 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,+ legacy: ExceptionList,+ ctx: ResolutionStage,+) -> Result<ExceptionList, UnhandledError> {+ 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());+ FrameResolver::resolve_exception_list_frames(team_id, legacy, debug_images, ctx).await+}++/// Resolves the retained legacy-order snapshot (set by wire-order+/// normalization) so grouping can compute the legacy fingerprint for issue+/// continuity. Runs after the canonical exception list is resolved, and always+/// through the local resolvers — so continuity holds on both the local and+/// remote resolution paths. The snapshot carries the same raw frames as the+/// canonical list, so the resolver cache serves them and this is nearly free.+#[derive(Clone, Default)]+pub struct LegacyOrderResolver;++impl ValueOperator for LegacyOrderResolver {+ type Item = ExceptionProperties;+ type Context = ResolutionStage;+ type HandledError = HandledError;+ type UnhandledError = UnhandledError;++ fn name(&self) -> &'static str {+ LEGACY_ORDER_RESOLVER_OPERATOR+ }++ async fn execute_value(+ &self,+ mut evt: ExceptionProperties,+ ctx: ResolutionStage,+ ) -> OperatorResult<Self> {+ let Some(legacy) = evt.legacy_order_exception_list.take() else {+ return Ok(Ok(evt));+ };++ // Legacy resolution only powers best-effort issue-continuity aliasing,+ // so it must never fail the event. On the remote path especially, this+ // runs through the local resolver even though the canonical list was+ // resolved remotely, so local storage/DB access can fail here where the+ // canonical resolution succeeded. Swallow any error: a missing legacy+ // 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),+ Err(e) => {+ metrics::counter!(LEGACY_ORDER_RESOLVE_FAILED).increment(1);+ 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.rsindex 42ffe8580c7b..d0040c5e3db7 100644--- a/rust/cymbal/src/modes/processing/stages/resolution/mod.rs+++ b/rust/cymbal/src/modes/processing/stages/resolution/mod.rs@@ -4,6 +4,7 @@ use tokio::sync::{OwnedSemaphorePermit, Semaphore};pub mod exception;pub mod frame;+pub mod legacy;pub mod properties;pub mod remote;@@ -15,6 +16,7 @@ use crate::{stages::resolution::{exception::ExceptionResolver,frame::FrameResolver,+ legacy::LegacyOrderResolver,properties::PropertiesResolver,remote::resolver::{resolve_batch, RemoteResolutionContext},},@@ -77,6 +79,8 @@ impl Stage for ResolutionStage {// list shape independently of how exception/frame resolution was// performed.return resolve_batch(batch, remote, self.clone())+ .await?+ .apply_operator(LegacyOrderResolver, self.clone()).await?.apply_operator(PropertiesResolver, self.clone()).await;@@ -87,6 +91,8 @@ impl Stage for ResolutionStage {.await?.apply_operator(FrameResolver, self.clone()).await?+ .apply_operator(LegacyOrderResolver, self.clone())+ .await?.apply_operator(PropertiesResolver, self.clone()).await}diff --git a/rust/cymbal/src/modes/processing/types/exception_properties.rs b/rust/cymbal/src/modes/processing/types/exception_properties.rsindex 4e71b1a77744..8f1529efca34 100644--- a/rust/cymbal/src/modes/processing/types/exception_properties.rs+++ b/rust/cymbal/src/modes/processing/types/exception_properties.rs@@ -11,6 +11,7 @@ use crate::{frames::releases::ReleaseInfo,issue_resolution::Issue,langs::native::DebugImage,+ modes::processing::normalization::normalize_wire_order,recursively_sanitize_properties,types::{event::AnyEvent, ExceptionList, OutputErrProps},};@@ -82,6 +83,20 @@ pub struct ExceptionProperties {#[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 {@@ -175,6 +190,16 @@ impl TryFrom<AnyEvent> for ExceptionProperties {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 deserializationevt.uuid = event.uuid;evt.timestamp = event.timestamp;diff --git a/rust/cymbal/tests/common/mod.rs b/rust/cymbal/tests/common/mod.rsindex 0e1c2bd66ebc..43cd5b4562fe 100644--- a/rust/cymbal/tests/common/mod.rs+++ b/rust/cymbal/tests/common/mod.rs@@ -503,5 +503,7 @@ pub fn build_event(num_exceptions: usize) -> ExceptionProperties {timestamp: String::new(),team_id: 7,issue: None,+ legacy_order_exception_list: None,+ legacy_order_resolved: None,}}diff --git a/rust/cymbal/tests/event.rs b/rust/cymbal/tests/event.rsindex aed38a492618..79e554744a6e 100644--- a/rust/cymbal/tests/event.rs+++ b/rust/cymbal/tests/event.rs@@ -753,6 +753,78 @@ async fn existing_issue_under_older_version_wins(db: PgPool) {assert_eq!(event.properties["$exception_issue_id"], json!(issue_id));}+#[sqlx::test(migrations = "./tests/test_migrations")]+async fn legacy_order_issue_wins_via_legacy_version(db: PgPool) {+ let harness = TestHarness::new(db);+ let mut input = make_event(vec![make_exception_with_stack(+ "Error",+ "boom",+ vec![+ frame_at(make_frame_js("main"), "src/app.js", 10, 1),+ frame_at(make_frame_js("crash"), "src/app.js", 42, 10),+ ],+ )]);+ // A crash-first SDK below any cutoff: wire-order normalization reverses+ // the frames at ingest.+ input.properties["$lib"] = json!("posthog-go");+ input.properties["$lib_version"] = json!("1.0.0");++ let (_, body): (_, SuccessResponse) = harness.post_event(&input).await;+ let event = body.first_event().as_ref().unwrap();+ let canonical_value = event.properties["$exception_fingerprint"]+ .as_str()+ .expect("fingerprint should be a string")+ .to_string();+ let issue_id = harness.get_issue_id().await;++ // The fingerprint the same event produced before wire-order normalization+ // deployed: the newest version, computed over the legacy (crash-first)+ // frame order.+ let mut legacy_list = extract_exception_list(&body);+ for exc in legacy_list.iter_mut() {+ if let Some(Stacktrace::Resolved { frames }) = &mut exc.stack {+ frames.reverse();+ }+ }+ let legacy_value = FingerprintVersion::V2.compute(&legacy_list).value;+ assert_ne!(legacy_value, canonical_value);++ // Simulate the issue having been created pre-normalization: its only+ // fingerprint row carries the legacy-order value.+ sqlx::query("UPDATE posthog_errortrackingissuefingerprintv2 SET fingerprint = $1 WHERE fingerprint = $2")+ .bind(&legacy_value)+ .bind(&canonical_value)+ .execute(&harness.db)+ .await+ .expect("Should repoint fingerprint row");++ let (_, body): (_, SuccessResponse) = harness.post_event(&input).await;+ let event = body.first_event().as_ref().unwrap();++ // Version selection finds the pre-flip issue through the V2Legacy hash:+ // the event carries the legacy fingerprint and version, links to the same+ // issue, and no canonical row is written — the issue stays keyed on its+ // pre-flip fingerprint until it ages out (or a later decision aliases it).+ assert_eq!(+ event.properties["$exception_fingerprint"],+ json!(legacy_value)+ );+ assert_eq!(+ event.properties["$exception_fingerprint_version"],+ json!("v2_legacy")+ );+ assert_eq!(event.properties["$exception_issue_id"], json!(issue_id));++ let canonical_rows: i64 = sqlx::query_scalar(+ "SELECT count(*) FROM posthog_errortrackingissuefingerprintv2 WHERE fingerprint = $1",+ )+ .bind(&canonical_value)+ .fetch_one(&harness.db)+ .await+ .expect("count should work");+ assert_eq!(canonical_rows, 0, "no alias row is written");+}+#[sqlx::test(migrations = "./tests/test_migrations")]async fn newer_version_merges_events_the_old_algorithm_splits(db: PgPool) {let harness = TestHarness::new(db);