Skip to content

feat(traces): span pipeline - #953

Merged
turnipdabeets merged 5 commits into
traces/04-transportfrom
traces/05-pipeline
Sep 18, 2026
Merged

turnipdabeets merged 5 commits into
traces/04-transportfrom
traces/05-pipeline

Conversation

@turnipdabeets

@turnipdabeets turnipdabeets commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Adds span creation and the end-of-span gates. PostHogTraces resolves a span's parent (an explicit traceparent string or handle, else the active span, else a new trace), attaches the posthogDistinctId and sessionId join keys from the request context, bounds live spans by count and by age so a leak cannot disable tracing, and hands each ended span to an exporter unless the client was disabled.

The traces option is validated key by key, falling back to the documented default with a warning. Dropped spans are counted per reason and reported at most once per flush interval.

The export queue arrives in the next PR; this one runs against a stand-in. Not reachable from the client yet.

Stack (PR 5 of 9, based on traces/04-transport):

  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 ← this PR
  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

💚 How did you test it?

Unit tests in posthog/test/tracing/test_pipeline.py and test_config.py cover parent resolution, join keys, live-span bounds, option validation and drop reporting.

📝 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
@greptile-apps

greptile-apps Bot commented Sep 14, 2026

Copy link
Copy Markdown
Contributor
Prompt To Fix All With AI
### Issue 1
posthog/tracing/_pipeline.py:148-156
**Shutdown race creates spans**

If `start_span()` passes the `_closed` check just before another thread calls `close()`, it can reserve a new live span after `close()` clears the registry and closes the exporter. Ending that span then calls `enqueue()` on the closed exporter, which defeats shutdown and can lose the span. Re-check `_closed` while holding the lock before reserving the ID.

### Issue 2
posthog/tracing/_pipeline.py:94-95
**Drop logging can escape**

`warn_if_due()` runs in `start_span()`'s `finally` block outside its exception handler. If an application logging handler raises, that exception escapes into the application and can override the span being returned, breaking the method's non-raising contract. Contain failures from `warn_if_due()` within `start_span()`.

### Issue 3
posthog/tracing/_pipeline.py:153-156
**Failed starts leak capacity**

The live-span ID is reserved before context extraction and span construction, but the broad exception path returns an inert span without removing it. If a context mapping raises from `get()`, the orphaned entry consumes capacity until age eviction and can block tracing for the configured maximum age. Remove the reservation whenever a post-reservation operation fails.

### Issue 4
posthog/tracing/_drops.py:46-49
**Fork inherits warning throttle**

Fork reinitialization clears pending drop counts but retains the parent's `_last_warning_at`. If the child drops a span shortly after a parent warning, its warning is suppressed; if no later tracing operation occurs, that drop is never reported. Reset `_last_warning_at` with the other process-local state.

---

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): span pipeline" | Re-trigger Greptile

Comment thread posthog/tracing/_pipeline.py
Comment thread posthog/tracing/_pipeline.py
Comment thread posthog/tracing/_pipeline.py
Comment thread posthog/tracing/_drops.py
@github-actions

github-actions Bot commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-09-17 03:42:58 UTC
Duration: 256418ms

✅ 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 ✅ 510ms
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 ✅ 511ms
Event Format.Event Uuid Is Valid ✅ 510ms
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 ✅ 510ms
Event Format.Set Properties Preserved ✅ 510ms
Event Format.Set Once Properties Preserved ✅ 511ms
Event Format.Groups Properties Preserved ✅ 510ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 510ms
Event Format.Event Has Required Root Fields Batch ✅ 514ms
Event Format.Event Uuid Is Valid Batch ✅ 514ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 513ms
Event Format.Distinct Id Is String Batch ✅ 514ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 514ms
Event Format.Custom Properties Preserved Batch ✅ 514ms
Event Format.Set Properties Preserved Batch ✅ 513ms
Event Format.Set Once Properties Preserved Batch ✅ 514ms
Event Format.Groups Properties Preserved Batch ✅ 514ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 513ms
Batch Behavior.Multiple Events In Single Batch ✅ 518ms
Batch Behavior.Batch Envelope Smoke ✅ 515ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 506ms
Batch Behavior.Flush At Triggers Batch ✅ 1012ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 512ms
Deduplication.Generates Unique Uuids ✅ 520ms
Deduplication.Different Events Same Content Different Uuids ✅ 513ms
Deduplication.Preserves Uuid On Retry ✅ 6518ms
Deduplication.Preserves Timestamp On Retry ✅ 6516ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6519ms
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 ✅ 13523ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6520ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3021ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6519ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 511ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 515ms
Response Format Validation.Success No Retry After When All Ok ✅ 512ms
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 ✅ 510ms
Retry Behavior.Retries On 408 ✅ 6515ms
Retry Behavior.Retries On 500 ✅ 6517ms
Retry Behavior.Retries On 503 ✅ 8522ms
Retry Behavior.Retries On 504 ✅ 6520ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3517ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11523ms
Retry Behavior.Does Not Retry On 400 ✅ 2514ms
Retry Behavior.Does Not Retry On 401 ✅ 2512ms
Retry Behavior.Does Not Retry On 402 ✅ 2514ms
Retry Behavior.Does Not Retry On 413 ✅ 2513ms
Retry Behavior.Does Not Retry On 415 ✅ 2513ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2513ms
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 ✅ 3518ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3515ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3516ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6522ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6522ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6518ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6521ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6517ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6518ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8517ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3514ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3518ms
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 ✅ 2513ms
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 ✅ 510ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 511ms
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 ✅ 10ms
Request Payload.Token In Flags Body Matches Init ✅ 10ms
Request Payload.Groups Round Trip ✅ 10ms
Request Payload.Groups Default To Empty Object ✅ 10ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 9ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 9ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 10ms
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 ✅ 10ms
Retry Behavior.Retries Flags On 502 ✅ 313ms
Retry Behavior.Retries Flags On 504 ✅ 314ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 512ms

