Skip to content

feat(drf): add automatic error tracking integration - #1036

Merged
hpouillot merged 9 commits into
mainfrom
feat/drf-error-tracking
Oct 9, 2026
Merged

hpouillot merged 9 commits into
mainfrom
feat/drf-error-tracking

Conversation

@hpouillot

@hpouillot hpouillot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Django REST Framework converts handled exceptions into responses before Django middleware can observe them. This adds an idiomatic DRF EXCEPTION_HANDLER that captures handled 5xx errors while preserving DRF behavior and excluding expected 4xx responses by default.

The integration is deliberately error-only: it imports DRF lazily, reuses the active Django request context, avoids duplicate captures, supports custom handlers and clients, and leaves unhandled exceptions for PosthogContextMiddleware. Request properties remain owned by the Django context middleware rather than a second DRF-specific extra_properties API.

Configuration follows the shared middleware contract:

  • capture_exceptions=True/False explicitly overrides inherited configuration.
  • Otherwise a boolean POSTHOG_MW_CAPTURE_EXCEPTIONS is inherited.
  • An explicitly configured POSTHOG_MW_CAPTURE_EXCEPTIONS=None inherits enable_exception_autocapture from the effective client.
  • An omitted or malformed setting preserves Django's legacy True default.
  • Client precedence is explicit client > legacy POSTHOG_DRF_CLIENT > POSTHOG_MW_CLIENT > global client.
  • POSTHOG_MW_REQUEST_FILTER applies to handled DRF errors as well as middleware-observed errors.

💚 How did you test it?

  • uv run --no-sync pytest -q posthog/test/integrations/test_drf_integration.py --timeout=30 — 24 passed, 4 subtests passed
  • uv run --no-sync pytest -q posthog/test/integrations/test_drf_integration.py posthog/test/integrations/test_middleware.py --timeout=30 — 55 passed, 4 subtests passed
  • uv run --no-sync ruff format --check .
  • uv run --no-sync ruff check .
  • uv run --no-sync mypy --no-site-packages --config-file mypy.ini posthog/integrations/drf.py posthog/test/integrations/test_drf_integration.py
  • uv run --no-sync make public_api_check
  • uv run --no-sync python -W error -c "import posthog; import posthog.integrations.drf"

📝 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 pi using GPT-5.6 and Cockpit child sessions 0efe934b-1904-4c35-a722-0937ad74480e and 1f64f01a-ab4f-4e7f-9ac6-e6f1d1c46ed7. The integration deliberately uses DRF's exception-handler hook rather than Django middleware because handled DRF exceptions no longer propagate to middleware. It captures 5xx responses by default, leaves 4xx capture opt-in, and never changes the delegated handler's response or exception behavior.

Exception metadata conformance

Reviewed against the canonical exception-event-metadata SDK specification. The consumed DRF response boundary emits level error, semantic mechanism type middleware, handled state true, and stable concrete source django_rest_framework.exception_handler; tests assert the complete typed metadata channel.

@hpouillot
hpouillot requested a review from a team as a code owner October 8, 2026 09:40
@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-08T15:14:54.519202+00:00
Duration: 259306ms

