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): carry inline source context on pass-through java frames (#76832)

Catalind53f200c1d08
diff --git a/rust/cymbal/src/core/symbolication/resolve.rs b/rust/cymbal/src/core/symbolication/resolve.rs
index 65a0d9d1670e..1320712976f5 100644
--- a/rust/cymbal/src/core/symbolication/resolve.rs
+++ b/rust/cymbal/src/core/symbolication/resolve.rs
@@ -101,9 +101,11 @@ where
team_id: i32,
catalog: &C,
_debug_images: &[DebugImage],
- _context_lines: usize, // Java frames have no source context to bound
+ // Bounds the source context a client sent on a pass-through (no map_id) frame.
+ // ProGuard-remapped frames drop context, so it only matters on that path.
+ context_lines: usize,
) -> Result<Vec<Frame>, UnhandledError> {
- self.resolve_frame(team_id, catalog).await
+ self.resolve_frame(team_id, catalog, context_lines).await
}
}
diff --git a/rust/cymbal/src/core/symbolication/symbol/mod.rs b/rust/cymbal/src/core/symbolication/symbol/mod.rs
index 94044582692d..cab25f176b9f 100644
--- a/rust/cymbal/src/core/symbolication/symbol/mod.rs
+++ b/rust/cymbal/src/core/symbolication/symbol/mod.rs
@@ -219,6 +219,9 @@ mod tests {
lineno: Some(42),
module: "com.acme.billing.InvoiceService".to_string(),
map_id: map_id.map(ToString::to_string),
+ context_line: None,
+ pre_context: Vec::new(),
+ post_context: Vec::new(),
method_synthetic: false,
meta: CommonFrameMetadata::default(),
})],
diff --git a/rust/cymbal/src/core/types/langs/java.rs b/rust/cymbal/src/core/types/langs/java.rs
index 62fbb6557891..2dc79339e2f9 100644
--- a/rust/cymbal/src/core/types/langs/java.rs
+++ b/rust/cymbal/src/core/types/langs/java.rs
@@ -8,7 +8,7 @@ use tracing::warn;
use crate::{
error::{FrameError, ProguardError, ResolveError, UnhandledError},
- frames::{record_frame_resolution_failure, Frame},
+ frames::{record_frame_resolution_failure, Context, ContextLine, Frame},
langs::{utils::add_raw_to_junk, CommonFrameMetadata},
symbolication::symbol_store::{
chunk_id::OrChunkId,
@@ -17,6 +17,10 @@ use crate::{
},
};
+// Per-line cap for the raw context copied into `Frame.junk_drawer`, matching the limit
+// `ContextLine::new` applies to the context we render.
+const JUNK_CONTEXT_LINE_CHARS: usize = 300;
+
// Namespace tag for the frame id construction below. It sits outside the digest on purpose:
// every other language's encoder emits a bare digest over a concatenation of fields the
// client controls, so any of them can be handed values that reproduce this construction's
@@ -31,6 +35,11 @@ pub struct RawJavaFrame {
pub lineno: Option<usize>, // The line number of the context line
pub module: String, // The java-import style module name the function is in
pub map_id: Option<String>, // ID of the proguard mapping symbol set this frame can be demangled with
+ pub context_line: Option<String>, // The line of code the exception came from
+ #[serde(default)]
+ pub pre_context: Vec<String>, // The lines of code before the context line
+ #[serde(default)]
+ pub post_context: Vec<String>, // The lines of code after the context line
#[serde(default)]
// Java compilers sometimes generate synthetic methods, for stuff like implied accessors from the source
// More info at https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.7.8
@@ -97,6 +106,15 @@ impl RawJavaFrame {
// every stored java id once and they re-resolve on next sight, which the ~30 minute
// TTL makes cheap. Fingerprints are unaffected: this id only appears as `raw_id` in
// the fingerprint record, never in the hash itself.
+ //
+ // Source context is folded in last, and only when the client actually sent some, so a
+ // frame without these fields keeps the id the fields-only construction gives it and
+ // records already stored under that id stay addressable. Unlike
+ // RawPythonFrame::frame_id, the lines go in length-prefixed with both sides counted:
+ // concatenating them raw would let pre_context ["ab", "c"] and ["a", "bc"] feed
+ // identical bytes, as would a line moved between pre_context and post_context, and a
+ // collision here renders one frame's source on another. No SDK populates these fields
+ // yet, so tightening their encoding costs no compatibility.
let mut hasher = Sha512::new();
update_optional(&mut hasher, self.filename.as_deref());
update_len_prefixed(&mut hasher, self.function.as_bytes());
@@ -111,18 +129,105 @@ impl RawJavaFrame {
}
update_len_prefixed(&mut hasher, self.module.as_bytes());
update_optional(&mut hasher, self.map_id.as_deref());
+ if self.context_line.is_some()
+ || !self.pre_context.is_empty()
+ || !self.post_context.is_empty()
+ {
+ update_optional(&mut hasher, self.context_line.as_deref());
+ for (side, lines) in [(0u8, &self.pre_context), (1u8, &self.post_context)] {
+ hasher.update([side]);
+ hasher.update((lines.len() as u64).to_be_bytes());
+ for line in lines {
+ update_len_prefixed(&mut hasher, line.as_bytes());
+ }
+ }
+ }
format!("{FRAME_ID_VERSION}:{:x}", hasher.finalize())
}
+ // Build source context out of the lines the client sent, mirroring
+ // RawPythonFrame::get_context. Only reachable from the pass-through (no map_id) path:
+ // ProGuard remapping moves the reported line, so client-captured context would no
+ // longer line up with the remapped location.
+ pub fn get_context(&self, context_lines: usize) -> Option<Context> {
+ let context_line = self.context_line.as_ref()?;
+ let lineno = self.lineno? as u32;
+
+ let line = ContextLine::new(lineno, context_line);
+
+ // The client chooses how many surrounding lines to send, so bound both sides by
+ // our own budget rather than storing whatever arrived. `get_context_lines`, used by
+ // the source-backed languages, takes at most `context_lines` on each side of the
+ // context line, so keep the lines closest to it and drop the outermost ones.
+ // `pre_context` arrives furthest-line-first, so the closest lines are at the end.
+ let pre_start = self.pre_context.len().saturating_sub(context_lines);
+ let before = self.pre_context[pre_start..]
+ .iter()
+ .rev()
+ .enumerate()
+ .map(|(i, line)| ContextLine::new_rel(lineno, -(i as i32) - 1, line.clone()))
+ .collect();
+ let after = self
+ .post_context
+ .iter()
+ .take(context_lines)
+ .enumerate()
+ .map(|(i, line)| ContextLine::new_rel(lineno, (i as i32) + 1, line.clone()))
+ .collect();
+ Some(Context {
+ before,
+ line,
+ after,
+ })
+ }
+
+ // `add_raw_to_junk` serializes the raw frame into `Frame.junk_drawer`, which is
+ // persisted with the stack-frame record (unlike `Frame.context`, which is
+ // `#[serde(skip)]`). Bounding only `get_context` would therefore leave unbounded
+ // client input reaching storage through the junk drawer, so bound the copy we hand it
+ // the same way: at most `context_lines` entries per side, each capped at the same
+ // length `ContextLine::new` enforces on the rendered context. Conversions that discard
+ // context pass 0 and store none of it, since keeping lines they never surface is pure
+ // waste.
+ fn bounded_for_junk(&self, context_lines: usize) -> Self {
+ if context_lines == 0 {
+ return Self {
+ context_line: None,
+ pre_context: Vec::new(),
+ post_context: Vec::new(),
+ ..self.clone()
+ };
+ }
+
+ // A single source line is otherwise unbounded, so one oversized line would land in
+ // every stored record even with the entry count capped.
+ let cap =
+ |line: &String| -> String { line.chars().take(JUNK_CONTEXT_LINE_CHARS).collect() };
+
+ let pre_start = self.pre_context.len().saturating_sub(context_lines);
+ Self {
+ context_line: self.context_line.as_ref().map(cap),
+ pre_context: self.pre_context[pre_start..].iter().map(cap).collect(),
+ post_context: self
+ .post_context
+ .iter()
+ .take(context_lines)
+ .map(cap)
+ .collect(),
+ ..self.clone()
+ }
+ }
+
pub async fn resolve_frame<C>(
&self,
team_id: i32,
catalog: &C,
+ context_lines: usize,
) -> Result<Vec<Frame>, UnhandledError>
where
C: SymbolCatalog<OrChunkId<ProguardRef>, FetchedMapping>,
{
- match self.resolve_impl(team_id, catalog).await {
+ match self.resolve_impl(team_id, catalog, context_lines).await {
Ok(frames) => Ok(frames),
Err(ResolveError::ResolutionError(FrameError::Proguard(e))) => {
Ok(vec![self.handle_resolution_error(e)])
@@ -143,7 +248,12 @@ impl RawJavaFrame {
}
}
- async fn resolve_impl<C>(&self, team_id: i32, catalog: &C) -> Result<Vec<Frame>, ResolveError>
+ async fn resolve_impl<C>(
+ &self,
+ team_id: i32,
+ catalog: &C,
+ context_lines: usize,
+ ) -> Result<Vec<Frame>, ResolveError>
where
C: SymbolCatalog<OrChunkId<ProguardRef>, FetchedMapping>,
{
@@ -154,7 +264,7 @@ impl RawJavaFrame {
// Short-circuit before `get_ref()` and the catalog lookup so these frames stop
// being counted (and logged) as resolution failures.
if self.map_id.is_none() {
- return Ok(vec![self.into()]);
+ return Ok(vec![(self, context_lines).into()]);
}
let r = self.get_ref()?;
@@ -263,12 +373,15 @@ impl<'a> From<(&'a RawJavaFrame, StackFrame<'a>)> for Frame {
junk_drawer: None,
code_variables: None,
synthetic: raw.meta.synthetic,
+ // Remapping moves the reported line, so any context the client captured
+ // describes a different location than the one we now report. Dropped here;
+ // only the pass-through conversion below carries context.
context: None,
suspicious: false,
module: Some(remapped.class().to_string()),
};
- add_raw_to_junk(&mut f, raw);
+ add_raw_to_junk(&mut f, &raw.bounded_for_junk(0));
f
}
@@ -278,7 +391,8 @@ impl<'a> From<(&'a RawJavaFrame, StackFrame<'a>)> for Frame {
// no map_id and so has no ProGuard mapping to demangle against. The client-provided
// module, method, file and line are the real ones, so we surface them as-is with
// `resolved: true` and no failure. This mirrors the direct `From<&RawX> for Frame`
-// conversions used by the catalog-free languages (python, go, php, ruby).
+// conversions used by the catalog-free languages (python, go, php, ruby). The `usize` is
+// the per-frame source-context budget, applied by `get_context`.
//
// INVARIANT: `resolved_name` deliberately stays `None`, even though the frame is
// resolved. `update_frame` in `modes/processing/fingerprinting/mod.rs` branches on
@@ -304,8 +418,8 @@ impl<'a> From<(&'a RawJavaFrame, StackFrame<'a>)> for Frame {
// The success metric is not emitted here: the `RawFrame` dispatcher in
// `symbolication/resolve.rs` already counts every frame that comes back with
// `resolved: true` toward `FRAME_RESOLVED`.
-impl From<&RawJavaFrame> for Frame {
- fn from(raw: &RawJavaFrame) -> Self {
+impl From<(&RawJavaFrame, usize)> for Frame {
+ fn from((raw, context_lines): (&RawJavaFrame, usize)) -> Self {
let mut f = Frame {
frame_id: FrameId::placeholder(),
mangled_name: raw.function.clone(),
@@ -324,12 +438,12 @@ impl From<&RawJavaFrame> for Frame {
junk_drawer: None,
code_variables: None,
synthetic: raw.meta.synthetic,
- context: None,
+ context: raw.get_context(context_lines),
suspicious: false,
module: Some(raw.module.clone()),
};
- add_raw_to_junk(&mut f, raw);
+ add_raw_to_junk(&mut f, &raw.bounded_for_junk(context_lines));
f
}
@@ -360,7 +474,7 @@ impl From<(&RawJavaFrame, ProguardError)> for Frame {
module: Some(raw.module.clone()),
};
- add_raw_to_junk(&mut f, raw);
+ add_raw_to_junk(&mut f, &raw.bounded_for_junk(0));
f
}
@@ -372,6 +486,7 @@ mod tests {
use crate::{
core::config::ResolverConfig,
+ frames::RawFrame,
symbolication::symbol_store::{
apple::AppleProvider, chunk_id::ChunkIdFetcher, hermesmap::HermesMapProvider,
native::NativeProvider, proguard::ProguardProvider, sourcemap::SourcemapProvider,
@@ -384,6 +499,9 @@ mod tests {
const PROGUARD_MAP: &str =
include_str!("../../../../tests/static/proguard/mapping_example.txt");
+ // The production default for ResolverConfig::context_line_count.
+ const CONTEXT_LINES: usize = 15;
+
fn raw_frame(module: &str, in_app: bool, map_id: Option<&str>) -> RawJavaFrame {
RawJavaFrame {
filename: Some("SourceFile".to_string()),
@@ -391,6 +509,9 @@ mod tests {
lineno: Some(14),
module: module.to_string(),
map_id: map_id.map(ToString::to_string),
+ context_line: None,
+ pre_context: Vec::new(),
+ post_context: Vec::new(),
method_synthetic: false,
meta: CommonFrameMetadata {
in_app,
@@ -452,7 +573,7 @@ mod tests {
for raw in &frames {
assert_eq!(raw.symbol_set_ref(), None);
- let resolved = raw.resolve_frame(1, &catalog).await.unwrap();
+ let resolved = raw.resolve_frame(1, &catalog, CONTEXT_LINES).await.unwrap();
assert_eq!(
resolved.len(),
1,
@@ -472,15 +593,15 @@ mod tests {
}
}
- // Guards the fingerprint-neutrality claim in the `From<&RawJavaFrame>` invariant
- // comment. Every field `update_frame` reads must match what the old failure path
- // produced, so flipping these frames to resolved cannot re-key existing issues.
+ // Guards the fingerprint-neutrality claim in the `From<(&RawJavaFrame, usize)>`
+ // invariant comment. Every field `update_frame` reads must match what the old failure
+ // path produced, so flipping these frames to resolved cannot re-key existing issues.
// If someone populates `resolved_name` on the pass-through path, this fails.
#[test]
fn pass_through_is_fingerprint_identical_to_the_old_failure_frame() {
let raw = raw_frame("com.acme.billing.InvoiceService", true, None);
- let passed_through: Frame = (&raw).into();
+ let passed_through: Frame = (&raw, CONTEXT_LINES).into();
let legacy: Frame = (&raw, ProguardError::NoMapId).into();
assert_eq!(passed_through.resolved_name, None);
@@ -507,7 +628,7 @@ mod tests {
let catalog = catalog_that_never_fetches(db);
let raw = raw_frame("a1.d", false, Some("[email protected]+3"));
- let resolved = raw.resolve_frame(1, &catalog).await.unwrap();
+ let resolved = raw.resolve_frame(1, &catalog, CONTEXT_LINES).await.unwrap();
assert_eq!(resolved.len(), 1);
let f = &resolved[0];
assert!(!f.resolved);
@@ -576,6 +697,179 @@ mod tests {
assert!(!id.chars().all(|c| c.is_ascii_hexdigit()), "{id}");
}
+ #[test]
+ fn pass_through_carries_source_context() {
+ let json = serde_json::json!({
+ "platform": "java",
+ "module": "com.acme.billing.InvoiceService",
+ "function": "charge",
+ "filename": "InvoiceService.java",
+ "lineno": 42,
+ "in_app": true,
+ "pre_context": [" void charge() {", " validate();"],
+ "context_line": " gateway.submit(invoice);",
+ "post_context": [" audit();", " }"],
+ });
+ let RawFrame::Java(raw) = serde_json::from_value(json).expect("valid java frame") else {
+ panic!("expected a java frame");
+ };
+
+ let f: Frame = (&raw, CONTEXT_LINES).into();
+ let ctx = f.context.expect("a pass-through frame carries its context");
+
+ assert_eq!(ctx.line.number, 42);
+ assert_eq!(ctx.line.line, " gateway.submit(invoice);");
+ // pre_context arrives furthest-line-first, and `before` is emitted outward from
+ // the context line, so the last input line lands first, at line 41.
+ assert_eq!(
+ ctx.before.iter().map(|l| l.number).collect::<Vec<_>>(),
+ vec![41, 40]
+ );
+ assert_eq!(ctx.before[0].line, " validate();");
+ assert_eq!(
+ ctx.after.iter().map(|l| l.number).collect::<Vec<_>>(),
+ vec![43, 44]
+ );
+ assert_eq!(ctx.after[0].line, " audit();");
+ }
+
+ #[test]
+ fn context_is_bounded_by_the_budget_keeping_the_nearest_lines() {
+ // Nothing stops a client from sending hundreds of surrounding lines, so the budget
+ // has to be enforced here rather than trusted.
+ let mut raw = raw_frame("com.acme.App", true, None);
+ raw.lineno = Some(100);
+ raw.context_line = Some(" boom();".to_string());
+ raw.pre_context = (90..100).map(|n| format!("line {n}")).collect();
+ raw.post_context = (101..111).map(|n| format!("line {n}")).collect();
+
+ let f: Frame = (&raw, 3).into();
+ let ctx = f.context.expect("context is present");
+
+ // Three lines each side, the ones closest to the context line, numbered outward.
+ assert_eq!(
+ ctx.before.iter().map(|l| l.number).collect::<Vec<_>>(),
+ vec![99, 98, 97]
+ );
+ assert_eq!(ctx.before[0].line, "line 99");
+ assert_eq!(
+ ctx.after.iter().map(|l| l.number).collect::<Vec<_>>(),
+ vec![101, 102, 103]
+ );
+ assert_eq!(ctx.after[2].line, "line 103");
+ }
+
+ #[test]
+ fn junked_raw_frame_respects_the_same_budget() {
+ // junk_drawer is persisted with the frame record, while Frame.context is not, so a
+ // bound that only covered get_context would still let oversized client input reach
+ // storage through here.
+ let mut raw = raw_frame("com.acme.App", true, None);
+ raw.lineno = Some(100);
+ raw.context_line = Some(" boom();".to_string());
+ raw.pre_context = (90..100).map(|n| format!("line {n}")).collect();
+ raw.post_context = (101..111).map(|n| format!("line {n}")).collect();
+
+ let passed_through: Frame = (&raw, 2).into();
+ let junked = &passed_through.junk_drawer.as_ref().unwrap()["raw_frame"];
+ assert_eq!(
+ junked["pre_context"],
+ serde_json::json!(["line 98", "line 99"])
+ );
+ assert_eq!(
+ junked["post_context"],
+ serde_json::json!(["line 101", "line 102"])
+ );
+
+ // Conversions that discard context store none of it, context_line included.
+ let failed: Frame = (&raw, ProguardError::NoMapId).into();
+ let junked = &failed.junk_drawer.as_ref().unwrap()["raw_frame"];
+ assert_eq!(junked["pre_context"], serde_json::json!([]));
+ assert_eq!(junked["post_context"], serde_json::json!([]));
+ assert_eq!(junked["context_line"], serde_json::Value::Null);
+ }
+
+ #[test]
+ fn junked_context_lines_are_length_capped() {
+ // Capping the entry count still leaves each line unbounded, so one enormous source
+ // line would otherwise be persisted in full on every record.
+ let mut raw = raw_frame("com.acme.App", true, None);
+ raw.lineno = Some(10);
+ raw.context_line = Some("c".repeat(5_000));
+ raw.pre_context = vec!["p".repeat(5_000)];
+ raw.post_context = vec!["q".repeat(5_000)];
+
+ let f: Frame = (&raw, CONTEXT_LINES).into();
+ let junked = &f.junk_drawer.as_ref().unwrap()["raw_frame"];
+
+ for value in [
+ &junked["context_line"],
+ &junked["pre_context"][0],
+ &junked["post_context"][0],
+ ] {
+ assert_eq!(value.as_str().unwrap().chars().count(), 300);
+ }
+ }
+
+ #[test]
+ fn absent_context_leaves_frame_and_hash_unchanged() {
+ // A frame with no context fields must produce no Frame.context and hash exactly as
+ // the fields-only construction does, so records stored under that id before these
+ // fields existed stay addressable.
+ let raw = raw_frame("com.acme.App", true, None);
+
+ let f: Frame = (&raw, CONTEXT_LINES).into();
+ assert_eq!(f.context, None);
+
+ // The fields-only stream: no context bytes appended at all.
+ let mut hasher = Sha512::new();
+ update_optional(&mut hasher, raw.filename.as_deref());
+ update_len_prefixed(&mut hasher, raw.function.as_bytes());
+ hasher.update([1u8]);
+ hasher.update((raw.lineno.unwrap() as u64).to_be_bytes());
+ update_len_prefixed(&mut hasher, raw.module.as_bytes());
+ update_optional(&mut hasher, raw.map_id.as_deref());
+ let base_id = format!("{FRAME_ID_VERSION}:{:x}", hasher.finalize());
+
+ assert_eq!(raw.frame_id(), base_id);
+
+ // Context does participate once it is present, so two frames that differ only in
+ // their captured source do not collide.
+ let with_ctx = RawJavaFrame {
+ context_line: Some(" doThing();".to_string()),
+ ..raw
+ };
+ assert_ne!(with_ctx.frame_id(), base_id);
+ }
+
+ #[test]
+ fn context_structure_does_not_alias_in_the_frame_id() {
+ // Concatenating the lines raw would make these collide, and since this id keys the
+ // frame cache and the stored record, a collision renders one frame's source on
+ // another.
+ let base = raw_frame("com.acme.App", true, None);
+ let split_a = RawJavaFrame {
+ pre_context: vec!["ab".to_string(), "c".to_string()],
+ ..base.clone()
+ };
+ let split_b = RawJavaFrame {
+ pre_context: vec!["a".to_string(), "bc".to_string()],
+ ..base.clone()
+ };
+ assert_ne!(split_a.frame_id(), split_b.frame_id());
+
+ // The same line on the other side of the context line is also a different frame.
+ let pre_only = RawJavaFrame {
+ pre_context: vec!["x".to_string()],
+ ..base.clone()
+ };
+ let post_only = RawJavaFrame {
+ post_context: vec!["x".to_string()],
+ ..base
+ };
+ assert_ne!(pre_only.frame_id(), post_only.frame_id());
+ }
+
#[test]
fn resolved_frames_under_application_id_promote_to_in_app() {
let mapping = proguard::ProguardMapping::new(PROGUARD_MAP.as_bytes());
diff --git a/rust/cymbal/src/modes/processing/stages/resolution/exception.rs b/rust/cymbal/src/modes/processing/stages/resolution/exception.rs
index 93758f8c8889..c389aee6d2d2 100644
--- a/rust/cymbal/src/modes/processing/stages/resolution/exception.rs
+++ b/rust/cymbal/src/modes/processing/stages/resolution/exception.rs
@@ -125,6 +125,9 @@ mod test {
function: "onClick".to_string(),
lineno: Some(14),
map_id: Some(map_id),
+ context_line: None,
+ pre_context: Vec::new(),
+ post_context: Vec::new(),
method_synthetic: false,
meta: CommonFrameMetadata::default(),
};