Skip to content

fix: prevent client lifecycle deadlocks - #832

Merged
marandaneto merged 29 commits into
mainfrom
fix/lifecycle-deadlocks
Aug 6, 2026
Merged

fix: prevent client lifecycle deadlocks#832
marandaneto merged 29 commits into
mainfrom
fix/lifecycle-deadlocks

Conversation

@marandaneto

@marandaneto marandaneto commented Aug 5, 2026

Copy link
Copy Markdown
Member

💡 Motivation and Context

Client lifecycle methods could deadlock when invoked reentrantly from consumer error callbacks, poller/cache-provider cleanup, executor hops, or concurrent threads. Forked clients could also inherit queue and synchronization locks held by threads that no longer exist.

This merges the drain signaling from #797 and serializes lifecycle ownership without holding state locks across user callbacks. It defers and coalesces callback lifecycle work, preserves queued delivery for normal join()/shutdown(), safely accounts for undrainable or interrupted queue work, hardens async cache-provider runner startup/close/executor behavior, and rebuilds fork-unsafe state before restarting child threads. The on_error and shutdown() documentation now explains direct deferred calls and the safe application-thread handoff pattern. Review follow-up also makes join()/shutdown() no-throw public APIs and removes redundant lifecycle status/error fields. Deferred callback requests are coalesced with a lock-protected dirty flag rather than a generation counter. Automated review follow-up adds per-attempt async-runner startup state, closes rejected/cancelled coroutines, daemonizes deferred helpers, and clarifies best-effort delivery semantics. Interpreter exit now shares one process-wide one-second best-effort flush budget across clients, then stops daemon consumers without joining in-flight transports. Read-only event loops supplied by custom policies are preserved rather than replaced with a platform-default loop.

💚 How did you test it?

  • uv run --extra test pytest -q --timeout=30 — 2008 passed, 15 skipped
  • uv run --extra test pytest -q --timeout=30 posthog/test/test_async_utils.py posthog/test/test_client.py posthog/test/test_consumer.py posthog/test/test_client_fork.py posthog/test/test_ai_capture_lane.py
  • Async runner startup/close stress loop — 50/50 passed
  • uv run --extra dev ruff format --check .
  • uv run --extra dev 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 python .github/scripts/check_public_api.py
  • uv run python -W error -c "import posthog"
  • Independent parallel reviews: clean

📝 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, independent reviewer agents, and autoreview. The final review found no concrete lifecycle, queue, fork, or async-runner defects. Autoreview's remaining read-only-loop concern was rejected after verification: uvloop permits per-instance wrapping, configured extensible policy loops are preserved, and the fallback is intentionally limited to loop implementations that prohibit the wrapping required for safe custom-executor reentry.

Serialize join and shutdown ownership without holding locks across user callbacks, defer reentrant callback lifecycle work, discard unflushed join queues safely, and rebuild fork-unsafe sync queues.
Ensure repeated flush requests from lifecycle callbacks share one non-daemon helper instead of accumulating blocked threads.
Run one strongest follow-up flush for callback requests that arrive while the coalesced helper is active.
Avoid creating one waiting lifecycle thread per callback while preserving deferred cleanup retries.
Keep one bounded deferred lifecycle waiter so callback shutdown requests survive an active owner's cleanup failure.
@marandaneto marandaneto self-assigned this Aug 5, 2026
marandaneto and others added 2 commits August 5, 2026 22:36
Combine the merged drain signaling behavior from #797 with serialized lifecycle shutdown before merging main.
# Conflicts:
#	posthog/client.py
#	posthog/test/test_client.py
@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-08-06 14:10:16 UTC
Duration: 256318ms

