From 19b03636f7785dabd6769aaec54548767dcb13e4 Mon Sep 17 00:00:00 2001 From: Daniel Visca Date: Tue, 17 Nov 2026 12:28:27 -0800 Subject: [PATCH 1/2] fix: mark whether the exception's trace was sampled capture_exception attaches the active span's trace ID even when the trace is not sampled, so readers look up traces that were never exported. Add $trace_sampled next to $trace_id and $span_id. Co-Authored-By: Claude Opus 5.5 --- .sampo/changesets/exception-trace-sampled.md | 5 ++ posthog/exception_utils.py | 5 +- posthog/test/test_client.py | 48 ++++++++++++++++++++ 3 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 .sampo/changesets/exception-trace-sampled.md diff --git a/.sampo/changesets/exception-trace-sampled.md b/.sampo/changesets/exception-trace-sampled.md new file mode 100644 index 000000000..71c41be58 --- /dev/null +++ b/.sampo/changesets/exception-trace-sampled.md @@ -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`. diff --git a/posthog/exception_utils.py b/posthog/exception_utils.py index da0d1dbcd..de8859314 100644 --- a/posthog/exception_utils.py +++ b/posthog/exception_utils.py @@ -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: @@ -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), } except Exception: return {} diff --git a/posthog/test/test_client.py b/posthog/test/test_client.py index 5381af3db..857aff5e2 100644 --- a/posthog/test/test_client.py +++ b/posthog/test/test_client.py @@ -772,6 +772,54 @@ 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) + @parameterized.expand([("capture",), ("capture_ai",)]) def test_capture_does_not_attach_otel_span_context_by_default(self, entrypoint): span_context = SpanContext( From f3f6b4424075823cd31a14f8cde191fadf012d33 Mon Sep 17 00:00:00 2001 From: Daniel Visca Date: Tue, 17 Nov 2026 12:55:04 -0800 Subject: [PATCH 2/2] fix: keep automatic trace IDs when only trace_sampled is supplied Co-Authored-By: Claude Sonnet 5.5 --- posthog/capture_event.py | 11 +++++++++-- posthog/test/test_client.py | 22 ++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/posthog/capture_event.py b/posthog/capture_event.py index 9d8886305..269f09848 100644 --- a/posthog/capture_event.py +++ b/posthog/capture_event.py @@ -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: @@ -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: diff --git a/posthog/test/test_client.py b/posthog/test/test_client.py index 857aff5e2..935cfed52 100644 --- a/posthog/test/test_client.py +++ b/posthog/test/test_client.py @@ -820,6 +820,28 @@ def test_capture_exception_explicit_trace_id_skips_trace_sampled(self): 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(