Skip to content

feat(traces): wire tracing into the client - #957

Merged
turnipdabeets merged 4 commits into
traces/08-before-span-sendfrom
traces/09-client-wiring
Sep 18, 2026
Merged

turnipdabeets merged 4 commits into
traces/08-before-span-sendfrom
traces/09-client-wiring

Conversation

@turnipdabeets

@turnipdabeets turnipdabeets commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Makes tracing usable. Adds the traces client option (tracing stays off until it is set), Client.start_span / get_active_span and their posthog module-level counterparts, with the active span scoped per client so two clients never parent to each other's spans.

  • flush() drains spans alongside events within the same budget.
  • shutdown() gives queued spans a final flush of up to 30 s and warns about any it discards.
  • An exit flush bounded by the existing exit deadline covers scripts that never call shutdown(), and a forked child drops the parent's spans.

Export failures, limits and the hook are documented on the option. Includes the changeset.

Stack (PR 9 of 9, based on traces/08-before-span-send):

  1. feat(traces): W3C trace context ids and traceparent parsing #949 traces/01-ids-traceparent
  2. feat(traces): OTLP span encoding and client-side validity #950 traces/02-otlp-encoding
  3. feat(traces): span handles #951 traces/03-span-handles
  4. feat(traces): span batch transport #952 traces/04-transport
  5. feat(traces): span pipeline #953 traces/05-pipeline
  6. feat(traces): span export queue with retries #954 traces/06-export
  7. feat(traces): per-span limits and exception stacktraces #955 traces/07-span-limits
  8. feat(traces): before_span_send hook #956 traces/08-before-span-send
  9. feat(traces): wire tracing into the client #957 traces/09-client-wiring ← this PR

💚 How did you test it?

Unit tests in posthog/test/tracing/test_client_traces.py cover the option, the client and module APIs, per-client active spans, flush, shutdown, exit flush and fork. The whole posthog/test/tracing suite was run on the rebased stack tip.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Implemented with Claude Code (Claude Opus 5) against the traces spec, one commit per slice so each PR reviews on its own. Rebased onto main and opened as a stacked draft in a later Claude Code session (Claude Fable 5.1).

🤖 Generated with Claude Code

https://claude.ai/code/session_012o7CtHLfcypjmXL7g9ZGRC

@turnipdabeets turnipdabeets self-assigned this Sep 14, 2026
@github-actions

github-actions Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-09-17 03:42:54 UTC
Duration: 256052ms

