Skip to content

feat(traces): span pipeline - #953

Open
turnipdabeets wants to merge 2 commits into
traces/04-transportfrom
traces/05-pipeline
Open

turnipdabeets wants to merge 2 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-15 22:09:38 UTC
Duration: 255873ms

✅ 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 512ms
Endpoint And Method.Does Not Use Legacy Endpoints 507ms
Required Headers.Has Authorization Bearer Header 508ms
Required Headers.Has Content Type Json 507ms
Required Headers.Has Posthog Sdk Info Format 508ms
Required Headers.Has Posthog Attempt Header 507ms
Required Headers.Has Posthog Request Id 507ms
Required Headers.Has Posthog Request Timestamp 507ms
Required Headers.Has User Agent 508ms
Body Format.Body Has Created At And Batch 508ms
Body Format.No Api Key In Body 507ms
Body Format.No Sent At In Body 507ms
Event Format.Event Has Required Root Fields 508ms
Event Format.Event Uuid Is Valid 507ms
Event Format.Event Timestamp Is Rfc3339 507ms
Event Format.Distinct Id Is String 508ms
Event Format.Distinct Id At Root Not Properties 508ms
Event Format.Custom Properties Preserved 507ms
Event Format.Set Properties Preserved 508ms
Event Format.Set Once Properties Preserved 507ms
Event Format.Groups Properties Preserved 507ms
Event Format.Sdk Generates Uuid If Not Provided 508ms
Event Format.Event Has Required Root Fields Batch 509ms
Event Format.Event Uuid Is Valid Batch 511ms
Event Format.Event Timestamp Is Rfc3339 Batch 509ms
Event Format.Distinct Id Is String Batch 510ms
Event Format.Distinct Id At Root Not Properties Batch 509ms
Event Format.Custom Properties Preserved Batch 509ms
Event Format.Set Properties Preserved Batch 510ms
Event Format.Set Once Properties Preserved Batch 510ms
Event Format.Groups Properties Preserved Batch 509ms
Event Format.Sdk Generates Uuid If Not Provided Batch 510ms
Batch Behavior.Multiple Events In Single Batch 512ms
Batch Behavior.Batch Envelope Smoke 510ms
Batch Behavior.Flush With No Events Sends Nothing 505ms
Batch Behavior.Flush At Triggers Batch 1007ms
Batch Behavior.Created At Reflects Batch Creation Time 508ms
Deduplication.Generates Unique Uuids 512ms
Deduplication.Different Events Same Content Different Uuids 509ms
Deduplication.Preserves Uuid On Retry 6515ms
Deduplication.Preserves Timestamp On Retry 6513ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6514ms
Deduplication.No Duplicate Events In Batch 513ms
Header Behavior On Retry.Attempt Header Starts At One 507ms
Header Behavior On Retry.Attempt Header Increments On Retry 13520ms
Header Behavior On Retry.Request Id Preserved On Retry 6516ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3017ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6515ms
Response Format Validation.Success Response Has Uuid Keyed Results 508ms
Response Format Validation.Success Response Has Ok For Each Event 513ms
Response Format Validation.Success No Retry After When All Ok 513ms
Response Format Validation.Success Retry After Present When Retry Events 1530ms
Response Format Validation.Success No Retry After When Drop Only 509ms
Response Format Validation.Response Echoes Request Id 508ms
Retry Behavior.Retries On 408 6511ms
Retry Behavior.Retries On 500 6516ms
Retry Behavior.Retries On 503 8519ms
Retry Behavior.Retries On 504 6516ms
Retry Behavior.Retryable Errors Have Retry After 3513ms
Retry Behavior.Respects Retry After On Retryable Error 11518ms
Retry Behavior.Does Not Retry On 400 2509ms
Retry Behavior.Does Not Retry On 401 2511ms
Retry Behavior.Does Not Retry On 402 2510ms
Retry Behavior.Does Not Retry On 413 2511ms
Retry Behavior.Does Not Retry On 415 2509ms
Retry Behavior.Non Retryable Errors Have No Retry After 2510ms
Retry Behavior.Implements Backoff 22523ms
Retry Behavior.Max Retries Respected 22521ms
Partial Batch Handling.Handles 200 Full Success 2509ms
Partial Batch Handling.Handles 200 With All Ok 3511ms
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 6517ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6517ms
Partial Batch Handling.Retries Only Retry Events From Partial 6518ms
Partial Batch Handling.Partial Retry Preserves Uuids 6517ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6512ms
Partial Batch Handling.Partial Retry Request Id Preserved 6517ms
Partial Batch Handling.Respects Retry After On Partial 8517ms
Partial Batch Handling.Unknown Result Treated As Terminal 3512ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 3514ms
Compression.Sends Gzip Content Encoding 508ms
Compression.No Content Encoding When Disabled 507ms
Compression.Compressed Body Is Decompressible 507ms
Error Handling.Does Not Retry On Unknown 4Xx 2510ms
Event Options.Cookieless Mode Override 508ms
Event Options.Disable Skew Correction Override 507ms
Event Options.Process Person Profile Override 508ms
Event Options.Product Tour Id Override 507ms
Event Options.Unset Options Omitted 507ms
Event Options.Options Override In Batch 509ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 508ms
Geoip And Historical Migration.Historical Migration Set In Body 507ms
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 7ms
Request Payload.Flags Request Uses V2 Query Param 6ms
Request Payload.Flags Request Hits Flags Path Not Decide 6ms
Request Payload.Flags Request Omits Authorization Header 6ms
Request Payload.Token In Flags Body Matches Init 6ms
Request Payload.Groups Round Trip 5ms
Request Payload.Groups Default To Empty Object 6ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 6ms
Request Payload.Disable Geoip Omitted Defaults To False 6ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 5ms
Request Lifecycle.No Flags Request On Init Alone 2ms
Request Lifecycle.No Flags Request On Normal Capture 506ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 10ms
Request Lifecycle.Mock Response Value Is Returned To Caller 6ms
Retry Behavior.Retries Flags On 502 309ms
Retry Behavior.Retries Flags On 504 309ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 508ms

@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 and others added 2 commits September 15, 2026 18:01
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.
@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.

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