Skip to content

feat: add async feature flag evaluation - #900

Open
marandaneto wants to merge 7 commits into
feat/async-client-capture-v2from
feat/async-client-flags-v2
Open

feat: add async feature flag evaluation#900
marandaneto wants to merge 7 commits into
feat/async-client-capture-v2from
feat/async-client-flags-v2

Conversation

@marandaneto

@marandaneto marandaneto commented Aug 26, 2026

Copy link
Copy Markdown
Member

💡 Motivation and Context

Continues the async SDK work for #103. This PR is stacked on #899, supersedes #720, and incorporates its open review feedback.

The new await AsyncPosthog.evaluate_flags(...) method sends a non-blocking /flags request and returns the existing FeatureFlagEvaluations snapshot. Its is_enabled(), get_flag(), and get_flag_payload() accessors remain synchronous because they only read the returned snapshot. Passing that snapshot to capture(flags=...) attaches the exact values used for application branching.

This PR intentionally does not add the deprecated single-flag client methods or deprecated capture(send_feature_flags=...) behavior. It also does not add local flag-definition polling or fallback caches. The initial async API focuses on the reported problem: remote evaluation when local evaluation is unavailable. This avoids synchronous Redis access, poller lifecycle failures, and the deferred flag-called-event races reported on #720.

$feature_flag_called events use the synchronous buffered capture() method from #899. Deduplication therefore happens before control returns without scheduling extra tasks. The client also tracks flag and remote-config requests as in-flight operations so shutdown waits before closing its instance-owned HTTP transport.

await get_remote_config_payload(...) provides the corresponding non-blocking remote-config API with bearer authentication and encoded request paths.

All changes remain additive. Existing synchronous clients and module-level APIs are unchanged. The new constructor options are appended to the new async client's signature.

playgrounds/fastapi-async-client demonstrates the complete stacked API in FastAPI, including buffered and immediate capture, identify operations, exception capture, flag evaluation, remote config, flush, and lifespan-managed shutdown.

💚 How did you test it?

  • uv run ruff format --check .
  • uv run ruff check .
  • uv run mypy --no-site-packages --config-file mypy.ini . | uv run mypy-baseline filter
  • uv run --extra test pytest --timeout=30 -q - 2298 passed, 15 skipped, 36 subtests passed
  • uv run --extra dev make public_api_check
  • uv lock --check
  • uv run python -W error -c "import posthog"
  • Generated and imported the posthoganalytics mirror with the async flag APIs
  • Autoreview against origin/feat/async-client-capture-v2 reported no actionable findings at 0b40643

📝 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. We narrowed the old #720 API to the recommended snapshot-based evaluation method and remote config. Prior review findings guided the retry contract, request sanitization, shutdown tracking, flag-called deduplication, and the decision to omit deprecated and local-evaluation surfaces from this stack.

@github-actions

github-actions Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-08-26 14:53:06 UTC
Duration: 256380ms

