Skip to content

fix(ai): only capture terminal, named Responses stop reasons - #919

Draft
bernatixer wants to merge 2 commits into
mainfrom
posthog/ai-responses-terminal-stop-reason
Draft

fix(ai): only capture terminal, named Responses stop reasons#919
bernatixer wants to merge 2 commits into
mainfrom
posthog/ai-responses-terminal-stop-reason

Conversation

@bernatixer

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

The Python SDK records raw Responses API statuses as $ai_stop_reason, and none of the three surfaces that do it agree with what the PostHog trace view understands:

  • The native OpenAI wrapper returns any status, so a background: true run records queued — a lifecycle state, not a stop reason — and a truncated run records the bare incomplete instead of max_output_tokens, which the trace view's truncation notice recognizes.
  • The streaming accumulator only reads status on response.completed, so streams that end incomplete or failed record no stop reason at all.
  • The LangChain callback reads only generation_info.finish_reason, so Responses API and Anthropic runs — which report through response_metadata — record nothing.

One shared _responses_stop_reason helper now does the mapping: non-terminal statuses yield nothing, an incomplete run is named by incomplete_details.reason, the other terminal statuses stand for themselves. All three surfaces route through it, and the LangChain callback reads the same metadata sources in the same priority order as the JS SDK's callback.

Ports PostHog/posthog-js#4700 and PostHog/posthog-js#4736 to Python. (The token-counts sibling was already ported in #906.)

💚 How did you test it?

  • 15 new unit cases: a parametrized table for extract_openai_stop_reason (terminal passthrough, incomplete_details.reason naming, bare-incomplete fallback, queued/in_progress yielding nothing, Chat Completions passthrough), a streaming test covering all three terminal lifecycle events plus the non-terminal lock, and a parametrized callback table (Responses metadata, Anthropic stop_reason, queued, and generation_info.finish_reason priority).
  • Revert-proven: with the source change stashed, exactly the 7 behavior-changing cases fail; the 8 passing rows are deliberate locks on unchanged behavior.
  • Full posthog/test/ai/openai + posthog/test/ai/langchain suites: no failure that isn't already failing on main (the remaining failures are real-API integration tests picking up this sandbox's non-OpenAI key).
  • ruff format --check, ruff check, repo-wide mypy | mypy-baseline filter (clean, 226 files), check_public_api.py (helper kept underscore-private, so no surface change), python -W error -c "import posthog".

📝 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, directed by a PostHog engineer, as the Python port of the stop-reason fixes that landed in posthog-js. Each of the three gaps was verified against this repo's code before writing: the wrapper and accumulator behavior differs from JS in opposite directions (JS over-fired with the wrong vocabulary, Python under-fires with nothing). The helper is underscore-private rather than public because the JS equivalent is not part of that package's export surface either, and check_public_api.py treats any bare name as API commitment. The langchain response_metadata shape was pinned against langchain-openai's own tests rather than assumed from the JS shapes. Skills invoked: writing-tests, writing-pr-descriptions.


Created with PostHog Desktop

The Python SDK recorded raw Responses API statuses as $ai_stop_reason across three surfaces, none of which matched what the trace view understands. The native wrapper returned any status, so a background run recorded queued as its stop reason, and a truncated run recorded the bare incomplete instead of max_output_tokens. The streaming accumulator only read status on response.completed, so streams that ended incomplete or failed recorded nothing. The LangChain callback read only generation_info.finish_reason, so Responses API and Anthropic runs, which report through response_metadata, recorded nothing at all.

One shared _responses_stop_reason helper now does the mapping: non-terminal statuses yield nothing, an incomplete run is named by incomplete_details.reason, and the other terminal statuses stand for themselves. All three surfaces route through it, and the LangChain callback reads the same metadata sources as the JS SDK's callback, in the same priority order.

Ports PostHog/posthog-js#4700 and PostHog/posthog-js#4736 to Python.

Generated-By: PostHog Desktop
Task-Id: 5cb23cd6-224c-4d86-bc24-97730d4c2f98
@bernatixer bernatixer self-assigned this Sep 3, 2026
@github-actions

github-actions Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-09-04 12:42:41 UTC
Duration: 256435ms