✅ 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 ✅ 515ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 508ms
Required Headers.Has Authorization Bearer Header ✅ 508ms
Required Headers.Has Content Type Json ✅ 509ms
Required Headers.Has Posthog Sdk Info Format ✅ 507ms
Required Headers.Has Posthog Attempt Header ✅ 508ms
Required Headers.Has Posthog Request Id ✅ 509ms
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 ✅ 508ms
Body Format.No Sent At In Body ✅ 508ms
Event Format.Event Has Required Root Fields ✅ 509ms
Event Format.Event Uuid Is Valid ✅ 507ms
Event Format.Event Timestamp Is Rfc3339 ✅ 509ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 513ms
Event Format.Distinct Id Is String ✅ 507ms
Event Format.Distinct Id At Root Not Properties ✅ 508ms
Event Format.Custom Properties Preserved ✅ 508ms
Event Format.Set Properties Preserved ✅ 508ms
Event Format.Set Once Properties Preserved ✅ 508ms
Event Format.Groups Properties Preserved ✅ 507ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 508ms
Event Format.Event Has Required Root Fields Batch ✅ 511ms
Event Format.Event Uuid Is Valid Batch ✅ 513ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 510ms
Event Format.Distinct Id Is String Batch ✅ 511ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 510ms
Event Format.Custom Properties Preserved Batch ✅ 510ms
Event Format.Set Properties Preserved Batch ✅ 510ms
Event Format.Set Once Properties Preserved Batch ✅ 510ms
Event Format.Groups Properties Preserved Batch ✅ 510ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 510ms
Batch Behavior.Multiple Events In Single Batch ✅ 512ms
Batch Behavior.Batch Envelope Smoke ✅ 512ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 505ms
Batch Behavior.Flush At Triggers Batch ✅ 1008ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 508ms
Deduplication.Generates Unique Uuids ✅ 512ms
Deduplication.Different Events Same Content Different Uuids ✅ 510ms
Deduplication.Preserves Uuid On Retry ✅ 6516ms
Deduplication.Preserves Timestamp On Retry ✅ 6514ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6519ms
Deduplication.No Duplicate Events In Batch ✅ 513ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 508ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13525ms
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 ✅ 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 ✅ 509ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1512ms
Response Format Validation.Success No Retry After When Drop Only ✅ 511ms
Response Format Validation.Response Echoes Request Id ✅ 507ms
Retry Behavior.Retries On 408 ✅ 6517ms
Retry Behavior.Retries On 500 ✅ 6513ms
Retry Behavior.Retries On 503 ✅ 8516ms
Retry Behavior.Retries On 504 ✅ 6514ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3524ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11513ms
Retry Behavior.Does Not Retry On 400 ✅ 2513ms
Retry Behavior.Does Not Retry On 401 ✅ 2510ms
Retry Behavior.Does Not Retry On 402 ✅ 2511ms
Retry Behavior.Does Not Retry On 413 ✅ 2510ms
Retry Behavior.Does Not Retry On 415 ✅ 2511ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2510ms
Retry Behavior.Implements Backoff ✅ 22530ms
Retry Behavior.Max Retries Respected ✅ 22522ms
Partial Batch Handling.Handles 200 Full Success ✅ 2511ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3512ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3513ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3512ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6514ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6519ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6518ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6519ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6514ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6514ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8517ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3513ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3516ms
Compression.Sends Gzip Content Encoding ✅ 508ms
Compression.No Content Encoding When Disabled ✅ 508ms
Compression.Compressed Body Is Decompressible ✅ 508ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2511ms
Event Options.Cookieless Mode Override ✅ 509ms
Event Options.Disable Skew Correction Override ✅ 508ms
Event Options.Process Person Profile Override ✅ 508ms
Event Options.Product Tour Id Override ✅ 509ms
Event Options.Unset Options Omitted ✅ 509ms
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 ✅ 508ms
Identity.Capture Ai Event Has Uuid ✅ 509ms
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 ✅ 8ms
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 ✅ 7ms
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 ✅ 7ms
Request Lifecycle.No Flags Request On Init Alone ✅ 2ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 507ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 13ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 7ms
Retry Behavior.Retries Flags On 502 ✅ 311ms
Retry Behavior.Retries Flags On 504 ✅ 310ms
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 ✅ 45ms
Versioned Boolean Matching.Matching Version 1 ✅ 47ms
Versioned Boolean Matching.Matching Version 2 ✅ 47ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 24ms

Comment thread posthog/integrations/drf.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/drf-error-tracking branch from 481bc5f to 82e25e3 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/drf-error-tracking branch from 82e25e3 to 686d569 Compare October 8, 2026 10:32
@hpouillot
hpouillot requested review from a team and ablaszkiewicz October 8, 2026 10:32
@hpouillot
hpouillot force-pushed the feat/drf-error-tracking branch from cd116a6 to ca5a306 Compare October 8, 2026 14:37
@hpouillot
hpouillot requested a review from a team October 8, 2026 14:37
@hpouillot
hpouillot merged commit 9baf8a5 into main Oct 9, 2026
43 checks passed
@hpouillot
hpouillot deleted the feat/drf-error-tracking branch October 9, 2026 09:25
eli-r-ph pushed a commit that referenced this pull request Oct 10, 2026
* feat(drf): add automatic error tracking integration

* fix(drf): align exception metadata with SDK spec

* chore(drf): type exception capture metadata

* fix(drf): honor Django request filtering

* test(drf): describe context data as properties

* feat(drf): support exception capture opt-out

* chore(drf): update public API snapshot

* fix(drf): align exception capture configuration

* test(drf): preserve omitted setting default

(cherry picked from commit 9baf8a5)
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