Skip to content

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

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

Shubham-dev-stack wants to merge 1 commit 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 Outdated
return None

val = float(raw_val)
if val < 0.0 or val > 1.0:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Breaking: NaN values for ai_trace_sample_rate / POSTHOG_AI_TRACE_SAMPLE_RATE silently bypass range validation with no warning and store nan on client.ai_trace_sample_rate.

Because IEEE 754 ordered comparisons with NaN are always False, float("nan") < 0.0 or float("nan") > 1.0 evaluates to False, so _resolve_ai_trace_sample_rate returns nan without logging a warning. At capture time (posthog/client.py:3326), self.ai_trace_sample_rate < 1.0 is also False, which silently disables sampling and sends 100% of AI events.

Minimal trigger (verified on 5dd94c3e):

# With POSTHOG_AI_TRACE_SAMPLE_RATE="nan" (or "NaN" / " NAN "), or:
client = Client("phc_test", ai_trace_sample_rate=float("nan"), send=False)
# Actual: client.ai_trace_sample_rate is nan, 0 warnings logged
# Expected: client.ai_trace_sample_rate is None, 1 warning logged

Consider checking math.isfinite(val) alongside the bounds check (and catching OverflowError on float(raw_val) for huge ints so Client.__init__ keeps its no-throw contract):

try:
    val = float(raw_val)
except OverflowError:
    log.warning("ai_trace_sample_rate out of range [0.0, 1.0]: %r. Ignoring.", raw_val)
    return None
if not math.isfinite(val) or not (0.0 <= val <= 1.0):
    log.warning("ai_trace_sample_rate out of range [0.0, 1.0]: %r. Ignoring.", val)
    return None

Consider adding regression tests covering float("nan"), POSTHOG_AI_TRACE_SAMPLE_RATE="nan" / "NaN", "inf", and "-inf".

Comment thread posthog/client.py
email_request_timeout_seconds: float = 15,
email_request_max_retries: int = 2,
migrated_from: Optional[str] = None,
ai_trace_sample_rate: Optional[float] = None,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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

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

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

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

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.

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

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: TestAiTraceSampleRate fails when POSTHOG_AI_TRACE_SAMPLE_RATE is set in the ambient environment, leaks 6 background Consumer threads, and omits unit coverage for several core paths.

Verified on 5dd94c3e:

  1. Running POSTHOG_AI_TRACE_SAMPLE_RATE=0.5 pytest posthog/test/ai/test_ai_trace_sample_rate.py fails at line 43 (AssertionError: 0.5 is not None) because setUp does not clear POSTHOG_AI_TRACE_SAMPLE_RATE from os.environ (compare posthog/test/test_capture_compression.py:19-23).
  2. Lines 34, 38, 42, 48, 54, and 61 construct Client("test_key", ...) with default sync_mode=False, send=True and never call shutdown(), leaving 6 live background Consumer threads running after the test class finishes (threads_before=1, threads_after=7).
  3. Every test calls client.capture(..., sync_mode=True): there is no unit coverage for capture_ai() (the v1 AI lane), queued mode (sync_mode=False), return values (None on drop vs UUID string on keep), end-to-end rate=0.0 dropping a traced $ai_* event, boundary inputs (NaN, inf, bool, blank env var, non-numeric kwargs), UUID / context-tag / super_properties trace IDs, and test_multi_item_positive_control_fixture (lines 213–231) claims to test trace-level sampling even though none of its 3 events carry $ai_trace_id.

Consider adding an env-clearing setUp, passing send=False / sync_mode=True (or shutting down clients in addCleanup), and adding coverage for capture_ai(), return values, queued mode, and boundary inputs.

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: The ambient env isolation (setUp/tearDown), addCleanup(client.shutdown) thread-leak fix (verified before=1, after=1 threads), capture_ai return-value test, rate=0.0 cases, and fixed multi-item fixture all look good and pass cleanly.

