Repository navigation
feat(ai): sample AI observability events by trace id (#965) - #1289
Shubham-dev-stack wants to merge 3 commits into
Conversation
Commit signatures resolvedGitHub now verifies every commit signature in this PR. No further action is needed. |
f679867 to
5dd94c3
Compare
dustinbyrne
left a comment
There was a problem hiding this comment.
Thanks for putting this together for #965! The Client sampling path works end-to-end (verified with sdk-mock-server across posthog.ai.openai.OpenAI and capture_ai on /i/v1/ai/events), but there are a few issues to address before this is ready to approve:
- Breaking:
NaNsample rates (float("nan")/POSTHOG_AI_TRACE_SAMPLE_RATE="nan") silently bypass validation with no warning and disable sampling. - Concern: The cross-SDK hash algorithm is still unsettled on #965 / PostHog/posthog-js#4997, and pure 32-bit FNV-1a severely clusters sequential trace IDs (
0/100kept ontrace-0..trace-99atrate=0.1). - Concern:
AsyncClient/AsyncPosthogomitsai_trace_sample_rateand silently ignoresPOSTHOG_AI_TRACE_SAMPLE_RATE. - Concern: The new unit tests fail when
POSTHOG_AI_TRACE_SAMPLE_RATEis set in the environment, leak 6 backgroundConsumerthreads, and omit unit coverage forcapture_ai(), queued mode, return values, and boundary inputs.
Follow-up outside this PR (once the cross-SDK hash contract is finalized): standardize AI trace sampling in PostHog/sdk-specs, document the option and posthog.ai.otel exclusion in PostHog/posthog.com, and track downstream $ai_trace_sample_rate upweighting in PostHog/posthog.
AI-assisted review.
| _TWO_TO_32 = 4294967296 # 2 ** 32 | ||
|
|
||
|
|
||
| def _fnv1a_32(text: str) -> int: |
There was a problem hiding this comment.
Concern: Pure 32-bit FNV-1a without a finalizer severely clusters sequential trace IDs and would lock in an unsettled cross-SDK hash contract.
Because 32-bit FNV-1a has weak avalanche on trailing bytes and _should_sample_ai_trace thresholds on h / 2**32 (high bits), sequential or shared-prefix trace IDs skew heavily. Verified on 5dd94c3e at rate=0.1:
trace-0..trace-99: 0 / 100 kept (0.0%)trace-0..trace-999: 183 / 1000 kept (18.3%)- Deterministic
uuid5control (1,000 IDs): 98 / 1000 kept (9.8%)
Since trace sampling must stay deterministic across SDKs (e.g., Python + Node via PostHog/posthog-js#4997, which is still open, and no spec exists in PostHog/sdk-specs yet), shipping raw FNV-1a now would make switching algorithms later a cross-SDK breaking change. Note that @fahad2932 raised this same FNV-1a clustering issue on #965, and CONTRIBUTING.md asks to align on public API / contracts before merging.
Policy decision needed: Before landing this, let's settle the canonical cross-SDK hash algorithm (e.g., FNV-1a + Murmur3 fmix32 finalizer or SHA-256 32-bit prefix), confirm UTF-8 byte input across Python and JS (TextEncoder vs charCodeAt), and pin shared cross-SDK test vectors (including sequential IDs and non-ASCII UTF-8 strings).
There was a problem hiding this comment.
Concern: Thanks for adding _fmix32 — it fixes the sequential-ID clustering (12/100 and 108/1000 at rate=0.1). Two parts of this cross-SDK contract decision are still open before merge:
- Cross-SDK sign-off:
PostHog/posthog-python#965andPostHog/posthog-js#4997still specify plain 32-bit FNV-1a withoutfmix32or a UTF-8 byte rule (and no peer server SDK orsdk-specsdoc implements it yet). Sinceposthog-pythonwill be the first SDK to ship this, we should get explicit maintainer confirmation (e.g.,@jakesciotto/team-llm-analytics&team-client-libraries) thatFNV-1a 32-bit over UTF-8 bytes + Murmur3 fmix32is the canonical contract and updateposthog-js#4997to match (TextEncoder+Math.imul(...) >>> 0) so mixed Python/Node stacks don't split traces. - Pinned test vectors:
test_fnv1a_32_and_fmix32_matches_specificationstill only asserts_fnv1a_32("") == 0x811C9DC5and0 <= mixed < 2**32. Once the canonical algorithm is confirmed, consider pinning exact uint32 vectors covering empty string, sequential IDs, UUIDs, and non-ASCII UTF-8 (for the currentfmix32(fnv1a_32(utf8))implementation:"" -> 0xAB3E7C0B,"trace-0" -> 0x31CCC93C,"trace-uuid-12345" -> 0xA095E0D6,"550e8400-e29b-41d4-a716-446655440000" -> 0x96E49D5D,"tracé-🚀" -> 0xF26CC0A9) soposthog-jscan mirror the exact same vectors.
There was a problem hiding this comment.
@PostHog/team-ai-observability we need your call on the cross-SDK hash contract for AI trace sampling before this merges. Python ships first, so whatever it uses becomes the contract that posthog-node (PostHog/posthog-js#4997) and other SDKs must match bit-for-bit. Otherwise mixed Python/Node stacks split traces.
Pinned test vectors: already done at 58b4a55. test_fnv1a_32_and_fmix32_matches_specification asserts the five UTF-8 fmix32(fnv1a_32(...)) vectors from the review comment above. An independent reimplementation produces the same values.
Existing hashing in the SDK, for reference:
| Where | Algorithm | Purpose | Cross-SDK contract? |
|---|---|---|---|
posthog/feature_flags.py _hash |
SHA-1, first 15 hex chars (60 bits) ÷ 0xFFFFFFFFFFFFFFF |
Flag rollout %, variants, holdouts | Yes. Matches the server and every SDK. |
posthog/_feature_flags_v2.py _hash01 |
Same SHA-1 60-bit (sha1_60_v1) |
v2 flag evaluation | Yes |
posthog/mcp/_ids.py _fnv1a_hex |
FNV-1a-like over code points (ord(ch)) |
Deterministic MCP session IDs | Only with the MCP TS SDK |
posthog/client.py |
SHA-256 | Flag definition cache fingerprints | No, internal |
posthog/emails.py |
SHA-256 | Attachment dedup | No |
Options for trace sampling (keep when hash / 2^N < rate):
| Option | Distribution on sequential IDs (rate=0.1) |
Cross-SDK cost | Notes |
|---|---|---|---|
| Plain FNV-1a 32-bit (what #965 / posthog-js#4997 specify) | Poor: trace-0..99 → 0%, trace-0..999 → 18.3% |
New contract | Not shippable as-is |
FNV-1a 32-bit over UTF-8 + Murmur3 fmix32 (this PR) |
Good: 12% / 10.8% | New contract; JS must use TextEncoder + Math.imul(...) >>> 0 |
Fast, but every SDK has to implement and agree on it |
Reuse flag bucketing hash (SHA-1 60-bit, e.g. _hash("ai_trace", trace_id)) |
Good: SHA-1 has no sequential-ID clustering, so no finalizer is needed | Already implemented and vector-pinned in every SDK and the server | UTF-8 handling already settled. One SHA-1 per AI event is negligible. Need to confirm posthog-node can do it synchronously in edge runtimes |
Suggestion: reuse the flag bucketing hash. It's the only option that's already a shared contract, so every SDK just reuses existing code. Whichever option you pick, I'd capture it in PostHog/sdk-specs (algorithm, prefix/salt, threshold, UTF-8 rule, vectors) and align posthog-js#4997 to it.
Can you confirm which algorithm should be canonical? Leaving this thread open until then.
There was a problem hiding this comment.
Let's reuse the flag bucketing hash (_hash in feature_flags.py, SHA-1 60-bit, e.g. _hash("ai_trace", trace_id) < rate) instead of adding a new one. It's already pinned in every SDK and the server, so PostHog/posthog-js#4997 reuses its existing code and we skip the FNV + fmix32 contract entirely. Agree on capturing the key/threshold in sdk-specs.
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.
5dd94c3 to
a7d2bbf
Compare
|
Thanks for the thorough review and testing with
|
dustinbyrne
left a comment
There was a problem hiding this comment.
Thanks for the quick turnaround addressing the previous review feedback! The NaN/OverflowError validation fixes, falsy-0 trace ID fix, helper module extraction, ambient env isolation, thread-leak cleanup, and Client/posthog.capture_ai docstrings all look good, and the end-to-end sdk-mock-server smoke test passed across posthog.ai.openai.OpenAI, Client.capture_ai, AsyncPosthog.capture_ai, and AsyncPosthog.capture_ai_immediate on direct properties trace IDs.
A few issues remain before this is ready to approve:
- Breaking:
AsyncClient._prepare_eventruns trace sampling before_fill_event_defaults, so$ai_trace_idvalues supplied viaposthog.tag("$ai_trace_id", ...)orsuper_propertiesare silently ignored (delivered even atrate=0.0, and missing$ai_trace_sample_ratewhen kept). - Breaking:
mypyfails onposthog/ai_trace_sample_rate.py:49(raw_valinferred asfloat, reassignedstr), which will break CI once workflows run. - Concern: The cross-SDK hash contract (
FNV-1a + fmix32over UTF-8) still needs maintainer sign-off across #965 and PostHog/posthog-js#4997 plus pinned concrete ASCII/UTF-8 hash test vectors (replied on the existing thread). - Concern:
AsyncClient.capture_ai's docstring inaccurately states thatbefore_senddrops returnNone. - Concern: Unit tests still omit default queued
Client(sync_mode=False),AsyncClientwithsend=True/fractional rate/before_send/context-tags/super_properties,UUIDtrace IDs, andassertNoLogson blank env vars (replied on the existing thread).
Follow-up outside this PR (once the cross-SDK hash contract is finalized): document ai_trace_sample_rate, POSTHOG_AI_TRACE_SAMPLE_RATE, $ai_trace_sample_rate, and the posthog.ai.otel exclusion in PostHog/posthog.com, standardize AI trace sampling in PostHog/sdk-specs, align PostHog/posthog-js#4997, and track downstream $ai_trace_sample_rate upweighting in PostHog/posthog.
AI-assisted review.
PostHog#965) Pass `_EventDefaults` into `AsyncClient._prepare_event` from both `_capture` and `_capture_immediate` so `$ai_trace_id` values supplied through `posthog.tag()` or `super_properties` are evaluated at admission time with `_fill_event_defaults` precedence while preserving explicit `None` overrides. Keep sampling before queueing so dropped events return `None` immediately and kept events carry `$ai_trace_sample_rate` before `_process_event` and `before_send`. Rename the helper module to `posthog/_ai_trace_sample_rate.py` with relative imports in `client.py` and `async_client.py` so `references/public_api_snapshot.txt` stays scoped to the client option. Annotate `raw_val: Any` for `mypy`, catch `TypeError` alongside `(ValueError, OverflowError)` in `_resolve_ai_trace_sample_rate`, clarify `AsyncClient.capture_ai`'s docstring around asynchronous `before_send` execution, and add unit tests covering pinned uint32 vectors, queued sync `Client`, `AsyncPosthog(..., send=True)` parity, `uuid.UUID` trace IDs, `TypeError` handling, and silent blank env vars.
|
@dustinbyrne Thanks for catching the I also renamed the helper module to
|
SDK performance: posthog-pythonBenchmarks completed. No changes flagged for review. Flags require at least a 5% change in the median and all six pairs agreeing on direction. This is a noise filter, not proof of a performance change or a CI gate. View all results
Values are medians of paired measurements. Not flagged does not mean unchanged. Unavailable means a measurement could not be provided, not zero. Estimated allocation measurements retain their instrumentation uncertainty. RSS measures the whole process, not just SDK allocations; observed peaks are sampled checkpoints. Paired ranges in the diagnostics describe variability, not confidence intervals. Each shard uses its own runner; compare Before PR against With PR within a row, not across shards. Compared 102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in |
…rate # Conflicts: # posthog/async_client.py # references/public_api_snapshot.txt
| 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 |
There was a problem hiding this comment.
This says posthog.capture_ai can drop events through ai_trace_sample_rate, but there's no posthog.ai_trace_sample_rate module setting and setup() never passes one to Client, so module-API users can only reach it through POSTHOG_AI_TRACE_SAMPLE_RATE. Add the module attribute and wire it through setup() like capture_ai_timeout, or say here that the env var is the only switch.
|
|
||
| def _fnv1a_32(text: str) -> int: | ||
| h = _FNV_OFFSET_BASIS_32 | ||
| for b in text.encode("utf-8"): |
There was a problem hiding this comment.
text.encode("utf-8") raises UnicodeEncodeError on a lone surrogate ("\ud800"), which json.dumps sends fine today. With a rate set, the event is now lost inside no_throw. Replace lone surrogates with U+FFFD before hashing (matches JS TextEncoder), e.g. text.encode("utf-16", "surrogatepass").decode("utf-16", "replace").encode("utf-8").
|
|
||
| asyncio.run(run_async()) | ||
|
|
||
| def test_queued_sync_client_sampling_and_flush(self): |
There was a problem hiding this comment.
Only the async tests cover a $ai_trace_id from tag() or super_properties. On Client this works only because sampling runs after _fill_event_defaults in _enqueue; moving the call up would let every tagged trace through at rate 0.0 with no failing test. Add a sync case: rate 0.0, trace id from tag()/super_properties, assert dropped.
| _TWO_TO_32 = 4294967296 # 2 ** 32 | ||
|
|
||
|
|
||
| def _fnv1a_32(text: str) -> int: |
There was a problem hiding this comment.
Let's reuse the flag bucketing hash (_hash in feature_flags.py, SHA-1 60-bit, e.g. _hash("ai_trace", trace_id) < rate) instead of adding a new one. It's already pinned in every SDK and the server, so PostHog/posthog-js#4997 reuses its existing code and we skip the FNV + fmix32 contract entirely. Agree on capturing the key/threshold in sdk-specs.
💡 Motivation and Context
Fixes #965.
High-throughput LLM workloads generate significant event volume across generation, span, and trace events. To control cost and storage while keeping complete distributed trace contexts intact, AI events belonging to the same trace need to be sampled deterministically.
This adds
ai_trace_sample_ratetoClientand supports thePOSTHOG_AI_TRACE_SAMPLE_RATEenvironment variable. Sampling applies specifically to events whose names start with$ai_and contain an$ai_trace_idproperty (checking both top-level and event properties for compatibility). By hashing the trace ID with 32-bit FNV-1a matching peer SDK implementations, all events within a trace are either kept or dropped together. Kept events receive the$ai_trace_sample_rateproperty before reachingbefore_sendor the submission lanes. Events without a trace ID, non-AI events, and calls when the sample rate is unset or1.0are preserved unconditionally.💚 How did you test it?
Added a dedicated test suite in
posthog/test/ai/test_ai_trace_sample_rate.pycovering:$ai_*events sharing the same$ai_trace_id(all kept or all dropped together).$ai_trace_idand non-$ai_*events regardless of the configured rate.$ai_trace_sample_rateproperty on retained events and preservation throughbefore_send.kwarg> environment variable > default) and defensive handling of out-of-range or malformed inputs.Verified that all 10 tests pass with pytest, formatted and linted with ruff, and validated the public API snapshot with
check_public_api.py.📝 Checklist
If releasing new changes
sampo addto generate a changeset file🤖 Agent context
Autonomy: Human-driven (agent-assisted)
The change was directed by Shubham-dev-stack to address #965 by aligning Python SDK AI trace sampling behavior with peer PostHog client implementations. FNV-1a 32-bit hashing was selected to ensure deterministic cohorting of distributed traces without external hashing dependencies.