Repository navigation
feat(ai): sample AI observability events by trace id (#965) #1289
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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. |
| 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() | ||
| 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): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Suggestion: Consider catching Observed locally on |
||
| 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 | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Breaking: Contract & causality: Sync Observed behavior (reproduced locally on
Minimal regression test (fails on 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 |
||
| 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``). | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Concern: Observed behavior (verified locally on Recommendation: Consider updating lines 722–724 to state that |
||
| 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) | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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, | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Concern:
For asyncio apps (e.g., FastAPI) relying on Consider moving the rate resolver and sampling helper into a small shared module (like |
||
| ): | ||
| """ | ||
| 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 | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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:
|
||
| 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: | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Breaking:
mypyfails here becauseraw_valis inferred asfloaton line 43 (narrowed fromOptional[float]) and then reassigned astron line 49.Observed locally on
a7d2bbffvs merge base84fc9e06:Running
mypy --no-site-packages --config-file mypy.ini . | mypy-baseline filterpasses on84fc9e06(Success: no issues found in 356 source files) and fails ona7d2bbff:Recommendation: Consider declaring
raw_val: Anybeforeif kwarg is not None:(Anyis already imported and keepsisinstance(raw_val, bool)compatible withwarn_unreachable = Trueinmypy.ini), then re-runningmypy --no-site-packages --config-file mypy.ini . | mypy-baseline filter.