✅ 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 515ms
Endpoint And Method.Does Not Use Legacy Endpoints 511ms
Required Headers.Has Authorization Bearer Header 510ms
Required Headers.Has Content Type Json 510ms
Required Headers.Has Posthog Sdk Info Format 510ms
Required Headers.Has Posthog Attempt Header 511ms
Required Headers.Has Posthog Request Id 510ms
Required Headers.Has Posthog Request Timestamp 510ms
Required Headers.Has User Agent 511ms
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 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 511ms
Event Format.Custom Properties Preserved 510ms
Event Format.Set Properties Preserved 510ms
Event Format.Set Once Properties Preserved 511ms
Event Format.Groups Properties Preserved 511ms
Event Format.Sdk Generates Uuid If Not Provided 511ms
Event Format.Event Has Required Root Fields Batch 514ms
Event Format.Event Uuid Is Valid Batch 514ms
Event Format.Event Timestamp Is Rfc3339 Batch 514ms
Event Format.Distinct Id Is String Batch 515ms
Event Format.Distinct Id At Root Not Properties Batch 515ms
Event Format.Custom Properties Preserved Batch 515ms
Event Format.Set Properties Preserved Batch 513ms
Event Format.Set Once Properties Preserved Batch 514ms
Event Format.Groups Properties Preserved Batch 515ms
Event Format.Sdk Generates Uuid If Not Provided Batch 514ms
Batch Behavior.Multiple Events In Single Batch 517ms
Batch Behavior.Batch Envelope Smoke 515ms
Batch Behavior.Flush With No Events Sends Nothing 506ms
Batch Behavior.Flush At Triggers Batch 1011ms
Batch Behavior.Created At Reflects Batch Creation Time 510ms
Deduplication.Generates Unique Uuids 517ms
Deduplication.Different Events Same Content Different Uuids 513ms
Deduplication.Preserves Uuid On Retry 6518ms
Deduplication.Preserves Timestamp On Retry 6518ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6520ms
Deduplication.No Duplicate Events In Batch 519ms
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 6520ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3020ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6519ms
Response Format Validation.Success Response Has Uuid Keyed Results 510ms
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 1515ms
Response Format Validation.Success No Retry After When Drop Only 513ms
Response Format Validation.Response Echoes Request Id 510ms
Retry Behavior.Retries On 408 6518ms
Retry Behavior.Retries On 500 6520ms
Retry Behavior.Retries On 503 8522ms
Retry Behavior.Retries On 504 6519ms
Retry Behavior.Retryable Errors Have Retry After 3518ms
Retry Behavior.Respects Retry After On Retryable Error 11522ms
Retry Behavior.Does Not Retry On 400 2513ms
Retry Behavior.Does Not Retry On 401 2512ms
Retry Behavior.Does Not Retry On 402 2514ms
Retry Behavior.Does Not Retry On 413 2514ms
Retry Behavior.Does Not Retry On 415 2514ms
Retry Behavior.Non Retryable Errors Have No Retry After 2514ms
Retry Behavior.Implements Backoff 22522ms
Retry Behavior.Max Retries Respected 22535ms
Partial Batch Handling.Handles 200 Full Success 2512ms
Partial Batch Handling.Handles 200 With All Ok 3516ms
Partial Batch Handling.Does Not Retry Dropped Events 3515ms
Partial Batch Handling.Does Not Retry Limited Events 3515ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6517ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6522ms
Partial Batch Handling.Retries Only Retry Events From Partial 6523ms
Partial Batch Handling.Partial Retry Preserves Uuids 6517ms
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 8521ms
Partial Batch Handling.Unknown Result Treated As Terminal 3516ms
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 510ms
Error Handling.Does Not Retry On Unknown 4Xx 2514ms
Event Options.Cookieless Mode Override 511ms
Event Options.Disable Skew Correction Override 511ms
Event Options.Process Person Profile Override 511ms
Event Options.Product Tour Id Override 511ms
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

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 9ms
Request Payload.Flags Request Hits Flags Path Not Decide 8ms
Request Payload.Flags Request Omits Authorization Header 9ms
Request Payload.Token In Flags Body Matches Init 8ms
Request Payload.Groups Round Trip 8ms
Request Payload.Groups Default To Empty Object 8ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 8ms
Request Payload.Disable Geoip Omitted Defaults To False 8ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 9ms
Request Lifecycle.No Flags Request On Init Alone 3ms
Request Lifecycle.No Flags Request On Normal Capture 509ms
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 513ms

marandaneto and others added 13 commits August 5, 2026 17:51
Propagate lifecycle callback context through the runner default executor and avoid unbounded drains when no consumer can process queued work.
Wrap all runner executor submissions with callback context and make shutdown discard only queues that have no live consumer.
Propagate lifecycle context through thread executors while leaving process-pool submissions picklable.
Track active provider calls without mutating event loops or wrapping executors, and make unbounded drains recover if all consumers stop.
Propagate callback context through known thread executors without affecting unrelated callers or serialization executors, and balance dequeued work if batching is interrupted.
Use a private context-aware event loop with a process-safe registry wrapper so thread-backed executor proxies remain reentrant without breaking serialization executors.
Carry callback context inside a serialization-safe callable so executor cancellation, process pools, and fork do not depend on shared registry state.
Use a context-aware platform event loop and make startup errors and concurrent close observable without orphaning runner threads.
Prevent close from publishing or stopping a loop during an active startup/run and close partially initialized loops on startup failure.
Submit concurrent work without holding completion locks, reject loop-thread synchronous reentry, and define close-during-startup cancellation.
Use the configured event-loop policy when extensible, fall back only for read-only implementations, and stabilize startup-close coverage.
@marandaneto
marandaneto marked this pull request as ready for review August 5, 2026 19:18
@marandaneto
marandaneto requested a review from a team as a code owner August 5, 2026 19:18
@greptile-apps

