Skip to content

feat: opt-in OTel trace/span IDs on regular capture() via capture_trace_context - #894

Merged
DanielVisca merged 4 commits into
mainfrom
posthog/capture-trace-context
Aug 25, 2026
Merged

feat: opt-in OTel trace/span IDs on regular capture() via capture_trace_context#894
DanielVisca merged 4 commits into
mainfrom
posthog/capture-trace-context

Conversation

@DanielVisca

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Today posthog-python only attaches OpenTelemetry trace_id/span_id to $exception events (capture_exception). Regular capture() events carry no OTel trace context, so they can't be correlated with backend traces. This adds an opt-in capture_trace_context client option that generalizes the existing behavior to capture()/capture_ai(), reusing the same _get_current_otel_span_properties() helper.

  • Default is off — zero behavior change for existing clients.
  • Explicit $trace_id/$span_id passed in properties win over the OTel span.
  • No-op when OTel isn't installed or no valid span is active.

💚 How did you test it?

TDD — failing tests first, then implementation:

  • test_capture_uses_current_otel_span_context_when_enabled (active span, explicit-properties-win, invalid span)
  • test_capture_does_not_attach_otel_span_context_by_default

End-to-end: real Client.capture() POST against a local mock ingestion endpoint, inside an active OTel span, dumping the server-side payload before vs after:

E2E before/after

pytest posthog/test/test_client.py posthog/test/test_exception_capture.py -q
226 passed

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed. (docstrings + public API snapshot)
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add — N/A, no release requested; changeset left to maintainer release flow

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

  • Built with Claude Code (PostHog Desktop).
  • Scope kept deliberately small: one client option, one capture-time merge, reusing _get_current_otel_span_properties() rather than duplicating OTel logic. Explicit-properties-win precedence mirrors capture_exception().
  • Validated red→green locally, then E2E via real HTTP POST against a local collector to confirm the wire payload changes only when the option is enabled.

Created with PostHog Desktop

…ce_context

Attach the active OpenTelemetry span's trace_id/span_id as `$trace_id`/`$span_id` properties on events captured with `capture()`/`capture_ai()`, behind an opt-in `capture_trace_context` client option. Reuses the existing `_get_current_otel_span_properties()` helper already used by `capture_exception()`. Explicit `$trace_id`/`$span_id` in properties win; default is off, so no behavior change for existing clients.

Generated-By: PostHog Desktop
Task-Id: 44c7be3e-4938-4f9a-bb80-89fd9d74db6d
@github-actions

