From a7d2bbff7d766a4a1f01de56e8bb18c70f841900 Mon Sep 17 00:00:00 2001 From: Shubham-dev-stack Date: Sat, 21 Nov 2026 19:24:33 +0530 Subject: [PATCH] feat(ai): sample AI observability events by trace id (#965) Add ai_trace_sample_rate option across sync Client and AsyncClient/AsyncPosthog, backed by POSTHOG_AI_TRACE_SAMPLE_RATE. AI events ($ai_*) sharing an $ai_trace_id are deterministically sampled by trace ID using 32-bit FNV-1a with a Murmur3 fmix32 finalizer to prevent clustering on sequential IDs. Sampling helpers are encapsulated in posthog.ai_trace_sample_rate, kept events gain $ai_trace_sample_rate before reaching before_send, non-AI events and untraced events are preserved, and invalid rates safely fallback without leaking unhandled exceptions or background threads. --- .sampo/changesets/ai-trace-sample-rate.md | 5 + posthog/__init__.py | 4 +- posthog/ai_trace_sample_rate.py | 118 +++++ posthog/async_client.py | 21 +- posthog/client.py | 27 +- posthog/test/ai/test_ai_trace_sample_rate.py | 464 +++++++++++++++++++ references/public_api_snapshot.txt | 8 +- 7 files changed, 638 insertions(+), 9 deletions(-) create mode 100644 .sampo/changesets/ai-trace-sample-rate.md create mode 100644 posthog/ai_trace_sample_rate.py create mode 100644 posthog/test/ai/test_ai_trace_sample_rate.py diff --git a/.sampo/changesets/ai-trace-sample-rate.md b/.sampo/changesets/ai-trace-sample-rate.md new file mode 100644 index 000000000..8f3f390bc --- /dev/null +++ b/.sampo/changesets/ai-trace-sample-rate.md @@ -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. diff --git a/posthog/__init__.py b/posthog/__init__.py index eafc2a3ac..b7e85066a 100644 --- a/posthog/__init__.py +++ b/posthog/__init__.py @@ -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. diff --git a/posthog/ai_trace_sample_rate.py b/posthog/ai_trace_sample_rate.py new file mode 100644 index 000000000..62e4d02cf --- /dev/null +++ b/posthog/ai_trace_sample_rate.py @@ -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() + 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): + 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 diff --git a/posthog/async_client.py b/posthog/async_client.py index 7401e3740..1d76b16c0 100644 --- a/posthog/async_client.py +++ b/posthog/async_client.py @@ -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, @@ -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") @@ -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") @@ -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: @@ -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): + return None, None return cleaned, sent_uuid async def _process_event( @@ -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``). The event uses a separate queue with a larger per-event size cap. The payload is sent as given, with no redaction or truncation. """ @@ -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) diff --git a/posthog/client.py b/posthog/client.py index 7d4de2c8a..97bae4405 100644 --- a/posthog/client.py +++ b/posthog/client.py @@ -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, @@ -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 @@ -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, ): """ Initialize a new PostHog client instance. @@ -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 + 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 @@ -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: @@ -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. @@ -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: diff --git a/posthog/test/ai/test_ai_trace_sample_rate.py b/posthog/test/ai/test_ai_trace_sample_rate.py new file mode 100644 index 000000000..fff060685 --- /dev/null +++ b/posthog/test/ai/test_ai_trace_sample_rate.py @@ -0,0 +1,464 @@ +import asyncio +import os +import unittest +from unittest.mock import patch + +from posthog.ai_trace_sample_rate import ( + AI_TRACE_SAMPLE_RATE_ENV_VAR, + _fmix32, + _fnv1a_32, + _should_sample_ai_trace, +) +from posthog.async_client import AsyncClient +from posthog.client import Client +from posthog.test.capture_helpers import record_sync_capture_sends + + +class TestAiTraceSampleRate(unittest.TestCase): + def setUp(self): + super().setUp() + self._orig_env = os.environ.get(AI_TRACE_SAMPLE_RATE_ENV_VAR) + os.environ.pop(AI_TRACE_SAMPLE_RATE_ENV_VAR, None) + + def tearDown(self): + if self._orig_env is not None: + os.environ[AI_TRACE_SAMPLE_RATE_ENV_VAR] = self._orig_env + else: + os.environ.pop(AI_TRACE_SAMPLE_RATE_ENV_VAR, None) + super().tearDown() + + def _create_client(self, **kwargs) -> Client: + defaults = {"sync_mode": True} + defaults.update(kwargs) + client = Client("test_key", **defaults) + self.addCleanup(client.shutdown) + return client + + def test_fnv1a_32_and_fmix32_matches_specification(self): + # Empty string yields FNV offset basis + self.assertEqual(_fnv1a_32(""), 0x811C9DC5) + # Deterministic 32-bit unsigned integers + h1 = _fnv1a_32("trace-uuid-12345") + h2 = _fnv1a_32("trace-uuid-12345") + self.assertEqual(h1, h2) + self.assertGreaterEqual(h1, 0) + self.assertLess(h1, 4294967296) + + # Murmur3 fmix32 finalizer bounds + mixed = _fmix32(h1) + self.assertGreaterEqual(mixed, 0) + self.assertLess(mixed, 4294967296) + + def test_sequential_trace_ids_distribution_with_fmix32(self): + # Without fmix32, pure 32-bit FNV-1a clusters sequential IDs (0/100 kept at rate 0.1). + # With fmix32 finalizer, sequential IDs achieve proper bit avalanche. + kept_100 = sum( + 1 for i in range(100) if _should_sample_ai_trace(f"trace-{i}", 0.1) + ) + self.assertEqual(kept_100, 12) # 12% on 100 items (not 0%) + + kept_1000 = sum( + 1 for i in range(1000) if _should_sample_ai_trace(f"trace-{i}", 0.1) + ) + self.assertEqual(kept_1000, 108) # 10.8% on 1000 items (close to target 10%) + + def test_should_sample_ai_trace_extremes(self): + # Rate 0.0 always drops + self.assertFalse(_should_sample_ai_trace("any-trace-id", 0.0)) + # Rate 1.0 always keeps + self.assertTrue(_should_sample_ai_trace("any-trace-id", 1.0)) + + def test_sample_rate_precedence_kwarg_over_env(self): + with patch.dict(os.environ, {AI_TRACE_SAMPLE_RATE_ENV_VAR: "0.2"}): + # Kwarg wins over env var + client = self._create_client(ai_trace_sample_rate=0.5) + self.assertEqual(client.ai_trace_sample_rate, 0.5) + + # Env var used when kwarg is None + client_env = self._create_client() + self.assertEqual(client_env.ai_trace_sample_rate, 0.2) + + # Default is None when neither is provided + client_default = self._create_client() + self.assertIsNone(client_default.ai_trace_sample_rate) + + def test_out_of_range_and_invalid_values_ignored(self): + # Negative rate ignored with warning + with self.assertLogs("posthog", level="WARNING") as cm: + client = self._create_client(ai_trace_sample_rate=-0.1) + self.assertIsNone(client.ai_trace_sample_rate) + self.assertTrue(any("out of range" in msg for msg in cm.output)) + + # Greater than 1.0 ignored with warning + with self.assertLogs("posthog", level="WARNING") as cm: + client = self._create_client(ai_trace_sample_rate=1.5) + self.assertIsNone(client.ai_trace_sample_rate) + self.assertTrue(any("out of range" in msg for msg in cm.output)) + + # Boolean values (subclass of int) rejected with warning + with self.assertLogs("posthog", level="WARNING") as cm: + client = self._create_client(ai_trace_sample_rate=True) + self.assertIsNone(client.ai_trace_sample_rate) + self.assertTrue( + any("Invalid ai_trace_sample_rate" in msg for msg in cm.output) + ) + + # Invalid env var string ignored with warning + with patch.dict(os.environ, {AI_TRACE_SAMPLE_RATE_ENV_VAR: "not_a_float"}): + with self.assertLogs("posthog", level="WARNING") as cm: + client = self._create_client() + self.assertIsNone(client.ai_trace_sample_rate) + self.assertTrue( + any( + "Invalid POSTHOG_AI_TRACE_SAMPLE_RATE" in msg + for msg in cm.output + ) + ) + + # Blank env var ignored silently without warning + with patch.dict(os.environ, {AI_TRACE_SAMPLE_RATE_ENV_VAR: " "}): + client = self._create_client() + self.assertIsNone(client.ai_trace_sample_rate) + + def test_nan_and_inf_values_rejected_with_warning(self): + # float("nan") kwarg must be rejected with warning + with self.assertLogs("posthog", level="WARNING") as cm: + client = self._create_client(ai_trace_sample_rate=float("nan")) + self.assertIsNone(client.ai_trace_sample_rate) + self.assertTrue(any("out of range" in msg for msg in cm.output)) + + # "nan" in env var must be rejected with warning + with patch.dict(os.environ, {AI_TRACE_SAMPLE_RATE_ENV_VAR: "nan"}): + with self.assertLogs("posthog", level="WARNING") as cm: + client = self._create_client() + self.assertIsNone(client.ai_trace_sample_rate) + self.assertTrue(any("out of range" in msg for msg in cm.output)) + + # "NaN" with whitespace in env var + with patch.dict(os.environ, {AI_TRACE_SAMPLE_RATE_ENV_VAR: " NaN "}): + with self.assertLogs("posthog", level="WARNING") as cm: + client = self._create_client() + self.assertIsNone(client.ai_trace_sample_rate) + self.assertTrue(any("out of range" in msg for msg in cm.output)) + + # "inf" and "-inf" rejected with warning + for inf_val in ("inf", "-inf"): + with patch.dict(os.environ, {AI_TRACE_SAMPLE_RATE_ENV_VAR: inf_val}): + with self.assertLogs("posthog", level="WARNING") as cm: + client = self._create_client() + self.assertIsNone(client.ai_trace_sample_rate) + self.assertTrue(any("out of range" in msg for msg in cm.output)) + + def test_overflow_integer_does_not_crash(self): + # Huge integer that overflows float conversion does not crash Client.__init__ + with self.assertLogs("posthog", level="WARNING") as cm: + client = self._create_client(ai_trace_sample_rate=10**1000) + self.assertIsNone(client.ai_trace_sample_rate) + self.assertTrue( + any("Invalid ai_trace_sample_rate" in msg for msg in cm.output) + ) + + def test_non_ai_events_never_sampled(self): + captured = record_sync_capture_sends(self) + client = self._create_client(ai_trace_sample_rate=0.0) + + # Non-$ai_* events must not be dropped even at sample rate 0.0 + ret1 = client.capture( + "$pageview", + distinct_id="user-1", + properties={ + "$current_url": "https://posthog.com", + "$ai_trace_id": "trace-1", + }, + ) + ret2 = client.capture( + "custom_event", + distinct_id="user-1", + properties={"some_key": "val", "$ai_trace_id": "trace-1"}, + ) + + self.assertIsNotNone(ret1) + self.assertIsNotNone(ret2) + self.assertEqual(len(captured), 2) + self.assertNotIn("$ai_trace_sample_rate", captured[0].get("properties", {})) + self.assertNotIn("$ai_trace_sample_rate", captured[1].get("properties", {})) + + def test_ai_events_without_trace_id_are_kept(self): + captured = record_sync_capture_sends(self) + client = self._create_client(ai_trace_sample_rate=0.0) + + # $ai_* event without $ai_trace_id is kept + ret = client.capture( + "$ai_generation", distinct_id="user-1", properties={"model": "gpt-4o"} + ) + + self.assertIsNotNone(ret) + self.assertEqual(len(captured), 1) + self.assertEqual(captured[0]["event"], "$ai_generation") + self.assertNotIn("$ai_trace_sample_rate", captured[0].get("properties", {})) + + def test_blank_or_whitespace_trace_id_is_kept(self): + captured = record_sync_capture_sends(self) + client = self._create_client(ai_trace_sample_rate=0.0) + + # Blank string trace id is treated as missing and kept + ret = client.capture( + "$ai_generation", distinct_id="user-1", properties={"$ai_trace_id": " "} + ) + + self.assertIsNotNone(ret) + self.assertEqual(len(captured), 1) + self.assertNotIn("$ai_trace_sample_rate", captured[0].get("properties", {})) + + def test_falsy_zero_trace_id_is_sampled(self): + captured = record_sync_capture_sends(self) + client = self._create_client(ai_trace_sample_rate=0.0) + + # Numeric 0 trace id should be sampled (dropped at rate 0.0), not treated as None + ret = client.capture( + "$ai_generation", distinct_id="user-1", properties={"$ai_trace_id": 0} + ) + + self.assertIsNone(ret) + self.assertEqual(len(captured), 0) + + def test_capture_ai_return_values_and_sample_rate_tag(self): + captured = record_sync_capture_sends(self) + # Find trace ids for keep and drop at 0.5 + kept_trace_id = next( + f"trace-{i}" + for i in range(100) + if _should_sample_ai_trace(f"trace-{i}", 0.5) + ) + dropped_trace_id = next( + f"trace-{i}" + for i in range(100) + if not _should_sample_ai_trace(f"trace-{i}", 0.5) + ) + + client = self._create_client(ai_trace_sample_rate=0.5) + + # Kept trace returns UUID string and attaches sample rate + uuid_kept = client.capture_ai( + "$ai_generation", + distinct_id="user-1", + properties={"$ai_trace_id": kept_trace_id}, + ) + self.assertIsInstance(uuid_kept, str) + self.assertEqual(len(captured), 1) + self.assertEqual(captured[0]["properties"]["$ai_trace_sample_rate"], 0.5) + + # Dropped trace returns None + captured.clear() + uuid_dropped = client.capture_ai( + "$ai_generation", + distinct_id="user-1", + properties={"$ai_trace_id": dropped_trace_id}, + ) + self.assertIsNone(uuid_dropped) + self.assertEqual(len(captured), 0) + + def test_ai_trace_sampling_drops_and_keeps_whole_traces(self): + kept_trace_id = next( + f"trace-cohort-{i}" + for i in range(100) + if _should_sample_ai_trace(f"trace-cohort-{i}", 0.5) + ) + dropped_trace_id = next( + f"trace-cohort-{i}" + for i in range(100) + if not _should_sample_ai_trace(f"trace-cohort-{i}", 0.5) + ) + + captured = record_sync_capture_sends(self) + client = self._create_client(ai_trace_sample_rate=0.5) + + # Emit multiple events for the kept trace — all must be kept with rate property + client.capture( + "$ai_generation", + distinct_id="user-1", + properties={"$ai_trace_id": kept_trace_id, "step": 1}, + ) + client.capture( + "$ai_span", + distinct_id="user-1", + properties={"$ai_trace_id": kept_trace_id, "step": 2}, + ) + + self.assertEqual(len(captured), 2) + for event in captured: + self.assertEqual(event["properties"]["$ai_trace_id"], kept_trace_id) + self.assertEqual(event["properties"]["$ai_trace_sample_rate"], 0.5) + + # Emit multiple events for the dropped trace — all must be dropped + captured.clear() + client.capture( + "$ai_generation", + distinct_id="user-1", + properties={"$ai_trace_id": dropped_trace_id, "step": 1}, + ) + client.capture( + "$ai_span", + distinct_id="user-1", + properties={"$ai_trace_id": dropped_trace_id, "step": 2}, + ) + + self.assertEqual(len(captured), 0) + + def test_before_send_sees_only_kept_events_with_sample_rate(self): + dropped_trace_id = next( + f"trace-bs-{i}" + for i in range(100) + if not _should_sample_ai_trace(f"trace-bs-{i}", 0.5) + ) + kept_trace_id = next( + f"trace-bs-{i}" + for i in range(100) + if _should_sample_ai_trace(f"trace-bs-{i}", 0.5) + ) + + before_send_calls = [] + + def my_before_send(event): + before_send_calls.append(event) + return event + + record_sync_capture_sends(self) + client = self._create_client( + ai_trace_sample_rate=0.5, + before_send=my_before_send, + ) + + # Dropped trace must never reach before_send + client.capture( + "$ai_generation", + distinct_id="user-1", + properties={"$ai_trace_id": dropped_trace_id}, + ) + self.assertEqual(len(before_send_calls), 0) + + # Kept trace reaches before_send and already carries $ai_trace_sample_rate + client.capture( + "$ai_generation", + distinct_id="user-1", + properties={"$ai_trace_id": kept_trace_id}, + ) + self.assertEqual(len(before_send_calls), 1) + self.assertEqual( + before_send_calls[0]["properties"]["$ai_trace_sample_rate"], 0.5 + ) + + def test_rate_one_means_no_sampling(self): + captured = record_sync_capture_sends(self) + client = self._create_client(ai_trace_sample_rate=1.0) + + client.capture( + "$ai_generation", + distinct_id="user-1", + properties={"$ai_trace_id": "any-trace-id"}, + ) + self.assertEqual(len(captured), 1) + self.assertNotIn("$ai_trace_sample_rate", captured[0].get("properties", {})) + + def test_async_client_sampling_parity(self): + async def run_async(): + # 1. AsyncClient with rate=0.0 drops traced $ai_* events + async with AsyncClient( + "phc_test", send=False, ai_trace_sample_rate=0.0 + ) as client_zero: + res_drop = client_zero.capture_ai( + "$ai_generation", + distinct_id="user-1", + properties={"$ai_trace_id": "trace-1"}, + ) + self.assertIsNone(res_drop) + + res_imm_drop = await client_zero.capture_ai_immediate( + "$ai_generation", + distinct_id="user-1", + properties={"$ai_trace_id": "trace-1"}, + ) + self.assertIsNone(res_imm_drop) + + # 2. AsyncClient honors POSTHOG_AI_TRACE_SAMPLE_RATE env var + with patch.dict(os.environ, {AI_TRACE_SAMPLE_RATE_ENV_VAR: "0.0"}): + async with AsyncClient("phc_test", send=False) as client_env: + self.assertEqual(client_env.ai_trace_sample_rate, 0.0) + res_env_drop = client_env.capture_ai( + "$ai_generation", + distinct_id="user-1", + properties={"$ai_trace_id": "trace-1"}, + ) + self.assertIsNone(res_env_drop) + + # 3. AsyncClient with rate=1.0 keeps events and returns UUID + async with AsyncClient( + "phc_test", send=False, ai_trace_sample_rate=1.0 + ) as client_one: + res_keep = client_one.capture_ai( + "$ai_generation", + distinct_id="user-1", + properties={"$ai_trace_id": "trace-1"}, + ) + self.assertIsInstance(res_keep, str) + + asyncio.run(run_async()) + + def test_multi_item_positive_control_fixture(self): + """Verifies item order, parity, and trace-level sampling across heterogeneous events.""" + captured = record_sync_capture_sends(self) + client = self._create_client(ai_trace_sample_rate=0.5) + + kept_trace_id = next( + f"ctrl-trace-{i}" + for i in range(100) + if _should_sample_ai_trace(f"ctrl-trace-{i}", 0.5) + ) + dropped_trace_id = next( + f"ctrl-trace-{i}" + for i in range(100) + if not _should_sample_ai_trace(f"ctrl-trace-{i}", 0.5) + ) + + test_events = [ + ( + "custom_login", + "user-1", + {"$ai_trace_id": dropped_trace_id}, + ), # Non-AI, kept + ("$ai_generation", "user-1", {"$ai_trace_id": kept_trace_id}), # AI kept + ( + "$ai_generation", + "user-2", + {"$ai_trace_id": dropped_trace_id}, + ), # AI dropped + ("$ai_metric", "user-3", {}), # AI without trace id, kept + ("$pageview", "user-4", {"$current_url": "/docs"}), # Non-AI, kept + ] + + results = [] + for ev, uid, props in test_events: + ret = client.capture(ev, distinct_id=uid, properties=props) + results.append((ev, ret is not None)) + + self.assertEqual( + results, + [ + ("custom_login", True), + ("$ai_generation", True), + ("$ai_generation", False), + ("$ai_metric", True), + ("$pageview", True), + ], + ) + + # Captured list preserves exact relative order of admitted events + self.assertEqual(len(captured), 4) + self.assertEqual( + [e["event"] for e in captured], + ["custom_login", "$ai_generation", "$ai_metric", "$pageview"], + ) + self.assertEqual(captured[1]["properties"]["$ai_trace_sample_rate"], 0.5) + self.assertNotIn("$ai_trace_sample_rate", captured[0].get("properties", {})) + self.assertNotIn("$ai_trace_sample_rate", captured[2].get("properties", {})) + self.assertNotIn("$ai_trace_sample_rate", captured[3].get("properties", {})) diff --git a/references/public_api_snapshot.txt b/references/public_api_snapshot.txt index d6063b7b2..0cb86474b 100644 --- a/references/public_api_snapshot.txt +++ b/references/public_api_snapshot.txt @@ -734,6 +734,7 @@ attribute posthog.ai.types.TokenUsage.reasoning_tokens: Optional[int] attribute posthog.ai.types.TokenUsage.web_search_count: Optional[int] attribute posthog.ai.types.ToolInProgress.block: StreamingContentBlock attribute posthog.ai.types.ToolInProgress.input_string: str +attribute posthog.ai_trace_sample_rate.AI_TRACE_SAMPLE_RATE_ENV_VAR = 'POSTHOG_AI_TRACE_SAMPLE_RATE' attribute posthog.api_key = None attribute posthog.args.ExcInfo = Union[Tuple[Type[BaseException], BaseException, Optional[TracebackType]], Tuple[None, None, None]] attribute posthog.args.ExceptionArg = Union[BaseException, ExcInfo] @@ -753,6 +754,7 @@ attribute posthog.args.OptionalSetArgs.options: NotRequired[Optional[Dict[str, A attribute posthog.args.OptionalSetArgs.properties: NotRequired[Optional[Dict[str, Any]]] attribute posthog.args.OptionalSetArgs.timestamp: NotRequired[Optional[Union[datetime, str]]] attribute posthog.args.OptionalSetArgs.uuid: NotRequired[Optional[Union[str, UUID]]] +attribute posthog.async_client.AsyncClient.ai_trace_sample_rate = _resolve_ai_trace_sample_rate(ai_trace_sample_rate, self.log) attribute posthog.async_client.AsyncClient.api_key = (project_api_key or '').strip() attribute posthog.async_client.AsyncClient.app_host = app_host attribute posthog.async_client.AsyncClient.before_send = before_send @@ -814,6 +816,7 @@ attribute posthog.capture_send.CaptureError.retry_exhausted = retry_exhausted or attribute posthog.capture_send.CaptureEventResult.details: Optional[str] = None attribute posthog.capture_send.CaptureEventResult.result: Optional[str] attribute posthog.capture_trace_context = False +attribute posthog.client.Client.ai_trace_sample_rate = _resolve_ai_trace_sample_rate(ai_trace_sample_rate, self.log) attribute posthog.client.Client.api_key = (project_api_key or '').strip() attribute posthog.client.Client.app_host = app_host attribute posthog.client.Client.before_send = before_send @@ -1381,14 +1384,14 @@ class posthog.ai.types.TokenUsage class posthog.ai.types.ToolInProgress class posthog.args.OptionalCaptureArgs class posthog.args.OptionalSetArgs -class posthog.async_client.AsyncClient(project_api_key: str, host: Optional[str] = None, *, debug: bool = False, max_queue_size: int = 10000, send: bool = True, on_error=None, flush_at: int = 100, flush_interval: float = 5.0, max_retries: int = 3, timeout: float = 15, thread: int = 1, disabled: bool = False, disable_geoip: bool = True, is_server: bool = True, historical_migration: bool = False, super_properties: Optional[dict[str, Any]] = None, super_options: Optional[dict[str, Any]] = None, before_send=None, log_captured_exceptions: bool = False, project_root: Optional[str] = None, capture_exception_code_variables: bool = False, code_variables_mask_patterns=None, code_variables_ignore_patterns=None, code_variables_mask_url_credentials=None, code_variables_detect_secrets=None, in_app_modules: Optional[list[str]] = None, capture_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_max_queue_size: int = 1000, capture_ai_timeout: float = 30, capture_ai_max_event_bytes: int = AI_MAX_MSG_SIZE, privacy_mode: bool = False, enable_full_ai_capture: bool = False, capture_trace_context: bool = False, secret_key: Optional[str] = None, personal_api_key: Optional[str] = None, feature_flags_request_timeout_seconds: float = 3, feature_flags_request_max_retries: int = 1, app_host: Optional[str] = None, email_request_timeout_seconds: float = 15, email_request_max_retries: int = 2, migrated_from: Optional[str] = None) +class posthog.async_client.AsyncClient(project_api_key: str, host: Optional[str] = None, *, debug: bool = False, max_queue_size: int = 10000, send: bool = True, on_error=None, flush_at: int = 100, flush_interval: float = 5.0, max_retries: int = 3, timeout: float = 15, thread: int = 1, disabled: bool = False, disable_geoip: bool = True, is_server: bool = True, historical_migration: bool = False, super_properties: Optional[dict[str, Any]] = None, super_options: Optional[dict[str, Any]] = None, before_send=None, log_captured_exceptions: bool = False, project_root: Optional[str] = None, capture_exception_code_variables: bool = False, code_variables_mask_patterns=None, code_variables_ignore_patterns=None, code_variables_mask_url_credentials=None, code_variables_detect_secrets=None, in_app_modules: Optional[list[str]] = None, capture_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_max_queue_size: int = 1000, capture_ai_timeout: float = 30, capture_ai_max_event_bytes: int = AI_MAX_MSG_SIZE, privacy_mode: bool = False, enable_full_ai_capture: bool = False, capture_trace_context: bool = False, secret_key: Optional[str] = None, personal_api_key: Optional[str] = None, feature_flags_request_timeout_seconds: float = 3, feature_flags_request_max_retries: int = 1, app_host: Optional[str] = None, email_request_timeout_seconds: float = 15, email_request_max_retries: int = 2, migrated_from: Optional[str] = None, ai_trace_sample_rate: Optional[float] = None) class posthog.async_client.AsyncPosthog class posthog.bucketed_rate_limiter.BucketedRateLimiter(bucket_size: Number, refill_rate: Number, refill_interval_seconds: Number, on_bucket_rate_limited: Optional[Callable[[Hashable], None]] = None, clock: Callable[[], float] = time.monotonic) class posthog.capture_compression.CaptureCompression class posthog.capture_send.CaptureDroppedEvent class posthog.capture_send.CaptureError(status: int | str, message: str, *, endpoint: str, retry_after: Optional[float] = None, request_id: Optional[str] = None, attempts: Optional[int] = None, retry_exhausted: Optional[list[str]] = None, drops: Optional[Sequence[tuple[str, Optional[str]]]] = None, event_results: Optional[dict[str, CaptureEventResult]] = None) class posthog.capture_send.CaptureEventResult(result: Optional[str], details: Optional[str] = None) -class posthog.client.Client(project_api_key: str, host=None, *, debug=False, max_queue_size=10000, send=True, on_error=None, flush_at=100, flush_interval=5.0, max_retries=3, sync_mode=False, timeout: float = 15, thread=1, poll_interval=30, personal_api_key=None, disabled=False, disable_geoip=True, is_server=True, historical_migration=False, feature_flags_request_timeout_seconds: float = 3, feature_flags_request_max_retries=1, super_properties=None, super_options=None, enable_exception_autocapture=False, log_captured_exceptions=False, project_root=None, privacy_mode=False, before_send=None, flag_fallback_cache_url=None, enable_local_evaluation=True, flag_definition_cache_provider: Optional[FlagDefinitionCacheProvider] = None, capture_exception_code_variables=False, code_variables_mask_patterns=None, code_variables_ignore_patterns=None, code_variables_mask_url_credentials=None, code_variables_detect_secrets=None, in_app_modules: list[str] | None = None, enable_exception_autocapture_rate_limiting=False, exception_autocapture_bucket_size=ExceptionCapture.DEFAULT_BUCKET_SIZE, exception_autocapture_refill_rate=ExceptionCapture.DEFAULT_REFILL_RATE, exception_autocapture_refill_interval_seconds=ExceptionCapture.DEFAULT_REFILL_INTERVAL_SECONDS, capture_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_max_queue_size: int = 1000, capture_ai_timeout: float = 30, capture_ai_max_event_bytes: int = AI_MAX_MSG_SIZE, secret_key=None, metrics: Optional[dict] = None, enable_full_ai_capture=False, capture_trace_context=False, _use_ai_lane=False, _enable_multimodal_capture=False, traces: Optional[dict] = None, app_host: Optional[str] = None, email_request_timeout_seconds: float = 15, email_request_max_retries: int = 2, migrated_from: Optional[str] = None) +class posthog.client.Client(project_api_key: str, host=None, *, debug=False, max_queue_size=10000, send=True, on_error=None, flush_at=100, flush_interval=5.0, max_retries=3, sync_mode=False, timeout: float = 15, thread=1, poll_interval=30, personal_api_key=None, disabled=False, disable_geoip=True, is_server=True, historical_migration=False, feature_flags_request_timeout_seconds: float = 3, feature_flags_request_max_retries=1, super_properties=None, super_options=None, enable_exception_autocapture=False, log_captured_exceptions=False, project_root=None, privacy_mode=False, before_send=None, flag_fallback_cache_url=None, enable_local_evaluation=True, flag_definition_cache_provider: Optional[FlagDefinitionCacheProvider] = None, capture_exception_code_variables=False, code_variables_mask_patterns=None, code_variables_ignore_patterns=None, code_variables_mask_url_credentials=None, code_variables_detect_secrets=None, in_app_modules: list[str] | None = None, enable_exception_autocapture_rate_limiting=False, exception_autocapture_bucket_size=ExceptionCapture.DEFAULT_BUCKET_SIZE, exception_autocapture_refill_rate=ExceptionCapture.DEFAULT_REFILL_RATE, exception_autocapture_refill_interval_seconds=ExceptionCapture.DEFAULT_REFILL_INTERVAL_SECONDS, capture_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_compression: Optional[Union[CaptureCompression, str]] = None, capture_ai_max_queue_size: int = 1000, capture_ai_timeout: float = 30, capture_ai_max_event_bytes: int = AI_MAX_MSG_SIZE, secret_key=None, metrics: Optional[dict] = None, enable_full_ai_capture=False, capture_trace_context=False, _use_ai_lane=False, _enable_multimodal_capture=False, traces: Optional[dict] = None, app_host: Optional[str] = None, email_request_timeout_seconds: float = 15, email_request_max_retries: int = 2, migrated_from: Optional[str] = None, ai_trace_sample_rate: Optional[float] = None) class posthog.consumer.Consumer(queue, api_key, flush_at=100, host=None, on_error=None, flush_interval=5.0, retries=3, timeout: float = 15, historical_migration=False, endpoint=_CAPTURE_V1_PATH, max_msg_size=MAX_MSG_SIZE, capture_compression=CaptureCompression.NONE) class posthog.contexts.ContextScope(parent=None, fresh: bool = False, capture_exceptions: bool = True, client: Optional[Client] = None) class posthog.emails.AsyncEmails(secret_key: Optional[str], *, host: Optional[str] = None, timeout: float = 15, max_retries: int = 2, disabled: bool = False, http_client: Any = None, migrated_from: Optional[str] = None) @@ -2061,6 +2064,7 @@ module posthog.ai.sanitization module posthog.ai.stream module posthog.ai.types module posthog.ai.utils +module posthog.ai_trace_sample_rate module posthog.args module posthog.async_client module posthog.bucketed_rate_limiter