✅ 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 514ms
Endpoint And Method.Does Not Use Legacy Endpoints 509ms
Required Headers.Has Authorization Bearer Header 508ms
Required Headers.Has Content Type Json 510ms
Required Headers.Has Posthog Sdk Info Format 509ms
Required Headers.Has Posthog Attempt Header 508ms
Required Headers.Has Posthog Request Id 508ms
Required Headers.Has Posthog Request Timestamp 508ms
Required Headers.Has User Agent 509ms
Body Format.Body Has Created At And Batch 508ms
Body Format.No Api Key In Body 509ms
Body Format.No Sent At In Body 508ms
Event Format.Event Has Required Root Fields 508ms
Event Format.Event Uuid Is Valid 509ms
Event Format.Event Timestamp Is Rfc3339 508ms
Event Format.Distinct Id Is String 509ms
Event Format.Distinct Id At Root Not Properties 508ms
Event Format.Custom Properties Preserved 509ms
Event Format.Set Properties Preserved 508ms
Event Format.Set Once Properties Preserved 509ms
Event Format.Groups Properties Preserved 508ms
Event Format.Sdk Generates Uuid If Not Provided 508ms
Event Format.Event Has Required Root Fields Batch 512ms
Event Format.Event Uuid Is Valid Batch 511ms
Event Format.Event Timestamp Is Rfc3339 Batch 511ms
Event Format.Distinct Id Is String Batch 510ms
Event Format.Distinct Id At Root Not Properties Batch 512ms
Event Format.Custom Properties Preserved Batch 510ms
Event Format.Set Properties Preserved Batch 511ms
Event Format.Set Once Properties Preserved Batch 511ms
Event Format.Groups Properties Preserved Batch 511ms
Event Format.Sdk Generates Uuid If Not Provided Batch 511ms
Batch Behavior.Multiple Events In Single Batch 514ms
Batch Behavior.Batch Envelope Smoke 512ms
Batch Behavior.Flush With No Events Sends Nothing 505ms
Batch Behavior.Flush At Triggers Batch 1009ms
Batch Behavior.Created At Reflects Batch Creation Time 508ms
Deduplication.Generates Unique Uuids 514ms
Deduplication.Different Events Same Content Different Uuids 510ms
Deduplication.Preserves Uuid On Retry 6513ms
Deduplication.Preserves Timestamp On Retry 6517ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6520ms
Deduplication.No Duplicate Events In Batch 515ms
Header Behavior On Retry.Attempt Header Starts At One 508ms
Header Behavior On Retry.Attempt Header Increments On Retry 13517ms
Header Behavior On Retry.Request Id Preserved On Retry 6518ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3017ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6518ms
Response Format Validation.Success Response Has Uuid Keyed Results 509ms
Response Format Validation.Success Response Has Ok For Each Event 511ms
Response Format Validation.Success No Retry After When All Ok 510ms
Response Format Validation.Success Retry After Present When Retry Events 1513ms
Response Format Validation.Success No Retry After When Drop Only 511ms
Response Format Validation.Response Echoes Request Id 508ms
Retry Behavior.Retries On 408 6517ms
Retry Behavior.Retries On 500 6517ms
Retry Behavior.Retries On 503 8520ms
Retry Behavior.Retries On 504 6517ms
Retry Behavior.Retryable Errors Have Retry After 3515ms
Retry Behavior.Respects Retry After On Retryable Error 11514ms
Retry Behavior.Does Not Retry On 400 2512ms
Retry Behavior.Does Not Retry On 401 2511ms
Retry Behavior.Does Not Retry On 402 2511ms
Retry Behavior.Does Not Retry On 413 2512ms
Retry Behavior.Does Not Retry On 415 2509ms
Retry Behavior.Non Retryable Errors Have No Retry After 2513ms
Retry Behavior.Implements Backoff 22532ms
Retry Behavior.Max Retries Respected 22522ms
Partial Batch Handling.Handles 200 Full Success 2511ms
Partial Batch Handling.Handles 200 With All Ok 3515ms
Partial Batch Handling.Does Not Retry Dropped Events 3511ms
Partial Batch Handling.Does Not Retry Limited Events 3511ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6519ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6518ms
Partial Batch Handling.Retries Only Retry Events From Partial 6520ms
Partial Batch Handling.Partial Retry Preserves Uuids 6519ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6518ms
Partial Batch Handling.Partial Retry Request Id Preserved 6515ms
Partial Batch Handling.Respects Retry After On Partial 8514ms
Partial Batch Handling.Unknown Result Treated As Terminal 3513ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 3517ms
Compression.Sends Gzip Content Encoding 509ms
Compression.No Content Encoding When Disabled 508ms
Compression.Compressed Body Is Decompressible 508ms
Error Handling.Does Not Retry On Unknown 4Xx 2510ms
Event Options.Cookieless Mode Override 508ms
Event Options.Disable Skew Correction Override 508ms
Event Options.Process Person Profile Override 509ms
Event Options.Product Tour Id Override 508ms
Event Options.Unset Options Omitted 508ms
Event Options.Options Override In Batch 510ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 508ms
Geoip And Historical Migration.Historical Migration Set In Body 508ms
Geoip And Historical Migration.Historical Migration Absent By Default 508ms

Feature_Flags Tests

17/17 tests passed

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

@greptile-apps

greptile-apps Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor
Prompt To Fix All With AI
### Issue 1
posthog/client.py:2685-2688
**Exit flush exceeds its deadline**

If thread creation is rejected during interpreter shutdown, this fallback runs the span flush synchronously. The exporter permits its first request even when no budget remains, and that request uses the client's timeout (15 seconds by default). Each client can therefore delay process exit well beyond the shared one-second deadline. Use a worker started before interpreter shutdown for exit flushing rather than falling back to synchronous network I/O, and test the rejected-thread path with a slow request.

### Issue 2
posthog/client.py:2514-2519
**Tracing initialization races with shutdown**

If shutdown runs after the initial state check but before the pipeline assignment, it sees `_traces is None` and completes without closing tracing. Initialization then publishes an open pipeline, and ending the span can start background exports after shutdown has returned. Subsequent shutdown calls skip cleanup because it is already marked complete. Coordinate pipeline initialization and shutdown with shared synchronization so shutdown cannot miss an in-progress initialization.

### Issue 3
posthog/client.py:2278-2281
**Fork cleanup restores inherited spans**

