Skip to content

fix(celery): capture task exceptions with exception autocapture - #1072

Draft
posthog[bot] wants to merge 1 commit into
mainfrom
posthog-self-driving/fixcelery-capture-task-exceptions-when-397797
Draft

posthog[bot] wants to merge 1 commit into
mainfrom
posthog-self-driving/fixcelery-capture-task-exceptions-when-397797

Conversation

@posthog

@posthog posthog Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

  • Python SDK users who turn on enable_exception_autocapture get no $exception events for Celery task errors. They must find and call PosthogCeleryIntegration.instrument() themselves, and the error tracking docs do not mention it.
  • Root cause: autocapture installs only sys.excepthook and threading.excepthook. Celery catches every task exception in its trace code, so those hooks never run.
  • Also, PosthogCeleryIntegration._on_task_retry did not capture the exception of a retried attempt.

Changes

  • Autocapture connects to Celery signals. When Celery is in sys.modules at client creation, ExceptionCapture connects to task_failure and task_retry. A Celery worker always imports Celery first, so workers are covered. Processes that do not use Celery import nothing new.
  • No double capture. When a PosthogCeleryIntegration with capture_exceptions=True is instrumented, autocapture skips the exception. The integration captures it once and applies its task_filter.
  • Retries are captured by both paths, from Retry.exc. A retry with no exception captures nothing.
  • ExceptionCapture.close() disconnects the signals. Lifecycle events and context propagation stay opt-in through the integration.
Signal source level mechanism.handled
task_failure celery.task_failure error false
task_retry celery.task_retry warning true

Note

Behavior change: projects with autocapture and Celery will start to get $exception events for task errors (and per-attempt retry warnings). The rate limiter of autocapture applies to these events too. Count $exception events with mechanism source celery.task_failure / celery.task_retry to measure adoption.

Follow-up outside this repo: add a Celery section to the Python error tracking install docs.

💚 How did you test it?

  • New unit tests for autocapture (failure, retry, defer to integration, close() disconnects, no Celery) and for retry capture in the integration.
  • End-to-end with real Celery (eager mode, uv run --with celery), with a task that raises KeyError and a task that retries once:
main this branch
$exception events 0 3: KeyError error, ConnectionError retry warning, ConnectionError final error
after close() — 0
  • ruff format --check, ruff check, mypy baseline, and the public API snapshot check pass.
  • Full pytest: 4716 passed. 3 AI-wrapper tests (langchain/test_callbacks.py x2, anthropic::test_integration_stop_reason) fail on main too, and are not related.

📝 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: Fully autonomous

  • Claude Code (PostHog Desktop), from an inbox report.
  • Rejected: auto-instrumenting the full PosthogCeleryIntegration. That adds billable lifecycle events and edits task headers without consent. Rejected: only a warning log. It still leaves users with no events.
  • Rejected: importing Celery on client creation. It costs import time in processes that only have Celery installed. A process that imports Celery after the client is created still needs the integration.

Created with PostHog Desktop from this inbox report.

🤖 Generated with Claude Code

Origin

  • Conversations: ticket
  • First signal: 2026-10-16
  • Inbox report: open
  • Likely cause: 52cd20e
  • Task started by: auto-start, after the report was rated P2 and ready to fix

Celery catches task exceptions, so sys.excepthook never sees them. Exception autocapture now connects to the Celery task_failure and task_retry signals when Celery is imported. An instrumented PosthogCeleryIntegration replaces this capture, so each exception is captured once. The integration also captures the exception of a retried task.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Generated-By: PostHog Desktop
Task-Id: 40cf8650-18a1-49a4-8f20-dff6cb63b0c8
@posthog posthog Bot added the self-driving label Oct 16, 2026
@posthog
posthog Bot requested a review from hpouillot October 16, 2026 19:42
@github-actions

github-actions Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-10-16T19:48:02.724184+00:00
Duration: 259898ms

✅ 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 ✅ 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 ✅ 511ms
Required Headers.Has Posthog Request Timestamp ✅ 510ms
Required Headers.Has User Agent ✅ 510ms
Body Format.Body Has Created At And Batch ✅ 509ms
Body Format.No Api Key In Body ✅ 510ms
Body Format.No Sent At In Body ✅ 510ms
Event Format.Event Has Required Root Fields ✅ 510ms
Event Format.Event Uuid Is Valid ✅ 510ms
Event Format.Event Timestamp Is Rfc3339 ✅ 510ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 517ms
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 ✅ 515ms
Event Format.Event Uuid Is Valid Batch ✅ 514ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 514ms
Event Format.Distinct Id Is String Batch ✅ 513ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 515ms
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 ✅ 513ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 514ms
Batch Behavior.Multiple Events In Single Batch ✅ 518ms
Batch Behavior.Batch Envelope Smoke ✅ 515ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 507ms
Batch Behavior.Flush At Triggers Batch ✅ 1011ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 511ms
Deduplication.Generates Unique Uuids ✅ 518ms
Deduplication.Different Events Same Content Different Uuids ✅ 513ms
Deduplication.Preserves Uuid On Retry ✅ 6519ms
Deduplication.Preserves Timestamp On Retry ✅ 6520ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6524ms
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 ✅ 13522ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6517ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3021ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6515ms
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 ✅ 513ms
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 ✅ 511ms
Retry Behavior.Retries On 408 ✅ 6516ms
Retry Behavior.Retries On 500 ✅ 6520ms
Retry Behavior.Retries On 503 ✅ 8522ms
Retry Behavior.Retries On 504 ✅ 6517ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3517ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11524ms
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 ✅ 2512ms
Retry Behavior.Does Not Retry On 415 ✅ 2513ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2514ms
Retry Behavior.Implements Backoff ✅ 22537ms
Retry Behavior.Max Retries Respected ✅ 22524ms
Partial Batch Handling.Handles 200 Full Success ✅ 2514ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3517ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3517ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3515ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6523ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6518ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6524ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6522ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6517ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6522ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8522ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3517ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3520ms
Compression.Sends Gzip Content Encoding ✅ 511ms
Compression.No Content Encoding When Disabled ✅ 511ms
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 ✅ 511ms
Event Options.Product Tour Id Override ✅ 510ms
Event Options.Unset Options Omitted ✅ 510ms
Event Options.Options Override In Batch ✅ 514ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 511ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 510ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 511ms

Capture_Ai Tests

✅ 5/5 tests passed

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

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 12ms
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 ✅ 11ms
Request Payload.Token In Flags Body Matches Init ✅ 10ms
Request Payload.Groups Round Trip ✅ 12ms
Request Payload.Groups Default To Empty Object ✅ 11ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 10ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 10ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 11ms
Request Lifecycle.No Flags Request On Init Alone ✅ 4ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 510ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 15ms
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

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 71ms
Versioned Boolean Matching.Matching Version 1 ✅ 68ms
Versioned Boolean Matching.Matching Version 2 ✅ 68ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 36ms

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant