Skip to content

feat(ai): sample AI observability events by trace id (#965) - #1289

Open
Shubham-dev-stack wants to merge 3 commits into
PostHog:mainfrom
Shubham-dev-stack:feat/ai-trace-sample-rate
Open

Shubham-dev-stack wants to merge 3 commits into
PostHog:mainfrom
Shubham-dev-stack:feat/ai-trace-sample-rate

Conversation

@Shubham-dev-stack

Copy link
Copy Markdown

💡 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_rate to Client and supports the POSTHOG_AI_TRACE_SAMPLE_RATE environment variable. Sampling applies specifically to events whose names start with $ai_ and contain an $ai_trace_id property (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_rate property before reaching before_send or the submission lanes. Events without a trace ID, non-AI events, and calls when the sample rate is unset or 1.0 are preserved unconditionally.

💚 How did you test it?

Added a dedicated test suite in posthog/test/ai/test_ai_trace_sample_rate.py covering:

  • Deterministic trace sampling across multiple $ai_* events sharing the same $ai_trace_id (all kept or all dropped together).
  • Preservation of events lacking $ai_trace_id and non-$ai_* events regardless of the configured rate.
  • Inclusion of the $ai_trace_sample_rate property on retained events and preservation through before_send.
  • Config resolution priority (kwarg > environment variable > default) and defensive handling of out-of-range or malformed inputs.
  • Multi-item control fixtures verifying parity and ordering across 100 deterministic trace IDs at a 50% rate.

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

  • All commits are signed (see Commit signing)
  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to 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.

@Shubham-dev-stack
Shubham-dev-stack requested a review from a team as a code owner November 21, 2026 13:55
@signed-commit-check

signed-commit-check Bot commented Nov 21, 2026 •

Copy link
Copy Markdown

Commit signatures resolved

GitHub now verifies every commit signature in this PR. No further action is needed.

@Shubham-dev-stack
Shubham-dev-stack force-pushed the feat/ai-trace-sample-rate branch from f679867 to 5dd94c3 Compare November 22, 2026 07:47

@dustinbyrne dustinbyrne left a comment

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.

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:

  1. Breaking: NaN sample rates (float("nan") / POSTHOG_AI_TRACE_SAMPLE_RATE="nan") silently bypass validation with no warning and disable sampling.
  2. 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/100 kept on trace-0..trace-99 at rate=0.1).
  3. Concern: AsyncClient / AsyncPosthog omits ai_trace_sample_rate and silently ignores POSTHOG_AI_TRACE_SAMPLE_RATE.
  4. Concern: The new unit tests fail when POSTHOG_AI_TRACE_SAMPLE_RATE is set in the environment, leak 6 background Consumer threads, and omit unit coverage for capture_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.

Comment thread posthog/client.py Resolved
Comment thread posthog/client.py Resolved
Comment thread posthog/client.py Outdated
_TWO_TO_32 = 4294967296 # 2 ** 32


def _fnv1a_32(text: str) -> int:

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: 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 uuid5 control (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).

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: 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:

  1. Cross-SDK sign-off: PostHog/posthog-python#965 and PostHog/posthog-js#4997 still specify plain 32-bit FNV-1a without fmix32 or a UTF-8 byte rule (and no peer server SDK or sdk-specs doc implements it yet). Since posthog-python will be the first SDK to ship this, we should get explicit maintainer confirmation (e.g., @jakesciotto / team-llm-analytics & team-client-libraries) that FNV-1a 32-bit over UTF-8 bytes + Murmur3 fmix32 is the canonical contract and update posthog-js#4997 to match (TextEncoder + Math.imul(...) >>> 0) so mixed Python/Node stacks don't split traces.
  2. Pinned test vectors: test_fnv1a_32_and_fmix32_matches_specification still only asserts _fnv1a_32("") == 0x811C9DC5 and 0 <= 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 current fmix32(fnv1a_32(utf8)) implementation: "" -> 0xAB3E7C0B, "trace-0" -> 0x31CCC93C, "trace-uuid-12345" -> 0xA095E0D6, "550e8400-e29b-41d4-a716-446655440000" -> 0x96E49D5D, "tracé-🚀" -> 0xF26CC0A9) so posthog-js can mirror the exact same vectors.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

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.

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.

Comment thread posthog/client.py Resolved
Comment thread posthog/client.py Resolved
Comment thread posthog/client.py Resolved
@dustinbyrne
dustinbyrne requested a review from a team November 23, 2026 21:16
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.
@Shubham-dev-stack
Shubham-dev-stack force-pushed the feat/ai-trace-sample-rate branch from 5dd94c3 to a7d2bbf Compare November 24, 2026 09:49
@Shubham-dev-stack

Copy link
Copy Markdown
Author

Thanks for the thorough review and testing with sdk-mock-server @dustinbyrne! I've addressed all the points across the implementation and test suite:

  • Validation & Bounds: Added explicit math.isfinite() bounds checking and OverflowError handling in _resolve_ai_trace_sample_rate, so NaN, inf, -inf, boolean inputs, and overflowing ints log a warning and fall back cleanly without bypassing validation.
  • Sequential Trace Hashing: Added the Murmur3 32-bit fmix32 finalizer step after the FNV-1a loop as discussed on Add ai_trace_sample_rate to sample AI observability events by trace id #965. This eliminates clustering on sequential IDs (trace-0..trace-99 at rate=0.1 now yields 12/100, and trace-0..trace-999 yields 10.8%).
  • Async Client Parity & Module Encapsulation: Extracted the sampling logic and environment variable resolver into posthog.ai_trace_sample_rate (matching posthog.release_id) and wired ai_trace_sample_rate into AsyncClient / AsyncPosthog across both capture_ai() and capture_ai_immediate().
  • Test Suite Hygiene & Coverage: Isolated ambient environment variables in setUp/tearDown, added deterministic cleanup to avoid background thread leaks, and added unit tests covering NaN/inf validation, capture_ai() return values, sequential trace distribution, and AsyncClient parity.
  • Docstrings: Documented the OTLP exporter distinction for posthog.ai.otel and updated the return parentheticals on Client.capture_ai, AsyncClient.capture_ai, and posthog.capture_ai.

@dustinbyrne dustinbyrne left a comment

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.

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:

  1. Breaking: AsyncClient._prepare_event runs trace sampling before _fill_event_defaults, so $ai_trace_id values supplied via posthog.tag("$ai_trace_id", ...) or super_properties are silently ignored (delivered even at rate=0.0, and missing $ai_trace_sample_rate when kept).
  2. Breaking: mypy fails on posthog/ai_trace_sample_rate.py:49 (raw_val inferred as float, reassigned str), which will break CI once workflows run.
  3. Concern: The cross-SDK hash contract (FNV-1a + fmix32 over 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).
  4. Concern: AsyncClient.capture_ai's docstring inaccurately states that before_send drops return None.
  5. Concern: Unit tests still omit default queued Client (sync_mode=False), AsyncClient with send=True/fractional rate/before_send/context-tags/super_properties, UUID trace IDs, and assertNoLogs on 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.

Comment thread posthog/async_client.py Resolved
Comment thread posthog/_ai_trace_sample_rate.py Resolved
Comment thread posthog/async_client.py Resolved
Comment thread posthog/ai_trace_sample_rate.py Resolved
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.
@Shubham-dev-stack

Copy link
Copy Markdown
Author

@dustinbyrne Thanks for catching the AsyncClient layering mismatch and mypy issue. I updated the branch to pass defaults into AsyncClient._prepare_event from both _capture and _capture_immediate, resolving $ai_trace_id with _fill_event_defaults precedence so context tags and super_properties are evaluated at admission time while an explicit properties={"$ai_trace_id": None} still overrides them.

I also renamed the helper module to posthog/_ai_trace_sample_rate.py with relative imports in posthog/client.py and posthog/async_client.py (restoring references/public_api_snapshot.txt to just the client option), declared raw_val: Any to resolve the mypy error, added TypeError handling to _resolve_ai_trace_sample_rate, and updated AsyncClient.capture_ai's docstring so it distinguishes queue admission from the background before_send worker. On the test side, posthog/test/ai/test_ai_trace_sample_rate.py now pins the five UTF-8 fmix32(fnv1a_32(...)) uint32 vectors and adds coverage for queued Client, AsyncPosthog(..., send=True, ...) across capture_ai and capture_ai_immediate with context tags/super_properties/None overrides/before_send, uuid.UUID trace IDs, TypeError inputs, and silent blank env vars.

ruff format --check ., ruff check ., check_public_api.py, mypy --no-site-packages --config-file mypy.ini posthog, and the targeted unit/client test suites are passing locally. Once @jakesciotto or team-llm-analytics / team-client-libraries confirm the FNV-1a 32-bit over UTF-8 + fmix32 cross-SDK contract for #965 and posthog-js#4997, this should be ready.

