Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .sampo/changesets/ai-trace-sample-rate.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
posthog: minor
---

Add `ai_trace_sample_rate` option and `POSTHOG_AI_TRACE_SAMPLE_RATE` environment variable to sample AI observability events (`$ai_*`) by trace ID across `Client` and `AsyncClient` / `AsyncPosthog` using 32-bit FNV-1a hashing with Murmur3 fmix32 finalization.
4 changes: 2 additions & 2 deletions posthog/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -609,8 +609,8 @@ def capture_ai(event: str, **kwargs: Unpack[OptionalCaptureArgs]) -> Optional[st
batching, endpoint) may change without notice.

Takes the same arguments and returns the same value as `capture()`: the
event UUID, or None when the event was not admitted (disabled client, or
dropped by `before_send`). The event is delivered on an isolated queue
event UUID, or None when the event was not admitted (disabled client,
dropped by `ai_trace_sample_rate`, or dropped by `before_send`). The event is delivered on an isolated queue
with its own consumer pool and a higher per-event size cap, posting to
the dedicated AI ingestion endpoint. The payload is sent as given — no
redaction or truncation is applied here.
Expand Down
118 changes: 118 additions & 0 deletions posthog/ai_trace_sample_rate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import logging
import math
import os
from typing import Any, Optional

__all__ = ["AI_TRACE_SAMPLE_RATE_ENV_VAR"]

AI_TRACE_SAMPLE_RATE_ENV_VAR = "POSTHOG_AI_TRACE_SAMPLE_RATE"

_FNV_OFFSET_BASIS_32 = 0x811C9DC5
_FNV_PRIME_32 = 0x01000193
_TWO_TO_32 = 4294967296 # 2 ** 32


def _fnv1a_32(text: str) -> int:
h = _FNV_OFFSET_BASIS_32
for b in text.encode("utf-8"):
h ^= b
h = (h * _FNV_PRIME_32) & 0xFFFFFFFF
return h


def _fmix32(h: int) -> int:
"""Murmur3 32-bit finalizer to improve bit avalanche on sequential and shared-prefix trace IDs."""
h ^= h >> 16
h = (h * 0x85EBCA6B) & 0xFFFFFFFF
h ^= h >> 13
h = (h * 0xC2B2AE35) & 0xFFFFFFFF
h ^= h >> 16
return h


def _should_sample_ai_trace(trace_id: str, rate: float) -> bool:
"""Return True if the trace should be kept under the sample rate."""
h = _fmix32(_fnv1a_32(trace_id))
return (h / _TWO_TO_32) < rate


def _resolve_ai_trace_sample_rate(
kwarg: Optional[float], log: logging.Logger
) -> Optional[float]:
if kwarg is not None:
raw_val = kwarg
source = "ai_trace_sample_rate"
else:
env_val = os.environ.get(AI_TRACE_SAMPLE_RATE_ENV_VAR)
if env_val is None or not env_val.strip():
return None
raw_val = env_val.strip()

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.

Breaking: mypy fails here because raw_val is inferred as float on line 43 (narrowed from Optional[float]) and then reassigned a str on line 49.

Observed locally on a7d2bbff vs merge base 84fc9e06:
Running mypy --no-site-packages --config-file mypy.ini . | mypy-baseline filter passes on 84fc9e06 (Success: no issues found in 356 source files) and fails on a7d2bbff:

posthog/ai_trace_sample_rate.py:49: error: Incompatible types in assignment (expression has type "str", variable has type "float")  [assignment]

Recommendation: Consider declaring raw_val: Any before if kwarg is not None: (Any is already imported and keeps isinstance(raw_val, bool) compatible with warn_unreachable = True in mypy.ini), then re-running mypy --no-site-packages --config-file mypy.ini . | mypy-baseline filter.

source = AI_TRACE_SAMPLE_RATE_ENV_VAR

if isinstance(raw_val, bool):
log.warning(
"Invalid %s: %r. Expected a float between 0.0 and 1.0. Ignoring.",
source,
raw_val,
)
return None

try:
val = float(raw_val)
except (ValueError, OverflowError):

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.

Suggestion: Consider catching TypeError alongside (ValueError, OverflowError) here (except (ValueError, TypeError, OverflowError):).

Observed locally on a7d2bbff: Passing a non-numeric object from untyped/dynamic config (e.g. Client("phc_test", sync_mode=True, ai_trace_sample_rate=[])) raises an uncaught TypeError: float() argument must be a string or a real number, not 'list' on line 61 instead of warning and ignoring like bool, invalid strings, and OverflowError. (Env vars are always strings and typed callers are protected by Optional[float], so this is optional defensive hardening.)