A few important supported paths still lack coverage in test_ai_trace_sample_rate.py:

  1. Queued Client (sync_mode=False): Every Client test currently passes sync_mode=True; consider adding a test in default queued mode (sync_mode=False + flush()) verifying kept traces deliver with $ai_trace_sample_rate and dropped traces are never queued.
  2. Real-delivery AsyncClient / AsyncPosthog (send=True): test_async_client_sampling_parity currently passes send=False with rates 0.0 and 1.0 only, so _AsyncConsumer, _process_event, _fill_event_defaults, before_send, and $ai_trace_sample_rate attachment are never exercised (which is how the context-tag/super_properties bug in _prepare_event slipped through). Consider adding an AsyncPosthog(..., send=True, ai_trace_sample_rate=0.5, before_send=...) test with patch_async_capture_send covering both queued capture_ai + flush() and capture_ai_immediate, including context-tagged and super_properties $ai_trace_id (plus explicit properties={"$ai_trace_id": None} overriding a context tag).
  3. UUID trace IDs & blank env no-warning check: Consider adding a test passing a uuid.UUID as $ai_trace_id (matching str(u)'s decision) and wrapping the blank POSTHOG_AI_TRACE_SAMPLE_RATE=" " case (line 119) in self.assertNoLogs("posthog", level="WARNING").

Comment thread posthog/client.py Outdated
if self.ai_trace_sample_rate is not None and self.ai_trace_sample_rate < 1.0:
event_name = msg.get("event")
if isinstance(event_name, str) and event_name.startswith("$ai_"):
trace_id = msg.get("properties", {}).get("$ai_trace_id") or msg.get(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion: Avoid or when reading $ai_trace_id and drop the unused top-level msg.get("$ai_trace_id") fallback.

Client._capture never puts $ai_trace_id at the top level of msg, so or msg.get("$ai_trace_id") is dead code — and using or turns a falsy $ai_trace_id: 0 passed to capture() / capture_ai() into None (silently skipping sampling even at rate=0.0, verified on 5dd94c3e), while treating "" as missing (kept) and " " as present (dropped). (Built-in wrappers like LangChain already replace falsy 0 with a UUID before capture, so this only affects direct capture() / capture_ai() callers.)

Consider checking is not None directly and treating blank strings consistently:

props = msg.get("properties") or {}
trace_id = props.get("$ai_trace_id")
if trace_id is not None:
    trace_id_str = str(trace_id)
    if trace_id_str.strip():
        ...

Comment thread posthog/client.py Outdated

_configure_posthog_logging()

AI_TRACE_SAMPLE_RATE_ENV_VAR = "POSTHOG_AI_TRACE_SAMPLE_RATE"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion: Consider keeping AI_TRACE_SAMPLE_RATE_ENV_VAR private (_AI_TRACE_SAMPLE_RATE_ENV_VAR) or moving it with the sampling helpers into a small shared module (following posthog/release_id.py and posthog/capture_compression.py), rather than expanding posthog.client's public API snapshot (references/public_api_snapshot.txt:817). Moving it into a dedicated module also makes it easy to share with AsyncClient without circular imports.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Suggestion: Thanks for moving the helpers out of posthog.client — posthog/ai_trace_sample_rate.py matches the existing posthog/release_id.py pattern. One optional cleanup to consider: since this module has no public classes/functions and import posthog binds posthog.ai_trace_sample_rate as a <module> attribute (which would silently shadow a future or attempted module-level setting) and adds module posthog.ai_trace_sample_rate + AI_TRACE_SAMPLE_RATE_ENV_VAR to references/public_api_snapshot.txt, renaming it to posthog/_ai_trace_sample_rate.py would keep the public API surface limited to the Client/AsyncClient option and attribute. Either way, consider switching posthog/client.py:57 to a relative import (from .ai_trace_sample_rate import ...) to match posthog/async_client.py:35 and AGENTS.md mirror-safety guidance.

Comment thread posthog/client.py
Set to 0 when a job runner already retries the send.
migrated_from: The email provider you moved from, such as
``"resend"``. ``emails`` sends it with every request.
ai_trace_sample_rate: Optional sample rate between 0.0 and 1.0 for

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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

@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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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

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

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

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

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

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

env_val = os.environ.get(AI_TRACE_SAMPLE_RATE_ENV_VAR)
if env_val is None or not env_val.strip():
return None
raw_val = env_val.strip()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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

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

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

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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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

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


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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

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

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

2 participants