Skip to content

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

Open
carlos-marchal-ph wants to merge 1 commit into
mainfrom
fix(aio)/ai-privacy-mode-leaks
Open

carlos-marchal-ph wants to merge 1 commit 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 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 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-22T16:32:00.814446+00:00
Duration: 259903ms

✅ 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 ✅ 517ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 511ms
Required Headers.Has Authorization Bearer Header ✅ 510ms
Required Headers.Has Content Type Json ✅ 512ms
Required Headers.Has Posthog Sdk Info Format ✅ 510ms
Required Headers.Has Posthog Attempt Header ✅ 510ms
Required Headers.Has Posthog Request Id ✅ 511ms
Required Headers.Has Posthog Request Timestamp ✅ 510ms
Required Headers.Has User Agent ✅ 510ms
Body Format.Body Has Created At And Batch ✅ 510ms
Body Format.No Api Key In Body ✅ 511ms
Body Format.No Sent At In Body ✅ 510ms
Event Format.Event Has Required Root Fields ✅ 510ms
Event Format.Event Uuid Is Valid ✅ 510ms
Event Format.Event Timestamp Is Rfc3339 ✅ 510ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 523ms
Event Format.Distinct Id Is String ✅ 510ms
Event Format.Distinct Id At Root Not Properties ✅ 511ms
Event Format.Custom Properties Preserved ✅ 510ms
Event Format.Set Properties Preserved ✅ 511ms
Event Format.Set Once Properties Preserved ✅ 510ms
Event Format.Groups Properties Preserved ✅ 510ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 510ms
Event Format.Event Has Required Root Fields Batch ✅ 514ms
Event Format.Event Uuid Is Valid Batch ✅ 514ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 513ms
Event Format.Distinct Id Is String Batch ✅ 515ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 514ms
Event Format.Custom Properties Preserved Batch ✅ 514ms
Event Format.Set Properties Preserved Batch ✅ 514ms
Event Format.Set Once Properties Preserved Batch ✅ 513ms
Event Format.Groups Properties Preserved Batch ✅ 514ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 513ms
Batch Behavior.Multiple Events In Single Batch ✅ 518ms
Batch Behavior.Batch Envelope Smoke ✅ 515ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 507ms
Batch Behavior.Flush At Triggers Batch ✅ 1010ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 511ms
Deduplication.Generates Unique Uuids ✅ 518ms
Deduplication.Different Events Same Content Different Uuids ✅ 512ms
Deduplication.Preserves Uuid On Retry ✅ 6520ms
Deduplication.Preserves Timestamp On Retry ✅ 6519ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6519ms
Deduplication.No Duplicate Events In Batch ✅ 518ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 510ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13528ms
Header Behavior On Retry.Request Id Preserved On Retry ✅ 6516ms
Header Behavior On Retry.Different Requests Have Different Request Ids ✅ 3020ms
Header Behavior On Retry.Request Timestamp Changes On Retry ✅ 6520ms
Response Format Validation.Success Response Has Uuid Keyed Results ✅ 511ms
Response Format Validation.Success Response Has Ok For Each Event ✅ 514ms
Response Format Validation.Success No Retry After When All Ok ✅ 513ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1516ms
Response Format Validation.Success No Retry After When Drop Only ✅ 513ms
Response Format Validation.Response Echoes Request Id ✅ 510ms
Retry Behavior.Retries On 408 ✅ 6518ms
Retry Behavior.Retries On 500 ✅ 6516ms
Retry Behavior.Retries On 503 ✅ 8522ms
Retry Behavior.Retries On 504 ✅ 6518ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3517ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11522ms
Retry Behavior.Does Not Retry On 400 ✅ 2514ms
Retry Behavior.Does Not Retry On 401 ✅ 2514ms
Retry Behavior.Does Not Retry On 402 ✅ 2513ms
Retry Behavior.Does Not Retry On 413 ✅ 2513ms
Retry Behavior.Does Not Retry On 415 ✅ 2514ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2512ms
Retry Behavior.Implements Backoff ✅ 22532ms
Retry Behavior.Max Retries Respected ✅ 22537ms
Partial Batch Handling.Handles 200 Full Success ✅ 2513ms
Partial Batch Handling.Handles 200 With All Ok ✅ 3518ms
Partial Batch Handling.Does Not Retry Dropped Events ✅ 3517ms
Partial Batch Handling.Does Not Retry Limited Events ✅ 3513ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6522ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6522ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6523ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6522ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6517ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6522ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8518ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3516ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry ✅ 3520ms
Compression.Sends Gzip Content Encoding ✅ 511ms
Compression.No Content Encoding When Disabled ✅ 511ms
Compression.Compressed Body Is Decompressible ✅ 510ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2512ms
Event Options.Cookieless Mode Override ✅ 511ms
Event Options.Disable Skew Correction Override ✅ 510ms
Event Options.Process Person Profile Override ✅ 511ms
Event Options.Product Tour Id Override ✅ 510ms
Event Options.Unset Options Omitted ✅ 510ms
Event Options.Options Override In Batch ✅ 514ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties ✅ 511ms
Geoip And Historical Migration.Historical Migration Set In Body ✅ 510ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 510ms

Capture_Ai Tests

✅ 5/5 tests passed

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

Feature_Flags Tests

✅ 17/17 tests passed

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

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

View Details
Test Status Duration
Versioned Boolean Matching.Matching Version Missing ✅ 70ms
Versioned Boolean Matching.Matching Version 1 ✅ 68ms
Versioned Boolean Matching.Matching Version 2 ✅ 69ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 35ms

"gen_ai.completion",
"llm.prompts",
"llm.input_messages",
"llm.output_messages",

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

High: OpenInference payloads bypass privacy redaction

OpenInference emits completion text under llm.choices.*, prompt values under llm.prompt_template.variables, and function arguments under llm.function_call, none of which this filter removes. (github.com) The telemetry recipient can therefore read this private content even with privacy_mode=True in either OTel integration, because the surviving attributes are forwarded to OTLP and serialized unchanged; include these payload attributes in the redaction rules. (raw.githubusercontent.com)

Suggested change
"llm.output_messages",
"llm.output_messages",
"llm.choices",
"llm.function_call",
"llm.prompt_template.template",
"llm.prompt_template.variables",

@veria-ai

veria-ai Bot commented Oct 22, 2026

Copy link
Copy Markdown

PR overview

The PR updates privacy-mode filtering for AI telemetry events in the OpenTelemetry integrations to keep content out of emitted events.

One issue remains open: the filter misses OpenInference attributes containing completion text, prompt variables, and function arguments. These attributes are forwarded unchanged to the telemetry recipient even when privacy_mode=True in either integration, allowing private content to leave the application despite the privacy setting.

Open issues (1)

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

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.

1 participant