Skip to content

feat(capture): route analytics through v1 submitter (capture v1, 4/6)#704

Merged
eli-r-ph merged 4 commits into
capture-v1/03-transportfrom
capture-v1/04-wire
Jul 6, 2026
Merged

feat(capture): route analytics through v1 submitter (capture v1, 4/6)#704
eli-r-ph merged 4 commits into
capture-v1/03-transportfrom
capture-v1/04-wire

Conversation

@eli-r-ph

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Fourth PR in the stacked Capture V1 series (stacked on #703). This is the one that makes capture_mode actually do something: it wires send_v1_batch (from #703) into both send paths, so the previously-inert v1 transport is now selectable end to end. Default is still v0, so existing callers are unaffected.

  • Async path (Consumer.request) — refactored to route via _send_analytics / _send_ai. _send_analytics picks the submitter by capture_mode: v1 -> the partial-retry send_v1_batch, v0 -> the legacy batch_post loop. _send_ai always uses the legacy submitter.
  • Sync path (Client._enqueue, sync_mode=True) — same branch: an analytics event in v1 goes through send_v1_batch([msg]); everything else stays on batch_post.
  • The dedicated AI endpoint has no v1 form, so $ai_* events routed to it always use the legacy submitter regardless of capture_mode. When the dedicated AI endpoint is not enabled, all events (including $ai_*) go to the single analytics destination and therefore follow capture_mode — exactly mirroring the v0 single-endpoint behavior.

Supporting changes: Client.max_retries is now stored so the sync path can forward it, and gzip/timeout/retries/historical_migration are forwarded to the v1 submitter so it honors the same config as v0.

💚 How did you test it?

  • test_consumer.py — new TestConsumerCaptureModeRouting: v0 -> batch_post, v1 -> send_v1_batch, config-forwarding, dedicated-AI split (analytics -> v1 submitter / $ai_* -> legacy AI endpoint), and AI-only batch skips the v1 submitter.
  • test_client.py — new TestClientSyncCaptureMode: v0 vs v1 sync submitter selection, config forwarding, dedicated-AI $ai_* event stays legacy, dedicated-AI analytics event uses v1.

Full test_consumer.py (25) and the new client class green; ruff format/check clean; mypy clean on client.py + consumer.py; regenerated references/public_api_snapshot.txt.

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change (v0 remains the default wire protocol).

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Authored with Cursor (Claude Opus 4.8) per the agreed plan. The routing split intentionally keeps the dedicated-AI destination on the legacy submitter — there is no v1 AI ingestion endpoint, so capture_mode only swaps the analytics submitter. This mirrors posthog-go, where CaptureMode likewise governs only the analytics path.

@greptile-apps

greptile-apps Bot commented Jun 27, 2026

Copy link
Copy Markdown
Contributor

Reviews (1): Last reviewed commit: "feat(capture): route analytics through v..." | Re-trigger Greptile

Comment thread posthog/consumer.py
Comment thread posthog/test/test_consumer.py Outdated
@github-actions

github-actions Bot commented Jun 27, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-07-06 21:09:53 UTC
Duration: 338827ms

✅ 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 516ms
Endpoint And Method.Does Not Use Legacy Endpoints 1009ms
Required Headers.Has Authorization Bearer Header 1008ms
Required Headers.Has Content Type Json 1008ms
Required Headers.Has Posthog Sdk Info Format 1009ms
Required Headers.Has Posthog Attempt Header 1009ms
Required Headers.Has Posthog Request Id 1009ms
Required Headers.Has Posthog Request Timestamp 1008ms
Required Headers.Has User Agent 1010ms
Body Format.Body Has Created At And Batch 1008ms
Body Format.No Api Key In Body 1008ms
Body Format.No Sent At In Body 1009ms
Event Format.Event Has Required Root Fields 1009ms
Event Format.Event Uuid Is Valid 1008ms
Event Format.Event Timestamp Is Rfc3339 1008ms
Event Format.Distinct Id Is String 1008ms
Event Format.Distinct Id At Root Not Properties 1009ms
Event Format.Custom Properties Preserved 1008ms
Event Format.Set Properties Preserved 1008ms
Event Format.Set Once Properties Preserved 1008ms
Event Format.Groups Properties Preserved 1008ms
Event Format.Sdk Generates Uuid If Not Provided 1009ms
Event Format.Event Has Required Root Fields Batch 1011ms
Event Format.Event Uuid Is Valid Batch 1011ms
Event Format.Event Timestamp Is Rfc3339 Batch 1012ms
Event Format.Distinct Id Is String Batch 1011ms
Event Format.Distinct Id At Root Not Properties Batch 1012ms
Event Format.Custom Properties Preserved Batch 1012ms
Event Format.Set Properties Preserved Batch 1011ms
Event Format.Set Once Properties Preserved Batch 1012ms
Event Format.Groups Properties Preserved Batch 1012ms
Event Format.Sdk Generates Uuid If Not Provided Batch 1012ms
Batch Behavior.Multiple Events In Single Batch 1507ms
Batch Behavior.Batch Envelope Smoke 1014ms
Batch Behavior.Flush With No Events Sends Nothing 1004ms
Batch Behavior.Flush At Triggers Batch 1508ms
Batch Behavior.Created At Reflects Batch Creation Time 1011ms
Deduplication.Generates Unique Uuids 1507ms
Deduplication.Different Events Same Content Different Uuids 1507ms
Deduplication.Preserves Uuid On Retry 7511ms
Deduplication.Preserves Timestamp On Retry 7516ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 7512ms
Deduplication.No Duplicate Events In Batch 1504ms
Header Behavior On Retry.Attempt Header Starts At One 1010ms
Header Behavior On Retry.Attempt Header Increments On Retry 14523ms
Header Behavior On Retry.Request Id Preserved On Retry 7509ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3514ms
Header Behavior On Retry.Request Timestamp Changes On Retry 7513ms
Response Format Validation.Success Response Has Uuid Keyed Results 1005ms
Response Format Validation.Success Response Has Ok For Each Event 1506ms
Response Format Validation.Success No Retry After When All Ok 1507ms
Response Format Validation.Success Retry After Present When Retry Events 2510ms
Response Format Validation.Success No Retry After When Drop Only 1508ms
Response Format Validation.Response Echoes Request Id 1008ms
Retry Behavior.Retries On 408 7515ms
Retry Behavior.Retries On 500 7510ms
Retry Behavior.Retries On 503 9517ms
Retry Behavior.Retries On 504 7510ms
Retry Behavior.Retryable Errors Have Retry After 4509ms
Retry Behavior.Respects Retry After On Retryable Error 12517ms
Retry Behavior.Does Not Retry On 400 3503ms
Retry Behavior.Does Not Retry On 401 3508ms
Retry Behavior.Does Not Retry On 402 3507ms
Retry Behavior.Does Not Retry On 413 3508ms
Retry Behavior.Does Not Retry On 415 3506ms
Retry Behavior.Non Retryable Errors Have No Retry After 3507ms
Retry Behavior.Implements Backoff 23531ms
Retry Behavior.Max Retries Respected 23511ms
Partial Batch Handling.Handles 200 Full Success 3010ms
Partial Batch Handling.Handles 200 With All Ok 4508ms
Partial Batch Handling.Does Not Retry Dropped Events 4508ms
Partial Batch Handling.Does Not Retry Limited Events 4508ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 7514ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 7512ms
Partial Batch Handling.Retries Only Retry Events From Partial 7507ms
Partial Batch Handling.Partial Retry Preserves Uuids 7517ms
Partial Batch Handling.Partial Retry Attempt Header Increments 7512ms
Partial Batch Handling.Partial Retry Request Id Preserved 7512ms
Partial Batch Handling.Respects Retry After On Partial 9513ms
Partial Batch Handling.Unknown Result Treated As Terminal 4504ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 4511ms
Compression.Sends Gzip Content Encoding 1008ms
Compression.No Content Encoding When Disabled 1009ms
Compression.Compressed Body Is Decompressible 1008ms
Error Handling.Does Not Retry On Unknown 4Xx 3508ms
Event Options.Cookieless Mode Override 1009ms
Event Options.Disable Skew Correction Override 1009ms
Event Options.Process Person Profile Override 1007ms
Event Options.Product Tour Id Override 1009ms
Event Options.Unset Options Omitted 1008ms
Event Options.Options Override In Batch 1012ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 1009ms
Geoip And Historical Migration.Historical Migration Set In Body 1008ms
Geoip And Historical Migration.Historical Migration Absent By Default 1009ms

Feature_Flags Tests

17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id 1006ms
Request Payload.Flags Request Uses V2 Query Param 1006ms
Request Payload.Flags Request Hits Flags Path Not Decide 1007ms
Request Payload.Flags Request Omits Authorization Header 1006ms
Request Payload.Token In Flags Body Matches Init 1006ms
Request Payload.Groups Round Trip 1007ms
Request Payload.Groups Default To Empty Object 1006ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False 1007ms
Request Payload.Disable Geoip Omitted Defaults To False 1006ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key 1007ms
Request Lifecycle.No Flags Request On Init Alone 502ms
Request Lifecycle.No Flags Request On Normal Capture 1507ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests 1010ms
Request Lifecycle.Mock Response Value Is Returned To Caller 1003ms
Retry Behavior.Retries Flags On 502 1006ms
Retry Behavior.Retries Flags On 504 1006ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event 1509ms

@eli-r-ph eli-r-ph force-pushed the capture-v1/03-transport branch from a901fdc to 7fd7dcd Compare June 27, 2026 23:16
@eli-r-ph eli-r-ph force-pushed the capture-v1/04-wire branch 2 times, most recently from 3274be1 to 5026185 Compare June 27, 2026 23:58
@eli-r-ph eli-r-ph force-pushed the capture-v1/03-transport branch 2 times, most recently from 32d7b02 to 3677400 Compare June 28, 2026 00:20
@eli-r-ph eli-r-ph force-pushed the capture-v1/04-wire branch from 5026185 to d1875fc Compare June 28, 2026 00:20
@eli-r-ph eli-r-ph self-assigned this Jun 28, 2026
@eli-r-ph eli-r-ph force-pushed the capture-v1/04-wire branch from d1875fc to 73e034f Compare June 28, 2026 00:45
@eli-r-ph eli-r-ph force-pushed the capture-v1/03-transport branch from 3677400 to c698bd5 Compare June 28, 2026 00:45
@eli-r-ph eli-r-ph requested a review from a team June 29, 2026 17:59
@eli-r-ph eli-r-ph marked this pull request as ready for review June 29, 2026 18:21
@eli-r-ph eli-r-ph requested a review from a team as a code owner June 29, 2026 18:21
@greptile-apps

greptile-apps Bot commented Jun 29, 2026

Copy link
Copy Markdown
Contributor

Reviews (2): Last reviewed commit: "feat(capture): wire capture_compression ..." | Re-trigger Greptile

@eli-r-ph eli-r-ph force-pushed the capture-v1/04-wire branch 2 times, most recently from 0b0adf7 to 335afbc Compare July 3, 2026 19:05
@eli-r-ph eli-r-ph force-pushed the capture-v1/04-wire branch from 335afbc to aecbab1 Compare July 6, 2026 19:49
@eli-r-ph eli-r-ph force-pushed the capture-v1/03-transport branch from 58cb3e5 to 46bbd7d Compare July 6, 2026 19:49
@eli-r-ph eli-r-ph force-pushed the capture-v1/04-wire branch from aecbab1 to 1210124 Compare July 6, 2026 19:57
eli-r-ph added 3 commits July 6, 2026 12:59
Wires send_v1_batch into both send paths so capture_mode actually takes
effect end to end. The consumer's async path (Consumer.request) and the
client's sync path (_enqueue) now pick the analytics submitter by
capture_mode: v1 -> the partial-retry send loop, v0 -> the legacy
batch_post. The dedicated AI endpoint has no v1 form, so $ai_* events on it
always use the legacy submitter regardless of capture_mode.

Refactors Consumer.request to route via _send_analytics/_send_ai helpers,
stores Client.max_retries so the sync path can pass it through, and forwards
gzip/timeout/retries/historical_migration to the v1 submitter. Default is
still v0, so existing callers are unaffected.

Adds consumer routing-matrix tests (v0/v1, dedicated-AI split, config
forwarding) and client sync-mode tests (v0 vs v1, dedicated-AI event stays
legacy, analytics event uses v1). ruff/mypy clean.
Resolve capture_compression once on the client (kwarg > env >
legacy gzip flag > none) and thread it to the v1 submitter via the
consumer and the sync path. Parameterize the capture_mode routing
tests and use consistent submitter labels.
@eli-r-ph eli-r-ph force-pushed the capture-v1/04-wire branch from 1210124 to 4afa7c7 Compare July 6, 2026 20:00
* chore(capture): add v1 compliance adapter mode and CI job

Teaches the SDK compliance adapter to speak capture-v1 and adds a second
CI job that runs the harness capture_v1 suite against it.

Splits the workflow into v0 + v1 jobs, both on the 0.10.0 harness
(which carries the capture_v1 suites), and adds adapter timing/debug
settings for reliable test execution.

* chore(capture): document capture_mode + release changeset (capture v1, 6/6) (#706)

* docs(capture): document capture_mode, capture_compression, and changeset

Adds the Sampo changeset for the opt-in capture_mode (v1 ingestion
protocol) and capture_compression, plus an AGENTS.md section mapping
capture_mode/capture_compression and their env vars to the modules and
routing that implement them, the v1 invariants to preserve, and the
sync_mode blocking-retry behavior.

User-facing usage stays in the official docs per the README convention.

* docs(capture): note v1 drop surfacing and Retry-After minimum

Document the two parity behaviors added to the v1 transport: server `drop`
verdicts are accumulated across attempts and surfaced via CaptureV1Error/
on_error even on a 2xx, and Retry-After acts as a minimum (max of configured
backoff and Retry-After, hard-capped) rather than a replacement.

* docs(capture): note the unified 30s retry backoff ceiling

MAX_BACKOFF_SECONDS (30s) caps both the exponential backoff and the
Retry-After clamp; update the v1 invariants note accordingly.

* docs(capture): document zstd compression and private helper names
@eli-r-ph eli-r-ph merged commit 1feb0cc into capture-v1/03-transport Jul 6, 2026
33 checks passed
@eli-r-ph eli-r-ph deleted the capture-v1/04-wire branch July 6, 2026 21:15
eli-r-ph added a commit that referenced this pull request Jul 6, 2026
…6) (#703)

* feat(capture): add v1 transport and partial-retry send loop

Adds the HTTP transport for POST /i/v1/analytics/events alongside the
pure transforms: a single Bearer-authed attempt (post_v1) with the
required v1 headers, response classification (parse_v1_response), and the
send loop (send_v1_batch) that resends only the events the server tags
"retry", logs drops, honors Retry-After, and raises CaptureV1Error on
terminal/transport failure or retry exhaustion so the consumer's existing
on_error path fires unchanged.

429 is terminal in v1 (unlike v0). A 2xx with an unparseable body is
terminal to avoid an infinite resend loop. A stable PostHog-Request-Id and
created_at span attempts; PostHog-Attempt increments.

Factors a shared gzip_compress helper out of request.post (no v0 behavior
change). Still inert: nothing calls send_v1_batch until the consumer wiring
PR. 74 capture_v1 tests (47 transform + 27 transport); ruff/mypy clean.

* fix(capture): stabilize v1 created_at, isolate compression, quiet drops

Address review of the v1 transport:
- Hoist the batch created_at out of the retry loop so the envelope stays
  stable across attempts (only the events list and PostHog-Attempt change).
- Isolate v1 request compression behind a CaptureCompression selector
  supporting gzip and zlib-wrapped deflate (RFC 1950), reverting the
  gzip_compress extraction from request.py so the v1 path owns its codecs.
- Stop logging per-event drops at WARNING; a server-chosen drop on a 2xx
  is not a delivery failure and is already carried on CaptureV1Error for
  batch-level surfacing via on_error.

* fix(capture): surface v1 drops and treat Retry-After as a minimum

Address review of the v1 transport (#703):
- Accumulate server `drop` verdicts across all attempts and raise
  CaptureV1Error even on a 2xx with no retry events (a success status is not
  full delivery) and when a later attempt clears the retries, so on_error sees
  every dropped uuid. Drops also ride along on the retry-exhaustion,
  malformed-2xx, and terminal non-2xx errors.
- _backoff treats Retry-After as a minimum (max of configured backoff and
  Retry-After), hard-capped at 1 day, matching posthog-go/posthog-rs so a small
  header can't retry earlier than the schedule and a hostile one can't park the
  consumer thread.

Adds drop-surfacing and backoff tests; regenerates public_api_snapshot.

* fix(capture): unify v1 retry backoff ceiling at 30s

Replace the 1-day RETRY_BACKOFF_CAP_SECONDS with a single MAX_BACKOFF_SECONDS
(30s) that both caps the exponential backoff and clamps the server Retry-After,
so the max retry wait is bounded and the default matches posthog-go/posthog-rs.
Retry-After remains a minimum; there is no separate large cap.

* refactor(capture): privatize v1 transport and compression resolver

Underscore-prefix the transport layer (post_v1, parse_v1_response,
send_v1_batch, response dataclasses, backoff ceiling) and the
compression resolver; declare __all__ so the public surface is
CaptureCompression, its env var name, and CaptureV1Error (which reaches
user code via on_error callbacks). Re-export CaptureCompression at the
package top level for symmetry with CaptureMode.

* feat(capture): add optional zstd compression for capture v1

Add CaptureCompression.ZSTD backed by the optional zstandard package
(pip install posthog[zstd]); Python has no stdlib zstd until 3.14.
Explicitly requesting zstd without the package raises ValueError
(fail loud at construction); requesting it via
POSTHOG_CAPTURE_COMPRESSION warns and falls back so operator config
never silently breaks capture. The server already decodes
Content-Encoding: zstd standard frames.

* fix(capture): satisfy mypy on env compression resolution

Rename the env-var lookup binding so it is not confused with the
explicit-kwarg resolved value (CaptureCompression | None vs
CaptureCompression).

* fix(capture): avoid unused-ignore on optional zstandard import

Annotate the module binding explicitly so mypy stays clean whether or
not the zstandard package is installed in the dev environment.

* feat(capture): route analytics through v1 submitter (capture v1, 4/6) (#704)

* feat(capture): route analytics through v1 submitter when enabled

Wires send_v1_batch into both send paths so capture_mode actually takes
effect end to end. The consumer's async path (Consumer.request) and the
client's sync path (_enqueue) now pick the analytics submitter by
capture_mode: v1 -> the partial-retry send loop, v0 -> the legacy
batch_post. The dedicated AI endpoint has no v1 form, so $ai_* events on it
always use the legacy submitter regardless of capture_mode.

Refactors Consumer.request to route via _send_analytics/_send_ai helpers,
stores Client.max_retries so the sync path can pass it through, and forwards
gzip/timeout/retries/historical_migration to the v1 submitter. Default is
still v0, so existing callers are unaffected.

Adds consumer routing-matrix tests (v0/v1, dedicated-AI split, config
forwarding) and client sync-mode tests (v0 vs v1, dedicated-AI event stays
legacy, analytics event uses v1). ruff/mypy clean.

* feat(capture): wire capture_compression through client and consumer

Resolve capture_compression once on the client (kwarg > env >
legacy gzip flag > none) and thread it to the v1 submitter via the
consumer and the sync path. Parameterize the capture_mode routing
tests and use consistent submitter labels.

* chore(capture): test $ai_* rides v1 when dedicated AI endpoint disabled

* chore(capture): v1 compliance adapter + CI job (capture v1, 5/6) (#705)

* chore(capture): add v1 compliance adapter mode and CI job

Teaches the SDK compliance adapter to speak capture-v1 and adds a second
CI job that runs the harness capture_v1 suite against it.

Splits the workflow into v0 + v1 jobs, both on the 0.10.0 harness
(which carries the capture_v1 suites), and adds adapter timing/debug
settings for reliable test execution.

* chore(capture): document capture_mode + release changeset (capture v1, 6/6) (#706)

* docs(capture): document capture_mode, capture_compression, and changeset

Adds the Sampo changeset for the opt-in capture_mode (v1 ingestion
protocol) and capture_compression, plus an AGENTS.md section mapping
capture_mode/capture_compression and their env vars to the modules and
routing that implement them, the v1 invariants to preserve, and the
sync_mode blocking-retry behavior.

User-facing usage stays in the official docs per the README convention.

* docs(capture): note v1 drop surfacing and Retry-After minimum

Document the two parity behaviors added to the v1 transport: server `drop`
verdicts are accumulated across attempts and surfaced via CaptureV1Error/
on_error even on a 2xx, and Retry-After acts as a minimum (max of configured
backoff and Retry-After, hard-capped) rather than a replacement.

* docs(capture): note the unified 30s retry backoff ceiling

MAX_BACKOFF_SECONDS (30s) caps both the exponential backoff and the
Retry-After clamp; update the v1 invariants note accordingly.

* docs(capture): document zstd compression and private helper names
eli-r-ph added a commit that referenced this pull request Jul 6, 2026
* feat(capture): add v1 wire serialization transforms

Add posthog/capture_v1.py with the pure (no-I/O) transform layer for
/i/v1/analytics/events:

- to_v1_event(): lifts sentinel properties into the typed options object
  (with the $ignore_sent_at -> disable_skew_correction rename), promotes
  $session_id/$window_id to top-level fields, relocates top-level
  $set/$set_once into properties (v1 has no top-level form), and strips
  $lib/$lib_version (server injects them from PostHog-Sdk-Info). Options are
  coerced to native JSON types or omitted, since a wrong type would 400 the
  whole batch. Pure: the input message is not mutated.
- build_v1_batch_body(): the api_key/sent_at-free envelope with a tz-aware
  RFC3339 created_at.
- Shared constants: path, required header names, result codes, retryable/
  terminal status sets.

Stacked on the capture_mode scaffolding; still inert (nothing calls these yet).

* refactor(capture): store v1 option coercers as callables

Hold the coercer function directly in _OPTION_SENTINELS instead of a
stringly-typed name keyed through a side _COERCERS dict, removing a
KeyError foot-gun and tightening the types.

* refactor(capture): privatize v1 transform helpers

Underscore-prefix the wire constants and transform functions and declare
an empty __all__: the transforms are submitter plumbing, not public API.
The user-facing surface (CaptureMode etc.) is exported elsewhere.

* feat(capture): v1 transport + partial-retry send loop (capture v1, 3/6) (#703)

* feat(capture): add v1 transport and partial-retry send loop

Adds the HTTP transport for POST /i/v1/analytics/events alongside the
pure transforms: a single Bearer-authed attempt (post_v1) with the
required v1 headers, response classification (parse_v1_response), and the
send loop (send_v1_batch) that resends only the events the server tags
"retry", logs drops, honors Retry-After, and raises CaptureV1Error on
terminal/transport failure or retry exhaustion so the consumer's existing
on_error path fires unchanged.

429 is terminal in v1 (unlike v0). A 2xx with an unparseable body is
terminal to avoid an infinite resend loop. A stable PostHog-Request-Id and
created_at span attempts; PostHog-Attempt increments.

Factors a shared gzip_compress helper out of request.post (no v0 behavior
change). Still inert: nothing calls send_v1_batch until the consumer wiring
PR. 74 capture_v1 tests (47 transform + 27 transport); ruff/mypy clean.

* fix(capture): stabilize v1 created_at, isolate compression, quiet drops

Address review of the v1 transport:
- Hoist the batch created_at out of the retry loop so the envelope stays
  stable across attempts (only the events list and PostHog-Attempt change).
- Isolate v1 request compression behind a CaptureCompression selector
  supporting gzip and zlib-wrapped deflate (RFC 1950), reverting the
  gzip_compress extraction from request.py so the v1 path owns its codecs.
- Stop logging per-event drops at WARNING; a server-chosen drop on a 2xx
  is not a delivery failure and is already carried on CaptureV1Error for
  batch-level surfacing via on_error.

* fix(capture): surface v1 drops and treat Retry-After as a minimum

Address review of the v1 transport (#703):
- Accumulate server `drop` verdicts across all attempts and raise
  CaptureV1Error even on a 2xx with no retry events (a success status is not
  full delivery) and when a later attempt clears the retries, so on_error sees
  every dropped uuid. Drops also ride along on the retry-exhaustion,
  malformed-2xx, and terminal non-2xx errors.
- _backoff treats Retry-After as a minimum (max of configured backoff and
  Retry-After), hard-capped at 1 day, matching posthog-go/posthog-rs so a small
  header can't retry earlier than the schedule and a hostile one can't park the
  consumer thread.

Adds drop-surfacing and backoff tests; regenerates public_api_snapshot.

* fix(capture): unify v1 retry backoff ceiling at 30s

Replace the 1-day RETRY_BACKOFF_CAP_SECONDS with a single MAX_BACKOFF_SECONDS
(30s) that both caps the exponential backoff and clamps the server Retry-After,
so the max retry wait is bounded and the default matches posthog-go/posthog-rs.
Retry-After remains a minimum; there is no separate large cap.

* refactor(capture): privatize v1 transport and compression resolver

Underscore-prefix the transport layer (post_v1, parse_v1_response,
send_v1_batch, response dataclasses, backoff ceiling) and the
compression resolver; declare __all__ so the public surface is
CaptureCompression, its env var name, and CaptureV1Error (which reaches
user code via on_error callbacks). Re-export CaptureCompression at the
package top level for symmetry with CaptureMode.

* feat(capture): add optional zstd compression for capture v1

Add CaptureCompression.ZSTD backed by the optional zstandard package
(pip install posthog[zstd]); Python has no stdlib zstd until 3.14.
Explicitly requesting zstd without the package raises ValueError
(fail loud at construction); requesting it via
POSTHOG_CAPTURE_COMPRESSION warns and falls back so operator config
never silently breaks capture. The server already decodes
Content-Encoding: zstd standard frames.

* fix(capture): satisfy mypy on env compression resolution

Rename the env-var lookup binding so it is not confused with the
explicit-kwarg resolved value (CaptureCompression | None vs
CaptureCompression).

* fix(capture): avoid unused-ignore on optional zstandard import

Annotate the module binding explicitly so mypy stays clean whether or
not the zstandard package is installed in the dev environment.

* feat(capture): route analytics through v1 submitter (capture v1, 4/6) (#704)

* feat(capture): route analytics through v1 submitter when enabled

Wires send_v1_batch into both send paths so capture_mode actually takes
effect end to end. The consumer's async path (Consumer.request) and the
client's sync path (_enqueue) now pick the analytics submitter by
capture_mode: v1 -> the partial-retry send loop, v0 -> the legacy
batch_post. The dedicated AI endpoint has no v1 form, so $ai_* events on it
always use the legacy submitter regardless of capture_mode.

Refactors Consumer.request to route via _send_analytics/_send_ai helpers,
stores Client.max_retries so the sync path can pass it through, and forwards
gzip/timeout/retries/historical_migration to the v1 submitter. Default is
still v0, so existing callers are unaffected.

Adds consumer routing-matrix tests (v0/v1, dedicated-AI split, config
forwarding) and client sync-mode tests (v0 vs v1, dedicated-AI event stays
legacy, analytics event uses v1). ruff/mypy clean.

* feat(capture): wire capture_compression through client and consumer

Resolve capture_compression once on the client (kwarg > env >
legacy gzip flag > none) and thread it to the v1 submitter via the
consumer and the sync path. Parameterize the capture_mode routing
tests and use consistent submitter labels.

* chore(capture): test $ai_* rides v1 when dedicated AI endpoint disabled

* chore(capture): v1 compliance adapter + CI job (capture v1, 5/6) (#705)

* chore(capture): add v1 compliance adapter mode and CI job

Teaches the SDK compliance adapter to speak capture-v1 and adds a second
CI job that runs the harness capture_v1 suite against it.

Splits the workflow into v0 + v1 jobs, both on the 0.10.0 harness
(which carries the capture_v1 suites), and adds adapter timing/debug
settings for reliable test execution.

* chore(capture): document capture_mode + release changeset (capture v1, 6/6) (#706)

* docs(capture): document capture_mode, capture_compression, and changeset

Adds the Sampo changeset for the opt-in capture_mode (v1 ingestion
protocol) and capture_compression, plus an AGENTS.md section mapping
capture_mode/capture_compression and their env vars to the modules and
routing that implement them, the v1 invariants to preserve, and the
sync_mode blocking-retry behavior.

User-facing usage stays in the official docs per the README convention.

* docs(capture): note v1 drop surfacing and Retry-After minimum

Document the two parity behaviors added to the v1 transport: server `drop`
verdicts are accumulated across attempts and surfaced via CaptureV1Error/
on_error even on a 2xx, and Retry-After acts as a minimum (max of configured
backoff and Retry-After, hard-capped) rather than a replacement.

* docs(capture): note the unified 30s retry backoff ceiling

MAX_BACKOFF_SECONDS (30s) caps both the exponential backoff and the
Retry-After clamp; update the v1 invariants note accordingly.

* docs(capture): document zstd compression and private helper names
eli-r-ph added a commit that referenced this pull request Jul 6, 2026
…701)

* feat(capture): add capture_mode config scaffolding

Introduce a CaptureMode enum (V0 legacy /batch/, V1 /i/v1/analytics/events)
and resolve_capture_mode() with precedence kwarg > POSTHOG_CAPTURE_MODE env >
V0. Plumb capture_mode through Client and Consumer (including fork-reinit and
the module-level default client). The mode is resolved and stored but inert in
this change: V0 still runs everywhere, so behavior is unchanged.

First of a stacked series adding Capture V1 support.

* test(capture): prove capture_mode kwarg precedence over env

Set the env to the opposite mode in each precedence row so every case
actually exercises kwarg-over-env, and assert an invalid kwarg raises
even when a valid env value is present.

* refactor(capture): make capture-mode resolver internal

Rename resolve_capture_mode to _resolve_capture_mode and declare
__all__ so only CaptureMode and the env var name are public API.
The resolver is plumbing for Client.__init__, not a user entry point.

* feat(capture): v1 wire serialization transforms (capture v1, 2/6) (#702)

* feat(capture): add v1 wire serialization transforms

Add posthog/capture_v1.py with the pure (no-I/O) transform layer for
/i/v1/analytics/events:

- to_v1_event(): lifts sentinel properties into the typed options object
  (with the $ignore_sent_at -> disable_skew_correction rename), promotes
  $session_id/$window_id to top-level fields, relocates top-level
  $set/$set_once into properties (v1 has no top-level form), and strips
  $lib/$lib_version (server injects them from PostHog-Sdk-Info). Options are
  coerced to native JSON types or omitted, since a wrong type would 400 the
  whole batch. Pure: the input message is not mutated.
- build_v1_batch_body(): the api_key/sent_at-free envelope with a tz-aware
  RFC3339 created_at.
- Shared constants: path, required header names, result codes, retryable/
  terminal status sets.

Stacked on the capture_mode scaffolding; still inert (nothing calls these yet).

* refactor(capture): store v1 option coercers as callables

Hold the coercer function directly in _OPTION_SENTINELS instead of a
stringly-typed name keyed through a side _COERCERS dict, removing a
KeyError foot-gun and tightening the types.

* refactor(capture): privatize v1 transform helpers

Underscore-prefix the wire constants and transform functions and declare
an empty __all__: the transforms are submitter plumbing, not public API.
The user-facing surface (CaptureMode etc.) is exported elsewhere.

* feat(capture): v1 transport + partial-retry send loop (capture v1, 3/6) (#703)

* feat(capture): add v1 transport and partial-retry send loop

Adds the HTTP transport for POST /i/v1/analytics/events alongside the
pure transforms: a single Bearer-authed attempt (post_v1) with the
required v1 headers, response classification (parse_v1_response), and the
send loop (send_v1_batch) that resends only the events the server tags
"retry", logs drops, honors Retry-After, and raises CaptureV1Error on
terminal/transport failure or retry exhaustion so the consumer's existing
on_error path fires unchanged.

429 is terminal in v1 (unlike v0). A 2xx with an unparseable body is
terminal to avoid an infinite resend loop. A stable PostHog-Request-Id and
created_at span attempts; PostHog-Attempt increments.

Factors a shared gzip_compress helper out of request.post (no v0 behavior
change). Still inert: nothing calls send_v1_batch until the consumer wiring
PR. 74 capture_v1 tests (47 transform + 27 transport); ruff/mypy clean.

* fix(capture): stabilize v1 created_at, isolate compression, quiet drops

Address review of the v1 transport:
- Hoist the batch created_at out of the retry loop so the envelope stays
  stable across attempts (only the events list and PostHog-Attempt change).
- Isolate v1 request compression behind a CaptureCompression selector
  supporting gzip and zlib-wrapped deflate (RFC 1950), reverting the
  gzip_compress extraction from request.py so the v1 path owns its codecs.
- Stop logging per-event drops at WARNING; a server-chosen drop on a 2xx
  is not a delivery failure and is already carried on CaptureV1Error for
  batch-level surfacing via on_error.

* fix(capture): surface v1 drops and treat Retry-After as a minimum

Address review of the v1 transport (#703):
- Accumulate server `drop` verdicts across all attempts and raise
  CaptureV1Error even on a 2xx with no retry events (a success status is not
  full delivery) and when a later attempt clears the retries, so on_error sees
  every dropped uuid. Drops also ride along on the retry-exhaustion,
  malformed-2xx, and terminal non-2xx errors.
- _backoff treats Retry-After as a minimum (max of configured backoff and
  Retry-After), hard-capped at 1 day, matching posthog-go/posthog-rs so a small
  header can't retry earlier than the schedule and a hostile one can't park the
  consumer thread.

Adds drop-surfacing and backoff tests; regenerates public_api_snapshot.

* fix(capture): unify v1 retry backoff ceiling at 30s

Replace the 1-day RETRY_BACKOFF_CAP_SECONDS with a single MAX_BACKOFF_SECONDS
(30s) that both caps the exponential backoff and clamps the server Retry-After,
so the max retry wait is bounded and the default matches posthog-go/posthog-rs.
Retry-After remains a minimum; there is no separate large cap.

* refactor(capture): privatize v1 transport and compression resolver

Underscore-prefix the transport layer (post_v1, parse_v1_response,
send_v1_batch, response dataclasses, backoff ceiling) and the
compression resolver; declare __all__ so the public surface is
CaptureCompression, its env var name, and CaptureV1Error (which reaches
user code via on_error callbacks). Re-export CaptureCompression at the
package top level for symmetry with CaptureMode.

* feat(capture): add optional zstd compression for capture v1

Add CaptureCompression.ZSTD backed by the optional zstandard package
(pip install posthog[zstd]); Python has no stdlib zstd until 3.14.
Explicitly requesting zstd without the package raises ValueError
(fail loud at construction); requesting it via
POSTHOG_CAPTURE_COMPRESSION warns and falls back so operator config
never silently breaks capture. The server already decodes
Content-Encoding: zstd standard frames.

* fix(capture): satisfy mypy on env compression resolution

Rename the env-var lookup binding so it is not confused with the
explicit-kwarg resolved value (CaptureCompression | None vs
CaptureCompression).

* fix(capture): avoid unused-ignore on optional zstandard import

Annotate the module binding explicitly so mypy stays clean whether or
not the zstandard package is installed in the dev environment.

* feat(capture): route analytics through v1 submitter (capture v1, 4/6) (#704)

* feat(capture): route analytics through v1 submitter when enabled

Wires send_v1_batch into both send paths so capture_mode actually takes
effect end to end. The consumer's async path (Consumer.request) and the
client's sync path (_enqueue) now pick the analytics submitter by
capture_mode: v1 -> the partial-retry send loop, v0 -> the legacy
batch_post. The dedicated AI endpoint has no v1 form, so $ai_* events on it
always use the legacy submitter regardless of capture_mode.

Refactors Consumer.request to route via _send_analytics/_send_ai helpers,
stores Client.max_retries so the sync path can pass it through, and forwards
gzip/timeout/retries/historical_migration to the v1 submitter. Default is
still v0, so existing callers are unaffected.

Adds consumer routing-matrix tests (v0/v1, dedicated-AI split, config
forwarding) and client sync-mode tests (v0 vs v1, dedicated-AI event stays
legacy, analytics event uses v1). ruff/mypy clean.

* feat(capture): wire capture_compression through client and consumer

Resolve capture_compression once on the client (kwarg > env >
legacy gzip flag > none) and thread it to the v1 submitter via the
consumer and the sync path. Parameterize the capture_mode routing
tests and use consistent submitter labels.

* chore(capture): test $ai_* rides v1 when dedicated AI endpoint disabled

* chore(capture): v1 compliance adapter + CI job (capture v1, 5/6) (#705)

* chore(capture): add v1 compliance adapter mode and CI job

Teaches the SDK compliance adapter to speak capture-v1 and adds a second
CI job that runs the harness capture_v1 suite against it.

Splits the workflow into v0 + v1 jobs, both on the 0.10.0 harness
(which carries the capture_v1 suites), and adds adapter timing/debug
settings for reliable test execution.

* chore(capture): document capture_mode + release changeset (capture v1, 6/6) (#706)

* docs(capture): document capture_mode, capture_compression, and changeset

Adds the Sampo changeset for the opt-in capture_mode (v1 ingestion
protocol) and capture_compression, plus an AGENTS.md section mapping
capture_mode/capture_compression and their env vars to the modules and
routing that implement them, the v1 invariants to preserve, and the
sync_mode blocking-retry behavior.

User-facing usage stays in the official docs per the README convention.

* docs(capture): note v1 drop surfacing and Retry-After minimum

Document the two parity behaviors added to the v1 transport: server `drop`
verdicts are accumulated across attempts and surfaced via CaptureV1Error/
on_error even on a 2xx, and Retry-After acts as a minimum (max of configured
backoff and Retry-After, hard-capped) rather than a replacement.

* docs(capture): note the unified 30s retry backoff ceiling

MAX_BACKOFF_SECONDS (30s) caps both the exponential backoff and the
Retry-After clamp; update the v1 invariants note accordingly.

* docs(capture): document zstd compression and private helper names
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