Skip to content

fix(aio): never drop or leak multimodal content in ai capture - #762

Merged
carlos-marchal-ph merged 2 commits into
mainfrom
fix(aio)/multimodal-capture-correctness
Jul 27, 2026
Merged

fix(aio): never drop or leak multimodal content in ai capture#762
carlos-marchal-ph merged 2 commits into
mainfrom
fix(aio)/multimodal-capture-correctness

Conversation

@carlos-marchal-ph

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

AI capture silently dropped or mangled content, and base64 redaction failed in both directions.

Dropped/mangled:

  • Gemini media/tool parts, Anthropic thinking + round-tripped content, OpenAI tool_calls, Responses API output items (streaming and non-streaming), and image-generation outputs were lost or given wrong type labels.
  • Appending a ChatCompletionMessage back into messages raised.
  • Streaming built plain-text-only output, so non-text blocks disappeared.

Redaction:

  • Raw (non-data-URL) base64 leaked on paths the per-provider sanitizers didn't cover (bare transcription audio, nested tool results, agent SDK).
  • Legitimate long tokens and shared references got redacted as if they were media.
  • Placeholders always said "image" regardless of the actual media type.

Fix routes every AI content property through one choke point (finalize_ai_contentredact_media) with structural, media-type-aware redaction, and normalizes typed SDK objects to plain dicts so nothing collapses to a repr string.

💚 How did you test it?

New tests added with the change:

  • test_capture_contract.py, test_capture_pipeline.py — end-to-end capture behavior across providers and streaming/non-streaming paths.
  • per-provider converter suites (test_openai_converter.py, test_gemini_converter.py, test_anthropic_converter.py, test_processor_content.py) and test_media.py.
  • expanded test_sanitization.py for the structural redactor (leak paths, over-redaction, media-specific placeholders).

ruff format and ruff check clean on all touched files.

📝 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) — Carlos is DRI.

The multimodal capture fix was human-authored. Claude Code (Opus 4.8) did a final cleanup pass: stripped the inline comments and newly-added docstrings this change introduced, keeping only those that guard against a specific breakage (ordering constraints, the base64-leak boundary, the single-choke-point invariant, and the back-compat wrappers/param that look deletable), and tightened the changelog entry to one sentence. Comments and docstrings that pre-existed or that the change only updated for accuracy were left alone.

@carlos-marchal-ph
carlos-marchal-ph requested a review from a team July 24, 2026 14:59
@carlos-marchal-ph carlos-marchal-ph self-assigned this Jul 24, 2026
@carlos-marchal-ph
carlos-marchal-ph requested a review from a team as a code owner July 24, 2026 14:59
@greptile-apps

greptile-apps Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

Security Review

Short raw base64 values in recognized media fields bypass redaction because the structural redactor requires at least 200 characters even when media context is explicit.

Prompt To Fix All With AI
Fix the following 1 code review issue. Work through them one at a time, proposing concise fixes.

---

### Issue 1 of 1
posthog/ai/sanitization.py:121-126
**Short media bypasses redaction**

When multimodal capture is disabled and a recognized media field contains valid raw base64 shorter than 200 characters, this length check leaves the value unchanged, causing raw Anthropic, Gemini, or OpenAI media data to be included in the captured AI event.

Reviews (1): Last reviewed commit: "fix: never drop or leak multimodal conte..." | Re-trigger Greptile