@greptile-apps

greptile-apps Bot commented Sep 15, 2026

Copy link
Copy Markdown
Contributor
Prompt To Fix All With AI
### Issue 1
posthog/tracing/_drops.py:47-50
**Failed warnings lose counts**

`warn_if_due()` clears the pending count and reasons before calling `log.warning()`. If a logging handler raises, the exception is suppressed but the drop report is permanently lost. Restore the count and reasons when logging fails so a later call can retry while preserving the non-raising contract.

---

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

Reviews (2): Last reviewed commit: "fix(traces): close the shutdown and fail..." | Re-trigger Greptile

Comment thread posthog/tracing/_drops.py

@dustinbyrne dustinbyrne left a comment

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.

Please preserve explicit service identity when resource attributes collide. At posthog/tracing/_config.py:137–140, the resolver replaces service_name/service_version before the encoder's identity protection runs. A shared resource map can therefore relabel every span despite the explicit service configuration.

For example, service_name="checkout" plus resource_attributes={"service.name": "shared-default"} currently resolves to shared-default; the explicit name should remain checkout. Please reverse that precedence and update the test that currently asserts resource attributes win.

Regression sketch (not executed): resolve conflicting explicit name/version and resource attributes, build the resource envelope, and assert the explicit identity survives while unrelated attributes remain. As a negative control, call the existing encoder directly with the same explicit identity and conflicting map.

Two non-blocking follow-ups:

  • _pipeline.py:92: the fallback diagnostic can itself escape start_span when DEBUG is enabled and an application logging handler raises. A malformed inbound parent triggers a diagnostic, then another unguarded diagnostic in the exception handler. Make that fallback log best-effort.
  • _pipeline.py:263–275: age eviction removes accounting but leaves the retained handle able to emit traceparent and create recorded children. Consider bounded/weak handle invalidation so it becomes a no-op after eviction.

These concern the private tracing foundation; no shipped Client tracing regression is claimed.

AI-assisted review with independent validation of the findings, source and existing CI; no new tests were run.

@dustinbyrne
dustinbyrne requested a review from a team September 15, 2026 21:52
@turnipdabeets

turnipdabeets commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor Author

@dustinbyrne Resource attributes winning is on purpose. Node does the same (resourceAttributes['service.name'] ?? serviceName), and so does our metrics config. The spec says traces config should mean the same thing as the other products, so changing it only here would make them disagree. Do we think the spec is wrong and this should change everywhere?

On the two notes:

  • The fallback debug log can only raise if an app installs a custom handler whose emit raises. Built-in handlers never raise. A handler like that breaks every SDK log line, so we treat it like the rest of the SDK does.
  • Evicted spans: we track live spans by id, same as Node, so an evicted span can still parent children. That is the same as a child of a remote parent that was never exported. We would rather not add weak references to handles just for the leak case.

@dustinbyrne dustinbyrne left a comment

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.

Thanks for the explanation. I checked Node traces and metrics: resource attributes do take precedence there. I over-weighted the spec wording and should have checked that convention before asking Python to differ. I withdraw the service-identity change request.

I also withdraw the custom-handler logging and age-eviction suggestions: neither warrants extra machinery in this PR. The shared spec wording can be clarified separately rather than changing Python alone. Approving.

AI-assisted follow-up source review, including Node parity and the rebased transport change; no new tests run locally.