github-actions Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-08-25 14:17:02 UTC
Duration: 256424ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 517ms
Endpoint And Method.Does Not Use Legacy Endpoints 511ms
Required Headers.Has Authorization Bearer Header 510ms
Required Headers.Has Content Type Json 511ms
Required Headers.Has Posthog Sdk Info Format 510ms
Required Headers.Has Posthog Attempt Header 511ms
Required Headers.Has Posthog Request Id 510ms
Required Headers.Has Posthog Request Timestamp 511ms
Required Headers.Has User Agent 510ms
Body Format.Body Has Created At And Batch 510ms
Body Format.No Api Key In Body 511ms
Body Format.No Sent At In Body 510ms
Event Format.Event Has Required Root Fields 512ms
Event Format.Event Uuid Is Valid 512ms
Event Format.Event Timestamp Is Rfc3339 510ms
Event Format.Distinct Id Is String 510ms
Event Format.Distinct Id At Root Not Properties 510ms
Event Format.Custom Properties Preserved 511ms
Event Format.Set Properties Preserved 510ms
Event Format.Set Once Properties Preserved 512ms
Event Format.Groups Properties Preserved 510ms
Event Format.Sdk Generates Uuid If Not Provided 510ms
Event Format.Event Has Required Root Fields Batch 515ms
Event Format.Event Uuid Is Valid Batch 514ms
Event Format.Event Timestamp Is Rfc3339 Batch 515ms
Event Format.Distinct Id Is String Batch 513ms
Event Format.Distinct Id At Root Not Properties Batch 514ms
Event Format.Custom Properties Preserved Batch 513ms
Event Format.Set Properties Preserved Batch 514ms
Event Format.Set Once Properties Preserved Batch 514ms
Event Format.Groups Properties Preserved Batch 513ms
Event Format.Sdk Generates Uuid If Not Provided Batch 513ms
Batch Behavior.Multiple Events In Single Batch 518ms
Batch Behavior.Batch Envelope Smoke 516ms
Batch Behavior.Flush With No Events Sends Nothing 506ms
Batch Behavior.Flush At Triggers Batch 1011ms
Batch Behavior.Created At Reflects Batch Creation Time 511ms
Deduplication.Generates Unique Uuids 518ms
Deduplication.Different Events Same Content Different Uuids 512ms
Deduplication.Preserves Uuid On Retry 6519ms
Deduplication.Preserves Timestamp On Retry 6521ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6520ms
Deduplication.No Duplicate Events In Batch 518ms
Header Behavior On Retry.Attempt Header Starts At One 510ms
Header Behavior On Retry.Attempt Header Increments On Retry 13528ms
Header Behavior On Retry.Request Id Preserved On Retry 6520ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3020ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6520ms
Response Format Validation.Success Response Has Uuid Keyed Results 510ms
Response Format Validation.Success Response Has Ok For Each Event 516ms
Response Format Validation.Success No Retry After When All Ok 513ms
Response Format Validation.Success Retry After Present When Retry Events 1516ms
Response Format Validation.Success No Retry After When Drop Only 513ms
Response Format Validation.Response Echoes Request Id 511ms
Retry Behavior.Retries On 408 6519ms
Retry Behavior.Retries On 500 6519ms
Retry Behavior.Retries On 503 8524ms
Retry Behavior.Retries On 504 6520ms
Retry Behavior.Retryable Errors Have Retry After 3517ms
Retry Behavior.Respects Retry After On Retryable Error 11522ms
Retry Behavior.Does Not Retry On 400 2515ms
Retry Behavior.Does Not Retry On 401 2513ms
Retry Behavior.Does Not Retry On 402 2512ms
Retry Behavior.Does Not Retry On 413 2515ms
Retry Behavior.Does Not Retry On 415 2513ms
Retry Behavior.Non Retryable Errors Have No Retry After 2514ms
Retry Behavior.Implements Backoff 22537ms
Retry Behavior.Max Retries Respected 22537ms
Partial Batch Handling.Handles 200 Full Success 2512ms
Partial Batch Handling.Handles 200 With All Ok 3517ms
Partial Batch Handling.Does Not Retry Dropped Events 3516ms
Partial Batch Handling.Does Not Retry Limited Events 3516ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6517ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6522ms
Partial Batch Handling.Retries Only Retry Events From Partial 6524ms
Partial Batch Handling.Partial Retry Preserves Uuids 6522ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6521ms
Partial Batch Handling.Partial Retry Request Id Preserved 6518ms
Partial Batch Handling.Respects Retry After On Partial 8522ms
Partial Batch Handling.Unknown Result Treated As Terminal 3516ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 3520ms
Compression.Sends Gzip Content Encoding 511ms
Compression.No Content Encoding When Disabled 510ms
Compression.Compressed Body Is Decompressible 511ms
Error Handling.Does Not Retry On Unknown 4Xx 2514ms
Event Options.Cookieless Mode Override 511ms
Event Options.Disable Skew Correction Override 510ms
Event Options.Process Person Profile Override 510ms
Event Options.Product Tour Id Override 510ms
Event Options.Unset Options Omitted 511ms
Event Options.Options Override In Batch 513ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 511ms
Geoip And Historical Migration.Historical Migration Set In Body 510ms
Geoip And Historical Migration.Historical Migration Absent By Default 510ms

Feature_Flags Tests

