Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .sampo/changesets/exception-trace-sampled.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
pypi/posthog: patch
---

`capture_exception` (and `capture` with `capture_trace_context`) now adds `$trace_sampled` next to the active OpenTelemetry span's `$trace_id` and `$span_id`. An unsampled trace still has a valid trace ID, so the SDK attaches it, but the trace itself is never exported. `$trace_sampled` tells readers such as error tracking's trace tab whether a stored trace can exist before they look it up. Like the trace and span IDs, it is only added when the event, context tags and super properties set neither `$trace_id` nor `$span_id`.
11 changes: 9 additions & 2 deletions posthog/capture_event.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,10 @@ def _build_event_defaults(
)


# Only these two keys point at a span, so only they suppress the SDK's ids.
_TRACE_ID_PROPERTIES = ("$trace_id", "$span_id")


def _fill_event_defaults(
msg: dict[str, Any], defaults: Optional[_EventDefaults]
) -> None:
Expand Down Expand Up @@ -273,10 +277,13 @@ def _fill_event_defaults(
):
properties[key] = {**_clean(dict(value)), **existing}
# A trace id and a span id from different spans would point at no real span,
# so a value for either key from any layer keeps out both of the SDK's ids.
# so a value for either key from any layer keeps out all of the SDK's trace
# properties. A caller-set `$trace_sampled` alone keeps its value.
trace_properties = defaults.trace_properties or {}
if not any(key in properties for key in trace_properties):
if not any(key in properties for key in _TRACE_ID_PROPERTIES):
for key, value in trace_properties.items():
if key in properties:
continue
if allowlist is None or key in allowlist:
properties[key] = _clean(value)
if defaults.library is not None:
Expand Down
5 changes: 4 additions & 1 deletion posthog/exception_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@
)


def _get_current_otel_span_properties() -> Dict[str, str]:
def _get_current_otel_span_properties() -> Dict[str, Any]:
try:
from opentelemetry import trace
except ImportError:
Expand All @@ -113,9 +113,12 @@ def _get_current_otel_span_properties() -> Dict[str, str]:
span_context = trace.get_current_span().get_span_context()
if not span_context.is_valid:
return {}
# An unsampled trace has a valid ID but is never exported, so readers need to
# know whether a stored trace can exist before they look one up.
return {
"$trace_id": f"{span_context.trace_id:032x}",
"$span_id": f"{span_context.span_id:016x}",
"$trace_sampled": bool(int(span_context.trace_flags) & 0x01),
Comment thread
DanielVisca marked this conversation as resolved.
Resolved
}
except Exception:
return {}
Expand Down
70 changes: 70 additions & 0 deletions posthog/test/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -772,6 +772,76 @@ def test_capture_uses_current_otel_span_context_when_enabled(
self.assertEqual(event["properties"]["$trace_id"], expected_trace_id)
self.assertEqual(event["properties"]["$span_id"], expected_span_id)

@parameterized.expand(
[
("sampled", TraceFlags.SAMPLED, True),
("not_sampled", TraceFlags.DEFAULT, False),
]
)
def test_capture_exception_marks_whether_the_trace_was_sampled(
self, _, trace_flags, expected_sampled
):
span_context = SpanContext(
trace_id=0x123,
span_id=0x456,
is_remote=False,
trace_flags=TraceFlags(trace_flags),
)

with (
patch_capture_send("client") as mock_post,
use_span(NonRecordingSpan(span_context)),
):
client = Client(FAKE_TEST_API_KEY, sync_mode=True)
client.capture_exception(Exception("test exception"))

properties = sent_batch(mock_post)[0]["properties"]
self.assertEqual(properties["$trace_id"], "00000000000000000000000000000123")
self.assertIs(properties["$trace_sampled"], expected_sampled)

def test_capture_exception_explicit_trace_id_skips_trace_sampled(self):
span_context = SpanContext(
trace_id=0x123,
span_id=0x456,
is_remote=False,
trace_flags=TraceFlags.SAMPLED,
)

with (
patch_capture_send("client") as mock_post,
use_span(NonRecordingSpan(span_context)),
):
client = Client(FAKE_TEST_API_KEY, sync_mode=True)
client.capture_exception(
Exception("test exception"), properties={"$trace_id": "custom-trace"}
)

properties = sent_batch(mock_post)[0]["properties"]
self.assertEqual(properties["$trace_id"], "custom-trace")
self.assertNotIn("$trace_sampled", properties)

def test_capture_exception_caller_trace_sampled_keeps_automatic_ids(self):
span_context = SpanContext(
trace_id=0x123,
span_id=0x456,
is_remote=False,
trace_flags=TraceFlags.SAMPLED,
)

with (
patch_capture_send("client") as mock_post,
use_span(NonRecordingSpan(span_context)),
):
client = Client(FAKE_TEST_API_KEY, sync_mode=True)
client.capture_exception(
Exception("test exception"), properties={"$trace_sampled": False}
)

properties = sent_batch(mock_post)[0]["properties"]
self.assertEqual(properties["$trace_id"], "00000000000000000000000000000123")
self.assertEqual(properties["$span_id"], "0000000000000456")
self.assertIs(properties["$trace_sampled"], False)

@parameterized.expand([("capture",), ("capture_ai",)])
def test_capture_does_not_attach_otel_span_context_by_default(self, entrypoint):
span_context = SpanContext(
Expand Down
Loading