Skip to content

fix(aio): keep content out of ai events in privacy mode - #1105

Merged
carlos-marchal-ph merged 11 commits into
mainfrom
fix(aio)/ai-privacy-mode-leaks
Oct 23, 2026
Merged

carlos-marchal-ph merged 11 commits into
mainfrom
fix(aio)/ai-privacy-mode-leaks

Conversation

@carlos-marchal-ph

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

privacy mode doesn't keep content out of AI events:

  • $ai_error is str(exc), never redacted. .parse() validation errors quote model output, gemini client-side validation quotes the prompt, langchain OutputParserException includes the full output, and openai-compatible servers echo the request in 4xx bodies.
  • langchain $exception autocapture ignores privacy.
  • remote MCP tool headers / authorization are sent verbatim in $ai_tools, privacy or not.
  • gemini: per-call posthog_privacy_mode=False undid a client default of True.
  • openai agents: audio model_config prompt/instructions and $ai_trace_metadata sent under privacy.
  • OTel processor/exporter had no privacy option and ignored the client's.

context: https://posthog.slack.com/archives/C0ACMS2BNTU/p1792232645298019

Changes

  • $ai_error under privacy (client or per-call/handler flag): built only from structured fields that pass a strict grammar, never message/traceback/attributes. format, shared with posthog-js:
    {Name}[: {status}][ {code}…][ param={param}][ request_id={id}][ (caused by A, B)]
    e.g. BadRequestError: 400 invalid_request_error param=messages[3].content request_id=req_123. applied to openai / anthropic / gemini (incl. embeddings), langchain generation/span/trace, openai agents. the middleware's fixed "Tool returned an error" text is kept.
  • langchain $exception skipped under privacy.
  • MCP tools: headers / authorization values on type == "mcp" tools become [REDACTED], always, without mutating the caller's objects. tool definitions otherwise unchanged and still sent under privacy.
  • gemini: per-call flag can only add redaction, matching openai/anthropic.
  • openai agents: under privacy, audio model_config prompt/instructions and $ai_trace_metadata set to None.
  • OTel: new privacy_mode and client kwargs on PostHogSpanProcessor / PostHogTraceExporter; also follows the module-level client. content attributes and exception messages stripped, list derived from the server's otel → $ai_* mapping. tool definitions and exception.type kept. if redaction fails the span is dropped, not sent.

Notes for reviewers

  • sdk-specs capture-ai only defines privacy as stripping content properties; this widens it to errors and OTel. spec update to follow.
  • new helpers are private; only public API change is the two OTel constructor kwargs (references/public_api_snapshot.txt).

💚 How did you test it?

  • new posthog/test/ai/test_privacy_mode.py: summarizer against real openai / anthropic / google-genai / pydantic errors and grammar rejections; MCP masking across providers and tool shapes; canary tests with a real Client(privacy_mode=True, enable_exception_autocapture=True) asserting a canary string appears nowhere in any captured event, incl. $exception, across every integration and OTel.
  • each fix reverted individually to confirm its test fails.
  • pytest posthog/test/ai 1288 passed; ruff, mypy (baseline), make public_api_check clean.

📝 Checklist

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

  • written by Claude Code (claude-opus-5-5) with subagents; audit of both SDKs first, then one implementation agent per repo against a shared spec so python and js match.
  • chose deterministic allowlisting for $ai_error over text scrubbing: regex/PII detection can't guarantee anything. rejected a full schema allowlist for $ai_tools (would silently drop new tool types); only the documented MCP credential slots are masked.
  • docs: PostHog/posthog.com branch fix(aio)/ai-privacy-mode-leaks.

🤖 Generated with Claude Code

@carlos-marchal-ph
carlos-marchal-ph requested a review from a team as a code owner October 22, 2026 16:26
@carlos-marchal-ph carlos-marchal-ph self-assigned this Oct 22, 2026
@carlos-marchal-ph
carlos-marchal-ph requested a review from a team October 22, 2026 16:26

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

PostHog Review · Standard · reviewed c399f7a: 1 Must fix, 1 Should fix.

Comment thread posthog/ai/otel/_privacy.py Outdated
Comment on lines +48 to +54
_CONTENT_ATTRIBUTE_ROOTS = (
"gen_ai.prompt",
"gen_ai.completion",
"llm.prompts",
"llm.input_messages",
"llm.output_messages",
)

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.

P1 · Redact OpenInference function calls and prompt-template content