17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 11ms
Request Payload.Flags Request Uses V2 Query Param 10ms
Request Payload.Flags Request Hits Flags Path Not Decide 9ms
Request Payload.Flags Request Omits Authorization Header 9ms
Request Payload.Token In Flags Body Matches Init 9ms
Request Payload.Groups Round Trip 10ms
Request Payload.Groups Default To Empty Object 9ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 9ms
Request Payload.Disable Geoip Omitted Defaults To False 10ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 9ms
Request Lifecycle.No Flags Request On Init Alone 3ms
Request Lifecycle.No Flags Request On Normal Capture 510ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 14ms
Request Lifecycle.Mock Response Value Is Returned To Caller 9ms
Retry Behavior.Retries Flags On 502 314ms
Retry Behavior.Retries Flags On 504 313ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 512ms

The initial snapshot was generated under Python 3.12, but CI runs the check under 3.11.11 and griffe's AST unparsing differs across versions (self._ph_client -> (self._ph_client), Callable[..., Any] -> (Callable[..., Any])). Regenerated in a pinned 3.11.11 uv env matching CI (uv sync --extra dev), so `make public_api_check` now passes there. No code changes.

Generated-By: PostHog Desktop
Task-Id: 44c7be3e-4938-4f9a-bb80-89fd9d74db6d
@DanielVisca
DanielVisca marked this pull request as ready for review August 24, 2026 22:53
@DanielVisca
DanielVisca requested a review from a team as a code owner August 24, 2026 22:53
@greptile-apps

greptile-apps Bot commented Aug 24, 2026

Copy link
Copy Markdown
Contributor
Prompt To Fix All With AI
### Issue 1
posthog/client.py:692
**Constructor arguments shift positionally**

If an existing external caller passes `code_variables_mask_patterns` or any later `Client`/`Posthog` option positionally, inserting `capture_trace_context` here shifts every subsequent value to the wrong setting. This can unintentionally enable trace-property capture and misconfigure masking, exception capture, capture mode, compression, or initialization behavior.

### Issue 2
posthog/test/test_client.py:649-682
**Trace tests omit capture_ai**

The feature explicitly covers both `capture()` and `capture_ai()`, but these tests exercise only `capture()`. Parameterizing the entrypoint would ensure a regression in the dedicated AI capture path cannot pass while breaking the newly documented trace-correlation behavior.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Reviews (1): Last reviewed commit: "chore: regenerate public API snapshot un..." | Re-trigger Greptile

Comment thread posthog/client.py Outdated
enable_local_evaluation=True,
flag_definition_cache_provider: Optional[FlagDefinitionCacheProvider] = None,
capture_exception_code_variables=False,
capture_trace_context=False,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Constructor arguments shift positionally

If an existing external caller passes code_variables_mask_patterns or any later Client/Posthog option positionally, inserting capture_trace_context here shifts every subsequent value to the wrong setting. This can unintentionally enable trace-property capture and misconfigure masking, exception capture, capture mode, compression, or initialization behavior.

Knowledge Base Used: Client lifecycle and configuration

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/client.py
Line: 692

Comment:
**Constructor arguments shift positionally**

If an existing external caller passes `code_variables_mask_patterns` or any later `Client`/`Posthog` option positionally, inserting `capture_trace_context` here shifts every subsequent value to the wrong setting. This can unintentionally enable trace-property capture and misconfigure masking, exception capture, capture mode, compression, or initialization behavior.