Setting the active ContextVar to `None` does not invalidate tokens held by inherited spans. When a process forks inside nested span blocks, exiting the inherited inner block in the child resets its old token and restores the parent process's outer span. Subsequent child spans then attach to that inherited span, violating fork isolation. Create a fresh active-span ContextVar in the child and rebind the pipeline to it, leaving inherited handles attached to the old variable. Add a nested-span fork test that checks parenting after the inner block exits.

---

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

Reviews (1): Last reviewed commit: "feat(traces): wire tracing into the clie..." | Re-trigger Greptile

Comment thread posthog/client.py Outdated
Comment thread posthog/client.py
Comment thread posthog/client.py Outdated
@greptile-apps

greptile-apps Bot commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Reviews (2): Last reviewed commit: "fix(traces): keep shutdown and fork isol..." | Re-trigger Greptile

Comment thread posthog/client.py
@veria-ai

veria-ai Bot commented Sep 16, 2026

Copy link
Copy Markdown

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 2 · PR risk: 0/10

@jzhu13 jzhu13 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewed against traces/08-before-span-send, and the rest of the stack from #949 up. Tests pass at the head, ruff, mypy, and the public API snapshot are clean. The lazy init under _traces_lock and the shutdown re-check are sound. Four items I would fix before merge; two of them are inherited from #954 and are best fixed there.