Comment on lines +121 to 126
)
if (
item.get("type") == "image_url"
and isinstance(item.get("image_url"), dict)
and "url" in item["image_url"]
strong
and len(value) >= _STRONG_CONTEXT_MIN_LEN
and _BASE64_BODY_RE.match(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 security Short media bypasses redaction

When multimodal capture is disabled and a recognized media field contains valid raw base64 shorter than 200 characters, this length check leaves the value unchanged, causing raw Anthropic, Gemini, or OpenAI media data to be included in the captured AI event.

Knowledge Base Used: AI Observability (posthog/ai)

Prompt To Fix With AI
This is a comment left during a code review.
Path: posthog/ai/sanitization.py
Line: 121-126

Comment:
**Short media bypasses redaction**

When multimodal capture is disabled and a recognized media field contains valid raw base64 shorter than 200 characters, this length check leaves the value unchanged, causing raw Anthropic, Gemini, or OpenAI media data to be included in the captured AI event.

**Knowledge Base Used:** [AI Observability (posthog/ai)](https://app.greptile.com/posthog-org-19734/-/custom-context/knowledge-base/posthog/posthog-python/-/docs/ai-observability.md)

How can I resolve this? If you propose a fix, please make it concise.

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.

Yeah how did you choose 200?

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.

Honestly, 200 is somewhat arbitrary — it's a heuristic to avoid false positives, not a number derived from any specific minimum media size.

The reasoning is:

  • Common non-media strings that happen to match the base64 charset (UUIDs at ~36 chars, SHA-256 hashes at 64 chars, short JWT segments, API keys) are typically well under 200 characters.
  • Real base64-encoded media is almost always orders of magnitude larger (even a 1×1 PNG is ~100 bytes → ~136 base64 chars, but any meaningful image is thousands).

The old code used len(text) > 20, which was too aggressive and caused over-redaction of legitimate tokens (one of the bugs mentioned in the PR description). 200 is a more conservative boundary.

The weak point of this choice is that it's not grounded in an actual lower bound for media payloads — it's "big enough to not be a normal string, small enough to not miss real media." If you want a tighter guarantee, it could be raised (e.g. to 500 or even 1000), since no real image/audio content is going to be under 500 base64 chars. But the current value is defensible as a conservative heuristic.

Tip: You can customize Greptile's behavior for this repo with .greptile/rules.md and .greptile/config.json.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

It's grounded on sampling from actual data and also makes no sense cost-wise to go through S3 for smaller blobs

@github-actions

github-actions Bot commented Jul 24, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-07-27 14:07:24 UTC
Duration: 338345ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint 517ms
Endpoint And Method.Does Not Use Legacy Endpoints 1009ms
Required Headers.Has Authorization Bearer Header 1009ms
Required Headers.Has Content Type Json 1009ms
Required Headers.Has Posthog Sdk Info Format 1010ms
Required Headers.Has Posthog Attempt Header 1009ms
Required Headers.Has Posthog Request Id 1010ms
Required Headers.Has Posthog Request Timestamp 1010ms
Required Headers.Has User Agent 1009ms
Body Format.Body Has Created At And Batch 1009ms
Body Format.No Api Key In Body 1009ms
Body Format.No Sent At In Body 1008ms
Event Format.Event Has Required Root Fields 1008ms
Event Format.Event Uuid Is Valid 1009ms
Event Format.Event Timestamp Is Rfc3339 1008ms
Event Format.Distinct Id Is String 1009ms
Event Format.Distinct Id At Root Not Properties 1008ms
Event Format.Custom Properties Preserved 1009ms
Event Format.Set Properties Preserved 1009ms
Event Format.Set Once Properties Preserved 1009ms
Event Format.Groups Properties Preserved 1008ms
Event Format.Sdk Generates Uuid If Not Provided 1009ms
Event Format.Event Has Required Root Fields Batch 1012ms
Event Format.Event Uuid Is Valid Batch 1013ms
Event Format.Event Timestamp Is Rfc3339 Batch 1012ms
Event Format.Distinct Id Is String Batch 1011ms
Event Format.Distinct Id At Root Not Properties Batch 1013ms
Event Format.Custom Properties Preserved Batch 1011ms
Event Format.Set Properties Preserved Batch 1013ms
Event Format.Set Once Properties Preserved Batch 1014ms
Event Format.Groups Properties Preserved Batch 1011ms
Event Format.Sdk Generates Uuid If Not Provided Batch 1013ms
Batch Behavior.Multiple Events In Single Batch 1507ms
Batch Behavior.Batch Envelope Smoke 1014ms
Batch Behavior.Flush With No Events Sends Nothing 1004ms
Batch Behavior.Flush At Triggers Batch 1509ms
Batch Behavior.Created At Reflects Batch Creation Time 511ms
Deduplication.Generates Unique Uuids 1507ms
Deduplication.Different Events Same Content Different Uuids 1507ms
Deduplication.Preserves Uuid On Retry 7515ms
Deduplication.Preserves Timestamp On Retry 7512ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 7508ms
Deduplication.No Duplicate Events In Batch 1508ms
Header Behavior On Retry.Attempt Header Starts At One 1009ms
Header Behavior On Retry.Attempt Header Increments On Retry 14523ms
Header Behavior On Retry.Request Id Preserved On Retry 7504ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3520ms
Header Behavior On Retry.Request Timestamp Changes On Retry 7508ms
Response Format Validation.Success Response Has Uuid Keyed Results 1011ms
Response Format Validation.Success Response Has Ok For Each Event 1506ms
Response Format Validation.Success No Retry After When All Ok 1507ms
Response Format Validation.Success Retry After Present When Retry Events 2511ms
Response Format Validation.Success No Retry After When Drop Only 1508ms
Response Format Validation.Response Echoes Request Id 1009ms
Retry Behavior.Retries On 408 7516ms
Retry Behavior.Retries On 500 7511ms
Retry Behavior.Retries On 503 9517ms
Retry Behavior.Retries On 504 7512ms
Retry Behavior.Retryable Errors Have Retry After 4510ms
Retry Behavior.Respects Retry After On Retryable Error 12517ms
Retry Behavior.Does Not Retry On 400 3504ms
Retry Behavior.Does Not Retry On 401 3508ms
Retry Behavior.Does Not Retry On 402 3507ms
Retry Behavior.Does Not Retry On 413 3509ms
Retry Behavior.Does Not Retry On 415 3507ms
Retry Behavior.Non Retryable Errors Have No Retry After 3506ms
Retry Behavior.Implements Backoff 23532ms
Retry Behavior.Max Retries Respected 23512ms
Partial Batch Handling.Handles 200 Full Success 3012ms
Partial Batch Handling.Handles 200 With All Ok 4508ms
Partial Batch Handling.Does Not Retry Dropped Events 4511ms
Partial Batch Handling.Does Not Retry Limited Events 4509ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 7513ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 7511ms
Partial Batch Handling.Retries Only Retry Events From Partial 7513ms
Partial Batch Handling.Partial Retry Preserves Uuids 7511ms
Partial Batch Handling.Partial Retry Attempt Header Increments 7508ms
Partial Batch Handling.Partial Retry Request Id Preserved 7512ms
Partial Batch Handling.Respects Retry After On Partial 9516ms
Partial Batch Handling.Unknown Result Treated As Terminal 4506ms
Partial Batch Handling.Mixed Ok Drop Limited No Retry 4509ms
Compression.Sends Gzip Content Encoding 1006ms
Compression.No Content Encoding When Disabled 1010ms
Compression.Compressed Body Is Decompressible 1009ms
Error Handling.Does Not Retry On Unknown 4Xx 3509ms
Event Options.Cookieless Mode Override 1007ms
Event Options.Disable Skew Correction Override 1009ms
Event Options.Process Person Profile Override 1009ms
Event Options.Product Tour Id Override 1009ms
Event Options.Unset Options Omitted 1009ms
Event Options.Options Override In Batch 1015ms
Geoip And Historical Migration.Geoip Disable Injected Into Properties 1009ms
Geoip And Historical Migration.Historical Migration Set In Body 1008ms
Geoip And Historical Migration.Historical Migration Absent By Default 1009ms

Feature_Flags Tests

17/17 tests passed

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

@@ -0,0 +1,5 @@
---
pypi/posthog: minor

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.

title is a fix, and here is a minor, do we fix the changeset or the title?

@marandaneto

Copy link
Copy Markdown
Member

looks like something that @PostHog/team-ai-observability should stamp? feels like very product specific, sdk changes is ok

Comment on lines +121 to 126
)
if (
item.get("type") == "image_url"
and isinstance(item.get("image_url"), dict)
and "url" in item["image_url"]
strong
and len(value) >= _STRONG_CONTEXT_MIN_LEN
and _BASE64_BODY_RE.match(value)
):

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.

Yeah how did you choose 200?

Generated-By: PostHog Code
Task-Id: b2e1882a-162c-41be-8e8f-7e76772fb1ae
@carlos-marchal-ph
carlos-marchal-ph merged commit 4c8a85a into main Jul 27, 2026
37 checks passed
@carlos-marchal-ph
carlos-marchal-ph deleted the fix(aio)/multimodal-capture-correctness branch July 27, 2026 14:14
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.

3 participants