Skip to content

feat(asgi): add error tracking middleware - #1037

Merged
hpouillot merged 4 commits into
mainfrom
feat/asgi-error-tracking
Oct 8, 2026
Merged

hpouillot merged 4 commits into
mainfrom
feat/asgi-error-tracking

Conversation

@hpouillot

@hpouillot hpouillot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Python users running FastAPI, Starlette, Litestar, or raw ASGI applications currently have no framework integration that automatically establishes PostHog request context and captures unhandled request exceptions. This adds dependency-free ASGI middleware that works directly with the ASGI protocol.

The middleware instruments HTTP and WebSocket scopes, adds request properties without collecting bodies or query strings, supports sync or async filters and extra properties, captures escaping exceptions once, and preserves normal ASGI propagation. Lifespan and custom scope types pass through untouched. Client-provided PostHog distinct/session tracing headers are ignored by default and can be enabled explicitly with trust_tracing_headers=True; they are analytics context and must never be treated as authentication or authorization.

The integration uses the SDK-internal typed metadata channel from #898 and follows the canonical exception event metadata specification. Escaping ASGI failures emit $exception_level: error, $exception_source: asgi.middleware, and an outermost mechanism with type: middleware, handled: false, synthetic: false, and exception_id: 0.

💚 How did you test it?

  • uv run --extra test pytest -q --timeout=30 — 4492 passed, 16 skipped, 48 subtests
  • uv run ruff format --check .
  • uv run ruff check .
  • uv run --extra dev mypy --no-site-packages --config-file mypy.ini . | uv run --extra dev mypy-baseline filter
  • uv run --extra dev make public_api_check
  • uv run python -W error -c "import posthog"

Tests assert request/context isolation, safe request properties, explicit tracing-header trust, filters, WebSockets, exception propagation, typed integration metadata, and final canonical event properties from a real client.

📝 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

A valid .sampo/changesets/asgi-error-tracking.md changeset was added directly.

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Implemented by the Pi coding agent in Cockpit. The implementation uses raw ASGI rather than depending on FastAPI or Starlette, omits query strings and bodies for privacy, makes client-controlled tracing identity opt-in, and lets handled framework responses pass without reporting them as exceptions. Human review is required.

@hpouillot
hpouillot requested a review from a team as a code owner October 8, 2026 09:41
@hpouillot hpouillot self-assigned this Oct 8, 2026
@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-10-08T10:43:07.271314+00:00
Duration: 259408ms

✅ All Tests Passed!

121/121 tests passed


Capture_V1 Tests

✅ 95/95 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint ✅ 514ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 508ms
Required Headers.Has Authorization Bearer Header ✅ 509ms
Required Headers.Has Content Type Json ✅ 509ms
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.Non Utc Event Timestamp Is Converted To Utc ✅ 513ms
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 ✅ 509ms
Event Format.Event Has Required Root Fields Batch ✅ 510ms
Event Format.Event Uuid Is Valid Batch ✅ 511ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 513ms
Event Format.Distinct Id Is String Batch ✅ 512ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 510ms
Event Format.Custom Properties Preserved Batch ✅ 512ms
Event Format.Set Properties Preserved Batch ✅ 511ms
Event Format.Set Once Properties Preserved Batch ✅ 510ms
Event Format.Groups Properties Preserved Batch ✅ 512ms
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 ✅ 506ms
Batch Behavior.Flush At Triggers Batch ✅ 1009ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 509ms
Deduplication.Generates Unique Uuids ✅ 514ms
Deduplication.Different Events Same Content Different Uuids ✅ 510ms
Deduplication.Preserves Uuid On Retry ✅ 6517ms
Deduplication.Preserves Timestamp On Retry ✅ 6518ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6520ms
Deduplication.No Duplicate Events In Batch ✅ 514ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 509ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13516ms
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 ✅ 6514ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 509ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 512ms
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 ✅ 510ms
Response Format Validation.Response Echoes Request Id ✅ 509ms
Retry Behavior.Retries On 408 ✅ 6518ms
Retry Behavior.Retries On 500 ✅ 6513ms
Retry Behavior.Retries On 503 ✅ 8519ms
Retry Behavior.Retries On 504 ✅ 6513ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3512ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11520ms
Retry Behavior.Does Not Retry On 400 ✅ 2510ms
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 ✅ 2511ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2512ms
Retry Behavior.Implements Backoff ✅ 22531ms
Retry Behavior.Max Retries Respected ✅ 22530ms
Partial Batch Handling.Handles 200 Full Success ✅ 2510ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3514ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3514ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3511ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6521ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6519ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6520ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6514ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6519ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6519ms
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 ✅ 3516ms
Compression.Sends Gzip Content Encoding ✅ 509ms
Compression.No Content Encoding When Disabled ✅ 508ms
Compression.Compressed Body Is Decompressible ✅ 509ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2510ms
Event Options.Cookieless Mode Override ✅ 509ms
Event Options.Disable Skew Correction Override ✅ 512ms
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 ✅ 511ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 508ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 509ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 508ms

Capture_Ai Tests

✅ 5/5 tests passed

View Details
Test Status Duration
Routing.Capture Ai Posts To Ai Endpoint ✅ 508ms
Routing.Capture Does Not Reroute Ai Named Events ✅ 509ms
Identity.Capture Ai Event Has Uuid ✅ 508ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 508ms
Timestamp Format.Non Utc Event Timestamp Is Converted To Utc ✅ 508ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 10ms
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 ✅ 8ms
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 ✅ 8ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 6ms
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 ✅ 311ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 509ms

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 53ms
Versioned Boolean Matching.Matching Version 1 ✅ 52ms
Versioned Boolean Matching.Matching Version 2 ✅ 51ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 27ms

@hpouillot
hpouillot force-pushed the feat/asgi-error-tracking branch from f07926f to 163293e Compare October 8, 2026 09:48
@hpouillot
hpouillot changed the base branch from main to hp/exception-event-metadata October 8, 2026 09:48
Comment thread posthog/integrations/asgi.py Outdated
@veria-ai

veria-ai Bot commented Oct 8, 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

@hpouillot
hpouillot force-pushed the feat/asgi-error-tracking branch from 163293e to 39a00c8 Compare October 8, 2026 10:22
Base automatically changed from hp/exception-event-metadata to main October 8, 2026 10:28
@hpouillot
hpouillot force-pushed the feat/asgi-error-tracking branch from 39a00c8 to e43ca8e Compare October 8, 2026 10:34
@hpouillot
hpouillot requested review from a team and ablaszkiewicz October 8, 2026 10:34

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

Looks good 👍 I was worried we would extract some unwanted headers but I see that we only capture very specific ones

@hpouillot
hpouillot merged commit 1c6a47a into main Oct 8, 2026
43 of 44 checks passed
@hpouillot
hpouillot deleted the feat/asgi-error-tracking branch October 8, 2026 14:07
eli-r-ph pushed a commit that referenced this pull request Oct 10, 2026
* feat(asgi): add error tracking middleware

* chore(asgi): type exception capture metadata

* fix(asgi): make tracing header trust explicit

* refactor(asgi): expose request properties terminology

(cherry picked from commit 1c6a47a)
eli-r-ph pushed a commit that referenced this pull request Oct 10, 2026
* feat(asgi): add error tracking middleware

* chore(asgi): type exception capture metadata

* fix(asgi): make tracing header trust explicit

* refactor(asgi): expose request properties terminology

(cherry picked from commit 1c6a47a)
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