**Knowledge Base Used:** [Client lifecycle and configuration](https://app.greptile.com/posthog-org-19734/-/custom-context/knowledge-base/posthog/posthog-python/-/docs/client-lifecycle-and-configuration.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Comment on lines +649 to +682
def test_capture_uses_current_otel_span_context_when_enabled(
self,
_,
context_trace_id,
context_span_id,
properties,
expected_trace_id,
expected_span_id,
):
span_context = SpanContext(
trace_id=context_trace_id,
span_id=context_span_id,
is_remote=False,
trace_flags=TraceFlags.SAMPLED,
)

with (
mock.patch("posthog.client.batch_post") as mock_post,
use_span(NonRecordingSpan(span_context)),
):
client = Client(
FAKE_TEST_API_KEY, sync_mode=True, capture_trace_context=True
)
client.capture(
"test_event", distinct_id="distinct_id", properties=properties
)

event = mock_post.call_args.kwargs["batch"][0]
if expected_trace_id is None:
self.assertNotIn("$trace_id", event["properties"])
self.assertNotIn("$span_id", event["properties"])
else:
self.assertEqual(event["properties"]["$trace_id"], expected_trace_id)
self.assertEqual(event["properties"]["$span_id"], expected_span_id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Trace tests omit capture_ai

The feature explicitly covers both capture() and capture_ai(), but these tests exercise only capture(). Parameterizing the entrypoint would ensure a regression in the dedicated AI capture path cannot pass while breaking the newly documented trace-correlation behavior.

Knowledge Base Used: Event capture and delivery

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/test/test_client.py
Line: 649-682

Comment:
**Trace tests omit capture_ai**

The feature explicitly covers both `capture()` and `capture_ai()`, but these tests exercise only `capture()`. Parameterizing the entrypoint would ensure a regression in the dedicated AI capture path cannot pass while breaking the newly documented trace-correlation behavior.

**Knowledge Base Used:** [Event capture and delivery](https://app.greptile.com/posthog-org-19734/-/custom-context/knowledge-base/posthog/posthog-python/-/docs/event-capture-and-delivery.md)

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@marandaneto marandaneto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated advisory code review.

Comment thread posthog/client.py Outdated
enable_local_evaluation=True,
flag_definition_cache_provider: Optional[FlagDefinitionCacheProvider] = None,
capture_exception_code_variables=False,
capture_trace_context=False,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blocking: Preserve existing positional constructor arguments — Inserting capture_trace_context in the middle of the public, non-keyword-only Client signature shifts every later positional argument. Existing callers passing code_variables_mask_patterns or subsequent settings positionally will silently assign those values to the wrong options, potentially enabling trace capture and misconfiguring code-variable redaction despite the advertised opt-in default. Append the new argument instead so existing calls retain their meaning.

Comment thread posthog/client.py
properties = {**(properties or {}), **system_context()}

if self.capture_trace_context:
properties = {**_get_current_otel_span_properties(), **properties}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

blocking: Super properties override explicit trace IDs — The documented “explicit properties win” guarantee does not hold when super_properties contains $trace_id or $span_id: _enqueue() merges super properties afterward with higher precedence, replacing both the current span and values passed directly to capture(). A reproduced event passed event-trace/event-span but sent super-trace/super-span, causing incorrect trace correlation.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

if thats intentional, thats ok

@marandaneto
marandaneto requested review from a team August 25, 2026 09:26
…eir slots

Inserting the option next to capture_exception_code_variables shifted every later Client/Posthog parameter by one position, so a caller passing code_variables_mask_patterns (or anything after it) positionally would silently land on the wrong setting. Move it to the end of the public parameters, matching how secret_key and metrics were appended rather than grouped with their related options. Snapshot regenerated under Python 3.11.11 to match CI.

Generated-By: PostHog Desktop
Task-Id: 44c7be3e-4938-4f9a-bb80-89fd9d74db6d
The option is documented as applying to both capture() and capture_ai(), but the tests only exercised capture(). Parameterize the entrypoint so a future divergence of capture_ai from the shared _capture path breaks the documented trace-correlation behavior instead of passing silently. Verified by mutation: gating the injection on the analytics lane fails capture_ai_active_context.

Generated-By: PostHog Desktop
Task-Id: 44c7be3e-4938-4f9a-bb80-89fd9d74db6d

Copy link
Copy Markdown
Contributor Author

Both comments were correct, pushed fixes.

capture_trace_context now sits at the end of the constructor so existing positional args keep their slots, and the trace context tests are parameterized over both capture() and capture_ai().

@DanielVisca
DanielVisca merged commit 550f5b5 into main Aug 25, 2026
42 checks passed
@DanielVisca
DanielVisca deleted the posthog/capture-trace-context branch August 25, 2026 16:09
DanielVisca added a commit that referenced this pull request Aug 25, 2026
PR #894 merged without a changeset, so Sampo has nothing pending and the option won't be published. Adds the missing minor changeset for the already-merged capture_trace_context option.

Generated-By: PostHog Desktop
Task-Id: 44c7be3e-4938-4f9a-bb80-89fd9d74db6d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants