Skip to content

feat: add asyncio capture client - #899

Open
marandaneto wants to merge 13 commits into
mainfrom
feat/async-client-capture-v2
Open

feat: add asyncio capture client#899
marandaneto wants to merge 13 commits into
mainfrom
feat/async-client-capture-v2

Conversation

@marandaneto

@marandaneto marandaneto commented Aug 26, 2026

Copy link
Copy Markdown
Member

💡 Motivation and Context

Implements the capture foundation for #103. This supersedes the capture work in #719 and incorporates its open review feedback.

This is additive. Existing Client, Posthog, and module-level APIs are unchanged. The new AsyncClient and AsyncPosthog classes are available through the optional posthog[async] extra, while plain import posthog continues to work without httpx installed.

capture() remains a synchronous, non-blocking queue write, matching the existing server SDK behavior discussed on #719. Callers can use await capture_immediate() when they need to wait for a delivery attempt. The client owns an asyncio queue, workers, and an instance-scoped HTTP transport. Shutdown stops admission, delivers accepted work, waits for in-flight immediate captures, and closes the transport without cancelling batches in progress.

The client is standalone instead of inheriting from the synchronous Client. It supports both capture wire protocols. Capture v0 uses httpx, while the existing v1 partial-retry submitter runs off the event loop to preserve its established protocol behavior.

💚 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 --verbose --timeout=30 - 2284 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 new classes
  • Autoreview against origin/main reported no actionable findings at 54cf24c

📝 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 replaced the old inheritance-based design with a standalone client, kept buffered capture synchronous, and added an awaitable immediate-delivery method. Review findings from #719 guided the lifecycle, transport ownership, event-loop blocking, retry, logging, and compatibility tests.

@marandaneto marandaneto self-assigned this Aug 26, 2026
@github-actions

github-actions Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-08-27 20:06:19 UTC
Duration: 256451ms

✅ 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 517ms
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 509ms
Required Headers.Has Posthog Request Timestamp 511ms
Required Headers.Has User Agent 510ms
Body Format.Body Has Created At And Batch 510ms
Body Format.No Api Key In Body 512ms
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.Distinct Id Is String 511ms
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 510ms
Event Format.Groups Properties Preserved 510ms
Event Format.Sdk Generates Uuid If Not Provided 510ms
Event Format.Event Has Required Root Fields Batch 514ms
Event Format.Event Uuid Is Valid Batch 514ms
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 514ms
Event Format.Set Once Properties Preserved Batch 513ms
Event Format.Groups Properties Preserved Batch 514ms
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 517ms
Deduplication.Different Events Same Content Different Uuids 513ms
Deduplication.Preserves Uuid On Retry 6515ms
Deduplication.Preserves Timestamp On Retry 6520ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6523ms
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 13527ms
Header Behavior On Retry.Request Id Preserved On Retry 6520ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3021ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6517ms
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 1518ms
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 6517ms
Retry Behavior.Retries On 503 8524ms
Retry Behavior.Retries On 504 6520ms
Retry Behavior.Retryable Errors Have Retry After 3516ms
Retry Behavior.Respects Retry After On Retryable Error 11518ms
Retry Behavior.Does Not Retry On 400 2512ms
Retry Behavior.Does Not Retry On 401 2513ms
Retry Behavior.Does Not Retry On 402 2513ms
Retry Behavior.Does Not Retry On 413 2512ms
Retry Behavior.Does Not Retry On 415 2512ms
Retry Behavior.Non Retryable Errors Have No Retry After 2513ms
Retry Behavior.Implements Backoff 22534ms
Retry Behavior.Max Retries Respected 22537ms
Partial Batch Handling.Handles 200 Full Success 2512ms
Partial Batch Handling.Handles 200 With All Ok 3515ms
Partial Batch Handling.Does Not Retry Dropped Events 3516ms
Partial Batch Handling.Does Not Retry Limited Events 3514ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6517ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6524ms
Partial Batch Handling.Retries Only Retry Events From Partial 6524ms
Partial Batch Handling.Partial Retry Preserves Uuids 6521ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6518ms
Partial Batch Handling.Partial Retry Request Id Preserved 6521ms
Partial Batch Handling.Respects Retry After On Partial 8522ms
Partial Batch Handling.Unknown Result Treated As Terminal 3513ms
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 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 511ms
Event Options.Options Override In Batch 515ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 510ms
Geoip And Historical Migration.Historical Migration Set In Body 511ms
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 11ms
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 10ms
Request Payload.Token In Flags Body Matches Init 10ms
Request Payload.Groups Round Trip 10ms
Request Payload.Groups Default To Empty Object 10ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 9ms
Request Payload.Disable Geoip Omitted Defaults To False 10ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 10ms
Request Lifecycle.No Flags Request On Init Alone 3ms
Request Lifecycle.No Flags Request On Normal Capture 511ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 15ms
Request Lifecycle.Mock Response Value Is Returned To Caller 9ms
Retry Behavior.Retries Flags On 502 314ms
Retry Behavior.Retries Flags On 504 315ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 512ms

@marandaneto

Copy link
Copy Markdown
Member Author

Usage examples

The three client modes are intended for different application lifecycles.

Long-running synchronous applications

Use the regular client for Django, Flask, workers, and other long-running synchronous processes. capture() queues events and returns quickly.

import posthog

client = posthog.Client(
    project_api_key="phc_project_key",
    host="https://us.i.posthog.com",
)

client.capture(
    "order completed",
    distinct_id="user-123",
    properties={"order_id": "order-456"},
)

# During application shutdown:
client.shutdown()

Short-lived synchronous processes

Use sync_mode=True for CLI scripts, serverless functions, tests, or jobs that may terminate before a background queue flushes. Each capture blocks until its delivery attempt and retries finish.

import posthog

client = posthog.Client(
    project_api_key="phc_project_key",
    host="https://us.i.posthog.com",
    sync_mode=True,
)

event_id = client.capture(
    "job completed",
    distinct_id="user-123",
)

if event_id is None:
    print("PostHog delivery attempt failed")

Avoid this mode in high-throughput or latency-sensitive request handlers.

Asyncio applications

Use AsyncPosthog for FastAPI, aiohttp, async workers, and other asyncio applications. Ordinary capture() remains synchronous and queue-based; capture_immediate() bypasses the queue and awaits the delivery attempt.

import posthog

async def run():
    async with posthog.AsyncPosthog(
        project_api_key="phc_project_key",
        host="https://us.i.posthog.com",
    ) as client:
        # Buffered capture: fast and intentionally not awaited.
        client.capture(
            "background event",
            distinct_id="user-123",
        )

        # Immediate capture: bypasses batching and waits for the request/retries.
        event_id = await client.capture_immediate(
            "important event",
            distinct_id="user-123",
        )

        if event_id is None:
            print("PostHog delivery attempt failed")

Leaving the async context flushes queued events and closes the client-owned HTTP transport.

@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
Comment thread posthog/async_client.py Outdated
Comment thread posthog/async_client.py
@veria-ai

veria-ai Bot commented Aug 26, 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: 2 · PR risk: 0/10

@greptile-apps

greptile-apps Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

Security Review

The v0 async transport follows redirects without restricting the destination origin. A cross-origin 307/308 response can therefore forward the request body containing the project API key and event payload to another origin.

Prompt To Fix All With AI
### Issue 1
posthog/_async_request.py:34
**Redirects expose capture credentials**

If the configured ingestion host returns a cross-origin 307 or 308 redirect, this client resends the v0 POST body containing the project API key and event batch to that origin, exposing capture credentials and analytics data. Restrict redirects to the configured origin or disable automatic redirect following.