@marandaneto
marandaneto requested a review from a team December 2, 2026 12:25
@github-actions

github-actions Bot commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

SDK performance: posthog-python

Benchmarks 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
Test Measurement Before PR With PR Change Assessment
Capture and deliver events (32-byte payload, burst)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (32-byte payload, steady)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Queue an event (32-byte payload)
Shard: capture
Allocated memory per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (32-byte payload)
Shard: capture
Allocations per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (4,096-byte payload)
Shard: capture
Allocated memory per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (4,096-byte payload)
Shard: capture
Allocations per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Refresh 1,000 flag definitions
Shard: flags-memory
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (32-byte payload, burst)
Shard: capture
Allocated memory per operation 75.2 KiB/op 75.47 KiB/op 0.4% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Allocations per operation 775.54 count/op 777.56 count/op 0.3% more Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Time per operation 50.99 µs/op 50.95 µs/op <0.1% less time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Idle process memory (RSS) 38 MiB 38.03 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 40.45 MiB 40.49 MiB 0.1% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 40.45 MiB 40.49 MiB 0.1% more memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process CPU time per operation 50.94 µs/op 51.95 µs/op 2% more time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 40.62 MiB 40.67 MiB 0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocated memory per operation 127.28 KiB/op 127.54 KiB/op 0.2% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocations per operation 767.54 count/op 769.54 count/op 0.3% more Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Time per operation 74.22 µs/op 74.61 µs/op 0.5% more time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Idle process memory (RSS) 41.6 MiB 41.65 MiB 0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 47.41 MiB 47.46 MiB 0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 47.41 MiB 47.46 MiB 0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process CPU time per operation 71.05 µs/op 72.18 µs/op 1.6% more time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 51.83 MiB 51.91 MiB 0.2% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocated memory per operation 80.26 KiB/op 80.52 KiB/op 0.3% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocations per operation 820.34 count/op 822.33 count/op 0.2% more Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Time per operation 61.66 µs/op 61.59 µs/op 0.1% less time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Idle process memory (RSS) 37.88 MiB 37.89 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 38.08 MiB 38.08 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 38.08 MiB 38.08 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process CPU time per operation 63.28 µs/op 63.11 µs/op 0.3% less time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 40.53 MiB 40.53 MiB No observed change Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocated memory per operation 132.43 KiB/op 132.7 KiB/op 0.2% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocations per operation 812.23 count/op 814.23 count/op 0.2% more Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Time per operation 78.62 µs/op 78.5 µs/op 0.2% less time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Idle process memory (RSS) 41.48 MiB 41.43 MiB 0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 41.97 MiB 41.92 MiB 0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 41.55 MiB 41.5 MiB 0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process CPU time per operation 75.71 µs/op 76.67 µs/op 1.3% more time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 41.79 MiB 41.81 MiB <0.1% more memory Not flagged
Queue an event (32-byte payload)
Shard: capture
Caller-thread CPU time per operation 30.82 µs/op 30.91 µs/op 0.3% more time Not flagged
Queue an event (32-byte payload)
Shard: capture
Time per operation 30.82 µs/op 30.91 µs/op 0.3% more time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Caller-thread CPU time per operation 31.15 µs/op 31.14 µs/op <0.1% less time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Time per operation 31.15 µs/op 31.16 µs/op <0.1% more time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocated memory per operation 246.53 KiB/op 246.53 KiB/op No observed change Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocations per operation 2,491.44 count/op 2,491.44 count/op No observed change Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Time per operation 89.87 µs/op 89.41 µs/op 0.5% less time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Process CPU time per operation 89.88 µs/op 89.41 µs/op 0.5% less time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocated memory per operation 2.37 MiB/op 2.37 MiB/op No observed change Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocations per operation 24,470.94 count/op 24,470.94 count/op No observed change Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Time per operation 826.33 µs/op 828.98 µs/op 0.3% more time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Process CPU time per operation 826.34 µs/op 829.05 µs/op 0.3% more time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocated memory per operation 23.6 MiB/op 23.6 MiB/op No observed change Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocations per operation 244,162.69 count/op 244,162.69 count/op No observed change Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Time per operation 8.15 ms/op 8.21 ms/op 0.7% more time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Process CPU time per operation 8.15 ms/op 8.21 ms/op 0.7% more time Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Idle process memory (RSS) 43.95 MiB 43.51 MiB 1% less memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Observed peak process memory (RSS) 44.27 MiB 43.81 MiB 1% less memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Process memory after settling (RSS) 44.27 MiB 43.81 MiB 1% less memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Lifetime peak process memory (RSS) 44.06 MiB 43.95 MiB 0.2% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Idle process memory (RSS) 43.9 MiB 43.94 MiB <0.1% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Observed peak process memory (RSS) 43.91 MiB 43.95 MiB <0.1% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Process memory after settling (RSS) 43.91 MiB 43.95 MiB <0.1% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Lifetime peak process memory (RSS) 43.76 MiB 43.79 MiB <0.1% more memory Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocated memory per operation 17.65 KiB/op 17.65 KiB/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocations per operation 180.77 count/op 180.77 count/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Time per operation 10.98 µs/op 10.99 µs/op <0.1% more time Not flagged
Evaluate one boolean flag
Shard: flags-single
Process CPU time per operation 10.98 µs/op 10.99 µs/op <0.1% more time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocated memory per operation 27.72 KiB/op 27.72 KiB/op No observed change Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocations per operation 271.28 count/op 271.28 count/op No observed change Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Time per operation 14.7 µs/op 14.72 µs/op 0.1% more time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Process CPU time per operation 14.7 µs/op 14.71 µs/op 0.1% more time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocated memory per operation 44.29 KiB/op 44.29 KiB/op No observed change Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocations per operation 434.28 count/op 434.28 count/op No observed change Not flagged
Evaluate a flag (early match)
Shard: flags-single
Time per operation 20.69 µs/op 20.65 µs/op 0.2% less time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Process CPU time per operation 20.69 µs/op 20.65 µs/op 0.2% less time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocated memory per operation 67.07 KiB/op 67.07 KiB/op No observed change Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocations per operation 651.28 count/op 651.28 count/op No observed change Not flagged
Evaluate a flag (late match)
Shard: flags-single
Time per operation 29.14 µs/op 29.2 µs/op 0.2% more time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Process CPU time per operation 29.14 µs/op 29.2 µs/op 0.2% more time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocated memory per operation 65.7 KiB/op 65.7 KiB/op No observed change Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocations per operation 634.77 count/op 634.77 count/op No observed change Not flagged
Evaluate a flag (no match)
Shard: flags-single
Time per operation 28.12 µs/op 27.89 µs/op 0.8% less time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Process CPU time per operation 28.12 µs/op 27.89 µs/op 0.8% less time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocated memory per operation 21.52 KiB/op 21.52 KiB/op No observed change Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocations per operation 217.28 count/op 217.28 count/op No observed change Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Time per operation 12.06 µs/op 12.12 µs/op 0.5% more time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Process CPU time per operation 12.06 µs/op 12.12 µs/op 0.5% more time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocated memory per operation 23.15 KiB/op 23.15 KiB/op No observed change Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocations per operation 222.78 count/op 222.78 count/op No observed change Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Time per operation 12.89 µs/op 12.83 µs/op 0.5% less time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Process CPU time per operation 12.89 µs/op 12.83 µs/op 0.5% less time Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocated memory per operation 16.8 KiB/op 16.8 KiB/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocations per operation 170.77 count/op 170.77 count/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Time per operation 10.42 µs/op 10.32 µs/op 1% less time Not flagged
Evaluate a rollout flag
Shard: flags-single
Process CPU time per operation 10.42 µs/op 10.32 µs/op 1% less time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocated memory per operation 17.81 KiB/op 17.81 KiB/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocations per operation 184.77 count/op 184.77 count/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Time per operation 11.34 µs/op 11.31 µs/op 0.3% less time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Process CPU time per operation 11.34 µs/op 11.31 µs/op 0.3% less time Not flagged

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 a02f63bb52f4c497b221523de98edaedcea1f8f4 → a41c51a8bb2df89053b7676c8cd56c29326ef895.

Full report and diagnostics

102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in comparison.json, including per-runner environments, resource limits, measurement methods, samples and checkpoints.

…rate

# Conflicts:
#	posthog/async_client.py
#	references/public_api_snapshot.txt
Comment thread posthog/__init__.py
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

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.

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"):

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.

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):

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.

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.

Comment thread posthog/client.py Outdated
_TWO_TO_32 = 4294967296 # 2 ** 32


def _fnv1a_32(text: str) -> int:

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.

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.

Comment thread posthog/async_client.py Resolved
Comment thread posthog/client.py Resolved

This branch has not been deployed

No deployments
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.

Add ai_trace_sample_rate to sample AI observability events by trace id

4 participants