✅ 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 518ms
Endpoint And Method.Does Not Use Legacy Endpoints 511ms
Required Headers.Has Authorization Bearer Header 510ms
Required Headers.Has Content Type Json 510ms
Required Headers.Has Posthog Sdk Info Format 511ms
Required Headers.Has Posthog Attempt Header 510ms
Required Headers.Has Posthog Request Id 510ms
Required Headers.Has Posthog Request Timestamp 511ms
Required Headers.Has User Agent 510ms
Body Format.Body Has Created At And Batch 511ms
Body Format.No Api Key In Body 510ms
Body Format.No Sent At In Body 511ms
Event Format.Event Has Required Root Fields 510ms
Event Format.Event Uuid Is Valid 511ms
Event Format.Event Timestamp Is Rfc3339 510ms
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 511ms
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 515ms
Event Format.Event Timestamp Is Rfc3339 Batch 513ms
Event Format.Distinct Id Is String Batch 514ms
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 514ms
Event Format.Groups Properties Preserved Batch 513ms
Event Format.Sdk Generates Uuid If Not Provided Batch 514ms
Batch Behavior.Multiple Events In Single Batch 518ms
Batch Behavior.Batch Envelope Smoke 516ms
Batch Behavior.Flush With No Events Sends Nothing 507ms
Batch Behavior.Flush At Triggers Batch 1011ms
Batch Behavior.Created At Reflects Batch Creation Time 511ms
Deduplication.Generates Unique Uuids 519ms
Deduplication.Different Events Same Content Different Uuids 513ms
Deduplication.Preserves Uuid On Retry 6520ms
Deduplication.Preserves Timestamp On Retry 6520ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry 6524ms
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 13523ms
Header Behavior On Retry.Request Id Preserved On Retry 6520ms
Header Behavior On Retry.Different Requests Have Different Request Ids 3020ms
Header Behavior On Retry.Request Timestamp Changes On Retry 6521ms
Response Format Validation.Success Response Has Uuid Keyed Results 510ms
Response Format Validation.Success Response Has Ok For Each Event 515ms
Response Format Validation.Success No Retry After When All Ok 512ms
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 6520ms
Retry Behavior.Retries On 500 6519ms
Retry Behavior.Retries On 503 8523ms
Retry Behavior.Retries On 504 6516ms
Retry Behavior.Retryable Errors Have Retry After 3517ms
Retry Behavior.Respects Retry After On Retryable Error 11519ms
Retry Behavior.Does Not Retry On 400 2514ms
Retry Behavior.Does Not Retry On 401 2514ms
Retry Behavior.Does Not Retry On 402 2515ms
Retry Behavior.Does Not Retry On 413 2513ms
Retry Behavior.Does Not Retry On 415 2524ms
Retry Behavior.Non Retryable Errors Have No Retry After 2513ms
Retry Behavior.Implements Backoff 22531ms
Retry Behavior.Max Retries Respected 22535ms
Partial Batch Handling.Handles 200 Full Success 2514ms
Partial Batch Handling.Handles 200 With All Ok 3519ms
Partial Batch Handling.Does Not Retry Dropped Events 3513ms
Partial Batch Handling.Does Not Retry Limited Events 3516ms
Partial Batch Handling.Prunes Ok Events On Partial Retry 6523ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry 6522ms
Partial Batch Handling.Retries Only Retry Events From Partial 6520ms
Partial Batch Handling.Partial Retry Preserves Uuids 6522ms
Partial Batch Handling.Partial Retry Attempt Header Increments 6524ms
Partial Batch Handling.Partial Retry Request Id Preserved 6517ms
Partial Batch Handling.Respects Retry After On Partial 8522ms
Partial Batch Handling.Unknown Result Treated As Terminal 3517ms
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 511ms
Error Handling.Does Not Retry On Unknown 4Xx 2513ms
Event Options.Cookieless Mode Override 511ms
Event Options.Disable Skew Correction Override 510ms
Event Options.Process Person Profile Override 510ms
Event Options.Product Tour Id Override 511ms
Event Options.Unset Options Omitted 510ms
Event Options.Options Override In Batch 513ms
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

Feature_Flags Tests

17/17 tests passed

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

Same behavior, less of it. The metadata sources in the callback normalize to dicts once instead of each carrying its own isinstance guard, and the Responses helper folds its None guard and nested incomplete branch into the checks that already covered them.

The tests drop a chat-completions passthrough case that test_openai.py already locks, hoist the imports the new cases share, and express the streaming behavior as a table rather than one test driving three accumulators, which also covers the failed status the old test missed.

Generated-By: PostHog Desktop
Task-Id: 5cb23cd6-224c-4d86-bc24-97730d4c2f98
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