greptile-apps Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Reviews (1): Last reviewed commit: "fix: preserve async runner loop policy" | Re-trigger Greptile

Document direct deferred lifecycle calls and the safe application-thread handoff pattern for callbacks that require blocking shutdown completion.
@marandaneto

Copy link
Copy Markdown
Member Author

@dustinbyrne some eyes here would be good since its a complex code path, but i managed to reproduce the bug before and it seems fixed now + extensible tests run locally

@posthog

posthog Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

🦔 ReviewHog reviewed this pull request

Found 0 must fix, 1 should fix, 5 consider.

Published 6 findings (view the review).

@posthog

posthog Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

ReviewHog Alpha 🦔 If you find any issues helpful - please reply "valid", "invalid", etc., for evaluation purposes 🙏

@posthog posthog Bot 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.

ReviewHog Report

Bugfix

Issues: 3 issues

Files (4)
  • posthog/client.py
  • posthog/consumer.py
  • posthog/__init__.py
  • .sampo/changesets/lifecycle-deadlocks.md
What were the main changes
  • Adds a lifecycle lock/condition to serialize join()/shutdown() ownership and prevent deadlocks from reentrant or concurrent calls
  • Defers and coalesces lifecycle (join/shutdown) and flush calls made from consumer error callbacks, poller threads, or cache-provider async runner threads via _is_lifecycle_callback_thread/_defer_lifecycle_from_callback/_defer_flush_from_callback
  • Adds discard_undrainable_queued_work() to _Lane to safely drop queued events when no consumer is running instead of blocking forever
  • Reworks lane flush()/join() to use unfinished_tasks polling with drain-signal integration and graceful handling of dead consumers
  • Rebuilds fork-unsafe lifecycle locks/state (_lifecycle_lock, deferred-flush state, shutdown event) before restarting child threads after fork
  • Consumer.next_batch now tracks pending_items and calls task_done on exceptions to avoid leaking unfinished_tasks counts on interruption
  • Updates public docstrings (init.py, client.py) clarifying that on_error callbacks must be non-blocking and lifecycle calls from callbacks are deferred
  • Adds changeset describing the lifecycle deadlock fix

Infrastructure

Issues: 3 issues

Files (1)
  • posthog/_async_utils.py
What were the main changes
  • Adds _ContextExecutorCall/_PlainExecutorCall to preserve contextvars across run_in_executor calls while remaining picklable for serializing executors
  • Adds _ContextEventLoop fallback for event loop policies that don't allow monkey-patching run_in_executor
  • Hardens _BackgroundEventLoopRunner startup: tracks _startup_error, _close_requested, and only restarts the thread if not alive
  • Hardens close(): tracks _closing_threads set, avoids deadlock when closing during startup or from the runner's own thread, adds owns_thread() to detect lifecycle-callback ownership
  • Ensures run() rejects synchronous calls from the runner thread itself and retries loop acquisition if closed concurrently

Comment thread posthog/client.py Outdated
Comment thread posthog/client.py
Comment thread posthog/_async_utils.py Outdated
Comment thread posthog/client.py
Comment thread posthog/_async_utils.py
Comment thread posthog/_async_utils.py Outdated
Comment thread posthog/client.py
Comment thread posthog/test/test_client.py
Comment thread posthog/client.py
Comment thread posthog/client.py Outdated
Comment thread posthog/client.py Outdated
Comment thread posthog/client.py Outdated
Comment thread posthog/client.py Outdated
@marandaneto
marandaneto requested a review from a team August 6, 2026 06:19
@marandaneto
marandaneto requested a review from dustinbyrne August 6, 2026 08:34
@marandaneto

Copy link
Copy Markdown
Member Author

@dustinbyrne tried to simplify as much as i could, also ran a few cycles of reviews with different models

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

ran a bunch of targeted tests locally to validate, all look good:

  • Full suite: 2045 passed, 16 skipped
  • Focused lifecycle suite on Python 3.11, 3.12, and 3.13: 305 passed + 14 subtests each
  • 150 concurrent lifecycle rounds with producer threads, two lanes, upload failures, and callback re-entry
  • 200 shutdown/delivery races: every accepted event delivered exactly once
  • 250 async run()/close() races plus 100 startup/close races
  • 100 forks while all relevant client/queue locks were held
  • Real HTTP 503/on-error shutdown with 40 accepted batches
  • Real in-flight synchronous request versus concurrent shutdown
  • Five-client atexit test completed in about 1.16s

@marandaneto
marandaneto merged commit 55370ee into main Aug 6, 2026
37 checks passed
@marandaneto
marandaneto deleted the fix/lifecycle-deadlocks branch August 6, 2026 18: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.

2 participants