@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/04-transport. Tests pass at the head, ruff is clean, parent precedence is correct, no user code runs under _lock, and start_span genuinely never raises. One item I would fix before merge.

Blocking

  1. posthog/tracing/_pipeline.py:223 (and _span.py:135 for the inert path) an empty or whitespace parent string suppresses the active-span default and starts a new root. Reproduced: inside with start_span("outer"), parent="" yields parent_span_id=None in a different trace; with the client disabled and a pass-through active, parent="" returns NoopSpan while parent=None returns a PassThroughSpan. request.headers.get("traceparent", "") and request.META.get("HTTP_TRACEPARENT", "") are common idioms, and a two-element list in the same position does fall back to the active span, so the two "unusable" paths disagree. Suggest treating a blank string as None after traceparent_header(parent), in both places, and keeping the non-empty-malformed path as a new root.

Non-blocking, recommended

  1. posthog/tracing/_pipeline.py:267 age eviction drops a legitimately long span that its caller does end, and its children export as orphans. Reproduced with a root older than max_span_age. The default is one hour; a batch-job wrapper span over an hour is realistic. The leak-recovery goal is served equally well by sweeping only when len(_live_spans) >= max_live_spans.
  2. posthog/tracing/_config.py:110 unknown keys are silently ignored while every known-but-invalid value warns. A mistyped before_span_send key in #956 means spans export unscrubbed with no signal, which is exactly what #957's fail-closed comment is trying to prevent. log.warning("Ignoring unknown traces option(s): %s", ...).
  3. posthog/tracing/_pipeline.py:262 join keys are neither stringified nor null-checked the way capture() does with stringify_id. An int distinct id becomes an OTLP intValue for posthogDistinctId, and if value: drops a distinct id of 0.
  4. Nits: a non-Mapping return from get_context makes the span inert because the try covers the call but not context.get; a child of a refused (at-limit) local parent is marked parent_is_remote=True on the wire; FakeTimer/fake_timers ship here with no consumer until #954, re-exported through an __all__ hack rather than posthog/test/tracing/conftest.py; duplicate assert at test_pipeline.py:46.

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

Comment thread posthog/tracing/_pipeline.py
@veria-ai

veria-ai Bot commented Sep 17, 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: 1 · PR risk: 0/10

@turnipdabeets

Copy link
Copy Markdown
Contributor Author

Thanks. Fixed in 19ea6ef:

  • 1: a blank parent means the default parent, in both the recording and inert paths.
  • 2: aged spans are swept only at the live-span bound, so a long span that ends is exported.
  • 3: unknown options warn.
  • 4: join keys are stringified and a 0 id is kept.
  • 5: a non-Mapping context no longer makes the span inert, duplicate assert removed. The refused-parent remote flag and the conftest move are still open.

@turnipdabeets

Copy link
Copy Markdown
Contributor Author

Follow-up, 78b6318: an unusable explicit parent (two-value list, foreign span object) now starts a new trace like a malformed header does, instead of falling back to the active span. Ready for another look.

turnipdabeets and others added 5 commits September 16, 2026 23:36
Adds span creation and the end-of-span gates. PostHogTraces resolves a span's
parent (an explicit traceparent string or handle, else the active span, else a
new trace), attaches the posthogDistinctId and sessionId join keys from the
request context, bounds live spans by count and by age so a leak cannot disable
tracing, and hands each ended span to an exporter unless the client was
disabled. The `traces` option is validated key by key, falling back to the
documented default with a warning. Dropped spans are counted per reason and
reported at most once per flush interval. The export queue arrives in the next
change; this one runs against a stand-in. Not reachable from the client.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TkZAsCciW4PV8ZdcCHmAbA
Re-check closed under the lock so a close() that lands mid-start cannot
reserve a live span after the registry was cleared. Release the reserved
slot when building the span fails, so it does not wait for age eviction.
Contain a raising logging handler inside the drop warning, and reset the
warning throttle in a forked child with the rest of its state.
…only at the bound

headers.get("traceparent", "") started a new root instead of nesting under
the active span. Aged spans are now swept only when the live-span bound is
reached, so a long span that does end is exported. Unknown traces options
warn instead of vanishing, join keys are stringified and a 0 id is kept,
and a non-mapping context no longer makes the span inert.
A two-value header list or a foreign span object fell back to the active
span while a malformed header string started a new root. Both now start
a new trace: an explicit parent the caller named must not silently
attach the span to a trace they did not.
@turnipdabeets
turnipdabeets merged commit ff7decc into main Sep 18, 2026
49 of 77 checks passed
@turnipdabeets
turnipdabeets deleted the traces/05-pipeline 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