✅ 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 518ms
Endpoint And Method.Does Not Use Legacy Endpoints 510ms
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 510ms
Body Format.Body Has Created At And Batch 510ms
Body Format.No Api Key In Body 510ms
Body Format.No Sent At In Body 511ms
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 510ms
Event Format.Custom Properties Preserved 510ms
Event Format.Set Properties Preserved 511ms
Event Format.Set Once Properties Preserved 510ms
Event Format.Groups Properties Preserved 509ms
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 513ms
Event Format.Event Timestamp Is Rfc3339 Batch 513ms
Event Format.Distinct Id Is String Batch 514ms
Event Format.Distinct Id At Root Not Properties Batch 513ms
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 513ms
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 1010ms
Batch Behavior.Created At Reflects Batch Creation Time 511ms
Deduplication.Generates Unique Uuids 517ms
Deduplication.Different Events Same Content Different Uuids 513ms
Deduplication.Preserves Uuid On Retry 6519ms
Deduplication.Preserves Timestamp On Retry 6519ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6522ms
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 13525ms
Header Behavior On Retry.Request Id Preserved On Retry 6519ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3021ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6519ms
Response Format Validation.Success Response Has Uuid Keyed Results 511ms
Response Format Validation.Success Response Has Ok For Each Event 514ms
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 512ms
Response Format Validation.Response Echoes Request Id 510ms
Retry Behavior.Retries On 408 6520ms
Retry Behavior.Retries On 500 6519ms
Retry Behavior.Retries On 503 8523ms
Retry Behavior.Retries On 504 6518ms
Retry Behavior.Retryable Errors Have Retry After 3518ms
Retry Behavior.Respects Retry After On Retryable Error 11517ms
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 2514ms
Retry Behavior.Does Not Retry On 415 2513ms
Retry Behavior.Non Retryable Errors Have No Retry After 2512ms
Retry Behavior.Implements Backoff 22531ms
Retry Behavior.Max Retries Respected 22537ms
Partial Batch Handling.Handles 200 Full Success 2512ms
Partial Batch Handling.Handles 200 With All Ok 3517ms
Partial Batch Handling.Does Not Retry Dropped Events 3513ms
Partial Batch Handling.Does Not Retry Limited Events 3516ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6522ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6517ms
Partial Batch Handling.Retries Only Retry Events From Partial 6523ms
Partial Batch Handling.Partial Retry Preserves Uuids 6518ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6517ms
Partial Batch Handling.Partial Retry Request Id Preserved 6518ms
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 3520ms
Compression.Sends Gzip Content Encoding 512ms
Compression.No Content Encoding When Disabled 509ms
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 510ms
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 510ms
Geoip And Historical Migration.Historical Migration Set In Body 510ms
Geoip And Historical Migration.Historical Migration Absent By Default 510ms

Feature_Flags Tests

17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 11ms
Request Payload.Flags Request Uses V2 Query Param 9ms
Request Payload.Flags Request Hits Flags Path Not Decide 9ms
Request Payload.Flags Request Omits Authorization Header 10ms
Request Payload.Token In Flags Body Matches Init 9ms
Request Payload.Groups Round Trip 10ms
Request Payload.Groups Default To Empty Object 9ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 10ms
Request Payload.Disable Geoip Omitted Defaults To False 9ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 9ms
Request Lifecycle.No Flags Request On Init Alone 4ms
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 314ms
Retry Behavior.Retries Flags On 504 314ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 512ms

@marandaneto
marandaneto marked this pull request as ready for review August 26, 2026 14:03
@marandaneto
marandaneto requested a review from a team as a code owner August 26, 2026 14:03
@greptile-apps

greptile-apps Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor
Prompt To Fix All With AI
### Issue 1
posthog/test/test_async_request.py:151-173
**Incomplete retry-flow coverage**

The success-path test covers only one transient failure before success, while `async_flags` supports multiple attempts and attempt-dependent backoff. A regression in later retries or exponential backoff progression would therefore pass this suite undetected.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Reviews (1): Last reviewed commit: "fix: evaluate flags for zero distinct ID" | Re-trigger Greptile

Comment thread posthog/test/test_async_request.py

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

Agent-led review, human-reviewed before posting.

Comment thread posthog/_async_request.py
"/flags/?v=2", content=data, headers=headers, timeout=timeout
)
return await asyncio.to_thread(_process_flags_response, response)
except (httpx_module.TimeoutException, httpx_module.NetworkError):

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.

httpx.RemoteProtocolError is a TransportError, but it is not a NetworkError. A server disconnect can therefore skip the configured retry. evaluate_flags() then catches the error and returns an empty snapshot. I reproduced this with feature_flags_request_max_retries=1: the first request raised RemoteProtocolError, the second would have succeeded, but the client made only one request. Could we include this transient error in the bounded retry policy and add a disconnect-then-success test?

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