With OpenInference LangChain instrumentation, spans carry model-generated arguments in llm.function_call and user inputs in llm.prompt_template.variables. Neither matches _is_content_attribute, so both OTel integrations export this content with privacy_mode=True, even after removing the message attributes. Extend the filter to cover these content fields.

Comment thread posthog/ai/otel/_privacy.py Outdated
Comment on lines +112 to +114
attributes=attributes,
events=events,
links=span.links,

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.

P2 · Preserve collection types supported by older OTel encoders

With supported OpenTelemetry SDK 1.20.0, privacy-mode spans retaining any attribute fail OTLP serialization: ReadableSpan.dropped_attributes reads .dropped, which this plain dict lacks. Nonempty event lists and link tuples fail similarly. Both integrations lose the export batch; use compatible bounded collections or raise the minimum OTel version.

@github-actions

github-actions Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-10-23T14:02:30.419574+00:00
Duration: 259190ms

✅ All Tests Passed!

121/121 tests passed


Capture_V1 Tests

✅ 95/95 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint ✅ 513ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 509ms
Required Headers.Has Authorization Bearer Header ✅ 508ms
Required Headers.Has Content Type Json ✅ 508ms
Required Headers.Has Posthog Sdk Info Format ✅ 508ms
Required Headers.Has Posthog Attempt Header ✅ 507ms
Required Headers.Has Posthog Request Id ✅ 507ms
Required Headers.Has Posthog Request Timestamp ✅ 508ms
Required Headers.Has User Agent ✅ 508ms
Body Format.Body Has Created At And Batch ✅ 508ms
Body Format.No Api Key In Body ✅ 508ms
Body Format.No Sent At In Body ✅ 507ms
Event Format.Event Has Required Root Fields ✅ 507ms
Event Format.Event Uuid Is Valid ✅ 508ms
Event Format.Event Timestamp Is Rfc3339 ✅ 507ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 531ms
Event Format.Distinct Id Is String ✅ 508ms
Event Format.Distinct Id At Root Not Properties ✅ 507ms
Event Format.Custom Properties Preserved ✅ 508ms
Event Format.Set Properties Preserved ✅ 508ms
Event Format.Set Once Properties Preserved ✅ 507ms
Event Format.Groups Properties Preserved ✅ 508ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 507ms
Event Format.Event Has Required Root Fields Batch ✅ 510ms
Event Format.Event Uuid Is Valid Batch ✅ 511ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 510ms
Event Format.Distinct Id Is String Batch ✅ 509ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 509ms
Event Format.Custom Properties Preserved Batch ✅ 509ms
Event Format.Set Properties Preserved Batch ✅ 508ms
Event Format.Set Once Properties Preserved Batch ✅ 509ms
Event Format.Groups Properties Preserved Batch ✅ 509ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 507ms
Batch Behavior.Multiple Events In Single Batch ✅ 510ms
Batch Behavior.Batch Envelope Smoke ✅ 510ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 503ms
Batch Behavior.Flush At Triggers Batch ✅ 1008ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 507ms
Deduplication.Generates Unique Uuids ✅ 511ms
Deduplication.Different Events Same Content Different Uuids ✅ 508ms
Deduplication.Preserves Uuid On Retry ✅ 6514ms
Deduplication.Preserves Timestamp On Retry ✅ 6513ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6518ms
Deduplication.No Duplicate Events In Batch ✅ 512ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 506ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13521ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6513ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3016ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6517ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 508ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 511ms
Response Format Validation.Success No Retry After When All Ok ✅ 509ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1512ms
Response Format Validation.Success No Retry After When Drop Only ✅ 510ms
Response Format Validation.Response Echoes Request Id ✅ 508ms
Retry Behavior.Retries On 408 ✅ 6515ms
Retry Behavior.Retries On 500 ✅ 6517ms
Retry Behavior.Retries On 503 ✅ 8518ms
Retry Behavior.Retries On 504 ✅ 6517ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3514ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11519ms
Retry Behavior.Does Not Retry On 400 ✅ 2511ms
Retry Behavior.Does Not Retry On 401 ✅ 2510ms
Retry Behavior.Does Not Retry On 402 ✅ 2510ms
Retry Behavior.Does Not Retry On 413 ✅ 2511ms
Retry Behavior.Does Not Retry On 415 ✅ 2511ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2511ms
Retry Behavior.Implements Backoff ✅ 22520ms
Retry Behavior.Max Retries Respected ✅ 22532ms
Partial Batch Handling.Handles 200 Full Success ✅ 2510ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3514ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3513ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3510ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6517ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6519ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6519ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6515ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6518ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6518ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8516ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3513ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3513ms
Compression.Sends Gzip Content Encoding ✅ 508ms
Compression.No Content Encoding When Disabled ✅ 507ms
Compression.Compressed Body Is Decompressible ✅ 508ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2509ms
Event Options.Cookieless Mode Override ✅ 508ms
Event Options.Disable Skew Correction Override ✅ 508ms
Event Options.Process Person Profile Override ✅ 508ms
Event Options.Product Tour Id Override ✅ 507ms
Event Options.Unset Options Omitted ✅ 508ms
Event Options.Options Override In Batch ✅ 510ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 507ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 508ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 507ms

