Skip to content

fix: support scoped async functions#569

Merged
marandaneto merged 3 commits into
mainfrom
fix/async-scoped-context
May 13, 2026
Merged

fix: support scoped async functions#569
marandaneto merged 3 commits into
mainfrom
fix/async-scoped-context

Conversation

@marandaneto
Copy link
Copy Markdown
Member

💡 Motivation and Context

Fixes #568.

posthog.scoped() previously wrapped async functions with a synchronous wrapper. That entered and exited the PostHog context before the returned coroutine was awaited, so context values such as identify_context() were unavailable inside async middleware/routes.

💚 How did you test it?

  • .venv/bin/python -m pytest posthog/test/test_contexts.py -q
  • .venv/bin/python -m ruff check posthog/contexts.py posthog/test/test_contexts.py

📝 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

@marandaneto marandaneto requested a review from a team as a code owner May 13, 2026 12:30
@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps Bot commented May 13, 2026

Prompt To Fix All With AI
Fix the following 2 code review issues. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 2
posthog/test/test_contexts.py:236-275
**Concurrent-task isolation not tested**

The primary motivation for this fix is that `@posthog.scoped()` is used on async route/middleware handlers that run concurrently in the same event loop. The new tests only verify single-task sequential execution via `asyncio.run()`, so they don't exercise the `contextvars` isolation that matters most in practice. A test using `asyncio.gather()` — where two coroutines set different identities simultaneously — would confirm that each task's `_context_stack` remains independent. Without it, a regression that replaces the `ContextVar` with a plain global would still pass the current tests.

### Issue 2 of 2
posthog/test/test_contexts.py:236-249
**New tests could be parameterised alongside their sync equivalents**

Per the project's preference for parameterised tests, `test_scoped_decorator_async_function` and `test_scoped_decorator_async_exception` largely mirror `test_scoped_decorator_with_context_ids` and `test_scoped_decorator_exception`. Parameterising them with `(sync_func, async_runner)` pairs (e.g. using `subTest` or a helper) would eliminate the duplication and make it trivial to add further variants without copy-pasting.

Reviews (1): Last reviewed commit: "fix: support scoped async functions" | Re-trigger Greptile

Comment thread posthog/test/test_contexts.py Outdated
Comment thread posthog/test/test_contexts.py Outdated
@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps Bot commented May 13, 2026

Reviews (2): Last reviewed commit: "test: cover concurrent scoped async isol..." | Re-trigger Greptile

@greptile-apps
Copy link
Copy Markdown
Contributor

greptile-apps Bot commented May 13, 2026

Reviews (3): Last reviewed commit: "test: parameterize scoped async cases" | Re-trigger Greptile

@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented May 13, 2026

posthog-python Compliance Report

Date: 2026-05-13 14:15:46 UTC
Duration: 4674924ms

⚠️ Some Tests Failed

29/45 tests passed, 16 failed


Capture Tests

29/29 tests passed

View Details
Test Status Duration
Format Validation.Event Has Required Fields 517ms
Format Validation.Event Has Uuid 1507ms
Format Validation.Event Has Lib Properties 1507ms
Format Validation.Distinct Id Is String 1507ms
Format Validation.Token Is Present 1507ms
Format Validation.Custom Properties Preserved 1507ms
Format Validation.Event Has Timestamp 1507ms
Retry Behavior.Retries On 503 9518ms
Retry Behavior.Does Not Retry On 400 3507ms
Retry Behavior.Does Not Retry On 401 3507ms
Retry Behavior.Respects Retry After Header 9510ms
Retry Behavior.Implements Backoff 23533ms
Retry Behavior.Retries On 500 7501ms
Retry Behavior.Retries On 502 7517ms
Retry Behavior.Retries On 504 7512ms
Retry Behavior.Max Retries Respected 23521ms
Deduplication.Generates Unique Uuids 1505ms
Deduplication.Preserves Uuid On Retry 7515ms
Deduplication.Preserves Uuid And Timestamp On Retry 14519ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 7511ms
Deduplication.No Duplicate Events In Batch 1504ms
Deduplication.Different Events Have Different Uuids 1507ms
Compression.Sends Gzip When Enabled 1507ms
Batch Format.Uses Proper Batch Structure 1507ms
Batch Format.Flush With No Events Sends Nothing 1005ms
Batch Format.Multiple Events Batched Together 1505ms
Error Handling.Does Not Retry On 403 3509ms
Error Handling.Does Not Retry On 413 3508ms
Error Handling.Retries On 408 7510ms

Feature_Flags Tests

⚠️ 0/16 tests passed, 16 failed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 509ms
Request Payload.Flags Request Uses V2 Query Param 300896ms
Request Payload.Flags Request Hits Flags Path Not Decide 300985ms
Request Payload.Flags Request Omits Authorization Header 301015ms
Request Payload.Token In Flags Body Matches Init 301000ms
Request Payload.Groups Round Trip 300991ms
Request Payload.Groups Default To Empty Object 300971ms
Request Payload.Person Properties Distinct Id Auto Populated When Caller Omits It 301038ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 300954ms
Request Payload.Disable Geoip Omitted Defaults To False 300952ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 301039ms
Request Lifecycle.No Flags Request On Init Alone 301031ms
Request Lifecycle.No Flags Request On Normal Capture 301024ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 300922ms
Request Lifecycle.Mock Response Value Is Returned To Caller 301024ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 301055ms

Failures

request_payload.request_with_person_properties_device_id

Field 'token' not found in /flags request body at path 'token'. Available keys: ['distinct_id', 'groups', 'person_properties', 'group_properties', 'geoip_disable', 'device_id', 'flag_keys_to_evaluate', 'sentAt', 'api_key']

request_payload.flags_request_uses_v2_query_param

No error message

request_payload.flags_request_hits_flags_path_not_decide

No error message

request_payload.flags_request_omits_authorization_header

No error message

request_payload.token_in_flags_body_matches_init

No error message

request_payload.groups_round_trip

No error message

request_payload.groups_default_to_empty_object

No error message

request_payload.person_properties_distinct_id_auto_populated_when_caller_omits_it

No error message

request_payload.disable_geoip_false_propagates_as_geoip_disable_false

No error message

request_payload.disable_geoip_omitted_defaults_to_false

No error message

request_payload.flag_keys_to_evaluate_contains_only_requested_key

No error message

request_lifecycle.no_flags_request_on_init_alone

No error message

request_lifecycle.no_flags_request_on_normal_capture

No error message

request_lifecycle.two_flag_calls_produce_two_remote_requests

No error message

request_lifecycle.mock_response_value_is_returned_to_caller

No error message

side_effect_events.get_feature_flag_captures_feature_flag_called_event

No error message

@marandaneto marandaneto merged commit 44c1261 into main May 13, 2026
26 checks passed
@marandaneto marandaneto deleted the fix/async-scoped-context branch May 13, 2026 14:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

@scoped doesn't work with async fastapi middleware

2 participants