Blocking

  1. posthog/__init__.py:1397 setup() runs on every module-level _proxy call and re-applies posthog.traces whenever default_client._traces is None. Reproduced: posthog.default_client = Posthog(key, traces={"service_name": "svc"}) followed by posthog.capture(...) before any span was recorded sets _traces_config to None, and posthog.start_span() returns NoopSpan for the life of the client. The line mirrors _metrics_config, but metrics=None means defaults-on while traces=None means off. It also undoes the init-failure latch at client.py:2542, so a failing init is retried and re-logged on every call. Suggest syncing only when traces is not None.
  2. posthog/client.py:2890 traces.flush(30.0) then traces.close(): the 30 s budget is never used for a retry because SpanExporter._drain stops on the first retry-later and flush skips the follow-up pass (#954 item 1). Reproduced: 3 queued spans, one 503 then ok, shutdown completed in under 1 s with 1 send and Discarding 3 span(s). Events in the same shutdown get lane retries with backoff. Fix in #954, or loop the flush here while queued and before the deadline.
  3. posthog/client.py:2639 the docstring's "at least one span request is attempted even when the budget is already spent" is false when the timer flush holds _flush_lock (#954 item 2). Reproduced: client.flush(timeout_seconds=0.2) during a slow timer request returned at 0.20 s with 0 requests, 2 spans queued, and no warning. A serverless runtime freezes the process and the spans are lost silently.
  4. posthog/client.py:2665 span_flush.join() is untimed. Measured: flush(timeout_seconds=0.2) with one queued span and a 3 s stalled request blocked 3.01 s, so the bound is timeout_seconds + client.timeout (15 s default). The exit paths bound the same join via _join_span_flush. Serverless handlers and PosthogCeleryIntegration.shutdown() hit this path. Either bound the join or document the worst case.

Non-blocking, recommended

  1. posthog/__init__.py:15 from posthog.tracing.span import Span in the bare form is private under pyright strict in this py.typed package: from posthog import Span errors with reportPrivateImportUsage (reproduced with pyright and basedpyright), while the snapshot advertises posthog.Span. Adjacent re-exports use X as X. check_strict_types.sh never imports Span, so CI cannot catch it.
  2. posthog/client.py:2537 atexit.register(self._atexit_spans) per sync-mode client is never unregistered, including by shutdown(). Reproduced: 20 short-lived sync clients that recorded a span stayed alive after shutdown() and gc.collect(), sole referrer the bound method. Sync-mode clients were previously collectable. atexit.unregister in _shutdown_once, or one module-level hook over the existing _client_registry WeakSet.
  3. posthog/client.py:2691 the inline fallback when Thread.start() raises runs the span flush before the lane flushes in _atexit, so under a container thread limit a slow traces endpoint (exempt first request, up to 15 s) leaves the lanes 0 s of the 1 s exit budget. Run lanes first on that path.
  4. Nits: _start_span_flush spawns a thread even with no spans queued, since it only checks _traces is None; reinit_after_fork(active_var=None) in _pipeline.py:117 has no production caller that omits the argument, and omitting it silently keeps the parent's ContextVar, so make it required; TRACE_ID/SPAN_ID, mock_session, and three copies of slow_send in test_client_traces.py duplicate helpers.py; a forked child loses span parenting (consistent with posthog.contexts, but worth one line in the start_span docstring pointing at parent=span).

Two things I could not verify from the repo: whether the public API shape was agreed on an issue first (CONTRIBUTING), and whether the changeset text is meant to cover AsyncClient, which gets neither the traces option nor the span methods.

Reviewed with Claude Code (Claude Fable 5.1). Behaviors above were reproduced against this branch head.

@turnipdabeets
turnipdabeets force-pushed the traces/09-client-wiring branch 2 times, most recently from 98856b0 to f2bba20 Compare September 17, 2026 01:22
Comment thread posthog/client.py
@turnipdabeets

Copy link
Copy Markdown
Contributor Author

Thanks. Fixed in f2bba20:

  • 1: setup() no longer overrides an explicit client config, and a failed init latches.
  • 5: Span is re-exported for pyright strict and covered by check_strict_types.sh.
  • 6: the sync-mode atexit hook is unregistered on shutdown.
  • 8: fork ContextVar is required, start_span docstring says what a forked child inherits. flush documents its worst case (item 4).
  • 2 and 3 depend on feat(traces): span export queue with retries #954 items 1 and 2. Item 7 and the empty-flush thread are still open.

@turnipdabeets
turnipdabeets force-pushed the traces/09-client-wiring branch from f2bba20 to c44a14c Compare September 17, 2026 02:08
@turnipdabeets

Copy link
Copy Markdown
Contributor Author

Follow-up, c44a14c:

  • 2 and 3: covered by feat(traces): span export queue with retries #954 (retry within the shutdown budget, budget starts once the lock is held). The flush docstring now states that contract.
  • 7: _start_span_flush hands back a waiter; when no thread can start, the caller runs it after the event lanes.
  • 8: no span thread when nothing is queued; test fixtures moved to a conftest.py, ids and the slow sender deduplicated.
    Ready for another look.

turnipdabeets and others added 4 commits September 16, 2026 23:36
Makes tracing usable. Adds the `traces` client option (tracing stays off until
it is set), Client.start_span / get_active_span and their posthog module-level
counterparts, with the active span scoped per client so two clients never
parent to each other's spans. flush() drains spans alongside events within the
same budget; shutdown() gives queued spans a final flush of up to 30 s and warns
about any it discards; an exit flush bounded by the existing exit deadline
covers scripts that never call shutdown(), and a forked child drops the
parent's spans. Export failures, limits and the hook are documented on the
option.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TkZAsCciW4PV8ZdcCHmAbA
Shutdown reads the pipeline under the same lock initialization publishes
it with, so an initialization in flight is either closed by shutdown or
sees the request and stays off. A forked child gets a fresh active-span
variable: an inherited handle exiting in the child resets the old one,
which would have restored the parent process's outer span.
…ces config off

setup() runs on every module-level call and re-applied posthog.traces
whenever no pipeline existed yet, so a default client built with its own
traces config lost it on the first capture(), and a failed init was
retried and re-logged on every call. The module option now applies only
where the client has none, and a failed init latches as False. Shutdown
unregisters the sync-mode exit drain so the client is collectable, the
flush docstring states its worst case, Span is re-exported for pyright
strict and checked in CI, the fork ContextVar is required, and the
start_span docstring says what a forked child inherits.
…e span thread when nothing is queued

When no thread could start at exit, the span flush ran before the event
lanes and could spend the whole exit budget. _start_span_flush now hands
back a waiter the caller runs after the lanes, and starts nothing when
the span queue is empty. The flush docstring describes the retry-within-
budget contract. Tracing test fixtures move to a conftest, and the client
tests reuse the shared ids and one slow sender.
@turnipdabeets
turnipdabeets force-pushed the traces/09-client-wiring branch from c44a14c to 71b482d Compare September 17, 2026 03:37

@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.

found same issue as here but lgtm if its ok as is

@turnipdabeets

Copy link
Copy Markdown
Contributor Author

Docs for this stack, as drafts to merge after the release: PostHog/posthog.com#20285 (Python library page and tracing install guide), PostHog/posthog#102724 (tracing empty state), PostHog/context-mill#399 (tracing agent skill).

@turnipdabeets
turnipdabeets merged commit 7abd976 into main Sep 18, 2026
49 of 77 checks passed
@turnipdabeets
turnipdabeets deleted the traces/09-client-wiring branch September 18, 2026 14:11
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.

3 participants