Capture_Ai Tests

✅ 5/5 tests passed

View Details
Test Status Duration
Routing.Capture Ai Posts To Ai Endpoint ✅ 509ms
Routing.Capture Does Not Reroute Ai Named Events ✅ 507ms
Identity.Capture Ai Event Has Uuid ✅ 508ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 507ms
Timestamp Format.Non Utc Event Timestamp Is Converted To Utc ✅ 508ms

Feature_Flags Tests

✅ 17/17 tests passed

View Details
Test Status Duration
Request Payload.Request With Person Properties Device Id ✅ 8ms
Request Payload.Flags Request Uses V2 Query Param ✅ 6ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 6ms
Request Payload.Flags Request Omits Authorization Header ✅ 6ms
Request Payload.Token In Flags Body Matches Init ✅ 7ms
Request Payload.Groups Round Trip ✅ 6ms
Request Payload.Groups Default To Empty Object ✅ 6ms
Request Payload.Disable Geoip False Propagates As Geoip Disable False ✅ 6ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 6ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 5ms
Request Lifecycle.No Flags Request On Init Alone ✅ 3ms
Request Lifecycle.No Flags Request On Normal Capture ✅ 506ms
Request Lifecycle.Two Flag Calls Produce Two Remote Requests ✅ 11ms
Request Lifecycle.Mock Response Value Is Returned To Caller ✅ 6ms
Retry Behavior.Retries Flags On 502 ✅ 309ms
Retry Behavior.Retries Flags On 504 ✅ 310ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 508ms

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 46ms
Versioned Boolean Matching.Matching Version 1 ✅ 45ms
Versioned Boolean Matching.Matching Version 2 ✅ 44ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 26ms

Comment thread posthog/ai/otel/_privacy.py Outdated
@veria-ai

veria-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Security review

No open security issues remain on this pull request.

Fixed/addressed: 2 · PR risk: 0/10

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

PostHog Review · Standard · reviewed 157ad38: 1 Must fix.

Comment thread posthog/ai/otel/_privacy.py Outdated
Comment on lines +26 to +29
"pydantic_ai.all_messages",
"final_result",
"tool_arguments",
"tool_response",

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.

P1 · Redact Pydantic AI model request parameters under privacy mode

With Pydantic AI 1.107.7, model_request_parameters contains instruction_parts[].content and prompted_output_template. _CONTENT_ATTRIBUTES omits this attribute, so both OTel integrations export prompt text with privacy mode enabled. A canary survives _redact_span and OTLP serialization; drop this attribute or redact its content fields.

@carlos-marchal-ph carlos-marchal-ph added the stamphog Request stamphog review label Oct 23, 2026

@stamphog stamphog Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Not approved — this change needs a human reviewer.

Re-adding the stamphog label gives the same result unless the changed files change.

stamphog can't approve this pull request, because two gates refused it. The deny-list gate matched the public_api category: the new privacy_mode and client kwargs on PostHogSpanProcessor and PostHogTraceExporter change the public API, and references/public_api_snapshot.txt is modified. The tier gate classified it as T2-never: a cross-cutting fix of 1206 lines across 19 files that touches many AI integrations at once.

Please ask a human reviewer to look at it. Splitting it up may also help, for example by moving the OTel constructor changes into their own pull request, separate from the privacy fixes in the other integrations.

  • posthog[bot] reviewed the current head.
Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✗ matches: public_api
size ✓ 549L, 13F substantive, 1206L/19F incl. docs/generated/snapshots — within ceiling
tier ✗ classified as T2-never: T2-never (1206L, 19F, cross-cutting, fix)
stamphog 2.6.1 .stamphog/policy.yml @ unknown · reviewed head 157ad38

@stamphog stamphog Bot removed the stamphog Request stamphog review label Oct 23, 2026

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

PostHog Review · Standard · reviewed 1fec9fd: 2 Must fix.