log.warning(
"Invalid %s: %r. Expected a float between 0.0 and 1.0. Ignoring.",
source,
raw_val,
)
return None

if not math.isfinite(val) or not (0.0 <= val <= 1.0):
log.warning(
"%s out of range [0.0, 1.0]: %r. Ignoring.",
source,
val,
)
return None

return val


def _sample_ai_trace_event(
msg: dict[str, Any], rate: Optional[float], log: logging.Logger
) -> bool:
"""Evaluate whether an event should be kept under ai_trace_sample_rate.

Returns False if the event is an $ai_* event with a valid $ai_trace_id that is
dropped by the hash-based sample rate. Returns True if the event should be kept.
When kept, injects $ai_trace_sample_rate into msg["properties"].
"""
if rate is None or rate >= 1.0:
return True

event_name = msg.get("event")
if not (isinstance(event_name, str) and event_name.startswith("$ai_")):
return True

props = msg.get("properties")
if not isinstance(props, dict):
return True

trace_id = props.get("$ai_trace_id")
if trace_id is None:
return True

trace_id_str = str(trace_id)
if not trace_id_str.strip():
return True

if not _should_sample_ai_trace(trace_id_str, rate):
log.debug(
"Event %s dropped by ai_trace_sample_rate (trace_id=%s)",
event_name,
trace_id_str,
)
return False

