Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(cymbal): resolve client-expanded native inline groups atomically (#67689)

Catalin Irimie91c23cdc30ac
diff --git a/rust/cymbal/src/core/metric_consts.rs b/rust/cymbal/src/core/metric_consts.rs
index f2b1308a6c51..af892d8f5a93 100644
--- a/rust/cymbal/src/core/metric_consts.rs
+++ b/rust/cymbal/src/core/metric_consts.rs
@@ -23,6 +23,10 @@ pub const FRAME_CACHE_MISSES: &str = "cymbal_frame_cache_misses";
pub const FRAME_DB_HITS: &str = "cymbal_frame_db_hits";
pub const FRAME_DB_MISSES: &str = "cymbal_frame_db_misses";
pub const FRAME_NOT_RESOLVED: &str = "cymbal_frame_not_resolved";
+// Client-expanded native inline groups, labeled by outcome: "replaced" when the
+// server expansion of the group's address superseded the client frames, "kept"
+// when resolution failed and the client expansion passed through.
+pub const NATIVE_INLINE_GROUPS: &str = "cymbal_native_inline_groups";
pub const S3_FETCH: &str = "cymbal_s3_fetch";
// S3 GET body size, in bytes, taken from the `Content-Length` header on the GET response
// (so it's recorded before we collect the body — sets us up to enforce a size cap here later).
diff --git a/rust/cymbal/src/core/types/langs/native.rs b/rust/cymbal/src/core/types/langs/native.rs
index 71c330ce6ef0..a0aa39abfd87 100644
--- a/rust/cymbal/src/core/types/langs/native.rs
+++ b/rust/cymbal/src/core/types/langs/native.rs
@@ -117,6 +117,16 @@ pub fn launch_invariant_addr(
/// present and a matching debug image was sent, the frame is symbolicated
/// server-side against the uploaded debug symbols; otherwise the client-side
/// enrichment fields (`function`/`filename`/`lineno`) pass through as-is.
+///
+/// SDKs that expand inline chains client-side send one *group* per physical
+/// frame: the physical frame first (`inline: false`), then the frames the
+/// client expanded from that same address, each tagged `inline: true` and
+/// carrying the same `instruction_addr`. The group resolves as a unit — the
+/// physical frame's address is symbolicated once, and either the server-side
+/// expansion replaces the whole group or the client's expansion is kept
+/// verbatim (see `FrameResolver`). Grouping keys off the `inline` markers,
+/// not bare address adjacency: recursion legitimately repeats an address
+/// across *distinct* physical frames, which must stay separate groups.
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RawNativeFrame {
pub instruction_addr: Option<String>,
@@ -130,6 +140,20 @@ pub struct RawNativeFrame {
pub filename: Option<String>,
pub lineno: Option<u32>,
pub colno: Option<u32>,
+ /// True when the SDK resolved this frame's `function`/`filename`/`lineno`
+ /// from debug info available in the running process. Informational for
+ /// addressed frames (the address still resolves server-side, group-wise
+ /// when `inline` markers are present); address-less frames pass through
+ /// regardless.
+ #[serde(default)]
+ pub client_resolved: bool,
+ /// Marks a frame the SDK synthesized by expanding the inline chain of the
+ /// nearest preceding non-inline frame, which carries the same
+ /// `instruction_addr`. Inline frames never resolve their own address —
+ /// that would re-expand the chain once per member (see the guard in
+ /// [`RawNativeFrame::resolve`]).
+ #[serde(default)]
+ pub inline: bool,
#[serde(flatten)]
pub meta: CommonFrameMetadata,
}
@@ -145,6 +169,18 @@ impl RawNativeFrame {
where
C: SymbolCatalog<OrChunkId<NativeRef>, ParsedNativeSymbols>,
{
+ // Inline members of a client-expanded group never resolve on their
+ // own: their address belongs to the group's physical frame, which
+ // resolves once for the whole group (`FrameResolver` then replaces or
+ // keeps the group atomically). Resolving a member here would expand
+ // the same inline chain once per member. That holds for orphaned
+ // members too (malformed or reordered input): resolving one
+ // independently could duplicate its group's expansion, so they pass
+ // through with their client fields instead.
+ if self.inline {
+ return Ok(vec![self.into()]);
+ }
+
// Frames without an instruction address (e.g. hand-built exception
// lists) carry only client-side resolution and pass through as-is.
let Some(instruction_addr) = self.instruction_addr.as_deref() else {
@@ -349,6 +385,18 @@ impl RawNativeFrame {
}
}
+ /// Whether this frame is an inline member of the client-expanded group led
+ /// by `lead`: it must be inline-marked and carry the lead's (physical)
+ /// instruction address and image. Any mismatch ends the group — a
+ /// malformed sequence degrades to independent frames rather than
+ /// mis-grouping.
+ pub fn continues_group_of(&self, lead: &RawNativeFrame) -> bool {
+ self.inline
+ && self.instruction_addr.is_some()
+ && self.instruction_addr == lead.instruction_addr
+ && self.image_addr == lead.image_addr
+ }
+
/// The uploaded debug symbol set this frame resolves against, identified by
/// the matched debug image's `debug_id` (the chunk_id used at upload). None
/// when no debug image matches the address, so there is no symbol set to
@@ -395,6 +443,14 @@ impl RawNativeFrame {
self.module
.as_ref()
.inspect(|m| hasher.update(m.as_bytes()));
+ // Resolution behavior branches on the inline marker (members pass
+ // through, physical frames symbolicate), so it must split the cache
+ // identity too — inlined self-recursion can make a member and its
+ // physical frame otherwise hash identically. Hashed only when set so
+ // every pre-marker frame id is unchanged.
+ if self.inline {
+ hasher.update(b"inline");
+ }
hasher.update(b"native");
format!("{:x}", hasher.finalize())
@@ -477,8 +533,178 @@ impl From<&RawNativeFrame> for Frame {
}
}
+#[cfg(test)]
+pub(crate) mod test_support {
+ use super::*;
+ use crate::langs::CommonFrameMetadata;
+
+ /// Wrap a fixture ELF in the upload ZIP layout (binary as `dwarf` at the
+ /// root, optional `__source/` bundle), mirroring what the CLI produces.
+ pub(crate) fn zip_fixture(elf: &[u8], source: Option<(&str, &str)>) -> Vec<u8> {
+ use std::io::{Cursor, Write};
+
+ let mut buffer = Cursor::new(Vec::new());
+ {
+ let mut zip = zip::ZipWriter::new(&mut buffer);
+ let options = zip::write::SimpleFileOptions::default()
+ .compression_method(zip::CompressionMethod::Deflated);
+ zip.start_file("dwarf", options).unwrap();
+ zip.write_all(elf).unwrap();
+
+ if let Some((dwarf_path, content)) = source {
+ let manifest = serde_json::json!({
+ "version": 1,
+ "files": { dwarf_path: "__source/0" },
+ });
+ zip.start_file("__source/manifest.json", options).unwrap();
+ zip.write_all(manifest.to_string().as_bytes()).unwrap();
+ zip.start_file("__source/0", options).unwrap();
+ zip.write_all(content.as_bytes()).unwrap();
+ }
+
+ zip.finish().unwrap();
+ }
+
+ posthog_symbol_data::write_symbol_data(posthog_symbol_data::ElfDebugInfo {
+ data: buffer.into_inner(),
+ })
+ .unwrap()
+ }
+
+ /// Build a catalog whose native provider serves `data` for `chunk_id`.
+ pub(crate) async fn catalog_for_chunk(
+ db: &sqlx::PgPool,
+ chunk_id: &str,
+ data: Vec<u8>,
+ ) -> crate::symbolication::symbol_store::Catalog {
+ use chrono::Utc;
+ use mockall::predicate;
+ use uuid::Uuid;
+
+ use crate::symbolication::symbol_store::{saving::SymbolSetRecord, MockS3Client};
+
+ let mut record = SymbolSetRecord {
+ id: Uuid::now_v7(),
+ team_id: 1,
+ set_ref: chunk_id.to_string(),
+ storage_ptr: Some(chunk_id.to_string()),
+ failure_reason: None,
+ created_at: Utc::now(),
+ content_hash: Some("fake-hash".to_string()),
+ last_used: Some(Utc::now()),
+ };
+ record.save(db).await.unwrap();
+
+ let mut client = MockS3Client::default();
+ client
+ .expect_get()
+ .with(
+ predicate::eq("test-bucket".to_string()),
+ predicate::eq(chunk_id.to_string()),
+ )
+ .returning(move |_, _| Ok(Some(bytes::Bytes::from(data.clone()))));
+
+ catalog_with_client(db, client)
+ }
+
+ /// Build a catalog with no stored symbol sets: every chunk_id lookup
+ /// reports missing symbols.
+ pub(crate) fn catalog_without_symbols(
+ db: &sqlx::PgPool,
+ ) -> crate::symbolication::symbol_store::Catalog {
+ catalog_with_client(
+ db,
+ crate::symbolication::symbol_store::MockS3Client::default(),
+ )
+ }
+
+ fn catalog_with_client(
+ db: &sqlx::PgPool,
+ client: crate::symbolication::symbol_store::MockS3Client,
+ ) -> crate::symbolication::symbol_store::Catalog {
+ use std::sync::Arc;
+
+ use crate::{
+ core::config::ResolverConfig,
+ symbolication::symbol_store::{
+ apple::AppleProvider, chunk_id::ChunkIdFetcher, hermesmap::HermesMapProvider,
+ native::NativeProvider, proguard::ProguardProvider, sourcemap::SourcemapProvider,
+ Catalog,
+ },
+ };
+
+ let mut config = ResolverConfig::init_with_defaults().unwrap();
+ config.object_storage_bucket = "test-bucket".to_string();
+
+ let client = Arc::new(client);
+
+ Catalog::new(
+ ChunkIdFetcher::new(
+ SourcemapProvider::new(&config),
+ client.clone(),
+ db.clone(),
+ config.object_storage_bucket.clone(),
+ ),
+ ChunkIdFetcher::new(
+ HermesMapProvider {},
+ client.clone(),
+ db.clone(),
+ config.object_storage_bucket.clone(),
+ ),
+ ChunkIdFetcher::new(
+ ProguardProvider {},
+ client.clone(),
+ db.clone(),
+ config.object_storage_bucket.clone(),
+ ),
+ ChunkIdFetcher::new(
+ AppleProvider {},
+ client.clone(),
+ db.clone(),
+ config.object_storage_bucket.clone(),
+ ),
+ ChunkIdFetcher::new(
+ NativeProvider {},
+ client.clone(),
+ db.clone(),
+ config.object_storage_bucket.clone(),
+ ),
+ )
+ }
+
+ pub(crate) fn native_frame_at(instruction_addr: u64, image_addr: u64) -> RawNativeFrame {
+ RawNativeFrame {
+ instruction_addr: Some(format!("0x{instruction_addr:x}")),
+ symbol_addr: None,
+ image_addr: Some(format!("0x{image_addr:x}")),
+ lang: Some("rust".to_string()),
+ module: Some("test_binary".to_string()),
+ function: None,
+ filename: None,
+ lineno: None,
+ colno: None,
+ client_resolved: false,
+ inline: false,
+ meta: CommonFrameMetadata::default(),
+ }
+ }
+
+ pub(crate) fn debug_image_at(debug_id: &str, image_addr: u64) -> DebugImage {
+ DebugImage {
+ debug_id: debug_id.to_string(),
+ image_addr: format!("0x{image_addr:x}"),
+ image_vmaddr: None,
+ image_size: Some(0x100000),
+ code_file: Some("/app/test_binary".to_string()),
+ image_type: Some("elf".to_string()),
+ arch: Some("x86_64".to_string()),
+ }
+ }
+}
+
#[cfg(test)]
mod test {
+ use super::test_support::*;
use super::*;
use crate::core::symbolication::resolve::Resolve;
@@ -581,6 +807,8 @@ mod test {
filename: Some("src/checkout.rs".to_string()),
lineno: Some(42),
colno: None,
+ client_resolved: true,
+ inline: false,
meta: CommonFrameMetadata::default(),
};
@@ -604,6 +832,8 @@ mod test {
filename: None,
lineno: None,
colno: None,
+ client_resolved: false,
+ inline: false,
meta: CommonFrameMetadata::default(),
};
@@ -618,131 +848,20 @@ mod test {
assert_ne!(launch_a.frame_id(&[]), launch_b.frame_id(&[]));
}
- /// Wrap a fixture ELF in the upload ZIP layout (binary as `dwarf` at the
- /// root, optional `__source/` bundle), mirroring what the CLI produces.
- fn zip_fixture(elf: &[u8], source: Option<(&str, &str)>) -> Vec<u8> {
- use std::io::{Cursor, Write};
-
- let mut buffer = Cursor::new(Vec::new());
- {
- let mut zip = zip::ZipWriter::new(&mut buffer);
- let options = zip::write::SimpleFileOptions::default()
- .compression_method(zip::CompressionMethod::Deflated);
- zip.start_file("dwarf", options).unwrap();
- zip.write_all(elf).unwrap();
-
- if let Some((dwarf_path, content)) = source {
- let manifest = serde_json::json!({
- "version": 1,
- "files": { dwarf_path: "__source/0" },
- });
- zip.start_file("__source/manifest.json", options).unwrap();
- zip.write_all(manifest.to_string().as_bytes()).unwrap();
- zip.start_file("__source/0", options).unwrap();
- zip.write_all(content.as_bytes()).unwrap();
- }
-
- zip.finish().unwrap();
- }
-
- posthog_symbol_data::write_symbol_data(posthog_symbol_data::ElfDebugInfo {
- data: buffer.into_inner(),
- })
- .unwrap()
- }
-
- /// Build a catalog whose native provider serves `data` for `chunk_id`.
- async fn catalog_for_chunk(
- db: &sqlx::PgPool,
- chunk_id: &str,
- data: Vec<u8>,
- ) -> crate::symbolication::symbol_store::Catalog {
- use chrono::Utc;
- use mockall::predicate;
- use std::sync::Arc;
- use uuid::Uuid;
-
- use crate::{
- core::config::ResolverConfig,
- symbolication::symbol_store::{
- apple::AppleProvider, chunk_id::ChunkIdFetcher, hermesmap::HermesMapProvider,
- native::NativeProvider, proguard::ProguardProvider, saving::SymbolSetRecord,
- sourcemap::SourcemapProvider, Catalog, MockS3Client,
- },
- };
-
- let mut config = ResolverConfig::init_with_defaults().unwrap();
- config.object_storage_bucket = "test-bucket".to_string();
-
- let mut record = SymbolSetRecord {
- id: Uuid::now_v7(),
- team_id: 1,
- set_ref: chunk_id.to_string(),
- storage_ptr: Some(chunk_id.to_string()),
- failure_reason: None,
- created_at: Utc::now(),
- content_hash: Some("fake-hash".to_string()),
- last_used: Some(Utc::now()),
- };
- record.save(db).await.unwrap();
-
- let mut client = MockS3Client::default();
- client
- .expect_get()
- .with(
- predicate::eq(config.object_storage_bucket.clone()),
- predicate::eq(chunk_id.to_string()),
- )
- .returning(move |_, _| Ok(Some(bytes::Bytes::from(data.clone()))));
- let client = Arc::new(client);
-
- Catalog::new(
- ChunkIdFetcher::new(
- SourcemapProvider::new(&config),
- client.clone(),
- db.clone(),
- config.object_storage_bucket.clone(),
- ),
- ChunkIdFetcher::new(
- HermesMapProvider {},
- client.clone(),
- db.clone(),
- config.object_storage_bucket.clone(),
- ),
- ChunkIdFetcher::new(
- ProguardProvider {},
- client.clone(),
- db.clone(),
- config.object_storage_bucket.clone(),
- ),
- ChunkIdFetcher::new(
- AppleProvider {},
- client.clone(),
- db.clone(),
- config.object_storage_bucket.clone(),
- ),
- ChunkIdFetcher::new(
- NativeProvider {},
- client.clone(),
- db.clone(),
- config.object_storage_bucket.clone(),
- ),
- )
- }
-
- fn native_frame_at(instruction_addr: u64, image_addr: u64) -> RawNativeFrame {
- RawNativeFrame {
- instruction_addr: Some(format!("0x{instruction_addr:x}")),
- symbol_addr: None,
- image_addr: Some(format!("0x{image_addr:x}")),
- lang: Some("rust".to_string()),
- module: Some("test_binary".to_string()),
- function: None,
- filename: None,
- lineno: None,
- colno: None,
- meta: CommonFrameMetadata::default(),
- }
+ /// Resolution behavior branches on the inline marker, so it must split the
+ /// per-frame cache identity: with inlined self-recursion, a group member
+ /// and its physical frame can carry identical address/name/file/line, and
+ /// a shared id would let one's cached result answer for the other.
+ #[test]
+ fn test_native_frame_id_distinguishes_inline_members() {
+ let mut physical = native_frame_at(0x100004000, 0x100000000);
+ physical.function = Some("recurse".to_string());
+ physical.filename = Some("src/lib.rs".to_string());
+ physical.lineno = Some(12);
+ let mut member = physical.clone();
+ member.inline = true;
+
+ assert_ne!(physical.frame_id(&[]), member.frame_id(&[]));
}
#[test]
@@ -837,18 +956,6 @@ mod test {
);
}
- fn debug_image_at(debug_id: &str, image_addr: u64) -> DebugImage {
- DebugImage {
- debug_id: debug_id.to_string(),
- image_addr: format!("0x{image_addr:x}"),
- image_vmaddr: None,
- image_size: Some(0x100000),
- code_file: Some("/app/test_binary".to_string()),
- image_type: Some("elf".to_string()),
- arch: Some("x86_64".to_string()),
- }
- }
-
#[test]
fn symbol_set_ref_is_matched_debug_id() {
let frame = native_frame_at(0x1000_4000, 0x1000_0000);
@@ -1196,4 +1303,83 @@ mod test {
assert_eq!(resolved.line, Some(7));
assert_eq!(resolved.lang, "rust");
}
+
+ /// Inline members of a client-expanded group never resolve their own
+ /// address, even when the symbol set could: the group's physical frame
+ /// resolves once for the whole group, and resolving members too would
+ /// re-expand the same inline chain per member.
+ #[sqlx::test(migrations = "./tests/test_migrations")]
+ async fn test_inline_marked_frames_pass_through_even_when_resolvable(db: sqlx::PgPool) {
+ use crate::frames::RawFrame;
+
+ const ELF: &[u8] = include_bytes!("../../../../tests/static/native/test_binary_inline");
+ let chunk_id = "140ab543-c098-09dc-22b6-11f72e46d6fe";
+ let catalog = catalog_for_chunk(&db, chunk_id, zip_fixture(ELF, None)).await;
+
+ let slide_base = 0x7f0000000000u64;
+ let mut raw = native_frame_at(slide_base + 0x1475, slide_base);
+ raw.inline = true;
+ raw.client_resolved = true;
+ raw.function = Some("inner_function".to_string());
+ raw.filename = Some("test_binary_inline.c".to_string());
+ raw.lineno = Some(7);
+ let frame = RawFrame::Native(raw);
+ let debug_images = vec![debug_image_at(chunk_id, slide_base)];
+
+ let frames = frame.resolve(1, &catalog, &debug_images, 15).await.unwrap();
+
+ assert_eq!(
+ frames.len(),
+ 1,
+ "inline member must not expand: {frames:#?}"
+ );
+ assert!(frames[0].resolved);
+ assert_eq!(frames[0].resolved_name.as_deref(), Some("inner_function"));
+ assert_eq!(frames[0].line, Some(7));
+ assert!(frames[0].resolve_failure.is_none());
+ }
+
+ /// Server-resolved names share one vocabulary with client-side resolution:
+ /// no Rust symbol-hash suffixes (`::h0123456789abcdef`) and no crate
+ /// disambiguators (`[abc123]`). posthog-rs normalizes its client-resolved
+ /// names to this same shape (`normalize_function_name`), which keeps issue
+ /// fingerprints — they hash the resolved function name — stable when a
+ /// customer starts or stops uploading debug symbols mid-stream.
+ #[sqlx::test(migrations = "./tests/test_migrations")]
+ async fn test_resolved_names_match_client_normalization_vocabulary(db: sqlx::PgPool) {
+ use crate::frames::RawFrame;
+
+ const ELF_ZST: &[u8] =
+ include_bytes!("../../../../tests/static/native/test_rust_binary.zst");
+ let elf = zstd::decode_all(ELF_ZST).unwrap();
+ let chunk_id = "d1dea836-4ad3-daad-dd96-0e8626f766e1";
+ let catalog = catalog_for_chunk(&db, chunk_id, zip_fixture(&elf, None)).await;
+
+ let slide_base = 0x7f0000000000u64;
+ let frame = RawFrame::Native(native_frame_at(slide_base + 0x10645, slide_base));
+ let debug_images = vec![debug_image_at(chunk_id, slide_base)];
+
+ let frames = frame.resolve(1, &catalog, &debug_images, 15).await.unwrap();
+ assert!(frames.len() >= 2, "expected an inline expansion");
+
+ let is_rust_symbol_hash = |segment: &str| {
+ segment.len() == 17
+ && segment.starts_with('h')
+ && segment[1..].chars().all(|c| c.is_ascii_hexdigit())
+ };
+
+ for frame in &frames {
+ let Some(name) = frame.resolved_name.as_deref() else {
+ panic!("resolved frame missing a resolved_name: {frame:#?}");
+ };
+ assert!(
+ !name.rsplit("::").next().is_some_and(is_rust_symbol_hash),
+ "symbol hash suffix leaked into resolved name: {name}"
+ );
+ assert!(
+ !name.contains('['),
+ "crate disambiguator leaked into resolved name: {name}"
+ );
+ }
+ }
}
diff --git a/rust/cymbal/src/modes/processing/stages/resolution/frame.rs b/rust/cymbal/src/modes/processing/stages/resolution/frame.rs
index f76265c4cbbb..97c3417e011c 100644
--- a/rust/cymbal/src/modes/processing/stages/resolution/frame.rs
+++ b/rust/cymbal/src/modes/processing/stages/resolution/frame.rs
@@ -4,7 +4,7 @@ use crate::{
error::UnhandledError,
frames::{Frame, RawFrame},
langs::native::DebugImage,
- metric_consts::FRAME_RESOLVER_OPERATOR,
+ metric_consts::{FRAME_RESOLVER_OPERATOR, NATIVE_INLINE_GROUPS},
stages::{pipeline::HandledError, resolution::ResolutionStage},
types::{
batch::Batch,
@@ -47,13 +47,19 @@ impl FrameResolver {
) -> Result<Exception, UnhandledError> {
exc.stack = match exc.stack {
Some(Stacktrace::Raw { frames }) => {
- let frame_batches: Batch<Vec<Frame>> = Batch::from(frames)
+ let units = partition_into_units(frames);
+ let frame_batches: Batch<Vec<Frame>> = Batch::from(units)
.apply_func(
- move |frame, ctx| {
+ move |unit, ctx| {
let debug_images = debug_images.clone();
async move {
- FrameResolver::resolve_frame(team_id, &frame, &debug_images, ctx)
- .await
+ FrameResolver::resolve_frame_unit(
+ team_id,
+ &unit,
+ &debug_images,
+ ctx,
+ )
+ .await
}
},
ctx,
@@ -68,6 +74,68 @@ impl FrameResolver {
Ok(exc)
}
+ /// Resolve one partition unit: a lone frame, or a client-expanded native
+ /// inline group (physical lead frame + the inline frames the client
+ /// expanded from the same address).
+ ///
+ /// The lead resolves through the normal per-frame path. When its address
+ /// symbolicates to an inline expansion, the server-side expansion
+ /// supersedes the whole group, so the chain isn't duplicated. When it
+ /// symbolicates to a single frame against a multi-layer client group, the
+ /// uploaded symbols carry no inline info for it (e.g. a stripped binary
+ /// that kept its build id): the server's canonical physical frame is kept
+ /// and the client's inline members are salvaged behind it, which stays
+ /// duplicate-free because the member layers are disjoint from the
+ /// physical layer. When it doesn't resolve at all, the client expansion
+ /// passes through verbatim. Members always go through the per-frame path
+ /// (their `inline` marker makes them resolution-free), so every emitted
+ /// frame is backed by the per-frame cache and stored records.
+ async fn resolve_frame_unit(
+ team_id: i32,
+ unit: &[RawFrame],
+ debug_images: &[DebugImage],
+ ctx: ResolutionStage,
+ ) -> Result<Vec<Frame>, UnhandledError> {
+ let (lead, members) = unit.split_first().expect("partition units are non-empty");
+
+ let mut frames =
+ FrameResolver::resolve_frame(team_id, lead, debug_images, ctx.clone()).await?;
+
+ if members.is_empty() {
+ return Ok(frames);
+ }
+
+ let server_resolved = frames.first().is_some_and(|f| f.resolved);
+ if server_resolved {
+ if frames.len() > 1 {
+ // Replaces even a slightly shallower multi-frame expansion:
+ // same-build symbols normally match the client's depth, and
+ // deferring to the server keeps debug-built and stripped
+ // clients of the same binary converging on identical stacks
+ // and fingerprints once symbols exist. Splicing the client's
+ // extra layers in would need chain alignment between two
+ // symbolications, which is exactly the duplication hazard the
+ // group contract avoids.
+ metrics::counter!(NATIVE_INLINE_GROUPS, "outcome" => "replaced").increment(1);
+ return Ok(frames);
+ }
+ // Single-frame resolution against a multi-layer client group: no
+ // inline info in the uploaded symbols. Keep the canonical physical
+ // frame, salvage the client members behind it.
+ metrics::counter!(NATIVE_INLINE_GROUPS, "outcome" => "merged_client_inlines")
+ .increment(1);
+ } else {
+ metrics::counter!(NATIVE_INLINE_GROUPS, "outcome" => "kept").increment(1);
+ }
+
+ for member in members {
+ frames.extend(
+ FrameResolver::resolve_frame(team_id, member, debug_images, ctx.clone()).await?,
+ );
+ }
+ Ok(frames)
+ }
+
pub async fn resolve_frame(
team_id: i32,
frame: &RawFrame,
@@ -95,6 +163,36 @@ impl FrameResolver {
}
}
+/// Split a raw stack into resolution units, preserving order. Consecutive
+/// native frames form one unit when they are a client-expanded inline group:
+/// a physical (non-inline) frame carrying an instruction address, followed by
+/// inline-marked frames carrying that same address. Everything else — other
+/// platforms, address-less frames, orphaned inline frames — is its own unit.
+///
+/// Grouping keys off the `inline` markers rather than address adjacency:
+/// direct recursion repeats the same return address across *distinct*
+/// physical frames, and those must stay separate groups.
+fn partition_into_units(frames: Vec<RawFrame>) -> Vec<Vec<RawFrame>> {
+ let mut units: Vec<Vec<RawFrame>> = Vec::new();
+
+ for frame in frames {
+ if let (Some(unit), RawFrame::Native(candidate)) = (units.last_mut(), &frame) {
+ if let Some(RawFrame::Native(lead)) = unit.first() {
+ if !lead.inline
+ && lead.instruction_addr.is_some()
+ && candidate.continues_group_of(lead)
+ {
+ unit.push(frame);
+ continue;
+ }
+ }
+ }
+ units.push(vec![frame]);
+ }
+
+ units
+}
+
impl ValueOperator for FrameResolver {
type Context = ResolutionStage;
type Item = ExceptionProperties;
@@ -124,3 +222,365 @@ impl ValueOperator for FrameResolver {
Ok(Ok(evt))
}
}
+
+#[cfg(test)]
+mod test {
+ use std::sync::Arc;
+
+ use tokio::sync::Semaphore;
+
+ use super::*;
+ use crate::{
+ langs::native::test_support::{
+ catalog_for_chunk, catalog_without_symbols, debug_image_at, native_frame_at,
+ zip_fixture,
+ },
+ modes::processing::config::ProcessingConfig,
+ symbolication::symbol::local::LocalSymbolResolver,
+ symbolication::symbol_store::Catalog,
+ };
+
+ fn client_frame(addr: u64, image_addr: u64, inline: bool, function: &str) -> RawFrame {
+ let mut frame = native_frame_at(addr, image_addr);
+ frame.inline = inline;
+ frame.client_resolved = true;
+ frame.function = Some(function.to_string());
+ frame.filename = Some("src/lib.rs".to_string());
+ frame.lineno = Some(10);
+ RawFrame::Native(frame)
+ }
+
+ fn unit_sizes(units: &[Vec<RawFrame>]) -> Vec<usize> {
+ units.iter().map(|u| u.len()).collect()
+ }
+
+ #[test]
+ fn partition_keeps_independent_frames_single() {
+ let frames = vec![
+ client_frame(0x10, 0x1, false, "a"),
+ client_frame(0x20, 0x1, false, "b"),
+ ];
+ assert_eq!(unit_sizes(&partition_into_units(frames)), vec![1, 1]);
+ }
+
+ #[test]
+ fn partition_groups_physical_frame_with_its_inline_members() {
+ let frames = vec![
+ client_frame(0x10, 0x1, false, "outer"),
+ client_frame(0x10, 0x1, true, "mid"),
+ client_frame(0x10, 0x1, true, "leaf"),
+ client_frame(0x20, 0x1, false, "next"),
+ ];
+ assert_eq!(unit_sizes(&partition_into_units(frames)), vec![3, 1]);
+ }
+
+ #[test]
+ fn partition_keeps_recursive_same_address_frames_separate() {
+ // Direct recursion repeats the same return address across distinct
+ // physical frames — bare address adjacency must not group them.
+ let frames = vec![
+ client_frame(0x10, 0x1, false, "recurse"),
+ client_frame(0x10, 0x1, false, "recurse"),
+ ];
+ assert_eq!(unit_sizes(&partition_into_units(frames)), vec![1, 1]);
+ }
+
+ #[test]
+ fn partition_keeps_recursive_inline_groups_separate() {
+ // Inlined recursion: each recursion level is its own group, delimited
+ // by its non-inline physical frame.
+ let frames = vec![
+ client_frame(0x10, 0x1, false, "recurse"),
+ client_frame(0x10, 0x1, true, "recurse_inner"),
+ client_frame(0x10, 0x1, false, "recurse"),
+ client_frame(0x10, 0x1, true, "recurse_inner"),
+ ];
+ assert_eq!(unit_sizes(&partition_into_units(frames)), vec![2, 2]);
+ }
+
+ #[test]
+ fn partition_orphan_inline_and_mismatches_stay_single() {
+ // An inline frame with no preceding physical frame (e.g. malformed
+ // input) stays alone, and a member with a different address or a
+ // different image does not join the preceding group.
+ let frames = vec![
+ client_frame(0x10, 0x1, true, "orphan"),
+ client_frame(0x20, 0x1, false, "lead"),
+ client_frame(0x21, 0x1, true, "stray_addr"),
+ client_frame(0x30, 0x1, false, "lead_2"),
+ client_frame(0x30, 0x2, true, "stray_image"),
+ ];
+ assert_eq!(
+ unit_sizes(&partition_into_units(frames)),
+ vec![1, 1, 1, 1, 1]
+ );
+ }
+
+ #[test]
+ fn partition_non_native_frames_break_groups() {
+ let custom: RawFrame = serde_json::from_str(
+ r#"{"platform": "custom", "function": "f", "in_app": true, "lang": "elixir"}"#,
+ )
+ .unwrap();
+ let frames = vec![
+ client_frame(0x10, 0x1, false, "lead"),
+ custom,
+ client_frame(0x10, 0x1, true, "member"),
+ ];
+ assert_eq!(unit_sizes(&partition_into_units(frames)), vec![1, 1, 1]);
+ }
+
+ const INLINE_ELF: &[u8] =
+ include_bytes!("../../../../../tests/static/native/test_binary_inline");
+ const INLINE_CHUNK_ID: &str = "140ab543-c098-09dc-22b6-11f72e46d6fe";
+ const SLIDE_BASE: u64 = 0x7f0000000000;
+ // 0x1475: after the -1 call-site adjustment the lookup lands inside
+ // inlined_leaf as inlined (via inner_function) into outer_function.
+ const INLINE_ADDR: u64 = SLIDE_BASE + 0x1475;
+
+ fn resolution_stage(db: &sqlx::PgPool, catalog: Catalog) -> ResolutionStage {
+ let mut config = ProcessingConfig::init_with_defaults().unwrap();
+ config.resolver.object_storage_bucket = "test-bucket".to_string();
+ ResolutionStage {
+ symbol_resolver: Arc::new(LocalSymbolResolver::new(
+ &config.resolver,
+ Arc::new(catalog),
+ db.clone(),
+ )),
+ symbol_resolution_limiter: Arc::new(Semaphore::new(4)),
+ remote: None,
+ }
+ }
+
+ fn client_expanded_group() -> Vec<RawFrame> {
+ vec![
+ client_frame(INLINE_ADDR, SLIDE_BASE, false, "client_outer"),
+ client_frame(INLINE_ADDR, SLIDE_BASE, true, "client_inner"),
+ client_frame(INLINE_ADDR, SLIDE_BASE, true, "client_leaf"),
+ ]
+ }
+
+ fn exception_with(frames: Vec<RawFrame>) -> Exception {
+ Exception {
+ exception_type: "Panic".to_string(),
+ exception_message: "boom".to_string(),
+ module: None,
+ exception_id: None,
+ mechanism: None,
+ thread_id: None,
+ stack: Some(Stacktrace::Raw { frames }),
+ }
+ }
+
+ fn resolved_frames(exc: Exception) -> Vec<Frame> {
+ match exc.stack {
+ Some(Stacktrace::Resolved { frames }) => frames,
+ other => panic!("expected a resolved stacktrace, got {other:?}"),
+ }
+ }
+
+ /// When the group's address symbolicates, the server expansion replaces
+ /// the whole client expansion — same logical frames, no duplication.
+ #[sqlx::test(migrations = "./tests/test_migrations")]
+ async fn client_expanded_group_is_replaced_by_server_expansion(db: sqlx::PgPool) {
+ let catalog = catalog_for_chunk(&db, INLINE_CHUNK_ID, zip_fixture(INLINE_ELF, None)).await;
+ let stage = resolution_stage(&db, catalog);
+ let debug_images = Arc::new(vec![debug_image_at(INLINE_CHUNK_ID, SLIDE_BASE)]);
+
+ let group = client_expanded_group();
+ let lead = group[0].clone();
+ let exc = exception_with(group);
+
+ let frames = resolved_frames(
+ FrameResolver::resolve_exception_frames(1, exc, debug_images.clone(), stage.clone())
+ .await
+ .unwrap(),
+ );
+
+ let names: Vec<_> = frames
+ .iter()
+ .map(|f| f.resolved_name.as_deref().unwrap())
+ .collect();
+ assert_eq!(
+ names,
+ ["outer_function", "inner_function", "inlined_leaf"],
+ "expected the server expansion to replace the client group"
+ );
+ assert!(frames.iter().all(|f| f.resolved));
+
+ // The replacement frames all carry ids derived from the group's
+ // physical frame, matching the single-address-frame contract.
+ for (index, frame) in frames.iter().enumerate() {
+ assert_eq!(frame.frame_id, lead.frame_id(1, index, &debug_images));
+ }
+
+ // A client group deeper than the server's multi-frame expansion is
+ // still replaced: the server's inline chain is canonical.
+ let mut deeper = client_expanded_group();
+ deeper.push(client_frame(INLINE_ADDR, SLIDE_BASE, true, "client_extra"));
+ let frames = resolved_frames(
+ FrameResolver::resolve_exception_frames(
+ 1,
+ exception_with(deeper),
+ debug_images.clone(),
+ stage,
+ )
+ .await
+ .unwrap(),
+ );
+ assert_eq!(frames.len(), 3);
+ assert!(frames.iter().all(|f| f.resolved));
+ }
+
+ /// When the address can't be symbolicated (no symbols uploaded), the
+ /// client's expansion passes through verbatim: the physical frame keeps
+ /// its client fields plus the failure reason, and the inline members
+ /// survive untouched.
+ #[sqlx::test(migrations = "./tests/test_migrations")]
+ async fn client_expanded_group_is_kept_when_symbols_are_missing(db: sqlx::PgPool) {
+ let catalog = catalog_without_symbols(&db);
+ let stage = resolution_stage(&db, catalog);
+ let debug_images = Arc::new(vec![debug_image_at(INLINE_CHUNK_ID, SLIDE_BASE)]);
+
+ let exc = exception_with(client_expanded_group());
+
+ let frames = resolved_frames(
+ FrameResolver::resolve_exception_frames(1, exc, debug_images.clone(), stage)
+ .await
+ .unwrap(),
+ );
+
+ let names: Vec<_> = frames
+ .iter()
+ .map(|f| f.resolved_name.as_deref().unwrap())
+ .collect();
+ assert_eq!(names, ["client_outer", "client_inner", "client_leaf"]);
+
+ // The physical frame records why server resolution didn't happen…
+ assert!(!frames[0].resolved);
+ assert!(frames[0]
+ .resolve_failure
+ .as_deref()
+ .is_some_and(|f| f.contains(INLINE_CHUNK_ID)));
+ // …while the client-expanded members pass through as resolved frames.
+ assert!(frames[1..].iter().all(|f| f.resolved));
+ assert!(frames[1..].iter().all(|f| f.resolve_failure.is_none()));
+ assert!(frames.iter().all(|f| f.line == Some(10)));
+ }
+
+ /// A single-frame resolution against a multi-layer client group means
+ /// the uploaded symbols carry no inline info (e.g. a stripped binary that
+ /// kept its build id): the server's canonical physical frame is kept and
+ /// the client's inline members are salvaged behind it.
+ #[sqlx::test(migrations = "./tests/test_migrations")]
+ async fn inline_less_symbols_keep_client_inline_members(db: sqlx::PgPool) {
+ const NOPIE_ELF: &[u8] =
+ include_bytes!("../../../../../tests/static/native/test_binary_nopie");
+ const NOPIE_CHUNK_ID: &str = "7561847b-1054-7eb3-7763-4415adfaa134";
+ // Non-PIE: loads at its link base; 0x14a8 is inside inner_function,
+ // which has no inlined callees, so the lookup yields a single frame.
+ const NOPIE_BASE: u64 = 0x1000000;
+ const NOPIE_ADDR: u64 = NOPIE_BASE + 0x14a8;
+
+ let catalog = catalog_for_chunk(&db, NOPIE_CHUNK_ID, zip_fixture(NOPIE_ELF, None)).await;
+ let stage = resolution_stage(&db, catalog);
+ let debug_images = Arc::new(vec![debug_image_at(NOPIE_CHUNK_ID, NOPIE_BASE)]);
+
+ let group = vec![
+ client_frame(NOPIE_ADDR, NOPIE_BASE, false, "client_physical"),
+ client_frame(NOPIE_ADDR, NOPIE_BASE, true, "client_inline_a"),
+ client_frame(NOPIE_ADDR, NOPIE_BASE, true, "client_inline_b"),
+ ];
+ let exc = exception_with(group);
+
+ let frames = resolved_frames(
+ FrameResolver::resolve_exception_frames(1, exc, debug_images.clone(), stage)
+ .await
+ .unwrap(),
+ );
+
+ let names: Vec<_> = frames
+ .iter()
+ .map(|f| f.resolved_name.as_deref().unwrap())
+ .collect();
+ assert_eq!(
+ names,
+ ["inner_function", "client_inline_a", "client_inline_b"],
+ "expected the server physical frame plus the client inline members"
+ );
+ assert!(frames[0].resolved);
+ assert!(frames[1..].iter().all(|f| f.resolve_failure.is_none()));
+ }
+
+ /// The same crash must fingerprint identically under the v2 normalizing
+ /// algorithm whether its inline group was kept (no symbols uploaded) or
+ /// replaced by the server expansion: v2 hashes every frame and only the
+ /// file-name component of sources, so the client's absolute paths and the
+ /// server's short names agree. (v1 stays frozen and splits on the path
+ /// spelling, which is why new issues key on v2.)
+ #[sqlx::test(migrations = "./tests/test_migrations")]
+ async fn kept_and_replaced_groups_fingerprint_identically_under_v2(db: sqlx::PgPool) {
+ use crate::fingerprinting::FingerprintVersion;
+
+ // Server-parity names (what posthog-rs actually sends) plus an
+ // absolute capture-host path for the fixture's source file.
+ let client_group = || -> Vec<RawFrame> {
+ [
+ ("outer_function", false),
+ ("inner_function", true),
+ ("inlined_leaf", true),
+ ]
+ .into_iter()
+ .map(|(function, inline)| {
+ let RawFrame::Native(mut frame) =
+ client_frame(INLINE_ADDR, SLIDE_BASE, inline, function)
+ else {
+ unreachable!("client_frame builds native frames");
+ };
+ frame.filename =
+ Some("/build/host/cymbal_tests/native/test_binary_inline.c".to_string());
+ frame.meta.in_app = true;
+ RawFrame::Native(frame)
+ })
+ .collect()
+ };
+ let debug_images = Arc::new(vec![debug_image_at(INLINE_CHUNK_ID, SLIDE_BASE)]);
+
+ // Distinct team ids so the two runs don't share cached frame records.
+ let kept_stage = resolution_stage(&db, catalog_without_symbols(&db));
+ let kept = FrameResolver::resolve_exception_frames(
+ 2,
+ exception_with(client_group()),
+ debug_images.clone(),
+ kept_stage,
+ )
+ .await
+ .unwrap();
+
+ let replaced_catalog =
+ catalog_for_chunk(&db, INLINE_CHUNK_ID, zip_fixture(INLINE_ELF, None)).await;
+ let replaced_stage = resolution_stage(&db, replaced_catalog);
+ let replaced = FrameResolver::resolve_exception_frames(
+ 1,
+ exception_with(client_group()),
+ debug_images.clone(),
+ replaced_stage,
+ )
+ .await
+ .unwrap();
+
+ // Sanity: the two paths really did produce different representations.
+ let kept_frames = resolved_frames(kept.clone());
+ let replaced_frames = resolved_frames(replaced.clone());
+ assert!(kept_frames[0].resolve_failure.is_some());
+ assert!(replaced_frames.iter().all(|f| f.resolved));
+
+ let kept_fp = FingerprintVersion::V2.compute(&vec![kept].into());
+ let replaced_fp = FingerprintVersion::V2.compute(&vec![replaced].into());
+ assert_eq!(
+ kept_fp.value, replaced_fp.value,
+ "kept: {:#?}\nreplaced: {:#?}",
+ kept_fp.record, replaced_fp.record
+ );
+ }
+}