This is review round 3 on this pull request. When findings keep coming back in the same code, the approach is usually the problem. Before the next fix, check whether a different design would remove the whole class of findings.

if metadata is not None:
kept[key] = metadata
continue
kept[key] = value

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.

P1 · Mask MCP credentials in retained OTel tool definitions

Vercel AI SDK telemetry serializes remote MCP tools into ai.prompt.tools, including args.authorization and args.headers. _without_content retains these definitions verbatim, so both OTel integrations export access tokens with privacy_mode=True; a credential canary survives OTLP encoding. Parse retained tool definitions and mask MCP credentials.

Comment thread posthog/ai/utils.py
Comment on lines +924 to +929
for source in sources
for key in _ERROR_CODE_FIELDS
if (
code := _matching(
_read_error_field(source, key), _ERROR_PROVIDER_CODE_RE
)

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.

P1 · Restrict privacy summaries to trusted diagnostic values

With privacy enabled, a LangChain tool exception with message request failed and code='sk-proj-secret-token-123' now exports that token in $ai_error; previously, _stringify_exception emitted only the message. _summarize_error_for_privacy accepts arbitrary exception attributes based on character syntax, which also accepts secrets. Allowlist known diagnostic values and omit unknown fields.

Comment thread posthog/ai/otel/_privacy.py

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

PostHog Review · Standard · reviewed f3df40e: 1 Must fix.

This is review round 4 on this pull request. When findings keep coming back in the same code, the approach is usually the problem. Before the next fix, check whether a different design would remove the whole class of findings.

"ai.prompt",
"ai.prompt.messages",
"ai.request.text",
"ai.documents",

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.

P1 · Strip document content from Vercel reranking attributes

Vercel AI SDK reranking spans store the original documents in ai.ranking, whose serialized entries contain document, originalIndex, and score. _without_content removes ai.documents but retains ai.ranking, so both OTel integrations still export the documents with privacy_mode=True. Drop this attribute or remove each entry's document content.

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

PostHog Review · Standard · reviewed 0621831: 1 Should fix.

This is review round 5 on this pull request. When findings keep coming back in the same code, the approach is usually the problem. Before the next fix, check whether a different design would remove the whole class of findings.

Comment thread posthog/ai/otel/exporter.py Outdated
for span in ai_spans:
warn_if_posthog_ai_gateway_otel_attributes(span.attributes)
privacy_mode = _otel_privacy_mode_enabled(self._privacy_mode, self._client)
ai_spans = [_redact_span(span, privacy_mode) for span in ai_spans]

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.

P2 · Isolate redaction failures to the affected span

A deeply nested JSON string in ai.prompt.tools raises RecursionError inside _redact_span, with privacy enabled or disabled. This unguarded comprehension aborts export before forwarding any spans, so BatchSpanProcessor loses healthy spans in the same batch. Catch redaction errors per span and drop only the failing span, matching PostHogSpanProcessor.

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

PostHog Review · Standard · reviewed ff9058f: 1 Must fix.

This is review round 6 on this pull request. When findings keep coming back in the same code, the approach is usually the problem. Before the next fix, check whether a different design would remove the whole class of findings.

if metadata is not None:
kept[key] = metadata
continue
kept[key] = value

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.

P1 · Redact credentials from Vercel request-header attributes

When Vercel AI SDK callers supply an Authorization header, its telemetry records ai.request.headers.Authorization. _without_content retains this attribute, so both OTel integrations export the credential with privacy_mode=True; a canary survives OTLP encoding. Mask sensitive request-header attributes before export.

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

PostHog Review · Standard · reviewed ad27041: 1 Must fix.

This is review round 7 on this pull request. When findings keep coming back in the same code, the approach is usually the problem. Before the next fix, check whether a different design would remove the whole class of findings.

Comment thread posthog/ai/otel/_privacy.py

@marandaneto marandaneto left a comment

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.

The code looks good; no qualifying findings. Verdict: correct.

@marandaneto

Copy link
Copy Markdown
Member

some bots pr open tho

@Radu-Raicea
Radu-Raicea removed the request for review from a team October 23, 2026 13:01
…ode-leaks

# Conflicts:
#	posthog/ai/gemini/_shared.py
@carlos-marchal-ph
carlos-marchal-ph merged commit 04e6a4c into main Oct 23, 2026
43 checks passed
@carlos-marchal-ph
carlos-marchal-ph deleted the fix(aio)/ai-privacy-mode-leaks branch October 23, 2026 15:22
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.

2 participants