props["$ai_trace_sample_rate"] = rate
return True
21 changes: 18 additions & 3 deletions posthog/async_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@
async_flags as _async_flags,
async_remote_config as _async_remote_config,
)
from .ai_trace_sample_rate import (
_resolve_ai_trace_sample_rate,
_sample_ai_trace_event,
)
from .args import (
ID_TYPES,
ExceptionArg,
Expand Down Expand Up @@ -136,8 +140,9 @@ class AsyncClient:
``flush()``, ``join()``, and ``shutdown()`` are awaitable lifecycle methods.
Leaving an ``async with`` block on the client calls ``shutdown()``.

The ``capture_ai_*``, ``privacy_mode`` and ``enable_full_ai_capture``
options work the same way as on :class:`posthog.Client`.
The ``capture_ai_*``, ``ai_trace_sample_rate``, ``privacy_mode`` and
``enable_full_ai_capture`` options work the same way as on
:class:`posthog.Client`.
"""

log = logging.getLogger("posthog")
Expand Down Expand Up @@ -187,6 +192,7 @@ def __init__(
email_request_timeout_seconds: float = 15,
email_request_max_retries: int = 2,
migrated_from: Optional[str] = None,
ai_trace_sample_rate: Optional[float] = None,
) -> None:
if flush_at <= 0:
raise ValueError("flush_at must be greater than zero")
Expand Down Expand Up @@ -290,6 +296,9 @@ def __init__(
else DEFAULT_CODE_VARIABLES_DETECT_SECRETS
)
self.in_app_modules = in_app_modules
self.ai_trace_sample_rate = _resolve_ai_trace_sample_rate(
ai_trace_sample_rate, self.log
)
self.project_root = project_root
if self.project_root is None:
try:
Expand Down Expand Up @@ -578,6 +587,8 @@ def _prepare_event(

msg["distinct_id"] = _stringify_id(msg.get("distinct_id"))
cleaned = clean(msg)
if not _sample_ai_trace_event(cleaned, self.ai_trace_sample_rate, self.log):

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.

Breaking: AsyncClient._prepare_event runs _sample_ai_trace_event before _fill_event_defaults (which runs later in _process_event), so $ai_trace_id values supplied via posthog.tag("$ai_trace_id", ...) or super_properties={"$ai_trace_id": ...} are invisible at sampling time.

Contract & causality: Sync Client._enqueue (posthog/client.py:3243-3278) merges context tags and super_properties via _fill_event_defaults before calling _sample_ai_trace_event. On AsyncClient, _build_capture_event (posthog/async_client.py:659-709) puts context tags and super_properties into defaults: _EventDefaults, which is not merged until _process_event (line 597). As a result, AsyncClient diverges from Client (contradicting the updated AsyncClient docstring and sdk-specs capture layer ordering).

Observed behavior (reproduced locally on a7d2bbff, with sync Client passing as control):

  • AsyncPosthog("phc_test", ai_trace_sample_rate=0.0) inside with posthog.new_context(): posthog.tag("$ai_trace_id", "trace-from-context") returns UUID strings from both capture_ai() and capture_ai_immediate() and delivers both events instead of returning None and dropping them.
  • AsyncPosthog("phc_test", ai_trace_sample_rate=0.0, super_properties={"$ai_trace_id": "trace-from-super"}) likewise returns a UUID string and delivers the event.
  • At ai_trace_sample_rate=0.5, a kept context-tagged trace is delivered without $ai_trace_sample_rate.

Minimal regression test (fails on a7d2bbff; equivalent sync Client control passes):

async with AsyncPosthog("phc_test", ai_trace_sample_rate=0.0, flush_interval=30) as client:
    with posthog.new_context():
        posthog.tag("$ai_trace_id", "trace-from-context")
        ret_q = client.capture_ai("$ai_generation", distinct_id="user-1")
        ret_i = await client.capture_ai_immediate("$ai_generation", distinct_id="user-1")
    await client.flush(timeout_seconds=1)
assert ret_q is None and ret_i is None and sent == []

Recommendation: Consider passing defaults into _prepare_event from _capture (line 743) and _capture_immediate (line 803) and resolving the effective $ai_trace_id with _fill_event_defaults precedence: check "$ai_trace_id" in cleaned["properties"] first (so explicit None still blocks fallback layers), otherwise scan defaults.property_layers (respecting defaults.property_allowlist), breaking on the first layer containing "$ai_trace_id" and applying clean(...). Keep sampling in _prepare_event so dropped events still return None immediately before queueing and kept events carry $ai_trace_sample_rate before _process_event / before_send. Consider adding async regression tests covering context tags, super_properties, explicit None override, and kept-trace $ai_trace_sample_rate tagging.

return None, None
return cleaned, sent_uuid

async def _process_event(
Expand Down Expand Up @@ -708,7 +719,9 @@ def capture_ai(
) -> Optional[str]:
"""Queue an AI event for the AI capture endpoint without blocking.

Takes the same arguments and returns the same value as ``capture()``.
Takes the same arguments and returns the same value as ``capture()``:
the event UUID, or None when the event was not admitted (disabled
client, dropped by ``ai_trace_sample_rate``, or dropped by ``before_send``).

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.

Concern: AsyncClient.capture_ai() does not return None when an event is dropped by before_send.

Observed behavior (verified locally on a7d2bbff): _capture() (posthog/async_client.py:738-752) queues the event and returns sent_uuid synchronously, while _run_before_send() runs asynchronously later inside _AsyncConsumer → _process_event() (line 598). Calling AsyncPosthog("phc_test", before_send=lambda e: None).capture_ai("$ai_generation", distinct_id="user-1") returns a UUID string even though the event is dropped before upload. (By contrast, capture_ai_immediate() awaits _process_event(), so its docstring at lines 784–785 is accurate.)

Recommendation: Consider updating lines 722–724 to state that capture_ai() returns None when not admitted (disabled or shut-down client, full queue, or dropped by ai_trace_sample_rate), and note that before_send runs asynchronously in the background worker (or point callers to capture_ai_immediate() if they need before_send drops reflected in the return value).

The event uses a separate queue with a larger per-event size cap. The
payload is sent as given, with no redaction or truncation.
"""
Expand Down Expand Up @@ -768,6 +781,8 @@ async def capture_ai_immediate(
"""Capture one AI event and wait until its delivery attempt completes.

Uses the AI capture endpoint and the ``capture_ai_*`` settings.
Returns the event UUID, or None when dropped by
``ai_trace_sample_rate`` or ``before_send``.
"""
self._log_non_ai_event(event)
return await self._capture_immediate(event, self._ai_lane, kwargs)
Expand Down
27 changes: 25 additions & 2 deletions posthog/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,10 @@
from posthog.tracing._pipeline import PostHogTraces
from posthog.tracing.span import Span
from posthog.tracing._span import inert_span as _inert_span
from posthog.ai_trace_sample_rate import (
_resolve_ai_trace_sample_rate,
_sample_ai_trace_event,
)
from posthog.capture_compression import (
CaptureCompression,
_resolve_capture_ai_compression,
Expand Down Expand Up @@ -189,6 +193,7 @@

_configure_posthog_logging()


MAX_DICT_SIZE = 50_000
_ATEXIT_FLUSH_TIMEOUT_SECONDS = 1.0
# The final span flush shutdown() allows; a request already in flight may
Expand Down Expand Up @@ -1226,6 +1231,7 @@ def __init__(
email_request_timeout_seconds: float = 15,
email_request_max_retries: int = 2,
migrated_from: Optional[str] = None,
ai_trace_sample_rate: Optional[float] = None,

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.

Concern: AsyncClient / AsyncPosthog does not accept ai_trace_sample_rate and silently ignores POSTHOG_AI_TRACE_SAMPLE_RATE.

AsyncClient supports capture_ai() / capture_ai_immediate(), documents AI-option parity with Client (posthog/async_client.py:139-140), and honors the SDK's other environment variables (POSTHOG_RELEASE_ID, POSTHOG_CAPTURE_COMPRESSION — verified on both 84fc9e06 and 5dd94c3e). On 5dd94c3e:

  • AsyncPosthog("phc_test", ai_trace_sample_rate=0.0) raises TypeError: AsyncClient.__init__() got an unexpected keyword argument 'ai_trace_sample_rate'.
  • With POSTHOG_AI_TRACE_SAMPLE_RATE=0.0, await client.capture_ai_immediate("$ai_generation", distinct_id="user-1", properties={"$ai_trace_id": "trace-1"}) silently ignores the env var (no warning), returns a UUID, and sends the event.

For asyncio apps (e.g., FastAPI) relying on POSTHOG_AI_TRACE_SAMPLE_RATE to cap LLM observability volume, silently capturing 100% of events is a surprising footgun.

Consider moving the rate resolver and sampling helper into a small shared module (like posthog/release_id.py / posthog/capture_compression.py) and wiring ai_trace_sample_rate into AsyncClient as well — or, if maintainers prefer scoping this PR to sync Client first, explicitly documenting that AsyncClient/AsyncPosthog is not yet covered in the docstring and .sampo/changesets/ai-trace-sample-rate.md.

):
"""
Initialize a new PostHog client instance.
Expand Down Expand Up @@ -1294,6 +1300,17 @@ def __init__(
Set to 0 when a job runner already retries the send.
migrated_from: The email provider you moved from, such as
``"resend"``. ``emails`` sends it with every request.
ai_trace_sample_rate: Optional sample rate between 0.0 and 1.0 for

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.

Suggestion: Consider adding two brief docstring clarifications so generated API docs stay accurate:

  1. Note here that ai_trace_sample_rate applies to events captured through Client (capture() / capture_ai() and provider wrappers), and does not apply to posthog.ai.otel (PostHogSpanProcessor / PostHogTraceExporter), which exports spans directly via OTLP.
  2. Update the None-return parenthetical in Client.capture_ai (posthog/client.py:2470-2471) and posthog.capture_ai (posthog/__init__.py:612-613) to mention events dropped by ai_trace_sample_rate alongside disabled clients and before_send.

AI observability events (``$ai_*``). Events carrying an
``$ai_trace_id`` are sampled by trace id using 32-bit FNV-1a
with Murmur3 fmix32 hashing so that entire traces are either
kept or dropped together. Kept events gain an
``$ai_trace_sample_rate`` property. Unset or 1.0 means no
sampling. Can also be set via the
``POSTHOG_AI_TRACE_SAMPLE_RATE`` environment variable. Applies
to events captured through ``Client`` (``capture()``,
``capture_ai()``, and provider wrappers); does not apply to
``posthog.ai.otel``, which exports spans directly via OTLP.
super_properties: Properties for every captured event. They fill
only keys the event leaves unset, before ``before_send`` runs.
``$set``, ``$set_once``, ``$groups`` and ``$group_set`` fill
Expand Down Expand Up @@ -1603,6 +1620,9 @@ def __init__(
else DEFAULT_CODE_VARIABLES_DETECT_SECRETS
)
self.in_app_modules = in_app_modules
self.ai_trace_sample_rate = _resolve_ai_trace_sample_rate(
ai_trace_sample_rate, self.log
)

if project_root is None:
try:
Expand Down Expand Up @@ -2399,8 +2419,8 @@ def capture_ai(

Takes the same arguments and returns the same value as `capture()`:
the event UUID, or None when the event was not admitted (disabled
client, or dropped by `before_send`). The event is queued on an
isolated AI lane with its own consumer pool and a higher per-event
client, dropped by `ai_trace_sample_rate`, or dropped by `before_send`).
The event is queued on an isolated AI lane with its own consumer pool and a higher per-event
size cap, posting to the dedicated AI ingestion endpoint. The payload
is sent as given — no redaction or truncation is applied here.

Expand Down Expand Up @@ -3254,6 +3274,9 @@ def _enqueue(

msg = clean(msg)

if not _sample_ai_trace_event(msg, self.ai_trace_sample_rate, self.log):
return None

if self.before_send:
event_name = msg.get("event")
try:
Expand Down
Loading