**How this was verified:** The redirect-following client sends the serialized v0 body that includes both the API key and captured events.

### Issue 2
posthog/async_client.py:343-345
**Callbacks block event loop**

A synchronous `before_send` callback executes inline before its result is checked for awaitability, so blocking I/O or sleeps stall unrelated request handlers, timers, delivery operations, and lifecycle calls on the same event loop. Offload synchronous callbacks while continuing to await asynchronous callbacks normally.

### Issue 3
posthog/_async_consumer.py:208-230
**Retry flow lacks coverage**

The new retry loop has no test covering multiple attempts, leaving retry classification, attempt limits, backoff, `Retry-After`, and recovery after a transient failure unprotected against regressions. Add a parameterized test that fails one or more attempts before succeeding and verifies the complete retry sequence.

---

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

Reviews (1): Last reviewed commit: "docs: clarify async alternative to sync ..." | Re-trigger Greptile

Comment thread posthog/_async_request.py Outdated
Comment thread posthog/async_client.py Outdated
Comment thread posthog/_async_consumer.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_consumer.py Outdated
Comment thread posthog/async_client.py Outdated
@dustinbyrne
dustinbyrne requested a review from a team August 26, 2026 18:09
@arnohillen

Copy link
Copy Markdown

follow_redirects=False drops the batch whenever the host answers /batch/ with a 307/308, since _process_response only accepts 200 and _is_retryable() treats 3xx as retryable (so it also burns all 4 attempts plus ~7s of backoff first), while the sync client and this PR's own capture_mode="v1" path both follow the redirect and deliver the body; restricting redirects to the configured origin would keep the credential fix without that divergence.

@arnohillen

Copy link
Copy Markdown

shutdown() calls flush(timeout_seconds=None), which awaits self._queue.join() with no timeout and no liveness check, so if a worker has exited (through run()'s catch-all async consumer stopped after an unexpected ..., or via cancellation) while events are still unacknowledged it is never replaced (_ensure_workers_started() returns early because _worker_tasks is non-empty, and a finished task still counts) and await client.shutdown() never returns; Client.flush() guards the same case with not any(consumer.is_alive() for consumer in self.consumers) plus discard_undrainable_queued_work().

@arnohillen

Copy link
Copy Markdown

capture() writes to the loop-bound asyncio.Queue from whatever thread calls it, so a call from a worker thread (Starlette runs def endpoints in a threadpool) raises Non-thread-safe operation invoked on an event loop other than the current one inside put_nowait whenever the loop has debug on (python -X dev or PYTHONASYNCIODEBUG=1): the event is queued but capture() returns None, the consumer parked in queue.get() is left permanently wedged so nothing already in the queue is ever delivered either, and await client.shutdown() then hangs forever; either route the write through loop.call_soon_threadsafe when self._loop is bound to another thread, or reject the call explicitly (same pattern in _enqueue_built_event).

@marandaneto

Copy link
Copy Markdown
Member Author

Thanks for the detailed reproductions, @arnohillen. Addressed in b7f70b5 and 54cf24c.

I first added focused tests on d59c99a; all three failed for the reported reasons:

  • same-origin 307 raised APIError instead of following the redirect;
  • shutdown timed out in queue.join() after all workers exited;
  • debug-loop capture from a worker thread returned None with Non-thread-safe operation invoked on an event loop other than the current one.

The same focused suite now passes (5 tests, including cross-origin redirect rejection and the shutdown-admission race). The implementation now:

  • follows only bounded, same-origin 307/308 redirects while rejecting cross-origin targets;
  • monitors queue drain against worker liveness and discards otherwise-undrainable work if all workers exit;
  • admits cross-thread buffered events through loop.call_soon_threadsafe() and rechecks shutdown state on the bound loop.

Full validation: 2284 tests passed, Ruff/mypy/public API/import checks passed, and the final autoreview reported no actionable findings.

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.

3 participants