Skip to content

feat(mcp): group sessions by ChatGPT, Codex and VS Code conversation ids - #1193

Open
lucasheriques wants to merge 20 commits into
mainfrom
lucas/mcp-client-meta-session
Open

lucasheriques wants to merge 20 commits into
mainfrom
lucas/mcp-client-meta-session

Conversation

@lucasheriques

@lucasheriques lucasheriques commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Servers that need tool schemas and results left unchanged turn conversation IDs off. On a stateless server that builds a fresh instance per request, every tool call then gets its own $session_id (PostHog/posthog#119784).

Some clients already name the conversation in each tool call's _meta. sdk-specs main defines which keys the SDKs read, from which clients, and in what order: "Session identity", from PostHog/sdk-specs#175 and #176. This PR implements those rules exactly. It is the twin of PostHog/posthog-js#5577.

Changes

  • _client_conversation.CLIENT_CONVERSATION_ROWS mirrors the spec table:

    • ChatGPT openai/session: 1 to 128 printable ASCII characters. Handle-free.
    • Codex sessionId: a UUID. Keeps the handle as a fallback.
    • VS Code vscode.conversationId: a UUID. Keeps the handle as a fallback.

    UUIDs are lowercased and the nil UUID is rejected.

  • Recognition. A key is read only from a request whose User-Agent or client name matches its row. The client name comes from the request's _meta clientInfo first, then the name the adapter resolved.

  • The client's id is session source 1 on tool calls, ahead of the handle and the transport. tools/list, resource requests, and initialize no longer read it. A handle echoed alongside it is stripped but ignored.

  • Handle-free (ChatGPT). Its client-facing tools/list has no conversation_id or _mcp_instructions, and it is minted no handle. The SDK's internal tool-cache pass still injects, so validation stays the same for every client.

  • Connection activity. On a one-client connection (stdio), a client-grouped call counts as activity, so the session doesn't rotate early.

  • $mcp_session_source on every instrument() event. The spec addition for it is docs(mcp-analytics): record which source grouped each session as $mcp_session_source sdk-specs#185.

  • PostHogMCP. prepare_tool_list and prepare_tool_call take headers, and prepare_tool_call also takes client_info. capture_tool_call takes request_meta. A ChatGPT prepare_tool_list still records conversation_id ownership.

  • On mcp 2.x low-level servers, the SDK's internal tools/list dispatch (Mcp-Param header validation) emits no event. That part is unchanged from the earlier version of this PR.

Not verified against real clients

  • Does openai/session stay the same for a whole ChatGPT conversation? Not verified. I have no ChatGPT connector session to log from. One way to confirm is to log _meta across a multi-turn chat.
  • Do the Codex versions in use today send sessionId? Partly verified, from source only. Codex adds it to tool-call _meta starting at rust-v0.156.0 (2026-09-22). Older installs fall back to the handle.

How I tested

  • pytest posthog/test/mcp: 745 passed on mcp 1.30.0 and 603 passed on mcp 2.3.0.
    • test_client_conversation_session.py covers every spec scenario and vector, and recognition examples.
    • It covers the manual API and connection rotation.
    • It covers real HTTP fleets over the official, FastMCP, and low-level server kinds: listings, and ChatGPT calls across pods.
  • ruff, mypy (CI mode with baseline), and the public API snapshot pass.
  • Pre-PR gate: two adversarial reviewers (Opus and Sonnet), on both mcp majors.
    • Fixed: counting client-grouped calls as activity also ran on shared stateless HTTP pods. There it kept the instance session alive and merged two unrelated clients. It now applies only to a one-client connection.
    • Fixed: a ChatGPT prepare_tool_list skipped recording ownership, so prepare_tool_call passed an echoed handle to the handler.
    • Both fixes have tests that fail on the previous commit.
    • Dismissed: the inactivity clock is reset by any request, not only tool calls, and is measured from arrival with >. It predates this PR and matches posthog-js, so it's a follow-up.
    • Dismissed: on mcp 1.x, a ChatGPT listing populates the tool cache without the analytics fields. A later client on that instance then gets the handle only as a text block, not mirrored into structuredContent. Mirroring is a MAY and the handle is still delivered.
    • Dismissed: the manual capture methods set $mcp_session_source only for a recognized client id (spec MAY, follow-up).

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Built with Claude Code (pstack poteto-mode) at Lucas's direction. An earlier version ranked openai/session below the transport session, with no recognition rules. Lucas decided the merged sdk-specs rules win, so this version implements them as written.

Read ChatGPT's `_meta["openai/session"]` conversation id as a session source
for calls with no conversation handle and no transport session, and stamp
`$mcp_session_source` (conversation, transport, client_metadata, generated)
on every event whose session the SDK resolves.

Why: on per-request stateless servers with `enable_conversation_id=False`
(common for ChatGPT/Claude directory submissions) every call got its own
`$session_id` (PostHog/posthog#119784). ChatGPT already sends a
per-conversation id, so grouping needs no schema or result change. Order is
handle, transport (token or mcp id), client id, generated, so it only groups
calls that fragment today. A call carrying it mints no handle and gets no
prompt-back. Same rule in `PostHogMCP.prepare_tool_call` via `request_meta`,
after an explicit `session_id`. Twin of posthog-js 3eb19d9 and ADR-0014; the
derivation `ses_35e4cc45ea3e5e1282c3f091de632132` is a cross-SDK contract.

Internals: `resolve_session_id_with_source` / `prepare_request` return a
`ResolvedSession(session_id, source)`, which the record_* functions take, so
the source reaches every event. `token`/`mcp` map to `transport` at the
property boundary. `handshake_session_id` becomes `handshake_session`. A
client-conversation session never stands in for an unobserved `initialize`,
like a conversation one.

Tested: `pytest posthog/test/mcp` -> 699 passed, 10 skipped on mcp 1.30.0 and
557 passed, 42 skipped on mcp 2.3.0 (incl. new parameterized
test_client_conversation_session.py plus a v1 FastMCP and a v2 wire-level
fresh-instance test); `ruff format --check`, `ruff check`, `mypy`,
`make public_api_check` clean.
Pre-PR gate findings on the TypeScript twin (posthog-js 26d720abd), applied
here:
- tools/list, resources/list|read and initialize resolved sessions without
  the client conversation id, which the spec's session order covers for every
  event. Each call site now passes it (`params.meta` on request handlers,
  `_meta` of the initialize params through `handshake_session`). Still
  per-request, never written to shared state, and it still does not stand in
  for an unobserved initialize.
- Custom events from `McpAnalytics.capture()` now carry `$mcp_session_source`,
  the instance's own source (`generated`, or `transport` for a token or mcp
  session id).
- `prepare_tool_call(session_id="")` already treated an empty id as absent;
  a regression case now pins it.

Tested: `pytest posthog/test/mcp` -> 714 passed, 11 skipped on mcp 1.30.0 and
570 passed, 45 skipped on mcp 2.3.0 (fastmcp uninstalled); new parameterized
cases failed before the fix (12 on mcp 2.3.0); `ruff format --check`,
`ruff check`, `mypy`, `make public_api_check` clean.
…ernal tools/list

What
- ToolCallLifecycle.prime_session now passes the request's client conversation to
  resolve_session_id, so a call carrying only openai/session returns at the
  client_metadata step before the memory branch. It no longer refreshes
  data.last_activity or rotates data.session_id, so ChatGPT calls cannot keep the
  instance's generated session alive past its inactivity window.
- The v2 tools/list wrapper skips analytics when the SDK calls the handler itself.
  On the 2026-07-28 streamable-HTTP path, mcp 2.3.0 runs tools/list during every
  tools/call (Mcp-Param-* validation) on a server without get_tool_input_schema
  (the low-level Server; MCPServer provides it). That call has no _meta, resolved
  to a fresh generated session, and emitted a phantom $mcp_tools_list. It is
  detected by the shared HTTP request's required Mcp-Method header naming a
  different method than the handler's own.

Why
Pre-PR gate findings on the client-metadata session work; the spec limits
events to requests the client sent.

Tested
- pytest posthog/test/mcp: mcp 1.30.0 716 passed, 11 skipped; mcp 2.3.0 576
  passed, 45 skipped (fastmcp uninstalled)
- ruff format --check, ruff check, mypy | mypy-baseline filter, make
  public_api_check: clean
- New tests failed before the fixes (instance state moved; phantom event emitted).
  A real tools/list still emits on both MCPServer and low-level Server.

@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 208707d: 1 Must fix.

See this review and its findings in PostHog Review. Comment @posthog review --deep for a Deep review. A Deep review takes longer and looks deeper than a Standard review.

Comment thread posthog/mcp/_instrumentation.py Resolved
@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-11-16T22:51:05.440901+00:00
Duration: 253247ms

✅ All Tests Passed!

271/271 tests passed


Capture_V1 Tests

✅ 95/95 tests passed

View Details
Test Status Duration
Endpoint And Method.Targets V1 Endpoint ✅ 516ms
Endpoint And Method.Does Not Use Legacy Endpoints ✅ 508ms
Required Headers.Has Authorization Bearer Header ✅ 509ms
Required Headers.Has Content Type Json ✅ 511ms
Required Headers.Has Posthog Sdk Info Format ✅ 508ms
Required Headers.Has Posthog Attempt Header ✅ 508ms
Required Headers.Has Posthog Request Id ✅ 508ms
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 ✅ 510ms
Body Format.No Sent At In Body ✅ 510ms
Event Format.Event Has Required Root Fields ✅ 512ms
Event Format.Event Uuid Is Valid ✅ 508ms
Event Format.Event Timestamp Is Rfc3339 ✅ 508ms
Event Format.Non Utc Event Timestamp Is Converted To Utc ✅ 520ms
Event Format.Distinct Id Is String ✅ 508ms
Event Format.Distinct Id At Root Not Properties ✅ 508ms
Event Format.Custom Properties Preserved ✅ 508ms
Event Format.Set Properties Preserved ✅ 508ms
Event Format.Set Once Properties Preserved ✅ 509ms
Event Format.Groups Properties Preserved ✅ 509ms
Event Format.Sdk Generates Uuid If Not Provided ✅ 509ms
Event Format.Event Has Required Root Fields Batch ✅ 511ms
Event Format.Event Uuid Is Valid Batch ✅ 511ms
Event Format.Event Timestamp Is Rfc3339 Batch ✅ 512ms
Event Format.Distinct Id Is String Batch ✅ 511ms
Event Format.Distinct Id At Root Not Properties Batch ✅ 511ms
Event Format.Custom Properties Preserved Batch ✅ 511ms
Event Format.Set Properties Preserved Batch ✅ 512ms
Event Format.Set Once Properties Preserved Batch ✅ 511ms
Event Format.Groups Properties Preserved Batch ✅ 511ms
Event Format.Sdk Generates Uuid If Not Provided Batch ✅ 511ms
Batch Behavior.Multiple Events In Single Batch ✅ 516ms
Batch Behavior.Batch Envelope Smoke ✅ 514ms
Batch Behavior.Flush With No Events Sends Nothing ✅ 505ms
Batch Behavior.Flush At Triggers Batch ✅ 1010ms
Batch Behavior.Created At Reflects Batch Creation Time ✅ 509ms
Deduplication.Generates Unique Uuids ✅ 514ms
Deduplication.Different Events Same Content Different Uuids ✅ 511ms
Deduplication.Preserves Uuid On Retry ✅ 6517ms
Deduplication.Preserves Timestamp On Retry ✅ 6512ms
Deduplication.Preserves Uuid And Timestamp On Batch Retry ✅ 6515ms
Deduplication.No Duplicate Events In Batch ✅ 513ms
Header Behavior On Retry.Attempt Header Starts At One ✅ 508ms
Header Behavior On Retry.Attempt Header Increments On Retry ✅ 13516ms
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 ✅ 6513ms
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 ✅ 511ms
Response Format Validation.Success Retry After Present When Retry Events ✅ 1513ms
Response Format Validation.Success No Retry After When Drop Only ✅ 510ms
Response Format Validation.Response Echoes Request Id ✅ 508ms
Retry Behavior.Retries On 408 ✅ 6511ms
Retry Behavior.Retries On 500 ✅ 6514ms
Retry Behavior.Retries On 503 ✅ 8515ms
Retry Behavior.Retries On 504 ✅ 6513ms
Retry Behavior.Retries On 404 ✅ 6513ms
Retry Behavior.Retries On 429 ✅ 6517ms
Retry Behavior.Retries On 502 ✅ 6513ms
Retry Behavior.Retryable Errors Have Retry After ✅ 3515ms
Retry Behavior.Respects Retry After On Retryable Error ✅ 11521ms
Retry Behavior.Does Not Retry On 400 ✅ 2510ms
Retry Behavior.Does Not Retry On 401 ✅ 2513ms
Retry Behavior.Does Not Retry On 402 ✅ 2511ms
Retry Behavior.Does Not Retry On 413 ✅ 2511ms
Retry Behavior.Does Not Retry On 415 ✅ 2512ms
Retry Behavior.Non Retryable Errors Have No Retry After ✅ 2511ms
Retry Behavior.Implements Backoff ✅ 19531ms
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 ✅ 3511ms
Partial Batch Handling.Does Not Retry Warning Events ✅ 3512ms
Partial Batch Handling.Prunes Ok Events On Partial Retry ✅ 6514ms
Partial Batch Handling.Prunes Dropped Events On Partial Retry ✅ 6515ms
Partial Batch Handling.Retries Only Retry Events From Partial ✅ 6516ms
Partial Batch Handling.Partial Retry Preserves Uuids ✅ 6514ms
Partial Batch Handling.Partial Retry Attempt Header Increments ✅ 6515ms
Partial Batch Handling.Partial Retry Request Id Preserved ✅ 6515ms
Partial Batch Handling.Respects Retry After On Partial ✅ 8519ms
Partial Batch Handling.Unknown Result Treated As Terminal ✅ 3510ms
Partial Batch Handling.Mixed Ok Drop Warning No Retry ✅ 3514ms
Compression.Sends Gzip Content Encoding ✅ 509ms
Compression.No Content Encoding When Disabled ✅ 508ms
Compression.Compressed Body Is Decompressible ✅ 508ms
Error Handling.Does Not Retry On Unknown 4Xx ✅ 2511ms
Event Options.Cookieless Mode Override ✅ 509ms
Event Options.Disable Skew Correction Override ✅ 508ms
Event Options.Process Person Profile Override ✅ 508ms
Event Options.Product Tour Id Override ✅ 508ms
Event Options.Unset Options Omitted ✅ 509ms
Event Options.Options Override In Batch ✅ 510ms
Geoip And Historical Migration.Historical Migration Absent By Default ✅ 509ms

Capture_Ai Tests

✅ 5/5 tests passed

View Details
Test Status Duration
Routing.Capture Ai Posts To Ai Endpoint ✅ 508ms
Routing.Capture Does Not Reroute Ai Named Events ✅ 508ms
Identity.Capture Ai Event Has Uuid ✅ 507ms
Identity.Capture Ai Keeps Supplied Uuid ✅ 508ms
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 ✅ 9ms
Request Payload.Flags Request Uses V4 Query Param ✅ 6ms
Request Payload.Flags Request Hits Flags Path Not Decide ✅ 7ms
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 ✅ 7ms
Request Payload.Disable Geoip Omitted Defaults To False ✅ 6ms
Request Payload.Flag Keys To Evaluate Contains Only Requested Key ✅ 6ms
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 ✅ 7ms
Retry Behavior.Retries Flags On 502 ✅ 310ms
Retry Behavior.Retries Flags On 504 ✅ 309ms
Side Effect Events.Get Feature Flag Captures Feature Flag Called Event ✅ 508ms

Feature_Flags_V4 Tests

✅ 150/150 tests passed

View Details
Test Status Duration
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Complete Split] ✅ 9ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Partial Split Missing Config Version] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Partial Split Missing Rule Type] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Partial Split Missing Rule Id] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Partial Split Missing Variant Key] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Split Wrong Type Config Version] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Split Wrong Type Rule Type] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Split Wrong Type Rule Id] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Split Wrong Type Experiment Id] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Split Extra Experiment Id] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Split Wrong Type Variant Key] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Wrong Rule Type Literal] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Unknown Fields] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Old Server Variant] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Old Server Boolean] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Old Server Null Variant] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Old Server False] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.V4 Value Takes Precedence] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Missing Flag] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Targeting Match Targeted Release] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Targeting Match Percentage Rollout] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Rollout Miss Percentage Rollout] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Rollout Miss Experiment] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Experiment Paused] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Holdout] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Holdout Variant Key] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.No Rule Match] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Missing Group Key] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Dependency Error] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Error] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Error With Value] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Malformed Sibling Isolation] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Partial Split String Value] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.V1 At V4] ✅ 6ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.V1 Failed] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Integral Json Number Context] ✅ 7ms
Legacy Getters.Legacy Getter Reads Reader Fixture[Readers.Flag Key Seed] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Target] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Rollout Hit] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Miss Return Default] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Miss Return Default Null] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Miss Continue] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.No Match Default] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.No Match Null] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Order First Match] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Order Targeting Miss] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Target] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Rollout Hit] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Miss Return Default] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Miss Return Default Null] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Miss Continue] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.No Match Default] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.No Match Null] ✅ 19ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Order First Match] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Order Targeting Miss] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Target] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Rollout Hit] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Miss Return Default] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Miss Return Default Null] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Miss Continue] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.No Match Default] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.No Match Null] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Order First Match] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Order Targeting Miss] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Unicode] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.String.Looks Boolean] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Zero] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Negative Decimal] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Short Decimal] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Exponent] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Max Safe Integer] ✅ 7ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Number.Min Safe Integer] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Empty] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Nested] ✅ 6ms
Legacy Getters.Legacy Getter Reads Typed Value[V2 Value.Object.Max Depth] ✅ 7ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Complete Split] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Partial Split Missing Config Version] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Partial Split Missing Rule Type] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Partial Split Missing Rule Id] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Partial Split Missing Variant Key] ✅ 4ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Split Wrong Type Config Version] ✅ 6ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Split Wrong Type Rule Type] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Split Wrong Type Rule Id] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Split Wrong Type Experiment Id] ✅ 4ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Split Extra Experiment Id] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Split Wrong Type Variant Key] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Wrong Rule Type Literal] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Unknown Fields] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Old Server Variant] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Old Server Boolean] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Old Server Null Variant] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Old Server False] ✅ 4ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.V4 Value Takes Precedence] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Missing Flag] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Targeting Match Targeted Release] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Targeting Match Percentage Rollout] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Rollout Miss Percentage Rollout] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Rollout Miss Experiment] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Experiment Paused] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Holdout] ✅ 4ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Holdout Variant Key] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.No Rule Match] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Missing Group Key] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Dependency Error] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Error] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Error With Value] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Malformed Sibling Isolation] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Partial Split String Value] ✅ 4ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.V1 At V4] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.V1 Failed] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Integral Json Number Context] ✅ 5ms
Legacy Payloads.Legacy Payload Reads Reader Fixture[Readers.Flag Key Seed] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Target] ✅ 4ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Rollout Hit] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Miss Return Default] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Miss Return Default Null] ✅ 4ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Miss Continue] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.No Match Default] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.No Match Null] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Order First Match] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Order Targeting Miss] ✅ 4ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Target] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Rollout Hit] ✅ 6ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Miss Return Default] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Miss Return Default Null] ✅ 4ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Miss Continue] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.No Match Default] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.No Match Null] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Order First Match] ✅ 4ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Order Targeting Miss] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Target] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Rollout Hit] ✅ 4ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Miss Return Default] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Miss Return Default Null] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Miss Continue] ✅ 4ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.No Match Default] ✅ 4ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.No Match Null] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Order First Match] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Order Targeting Miss] ✅ 4ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Unicode] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.String.Looks Boolean] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Zero] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Negative Decimal] ✅ 4ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Short Decimal] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Exponent] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Max Safe Integer] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Number.Min Safe Integer] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Empty] ✅ 5ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Nested] ✅ 4ms
Legacy Payloads.Legacy Payload Is The Typed Value[V2 Value.Object.Max Depth] ✅ 5ms

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 ✅ 44ms
Versioned Boolean Matching.Matching Version 2 ✅ 45ms
Versioned Boolean Matching.Version Only Reload 1 2 1 2 Missing ✅ 24ms

@github-actions

github-actions Bot commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

SDK performance: posthog-python

Benchmarks completed. No changes flagged for review.

Flags require at least a 5% change in the median and all six pairs agreeing on direction. This is a noise filter, not proof of a performance change or a CI gate.

View all results
Test Measurement Before PR With PR Change Assessment
Capture and deliver events (32-byte payload, burst)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (32-byte payload, steady)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Queue an event (32-byte payload)
Shard: capture
Allocated memory per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (32-byte payload)
Shard: capture
Allocations per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (4,096-byte payload)
Shard: capture
Allocated memory per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Queue an event (4,096-byte payload)
Shard: capture
Allocations per operation — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​; head:​ Background preparation has no public completion boundary before flush; see capture.​drain for full-pipeline allocations.​
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Refresh 1,000 flag definitions
Shard: flags-memory
Managed heap after settling — — — unavailable; base:​ unsupported; head:​ unsupported; base:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​; head:​ CPython has no uninstrumented total managed-heap byte counter; tracing would distort this RSS pass.​
Capture and deliver events (32-byte payload, burst)
Shard: capture
Allocated memory per operation 133.67 KiB/op 133.67 KiB/op <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Allocations per operation 1,345.53 count/op 1,345.53 count/op <0.1% fewer Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Time per operation 119.67 µs/op 121.08 µs/op 1.2% more time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Idle process memory (RSS) 37.77 MiB 37.75 MiB <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 40.21 MiB 40.2 MiB <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 40.21 MiB 40.2 MiB <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process CPU time per operation 119.04 µs/op 120.53 µs/op 1.3% more time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 40.43 MiB 40.43 MiB No observed change Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocated memory per operation 185.76 KiB/op 185.76 KiB/op No observed change Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocations per operation 1,337.57 count/op 1,337.57 count/op No observed change Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Time per operation 146.5 µs/op 149.5 µs/op 2% more time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Idle process memory (RSS) 41.35 MiB 41.27 MiB 0.2% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 47.14 MiB 47.05 MiB 0.2% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 47.14 MiB 47.05 MiB 0.2% less memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process CPU time per operation 134.72 µs/op 138 µs/op 2.4% more time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 51.6 MiB 51.57 MiB <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocated memory per operation 138.74 KiB/op 138.74 KiB/op <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocations per operation 1,390.38 count/op 1,390.38 count/op <0.1% more Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Time per operation 132.19 µs/op 130.84 µs/op 1% less time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Idle process memory (RSS) 37.64 MiB 37.68 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 37.82 MiB 37.83 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 37.82 MiB 37.83 MiB <0.1% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process CPU time per operation 127.79 µs/op 126.62 µs/op 0.9% less time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 40.43 MiB 40.43 MiB No observed change Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocated memory per operation 190.91 KiB/op 190.91 KiB/op <0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocations per operation 1,382.29 count/op 1,382.29 count/op <0.1% fewer Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Time per operation 154.23 µs/op 157.45 µs/op 2.1% more time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Idle process memory (RSS) 41.15 MiB 41.15 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 41.61 MiB 41.6 MiB <0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 41.21 MiB 41.2 MiB <0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process CPU time per operation 142.41 µs/op 146.64 µs/op 3% more time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 41.61 MiB 41.52 MiB 0.2% less memory Not flagged
Queue an event (32-byte payload)
Shard: capture
Caller-thread CPU time per operation 91.64 µs/op 85.98 µs/op 6.2% less time Not flagged
Queue an event (32-byte payload)
Shard: capture
Time per operation 94.08 µs/op 85.97 µs/op 8.6% less time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Caller-thread CPU time per operation 85.7 µs/op 92.05 µs/op 7.4% more time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Time per operation 87.28 µs/op 92.05 µs/op 5.5% more time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocated memory per operation 225.43 KiB/op 225.43 KiB/op No observed change Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocations per operation 2,279.42 count/op 2,279.42 count/op No observed change Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Time per operation 115.38 µs/op 114.25 µs/op 1% less time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Process CPU time per operation 115.4 µs/op 114.26 µs/op 1% less time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocated memory per operation 2.17 MiB/op 2.17 MiB/op No observed change Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocations per operation 22,413.69 count/op 22,413.69 count/op No observed change Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Time per operation 1.07 ms/op 1.08 ms/op 0.5% more time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Process CPU time per operation 1.07 ms/op 1.08 ms/op 0.4% more time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocated memory per operation 21.63 MiB/op 21.63 MiB/op No observed change Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocations per operation 223,655.44 count/op 223,655.44 count/op No observed change Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Time per operation 11.05 ms/op 10.88 ms/op 1.5% less time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Process CPU time per operation 11.05 ms/op 10.88 ms/op 1.5% less time Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Idle process memory (RSS) 43.83 MiB 43.84 MiB <0.1% more memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Observed peak process memory (RSS) 44.17 MiB 44.16 MiB <0.1% less memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Process memory after settling (RSS) 44.17 MiB 44.16 MiB <0.1% less memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Lifetime peak process memory (RSS) 43.9 MiB 43.96 MiB 0.1% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Idle process memory (RSS) 42.97 MiB 42.96 MiB <0.1% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Observed peak process memory (RSS) 42.98 MiB 42.96 MiB <0.1% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Process memory after settling (RSS) 42.98 MiB 42.94 MiB <0.1% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Lifetime peak process memory (RSS) 42.73 MiB 43.05 MiB 0.8% more memory Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocated memory per operation 15.74 KiB/op 15.74 KiB/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocations per operation 162.77 count/op 162.77 count/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Time per operation 8.15 µs/op 8.13 µs/op 0.3% less time Not flagged
Evaluate one boolean flag
Shard: flags-single
Process CPU time per operation 8.15 µs/op 8.13 µs/op 0.3% less time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocated memory per operation 24.6 KiB/op 24.6 KiB/op No observed change Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocations per operation 239.28 count/op 239.28 count/op No observed change Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Time per operation 11.39 µs/op 11.4 µs/op <0.1% more time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Process CPU time per operation 11.39 µs/op 11.4 µs/op <0.1% more time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocated memory per operation 39.81 KiB/op 39.81 KiB/op No observed change Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocations per operation 388.27 count/op 388.27 count/op No observed change Not flagged
Evaluate a flag (early match)
Shard: flags-single
Time per operation 16.35 µs/op 16.27 µs/op 0.5% less time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Process CPU time per operation 16.35 µs/op 16.27 µs/op 0.5% less time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocated memory per operation 60.59 KiB/op 60.59 KiB/op No observed change Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocations per operation 584.27 count/op 584.27 count/op No observed change Not flagged
Evaluate a flag (late match)
Shard: flags-single
Time per operation 23.44 µs/op 23.33 µs/op 0.5% less time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Process CPU time per operation 23.44 µs/op 23.33 µs/op 0.5% less time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocated memory per operation 59.22 KiB/op 59.22 KiB/op No observed change Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocations per operation 567.77 count/op 567.77 count/op No observed change Not flagged
Evaluate a flag (no match)
Shard: flags-single
Time per operation 22.1 µs/op 22.05 µs/op 0.2% less time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Process CPU time per operation 22.1 µs/op 22.05 µs/op 0.2% less time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocated memory per operation 19.04 KiB/op 19.04 KiB/op No observed change Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocations per operation 192.27 count/op 192.27 count/op No observed change Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Time per operation 9.24 µs/op 9.18 µs/op 0.6% less time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Process CPU time per operation 9.24 µs/op 9.18 µs/op 0.6% less time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocated memory per operation 20.66 KiB/op 20.66 KiB/op No observed change Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocations per operation 197.77 count/op 197.77 count/op No observed change Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Time per operation 9.76 µs/op 9.7 µs/op 0.6% less time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Process CPU time per operation 9.76 µs/op 9.7 µs/op 0.6% less time Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocated memory per operation 14.89 KiB/op 14.89 KiB/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocations per operation 152.77 count/op 152.77 count/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Time per operation 7.61 µs/op 7.7 µs/op 1.2% more time Not flagged
Evaluate a rollout flag
Shard: flags-single
Process CPU time per operation 7.61 µs/op 7.7 µs/op 1.2% more time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocated memory per operation 15.9 KiB/op 15.9 KiB/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocations per operation 166.77 count/op 166.77 count/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Time per operation 8.51 µs/op 8.5 µs/op 0.2% less time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Process CPU time per operation 8.51 µs/op 8.5 µs/op 0.2% less time Not flagged

Values are medians of paired measurements. Not flagged does not mean unchanged. Unavailable means a measurement could not be provided, not zero. Estimated allocation measurements retain their instrumentation uncertainty. RSS measures the whole process, not just SDK allocations; observed peaks are sampled checkpoints. Paired ranges in the diagnostics describe variability, not confidence intervals.

Each shard uses its own runner; compare Before PR against With PR within a row, not across shards.

Compared 97b4e45d216f3f5a8ebc5baf5c59aa6d88696a58 → f84fefb0dbf7564c62cfb4b6acfb993ed926316a.

Full report and diagnostics

102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in comparison.json, including per-runner environments, resource limits, measurement methods, samples and checkpoints.

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

Reproduced a custom-event attribution regression: after a token-bearing request, a metadata-only caller’s in-tool capture can inherit the previous caller’s session and person. The same public-entry test passes on base and fails on this head.

The metadata policy also needs reconciliation with the current canonical MCP specification; the linked spec proposal remains open. Details and executed evidence are inline.

AI-assisted review.

Comment thread posthog/mcp/_instrumentation.py Resolved
Comment thread posthog/mcp/session.py Resolved
…x, VS Code)

Rework the openai/session change to the merged sdk-specs rules
(PostHog/sdk-specs 2026-11-04-mcp-client-conversation-ids and
-codex-vscode-conversation-ids), matching posthog-js#5577:

- _client_conversation.CLIENT_CONVERSATION_ROWS mirrors the spec table:
  openai/session (1-128 printable ASCII, handle-free), Codex sessionId and
  VS Code vscode.conversationId (UUID, lowercased, non-nil, handle kept).
- A key is read only from a request its row recognizes by User-Agent or
  client name (_meta clientInfo first, then the adapter's resolved name).
- The client id is session source 1, ahead of the handle and transport, on
  tool calls only (tools/list, resources and initialize no longer read it).
  A handle echoed with it is stripped but ignored.
- A handle-free client's client-facing listing has no conversation_id or
  _mcp_instructions, and it is minted no handle. The SDK's internal cache
  pass still injects, so validation stays client-agnostic.
- Client- and handle-grouped calls count as connection activity, so a
  stdio session does not rotate early (gate finding from the JS port).
- PostHogMCP: prepare_tool_list/prepare_tool_call take headers
  (+client_info), capture_tool_call takes request_meta.

Tested: pytest posthog/test/mcp 743 passed on mcp 1.30.0, 601 passed on
mcp 2.3.0; the new tests cover every spec scenario and vector, including
real HTTP fleets over official, fastmcp and lowlevel servers. ruff, mypy
(CI mode with baseline) and the public API snapshot pass.

@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 02a4815: 1 Must fix, 1 Should fix. This pull request is large, so the review ran in 4 parts with less depth than usual.

Comment thread posthog/mcp/_instrument_fastmcp.py Resolved
Comment thread posthog/mcp/posthog_mcp.py Resolved
Comment thread posthog/mcp/_instrumentation.py Resolved
@veria-ai

veria-ai Bot commented Nov 5, 2026 •

Copy link
Copy Markdown

PR overview

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

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

Reviews

- Count a client-grouped call as connection activity only on a one-client
  connection (no HTTP request, no token, no transport id). On a shared
  stateless HTTP pod, ChatGPT calls kept the instance session alive and
  merged two unrelated clients into one $session_id.
- PostHogMCP.prepare_tool_list for a handle-free client still records
  conversation_id ownership, so prepare_tool_call strips an echoed handle
  like the automatic path does.

Tested: both regressions have tests that fail on 02a4815 and pass now;
pytest posthog/test/mcp 745 passed on mcp 1.30.0 and 603 on mcp 2.3.0;
ruff, mypy (CI mode) and the public API check pass.
@lucasheriques lucasheriques changed the title feat(mcp): group stateless ChatGPT calls by openai/session feat(mcp): group sessions by ChatGPT, Codex and VS Code conversation ids Nov 5, 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 3cbcd29: 1 Must fix, 2 Should fix. This pull request is large, so the review ran in 4 parts with less depth than usual.

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.

Comment thread posthog/mcp/_instrumentation.py Resolved
Comment thread posthog/mcp/posthog_mcp.py Resolved
Comment thread posthog/mcp/_instrumentation.py Resolved

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

The earlier recognition, bounds and precedence feedback is addressed. The custom-event attribution regression remains and now also reproduces when the second caller supplies its own token.

I also reproduced session/identity merging for handle-free HTTP calls without usable metadata, output-validation failures after mixed-client FastMCP listings, and schema-invalid results after mixed manual listings. The corresponding base controls pass; details are inline.

AI-assisted review.

Comment thread posthog/mcp/_instrumentation.py Resolved
Comment thread posthog/mcp/_instrumentation.py Resolved
Comment thread posthog/mcp/_instrument_fastmcp.py Resolved
Comment thread posthog/mcp/posthog_mcp.py Resolved
@dustinbyrne
dustinbyrne requested a review from a team November 5, 2026 22:28
Resolve conflicts with main's bounded intent scans, unknown-tool event and
new_session_id: keep lists_conversation_id and the client-conversation imports,
and thread the resolved session through record_unknown_tool so $mcp_unknown_tool
carries $mcp_session_source like every other event. Code matches the merged
spec plus sdk-specs#185.

Tested: uv run pytest posthog/test/mcp (776 passed, 11 skipped); ruff format and
check, mypy-baseline filter, public API check, import under -W error all clean.
Full suite: 6326 passed, 12 failed outside posthog/mcp (langchain, metrics autocapture fork).

@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 08774e9: 1 Must fix. This pull request is large, so the review ran in 4 parts with less depth than usual.

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.

Comment thread posthog/mcp/_instrument_v2.py Resolved
@lucasheriques lucasheriques added the stamphog Request stamphog review label Nov 9, 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 auto-review this pull request because two gates refused it. The deny-list gate flagged it for matching the auth and public_api categories, which fits the session and identity changes in posthog/mcp/session.py, posthog/mcp/_instrumentation.py and posthog/mcp/posthog_mcp.py, and the signature changes recorded in references/public_api_snapshot.txt. The tier gate classified it as T2-never because it is a cross-cutting feature spanning 22 files and 1508 lines. The size gate passed, so size is not the blocker.

Please ask a human reviewer to look at it. Splitting it, for example into the client-conversation parsing module, the session resolution changes, and the PostHogMCP API changes, may make that review easier, but the sensitive areas will still need a human.

  • posthog[bot] reviewed the current head.
Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✗ matches: auth, public_api
size ✓ 722L, 13F substantive, 1508L/22F incl. docs/generated/snapshots — within ceiling
tier ✗ classified as T2-never: T2-never (1508L, 22F, cross-cutting, feat)
stamphog 2.7.0 .stamphog/policy.yml @ unknown · reviewed head 08774e9

@stamphog stamphog Bot removed the stamphog Request stamphog review label Nov 9, 2026

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

Complete read-only follow-up against current base 133d7d12c3f15b04287b6d8389b0412fb7dfe6de.

The recognition table, validation, namespaced derivation and metadata precedence now match the canonical MCP contract, including automatic session-source reporting. All four required regressions from my prior review still reproduce against this updated base: custom capture inherits the previous caller's identity; missing/empty handle-free HTTP metadata merges sessions and person properties; mixed-client official FastMCP listings turn successful strict output into errors; and manual listing/preparation returns a schema-incompatible result.

I independently reproduced the existing MCP 2.x internal-list ownership report: base passes all four cases; head fails fresh raw HTTP/no-resolver with JSON-RPC -32603, while warm-listing and resolver controls pass. The adversarial pass also identified a tracked public-import removal; the old import/string-return smoke test passes on base and raises ImportError on head.

These are five P1 corrections plus one P2 compatibility correction, so I cannot recommend approval yet. Current CI is green (26 successes, one neutral), but it does not cover these sequences. The exact regressions pass on the current base and fail on this head. Full local suites also have nine identical standalone FastMCP dependency/import failures on both revisions; those are environmental, not additional PR regressions. No live PostHog delivery, provider integration, deployed profile mutation or UI verification was performed.

AI-assisted review.

Comment thread posthog/mcp/_instrumentation.py Resolved
Comment thread posthog/mcp/_instrumentation.py Resolved
Comment thread posthog/mcp/_instrument_fastmcp.py Resolved
Comment thread posthog/mcp/posthog_mcp.py Resolved
Comment thread posthog/mcp/_instrument_v2.py Resolved
Comment thread posthog/mcp/asgi.py Resolved
@dustinbyrne
dustinbyrne requested a review from a team November 9, 2026 21:17
A custom event captured inside a tool read the server-wide data.session_id.
On a shared stateless HTTP server, another request finishing while the tool
awaited moved that slot, so the event took the other caller's session and
identity (Dustin's P1 on this PR).

Each adapter now runs the tool body inside lifecycle.in_tool(), which binds
the call's session to a ContextVar keyed to its server and resets it when the
body returns. The session is the call's client conversation id or handle
(echoed, or minted for this call, as posthog-js does) when it has one, else
its primed transport session. The host's on_feedback handler runs bound to
the $mcp_feedback session. Rules 1 and 2 move into resolve_anchored_session
so the resolver and the binding share them.

Tested: overlap rows (no id, client id, echoed and minted handle), an
on_feedback overlap, and outside-a-tool rows (same server after a call,
another server inside one) fail before and pass after; dropping each part
of the binding turns its rows red. pytest posthog/test/mcp: 884 passed.
ruff, public API snapshot clean; mypy unchanged (5 errors in untouched files).

@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 4b103b5: 1 Should fix. This pull request is large, so the review ran in 4 parts with less depth than usual.

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/mcp/_instrumentation.py Resolved
…ll's outcome

A handle minted for a call groups it only once its result delivers it. The
in-tool binding put custom events on that handle's session right away, but a
call that raised, or whose result could not carry the handle, records its
$mcp_tool_call under the fallback session. The two then split (reviewhog's
P2 on this PR).

While a call runs on a handle minted for it, in_tool buffers its custom events.
When the call records its outcome (result, error, unknown tool), they are sent
with that event's session, without the call waiting on them or failing because
of them. Each adapter settles whatever is left in a finally with the primed
session, so a cancelled call, or one that records nothing, loses none. They
keep the duration they had when captured. Work the tool started that captures
later goes straight to the settled session. Echoed handles and client
conversation ids are unchanged.

Tested: a parameterized test crosses the outcome (delivered, undelivered,
raised) with when the event is captured (in the tool, after the call settles);
5 of 6 rows fail before. test_minted_handle_custom_events.py runs cancellation
(in the tool, and while the call records), an empty tool name, an unbuildable
event and the duration through the real mcp 1.x adapters; all fail without the
fix. pytest posthog/test/mcp: 895 passed. ruff, public API snapshot clean;
mypy unchanged. The mcp 2.x adapter gets the same finally; CI runs it.

@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 be1d543: 2 Should fix. This pull request is large, so the review ran in 4 parts with less depth than usual.

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.

Comment thread posthog/mcp/__init__.py Resolved
Comment thread posthog/mcp/__init__.py Resolved
Comment thread posthog/mcp/__init__.py Resolved

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

The earlier exact attribution, ownership, compatibility and undelivered-handle reproductions now pass.

Three required regressions remain: overlapping listings can invalidate a successful strict-output call on official MCP 1.28.1; deferred captures lose scalar properties after normal dictionary reuse; and the first custom event in a recognized conversation loses configured person attribution. There is also an optional recommendation to bound raw deferred-event retention.

Details and executed base/head controls are inline. The equivalent listing-overlap test passes on MCP 2.3.0.

AI-assisted review.

# block on the minting response only.
delivered = False
if lifecycle.conversation_id:
if lifecycle.mirrors_output_instructions:

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] Keep an in-flight result compatible with its validation schema

Compared base f22511891225fb15a4e6a0f889e723e9b5d0ebe4 with head be1d543c1909f6b9d21e1aa449258cbc60dc8af1.

IMPORTANT · REQUIRED · Introduced by the whole PR relative to base.
Related: _instrumentation.py:595–601,1362–1367.

A successful strict-output tool becomes an MCP error when another client lists tools while it awaits:

  1. ChatGPT tools/list caches the strict schema without _mcp_instructions.
  2. An ordinary tools/call enters its handler and awaits application work.
  3. Another ordinary tools/list enables shared mirroring.
  4. The first tool returns its valid result, but instrumentation adds a field forbidden by the older retained schema.
class StrictResult(BaseModel):
    model_config = ConfigDict(extra="forbid")
    value: int

@server.tool()
async def probe() -> StrictResult:
    entered.set()
    await release.wait()
    return StrictResult(value=7)

The caller receives:

Output validation error: Additional properties are not allowed
('_mcp_instructions' was unexpected)

with isError: true, instead of its successful structured result.

Official MCP 1.28.1 retains the cached Tool before awaiting dispatch and validates against that object afterwards (mcp/server/lowlevel/server.py:527–541,565–575). The instrumentation reads the shared mirroring flag after the await. A later listing changes that flag but not the schema retained by the in-flight validator.

This violates canonical Observer-only instrumentation and the official structured-output contract.

Executed public HTTP/ASGI evidence:

MCP 1.28.1 Base f225118… Head be1d543…
Listing completes before call Pass Pass
Listing overlaps call Pass Client receives validation error

Base 2 passed, exit 0; head 1 failed / 1 passed, exit 1. No private-state mutation or malformed result is required.

Consider binding mirroring to the validation schema applicable at dispatch, before execution can yield, rather than a later listing’s mutable flag. Preserve handle-free advertisement and the passing sequential behavior.

Limits: Demonstrated on official MCP 1.28.1. The equivalent modern-HTTP test on MCP 2.3.0 passes both cases on base/head. This is not specifically caused by the latest buffering commit, and the earlier sequential reproduction remains fixed.

Executed standalone regression harness

Run with official MCP 1.28.1 on each revision:

pytest -q -s --asyncio-mode=auto test_concurrent_output_listing_standalone.py
import asyncio
import json
import httpx
import pytest
from pydantic import BaseModel, ConfigDict
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
from posthog.mcp import instrument, MCPAnalyticsOptions
from posthog.test.mcp._helpers import FakeClient

CHATGPT = "openai-mcp/1.0.0 (ChatGPT)"
OTHER = "example-client/1.0"
HEADERS = {
    "content-type": "application/json",
    "accept": "application/json, text/event-stream",
    "mcp-protocol-version": "2025-06-18",
}

class StrictResult(BaseModel):
    model_config = ConfigDict(extra="forbid")
    value: int

async def rpc(http, method, params, ua, index):
    response = await http.post(
        "/mcp",
        headers={**HEADERS, "user-agent": ua},
        json={
            "jsonrpc": "2.0", "id": index,
            "method": method, "params": params,
        },
    )
    assert response.status_code == 200, response.text
    body = response.json()
    assert "error" not in body, body
    return body["result"]

@pytest.mark.parametrize("overlap", [False, True])
async def test_output_schema_remains_valid_when_another_client_lists(overlap):
    server = FastMCP(
        "listing-overlap", stateless_http=True, json_response=True,
        transport_security=TransportSecuritySettings(
            enable_dns_rebinding_protection=False
        ),
    )
    entered, release = asyncio.Event(), asyncio.Event()

    @server.tool()
    async def probe() -> StrictResult:
        entered.set()
        await release.wait()
        return StrictResult(value=7)

    analytics = instrument(
        server, FakeClient(),
        MCPAnalyticsOptions(
            context=False, capture_model=False,
            send_initialize_event=False,
        ),
    )
    app = server.streamable_http_app()
    async with server.session_manager.run():
        async with httpx.AsyncClient(
            transport=httpx.ASGITransport(app=app),
            base_url="http://localhost",
        ) as http:
            await rpc(http, "tools/list", {}, CHATGPT, 1)
            if not overlap:
                await rpc(http, "tools/list", {}, OTHER, 2)
            task = asyncio.create_task(rpc(
                http, "tools/call",
                {"name": "probe", "arguments": {}}, OTHER, 3,
            ))
            try:
                await asyncio.wait_for(entered.wait(), 5)
                if overlap:
                    await rpc(http, "tools/list", {}, OTHER, 2)
            finally:
                release.set()
            result = await asyncio.wait_for(task, 5)
            await analytics.flush()
    print(json.dumps({"overlap": overlap, "result": result}))
    assert not result.get("isError"), result
    assert result["structuredContent"]["value"] == 7

The harness is formatting-equivalent to the executed source. Environment: Python 3.11.13, pytest 8.4.1, pytest-asyncio 1.0.0, httpx 0.28.1, Pydantic 2.12.5.

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.

Fixed in 2c81e3e. Whether the handle is mirrored into structuredContent is now read once, when the call starts. That's the same moment the SDK retains the tool schema it validates against, so a listing that lands while the tool awaits can't add _mcp_instructions to a strict result.

test_a_listing_during_a_call_leaves_its_structured_result_valid flips the listing state while a strict-output tool awaits. It fails before.

Comment thread posthog/mcp/__init__.py
"event_type": MCPAnalyticsEventType.CUSTOM,
"event_name": event,
"timestamp": datetime.now(timezone.utc),
"properties": properties,

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] Snapshot scalar properties before returning from deferred capture

Compared base f22511891225fb15a4e6a0f889e723e9b5d0ebe4 with head be1d543c1909f6b9d21e1aa449258cbc60dc8af1.

IMPORTANT · REQUIRED · Introduced by deferred capture.
Related: posthog/mcp/__init__.py:175–179.

Reusing a dictionary after awaited capture now changes the contents of earlier events:

properties = {"step": 0}
await analytics.capture("progress", properties)
properties["step"] = 1
await analytics.capture("progress", properties)
properties.clear()

Expected: the events retain step=0 and step=1. Actual: both are emitted without step.

The shallow event-input copy retains the caller-owned properties mapping until settlement. Base awaited materialization, which copied its top-level entries into the outgoing mapping before returning.

Executed public HTTP/ASGI comparison, both official majors:

Case Base Head
Minted-handle call [0, 1] Both scalar properties absent
Anchoring-disabled control [0, 1] [0, 1]

No concurrency, malformed input or private-state mutation is required. This regresses established observable capture behavior; the timestamp represents capture time while its payload instead reflects later application state.

Consider snapshotting the top-level mapping when accepting the deferred event, preserving fail-closed handling and final session selection.

Scope: This establishes top-level scalar preservation only. Nested mutation fails on base too; no deep-copy contract is inferred. Automatic events and identities are not shown to be lost.

Each major’s scalar cases produce base 2 passed, head 1 failed / 1 passed. The complete shared harness below produces base 4 passed, head 2 failed / 2 passed, including the separate optional allocation measurement.

Executed shared scalar/retention harness

Run with the same selected MCP version—1.28.1 or 2.3.0—on both revisions:

pytest -q -s --asyncio-mode=auto test_deferred_capture_standalone.py

Use -k snapshots for the scalar cases and -k large_progress for retention.

import importlib.metadata
import json
import tracemalloc
import httpx
import pytest
from posthog.mcp import instrument, MCPAnalyticsOptions
from posthog.test.mcp._helpers import FakeClient

MAJOR = int(importlib.metadata.version("mcp").split(".")[0])
if MAJOR < 2:
    from mcp.server.fastmcp import FastMCP
    from mcp.server.transport_security import TransportSecuritySettings
else:
    from mcp.server.mcpserver import MCPServer
    from posthog.test.mcp._helpers_v2 import modern_headers, modern_meta

async def call_tool(body, client, anchored):
    server = (
        FastMCP(
            "deferred-controls", stateless_http=True, json_response=True,
            transport_security=TransportSecuritySettings(
                enable_dns_rebinding_protection=False
            ),
        )
        if MAJOR < 2 else MCPServer("deferred-controls")
    )

    @server.tool()
    async def probe() -> str:
        await body(analytics)
        return "ok"

    analytics = instrument(
        server, client,
        MCPAnalyticsOptions(
            enable_conversation_id=anchored,
            context=False, capture_model=False,
            send_initialize_event=False,
        ),
    )
    app = (
        server.streamable_http_app() if MAJOR < 2
        else server.streamable_http_app(
            json_response=True, stateless_http=True
        )
    )
    async with server.session_manager.run():
        async with httpx.AsyncClient(
            transport=httpx.ASGITransport(app=app),
            base_url="http://127.0.0.1:8000",
        ) as http:
            headers = (
                {
                    "content-type": "application/json",
                    "accept": "application/json, text/event-stream",
                    "mcp-protocol-version": "2025-06-18",
                }
                if MAJOR < 2 else modern_headers("tools/call", "probe")
            )
            response = await http.post(
                "/mcp",
                headers={**headers, "user-agent": "example-client/1.0"},
                json={
                    "jsonrpc": "2.0", "id": 1, "method": "tools/call",
                    "params": {
                        "name": "probe", "arguments": {},
                        "_meta": {} if MAJOR < 2 else modern_meta(),
                    },
                },
            )
            assert response.status_code == 200, response.text
            result = response.json()
            assert "error" not in result
            assert not result["result"].get("isError"), result
            if anchored:
                assert "conversation_id" in json.dumps(result)
            await analytics.flush()

@pytest.mark.parametrize("anchored", [False, True])
async def test_capture_snapshots_properties_before_returning(anchored):
    client = FakeClient()

    async def body(analytics):
        props = {"step": 0}
        await analytics.capture("progress", props)
        props["step"] = 1
        await analytics.capture("progress", props)
        props.clear()

    await call_tool(body, client, anchored)
    events = [e for e in client.events if e["event"] == "progress"]
    assert len(events) == 2
    actual = [e["properties"].get("step") for e in events]
    print(json.dumps({"anchored": anchored, "steps": actual}))
    assert actual == [0, 1]

class CountingClient:
    """Never retains event payloads itself."""
    def __init__(self):
        self.count = 0
        self.largest_blob = 0

    def capture(self, event, **kwargs):
        if event == "progress":
            self.count += 1
            self.largest_blob = max(
                self.largest_blob,
                len(kwargs["properties"].get("blob", "")),
            )

@pytest.mark.parametrize("anchored", [False, True])
async def test_large_progress_events_do_not_accumulate_before_sink_limits(
    anchored,
):
    client = CountingClient()
    observed = {}

    async def body(analytics):
        tracemalloc.start()
        before = tracemalloc.get_traced_memory()[0]
        try:
            for index in range(64):
                await analytics.capture(
                    "progress",
                    {"blob": str(index) + ":" + "x" * (256 * 1024)},
                )
            current, peak = tracemalloc.get_traced_memory()
            observed.update(
                retained_bytes=current-before,
                peak_bytes=peak-before,
                captures_before_tool_returns=client.count,
            )
        finally:
            tracemalloc.stop()

    await call_tool(body, client, anchored)
    print(json.dumps({
        "anchored": anchored, **observed,
        "total_captures": client.count,
        "largest_sink_blob": client.largest_blob,
    }))
    assert client.count == 64
    assert observed["retained_bytes"] < 2 * 1024 * 1024

The harness is formatting-equivalent to the executed source. The memory threshold detects the change, not an agreed future cap/drop contract.

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.

Fixed in cd5fb1d. A deferred event copies its top-level properties and event_options when it's captured, so reusing or clearing the dict afterwards doesn't change it. Nested values aren't copied, which matches base.

test_a_custom_event_keeps_the_properties_it_was_captured_with runs your [0, 1] case anchored and not anchored. test_a_custom_event_keeps_the_options_it_was_captured_with does the same for process_person_profile.

On the design: the bot said this was round 6, with findings recurring in the deferred-capture code. So rather than patch each one, I changed how deferral works in cd5fb1d. Every custom event captured during a tool call waits for the call to settle, minted handle or not, and is fixed when captured. Its top-level properties and event_options are copied, its duration is set, and the contextvars context that before_send will run in is saved. Only the session is bound later, when it goes out with the call's own session and the identity resolved for it.

Comment thread posthog/mcp/_instrumentation.py Outdated
Comment on lines +639 to +643
anchored = resolve_anchored_session(
self.conversation_id, self.client_conversation
)
pending = self.pending_custom_events if self.minted_conversation_id else None
with bind_in_tool_session(self.data, anchored or primed, pending):

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] Resolve person attribution before the first metadata-conversation capture

Compared base f22511891225fb15a4e6a0f889e723e9b5d0ebe4 with head be1d543c1909f6b9d21e1aa449258cbc60dc8af1.

IMPORTANT · REQUIRED · Exposed by conversation anchoring, not specifically the buffering commit.
Related: __init__.py:166–182, _capture.py:34–35.

The first custom event in a recognized conversation is anonymous despite an explicit configured identity and a correctly identified preceding listing:

@server.tool()
async def probe() -> str:
    await analytics.capture("inside_tool")
    return "ok"

analytics = instrument(
    server, client,
    MCPAnalyticsOptions(
        send_tools_list_event=True,
        identify=UserIdentity(
            distinct_id="bob", properties={"plan": "pro"}
        ),
    ),
)

Request sequence:

  1. ChatGPT tools/list is recorded as Bob with $set.plan="pro".
  2. The first call carrying openai/session succeeds, but its custom event uses the session-derived anonymous ID, omits $set, and sets $process_person_profile=false.
  3. Its automatic tool event is correctly Bob.
  4. A second call in that conversation records both events as Bob.

Expected: the first custom event also carries Bob and the plan.

The request-local binding selects the new metadata session before its actor is cached. Recognized metadata captures materialize immediately, before result recording runs prepare_session()/handle_identify(). Later identification cannot rewrite the already-materialized custom event.

The canonical Person identity requirement requires resolved request identity and properties on identified events.

Executed public-entry evidence:

Observation, both official majors Base Head
Preceding listing Bob + plan Bob + plan
Both automatic calls Bob + plan Bob + plan
Repeated-conversation custom control Bob + plan Bob + plan
First custom event Bob + plan Anonymous; no $set

Each major: base 2 passed, exit 0; head 2 failed, exit 1, covering anchoring on and off. Protocol, tool responses and all controls pass before the first-custom identity assertion.

The listing is supported discovery, not private cache manipulation. Anonymous capture before any previous identity resolution is not the claim. Nor does this require base custom and automatic events to share a session—the assertion concerns configured person attribution.

Consider making this request’s resolved attribution available before immediate custom capture, while retaining request isolation and never borrowing another request’s cached actor.

Limits: This loses custom-event person attribution, not cross-person isolation. Automatic identity remains correct. No live profile mutation or privacy incident is claimed. Runtime coverage is ChatGPT metadata, not equivalent Codex/VS Code cases.

Executed identity regression harness

Run on both revisions with the same MCP version:

pytest -q -s --asyncio-mode=auto test_first_metadata_identity.py
import importlib.metadata
import json
import httpx
import pytest
from posthog.mcp import instrument, MCPAnalyticsOptions, UserIdentity
from posthog.test.mcp._helpers import FakeClient

MAJOR = int(importlib.metadata.version("mcp").split(".")[0])
if MAJOR < 2:
    from mcp.server.fastmcp import FastMCP
    from mcp.server.transport_security import TransportSecuritySettings
else:
    from mcp.server.mcpserver import MCPServer
    from posthog.test.mcp._helpers_v2 import modern_headers, modern_meta

@pytest.mark.parametrize("anchored", [False, True])
async def test_first_metadata_custom_event_preserves_static_identity(
    anchored,
):
    client = FakeClient()
    server = (
        FastMCP(
            "first-identity", stateless_http=True, json_response=True,
            transport_security=TransportSecuritySettings(
                enable_dns_rebinding_protection=False
            ),
        )
        if MAJOR < 2 else MCPServer("first-identity")
    )

    @server.tool()
    async def probe() -> str:
        await analytics.capture("inside_tool")
        return "ok"

    analytics = instrument(
        server, client,
        MCPAnalyticsOptions(
            context=False, capture_model=False,
            send_initialize_event=False, send_tools_list_event=True,
            enable_conversation_id=anchored,
            identify=UserIdentity(
                distinct_id="bob", properties={"plan": "pro"}
            ),
        ),
    )
    app = (
        server.streamable_http_app() if MAJOR < 2
        else server.streamable_http_app(
            json_response=True, stateless_http=True
        )
    )
    async with server.session_manager.run():
        async with httpx.AsyncClient(
            transport=httpx.ASGITransport(app=app),
            base_url="http://127.0.0.1:8000",
        ) as http:
            async def rpc(method, params, index):
                headers = (
                    {
                        "content-type": "application/json",
                        "accept": "application/json, text/event-stream",
                        "mcp-protocol-version": "2025-06-18",
                    }
                    if MAJOR < 2
                    else modern_headers(method, params.get("name"))
                )
                meta = {} if MAJOR < 2 else modern_meta()
                if method == "tools/call":
                    meta["openai/session"] = "first-review-conversation"
                response = await http.post(
                    "/mcp",
                    headers={
                        **headers,
                        "user-agent": "openai-mcp/1.0.0 (ChatGPT)",
                    },
                    json={
                        "jsonrpc": "2.0", "id": index,
                        "method": method,
                        "params": {**params, "_meta": meta},
                    },
                )
                assert response.status_code == 200, response.text
                result = response.json()
                assert "error" not in result
                assert not result["result"].get("isError"), result

            await rpc("tools/list", {}, 1)
            await analytics.flush()
            for index in [2, 3]:
                await rpc(
                    "tools/call",
                    {"name": "probe", "arguments": {}}, index,
                )
                await analytics.flush()

    custom = [e for e in client.events if e["event"] == "inside_tool"]
    calls = [e for e in client.events if e["event"] == "$mcp_tool_call"]
    listing = next(
        e for e in client.events if e["event"] == "$mcp_tools_list"
    )
    print(json.dumps({
        "anchored": anchored, "listing": listing,
        "custom": custom, "calls": calls,
    }))
    assert listing["distinct_id"] == "bob"
    assert listing["properties"]["$set"]["plan"] == "pro"
    assert len(custom) == len(calls) == 2
    assert all(
        e["distinct_id"] == "bob"
        and e["properties"]["$set"]["plan"] == "pro"
        for e in calls
    )
    assert custom[1]["distinct_id"] == "bob"
    assert custom[1]["properties"]["$set"]["plan"] == "pro"
    assert custom[0]["distinct_id"] == "bob"
    assert custom[0]["properties"]["$set"]["plan"] == "pro"

The harness is formatting-equivalent to the executed source.

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.

Fixed in cd5fb1d. Custom events captured during a call now go out when the call settles, after identify has run for its session. So the first custom event in a conversation carries the configured identity and $set.

test_the_first_custom_event_in_a_conversation_carries_its_identity covers a client id, an echoed handle and a minted handle, with a static UserIdentity(distinct_id="bob", properties={"plan": "pro"}). The client-id and echoed-handle rows fail before.

Comment thread posthog/mcp/__init__.py Outdated
pending = unsettled_custom_events(data)
if pending is not None:
# Sent once the call settles; its duration is still the moment it was captured.
pending.events.append({**event_input, "duration": 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.

[P2] Bound deferred payloads before downstream queue limits

Compared base f22511891225fb15a4e6a0f889e723e9b5d0ebe4 with head be1d543c1909f6b9d21e1aa449258cbc60dc8af1.

MINOR · OPTIONAL · Introduced by deferred capture.
Related: session.py:38–45, _instrumentation.py:653–674.

A call minting a handle retains every full custom payload until completion:

for index in range(64):
    await analytics.capture(
        "progress", {"blob": str(index) + ":" + "x" * (256 * 1024)}
    )

pending.events has no count or retained-byte bound. Inputs have not reached truncation, before_send or the host queue. Settlement creates one task per retained event.

The executed harness below uses a counting/discarding client that retains no payloads:

Minted-handle case Base retained allocation Head retained allocation
MCP 1.28.1 26,934 bytes 16,807,366 bytes
MCP 2.3.0 21,610 bytes 16,806,302 bytes

Anchoring-off controls remain approximately 24–29 KB on head. Head forwards zero captures before the tool returns and all 64 afterwards. Downstream blobs are approximately 101 KB, while the list retains their original 256 KiB inputs.

Consider an internal count-and-size budget with explicit overflow handling and bounded settlement work, preserving outcome-dependent attribution.

Why optional: The mechanism is confirmed, but this deliberately large fixture does not establish typical residency or likely exhaustion. It measures wrapper-stage Python allocations, not a real host queue’s total memory, RSS, OOM or production harm. All 64 events eventually reach the sink.

The observer-only requirement bounds per-session state/pending tasks, but does not specify an exact per-invocation raw-byte budget. Downstream limits cannot constrain this new list; their existing implementation is not alleged to be broken.

Executed measurement: Run the complete harness below with -k large_progress. Each major yields base 2 passed, head 1 failed / 1 passed. The 2 MiB detector and current delivery-count assertion are not a proposed post-fix cap/drop contract; that policy needs corresponding assertions.

Executed shared scalar/retention harness

Run with the same selected MCP version—1.28.1 or 2.3.0—on both revisions:

pytest -q -s --asyncio-mode=auto test_deferred_capture_standalone.py

Use -k snapshots for the scalar cases and -k large_progress for retention.

import importlib.metadata
import json
import tracemalloc
import httpx
import pytest
from posthog.mcp import instrument, MCPAnalyticsOptions
from posthog.test.mcp._helpers import FakeClient

MAJOR = int(importlib.metadata.version("mcp").split(".")[0])
if MAJOR < 2:
    from mcp.server.fastmcp import FastMCP
    from mcp.server.transport_security import TransportSecuritySettings
else:
    from mcp.server.mcpserver import MCPServer
    from posthog.test.mcp._helpers_v2 import modern_headers, modern_meta

async def call_tool(body, client, anchored):
    server = (
        FastMCP(
            "deferred-controls", stateless_http=True, json_response=True,
            transport_security=TransportSecuritySettings(
                enable_dns_rebinding_protection=False
            ),
        )
        if MAJOR < 2 else MCPServer("deferred-controls")
    )

    @server.tool()
    async def probe() -> str:
        await body(analytics)
        return "ok"

    analytics = instrument(
        server, client,
        MCPAnalyticsOptions(
            enable_conversation_id=anchored,
            context=False, capture_model=False,
            send_initialize_event=False,
        ),
    )
    app = (
        server.streamable_http_app() if MAJOR < 2
        else server.streamable_http_app(
            json_response=True, stateless_http=True
        )
    )
    async with server.session_manager.run():
        async with httpx.AsyncClient(
            transport=httpx.ASGITransport(app=app),
            base_url="http://127.0.0.1:8000",
        ) as http:
            headers = (
                {
                    "content-type": "application/json",
                    "accept": "application/json, text/event-stream",
                    "mcp-protocol-version": "2025-06-18",
                }
                if MAJOR < 2 else modern_headers("tools/call", "probe")
            )
            response = await http.post(
                "/mcp",
                headers={**headers, "user-agent": "example-client/1.0"},
                json={
                    "jsonrpc": "2.0", "id": 1, "method": "tools/call",
                    "params": {
                        "name": "probe", "arguments": {},
                        "_meta": {} if MAJOR < 2 else modern_meta(),
                    },
                },
            )
            assert response.status_code == 200, response.text
            result = response.json()
            assert "error" not in result
            assert not result["result"].get("isError"), result
            if anchored:
                assert "conversation_id" in json.dumps(result)
            await analytics.flush()

@pytest.mark.parametrize("anchored", [False, True])
async def test_capture_snapshots_properties_before_returning(anchored):
    client = FakeClient()

    async def body(analytics):
        props = {"step": 0}
        await analytics.capture("progress", props)
        props["step"] = 1
        await analytics.capture("progress", props)
        props.clear()

    await call_tool(body, client, anchored)
    events = [e for e in client.events if e["event"] == "progress"]
    assert len(events) == 2
    actual = [e["properties"].get("step") for e in events]
    print(json.dumps({"anchored": anchored, "steps": actual}))
    assert actual == [0, 1]

class CountingClient:
    """Never retains event payloads itself."""
    def __init__(self):
        self.count = 0
        self.largest_blob = 0

    def capture(self, event, **kwargs):
        if event == "progress":
            self.count += 1
            self.largest_blob = max(
                self.largest_blob,
                len(kwargs["properties"].get("blob", "")),
            )

@pytest.mark.parametrize("anchored", [False, True])
async def test_large_progress_events_do_not_accumulate_before_sink_limits(
    anchored,
):
    client = CountingClient()
    observed = {}

    async def body(analytics):
        tracemalloc.start()
        before = tracemalloc.get_traced_memory()[0]
        try:
            for index in range(64):
                await analytics.capture(
                    "progress",
                    {"blob": str(index) + ":" + "x" * (256 * 1024)},
                )
            current, peak = tracemalloc.get_traced_memory()
            observed.update(
                retained_bytes=current-before,
                peak_bytes=peak-before,
                captures_before_tool_returns=client.count,
            )
        finally:
            tracemalloc.stop()

    await call_tool(body, client, anchored)
    print(json.dumps({
        "anchored": anchored, **observed,
        "total_captures": client.count,
        "largest_sink_blob": client.largest_blob,
    }))
    assert client.count == 64
    assert observed["retained_bytes"] < 2 * 1024 * 1024

The harness is formatting-equivalent to the executed source. The memory threshold detects the change, not an agreed future cap/drop contract.

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.

Fixed in cd5fb1d. A call holds at most 1,000 custom events (MAX_DEFERRED_CUSTOM_EVENTS). Beyond that the rest are dropped, with one warning per call. Each held event keeps a top-level copy of its properties, nothing deeper. Covered by test_a_call_sends_at_most_its_bound_of_custom_events.

Review then found that deferring every in-call event meant a shutdown mid-call could lose one. ff5b17f and 7fc8fc8 make analytics.flush() settle running calls early. It uses the session each call already knows and runs identify for it first, so the documented flush-then-shutdown still delivers them.

@dustinbyrne
dustinbyrne requested a review from a team November 17, 2026 21:28
…-session

# Conflicts:
#	posthog/mcp/__init__.py
#	posthog/mcp/posthog_mcp.py
#	references/public_api_snapshot.txt
Comment thread posthog/mcp/_instrumentation.py Resolved
@lucasheriques lucasheriques added the stamphog Request stamphog review label Nov 23, 2026
@stamphog stamphog Bot removed the stamphog Request stamphog review label Nov 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 yet — waiting on the conditions below.

Add the stamphog label to request another review once you have addressed this.

stamphog can't auto-review this pull request because two gates refused it. The deny-list gate matched sensitive areas: auth in posthog/test/mcp/test_session_token.py and public_api in references/public_api_snapshot.txt. The size gate also failed: the change has 1358 substantive lines against a 1200-line ceiling, and the tier gate follows from the deny-list match.

Please ask a human reviewer to look at it, since the auth and public API paths need a person to sign off. Splitting it would also help the size problem. For example, the _client_conversation.py module and its tests could land separately from the instrumentation changes and the PostHogMCP signature changes.

Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✗ matches: auth in posthog/test/mcp/test_session_token.py; public_api in references/public_api_snapshot.txt
every_file_attested ✓ not a bot PR
size ✗ too large for auto-review (1358L substantive in global — ceiling is 1200L; 1358L, 13F total, 2734L/26F incl. docs/generated/snapshots)
tier ✗ T2-never because the deny-list matched auth, public_api
stamphog 2.9.1 .stamphog/policy.yml @ unknown · reviewed head 708e493

…rored

The SDK validates a call's result against the tool schema it held when the
call started. Whether the handle is mirrored into structuredContent was read
after the tool awaited, from state the latest listing sets. So a handle-free
(ChatGPT) listing that cached the strict schema, then an ordinary listing
landing mid-call, made a valid strict-output result fail validation with
"'_mcp_instructions' was unexpected" (Dustin's P1 on this PR).

The lifecycle now reads it once, when the call starts.

Tested: test_minted_handle_custom_events.py flips the listing state while a
strict-output tool awaits and asserts no _mcp_instructions in its result;
fails before. pytest posthog/test/mcp: 947 passed.
…th its call

Custom events captured during a call already waited for the call to settle
when it ran on a minted handle. Review found the wait leaked: the event kept
the caller's properties dict, so later mutation rewrote it; the buffer had no
bound; before_send ran after the tool's context managers exited, losing a
tool-local ContextVar (consent, redaction); and outside minted calls the
first custom event in a conversation went out anonymous, before identify
(Dustin's P1s and P2, posthog bot P2s, veria-ai's findings on this PR).

Every custom event captured during a call now waits for the call, so it goes
out with the call's own session and the identity identify resolved for it.
What is fixed at capture time: its top-level properties (copied), its
duration, and the context before_send runs in. Only the session is bound when
the call settles. A call holds at most 1,000 custom events; the rest are
dropped with one warning.

Tested: parameterized tests for properties reused across captures (anchored
and not), the bound, a before_send reading a ContextVar the tool reset, and
the first custom event's identity for a client id, an echoed handle and a
minted handle; all fail before except the rows that already held. pytest
posthog/test/mcp: 954 passed. ruff, public API snapshot clean; mypy unchanged.
…ns are fixed at capture

Deferring every in-call custom event until the call settles meant one
captured during a long tool was lost if the server flushed and shut down
first; before, a non-anchored call sent it at once. The capture-time snapshot
also missed event_options (process_person_profile), and a mapping that could
not be copied broke the tool (adversarial review of the previous commit).

analytics.flush() now settles every running call's custom events with the
session the call already knows (its client id or echoed handle, else the
primed one); later captures from that call go straight out. The snapshot
copies event_options' top level too, and an uncopyable mapping drops the
event with a log line.

Tested: a flush while a call runs (anchored and not), options changed after
capture with an identified caller, and an unreadable mapping; all fail
before. pytest posthog/test/mcp: 958 passed.
…capture

Review of the flush that settles running calls early found three gaps: the
early-settled custom events went out before identify ran, so anonymous; a
flush landing while a call recorded its outcome used the session known at
the call's start instead of its delivered handle; and a flush on another
thread racing a capture stranded the event in a list nothing settled.

An early settle now runs identify for the session it sends with. A call that
has started recording its outcome is left to that record. Deferral and
settlement share a lock, the event is copied before taking it, and a capture
that loses the race goes straight out with the settled session.

Tested: a flush mid-call keeps the call's identity, a flush while a call
records keeps its delivered handle's session, and a flush on another thread
racing a capture sends it once; all fail before. pytest posthog/test/mcp: 963
passed. ruff, public API snapshot clean; mypy unchanged.
Comment thread posthog/mcp/_instrumentation.py Resolved

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

The five earlier review threads (mixed-client MCP 1.x strict-output listings, deferred property mutation, first-conversation custom-event identity, deferred event bounding, and non-flushing overlap) are addressed for normal call completion, and the client conversation ID recognition, FNV-1a derivation, $mcp_session_source wire mapping, and PostHogMCP APIs align well with sdk-specs.

Verification reproduced two Breaking regressions introduced by the new early-flush path (ff5b17f / 7fc8fc88) and three Concern issues on both MCP 1.30.0 and MCP 2.3.0:

  • Early flush() ContextVar identity leak (Breaking): replied directly on the open @veria-ai thread (#discussion_r4672884007) with executed evidence for zero-custom-event $set/$groups leakage, anonymous-call takeover, and shutdown-flush anonymization.
  • Stateless HTTP header-based flush() poisoning data.session_id and splitting minted-handle sessions (Breaking): inline on posthog/mcp/_instrumentation.py.
  • Cancelled calls dropping known session/identity, flush() settle_early TOCTOU / missing exception guard, and handle-free ChatGPT calls sharing data.session_id when enable_conversation_id=False (Concern): inline below, along with two minor Suggestion items (posthog/mcp/README.md and posthog/mcp/asgi.py).
  • Follow-up (non-blocking, external repos): PostHog/posthog.com MCP Analytics docs (events.mdx, conversation-id.mdx, custom-events.mdx, installation/python.mdx) and PostHog/posthog (posthog/taxonomy/taxonomy.py) will need follow-up updates for client conversation IDs and $mcp_session_source.

AI-assisted review.

Comment thread posthog/mcp/_instrumentation.py Outdated
Comment on lines +654 to +662
async def settle_early() -> None:
session = known or primed
await handle_identify(
self.data, session.session_id, self.request, self.extra
)
self._settle_custom_events(session)

pending.settle_early = settle_early
self.data.calls_holding_custom_events.add(pending)

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: Even with ordinary HTTP-header identify (get_request_headers(extra), no ContextVar), a concurrent flush() on a shared stateless HTTP server poisons the shared data.session_id with an in-flight caller's identity and splits post-flush custom events from their minted-handle $mcp_tool_call.

Minimal trigger: Default enable_conversation_id=True + header-based identify. Alice (example-client/1.0, x-user: alice) enters a first-turn tool call (minted handle → known is None, request_session_id is None, so primed is the shared server-wide data.session_id). While Alice awaits, another request or hook calls await analytics.flush(). Alice then captures "alice_after_flush" and completes; afterwards, anonymous Carol calls tools/list.

Executed base (97b4e45d) vs head (7fc8fc88) on both MCP 1.30.0 and MCP 2.3.0:

  • On base 97b4e45d, Carol's $mcp_tools_list stayed anonymous (base never called handle_identify on data.session_id during flush()).
  • On head 7fc8fc88, both assertions fail on v1 and v2:
    • Session split: "alice_after_flush" lands on data.session_id ($mcp_session_source="generated") while Alice's $mcp_tool_call lands on her minted handle ($mcp_session_source="conversation"), because settle_early() locked pending.settled = primed even when pending.events was empty.
    • Shared-session poisoning: Carol's anonymous $mcp_tools_list is emitted with distinct_id='alice' and $set={'alice_only': True}, because settle_early() cached Alice's identity in data.identified_sessions[data.session_id].

This violates sdk-specs (795b69f) "Session identity" (lines 383–386) and "Person identity" (lines 541–550), and fixing ContextVar propagation in #discussion_r4672884007 alone will not fix it. Consider (1) returning early from settle_early() without marking pending.settled or running handle_identify() when pending.events is empty, and (2) when an HTTP minted-handle call does have buffered custom events to flush early, never writing that caller's identity into data.identified_sessions[data.session_id] (e.g., use a per-request isolated session or stamp the resolved identity directly on those early-settled events without mutating the shared session cache), plus a v1+v2 stateless HTTP regression test.

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.

Fixed in 60e836e, by removing the feature rather than patching it. Since this round's findings kept landing on flush() settling running calls, I weighed what that feature was buying. It let a flush send custom events from a call still running, so a server stopping mid-call wouldn't lose them. The cost was running identify and settlement outside the call's own context and thread, which is where this thread, veria-ai's ContextVar case and the settle_early race all came from.

So flush() no longer touches running calls. Custom events captured during a call go out when the call ends, with its own session and identity, just like the call's own $mcp_tool_call. A server that stops while a call runs loses both, and the README and changeset now say so.

Tested. test_a_flush_during_a_call_leaves_its_custom_events_to_the_call flushes mid-call and checks that the custom event still matches its call's session and identity. An adversarial review ran five overlapping callers (client id, echoed, minted, token, none) with header and ContextVar identify. It ran on the official FastMCP, standalone fastmcp and lowlevel adapters, with flush() looping on the same loop and on another thread. Every custom event matched its own call.

Comment thread posthog/mcp/_instrumentation.py Outdated
Comment on lines +666 to +672
def settle_left_over_custom_events(self, primed: ResolvedSession) -> None:
"""Adapters call this once the call is over. A call that ended without
recording anything (cancelled, or a path that records nothing) sends what
it held back with its primed session."""
if self.pending_custom_events.settled is None:
self._settle_custom_events(primed)

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: settle_left_over_custom_events() settles held-back custom events with bare primed instead of known or primed, dropping recognized client conversation IDs (ChatGPT/Codex/VS Code), echoed conversation_id handles, and their cached user identity when a call is cancelled (or has an empty tool name).

Observed on head 7fc8fc88 (executed on both MCP 1.30.0 and MCP 2.3.0):

  • Turn 1 identifies an echoed-handle or ChatGPT openai/session conversation as "alice". Turn 2 captures "inside_tool" and is cancelled (asyncio.CancelledError).
  • Actual: "inside_tool" is emitted with a generated session ($mcp_session_source="generated") and anonymous distinct_id instead of HANDLE_SESSION / CHATGPT_SESSION ("conversation" / "client_metadata") and distinct_id="alice". (Base 97b4e45d also fell back to data.session_id for echoed handles; for the new client conversation IDs and deferred in-tool binding, this violates sdk-specs (795b69f) lines 383–386 and diverges from settle_early() at line 655.)

Consider extracting def _known_session(self, primed: ResolvedSession) -> ResolvedSession using resolve_anchored_session(None if self.minted_conversation_id else self.conversation_id, self.client_conversation) or primed and calling it in both settle_early() and settle_left_over_custom_events(), with a regression test asserting $session_id, $mcp_session_source, and cached distinct_id on cancelled calls.

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.

Fixed in 60e836e and f84fefb.

  • Session. A call that records nothing (cancelled, empty tool name) settles its held events with its client conversation id or echoed handle session when it has one. Otherwise it uses the primed session, since a minted handle counts only once delivered.
  • Identity. A review then found those events were still anonymous, because recording is what runs identify. So f84fefb runs identify first, in a task of its own, which lets a cancelled call do it, and keeps the call's context.

Tested. test_a_call_that_records_nothing_sends_its_custom_events_with_its_conversation covers a client id and an echoed handle. It asserts $session_id, $mcp_session_source and distinct_id, with no earlier call to warm the identity, and fails before.

Comment thread posthog/mcp/__init__.py Outdated
Comment on lines 206 to 209
for pending in list(data.calls_holding_custom_events):
if pending.settle_early is not None:
await pending.settle_early()
await drain_pending(data)

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: Because commit 7fc8fc88 explicitly supports cross-thread flush() (session.py:71), reading pending.settle_early twice here creates a TOCTOU race and has no exception guard before drain_pending(data):

for pending in list(data.calls_holding_custom_events):
    if pending.settle_early is not None:
        await pending.settle_early()  # TypeError if tool thread sets settle_early = None here
await drain_pending(data)             # skipped if settle_early() raises

Exercising the two-bytecode clearing window deterministically raises TypeError: 'NoneType' object is not callable at posthog/mcp/__init__.py:208 on both MCP 1.30.0 and MCP 2.3.0, aborting flush() before drain_pending(data). (Under CPython 3.12's GIL, 5,000 iterations of concurrent add/discard vs list(data.calls_holding_custom_events) did not raise RuntimeError, though guarding calls_holding_custom_events with a threading.Lock matches PendingCustomEvents.lock / _tasks_lock and keeps free-threaded Python 3.13t/3.14t safe.)

Consider binding settle_early = pending.settle_early once to a local variable, wrapping await settle_early() in try/except Exception (logging and continuing so drain_pending(data) always runs), and guarding data.calls_holding_custom_events with a threading.Lock.

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.

Fixed in 60e836e: settle_early is gone, along with the cross-thread flush settlement it supported (see the thread on line 662). The lock in PendingCustomEvents stays for a tool's own threads capturing while its call settles. A review ran 300 captures from a tool thread across settlement on every adapter, and all arrived with the call's session and identity.

Comment on lines +874 to +881
request_session_id = (
new_session_id()
if (client_conversation is not None or (minted and handle_free))
and not carries_session
and get_request(extra) is not None
and not _is_sse_request(extra)
else 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: Gating request_session_id on (minted and handle_free) causes handle-free (ChatGPT) sessionless HTTP calls without a usable openai/session to fall back to the shared process data.session_id whenever enable_conversation_id=False (the exact setup in PostHog/posthog#119784) or whenever a tool declares its own conversation_id parameter.

Executed on head 7fc8fc88 (both MCP 1.30.0 and MCP 2.3.0): With enable_conversation_id=False and header-based identify, two ChatGPT calls from Alice and Bob without openai/session share $session_id (ses_01a20acb-...) and Bob inherits Alice's $set properties via merge_identities(). (This also failed on base 97b4e45d, so it is pre-existing rather than a regression, but it diverges from sdk-specs (795b69f) "Session identity" Rule 4 and posthog-js (f05a993) packages/mcp/src/extensions/session.ts:192, which checks !carriedSessionId && client?.row?.handleFree && getRequestHeaders(extra) without requiring minted.)

Changing (minted and handle_free) to handle_free only affects handle-free clients and leaves test_a_route_without_the_middleware_keeps_the_fallback (non-ChatGPT client) untouched. Consider aligning with posthog-js / sdk-specs Rule 4 and adding a test asserting distinct $session_id, $mcp_session_source == "generated", and isolated $set when enable_conversation_id=False.

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.

Fixed in b3edcb1. A handle-free client's sessionless HTTP call now gets a fresh request session whether or not a handle was minted, matching posthog-js and spec rule 4. Calls with anchoring off, or with a tool that owns conversation_id, no longer share the process session.

A review pointed out the upgrade cost: these ChatGPT calls stopped tripping the "PostHogMcpStatelessSessionMiddleware never attached" warning, which names the fix. f84fefb makes the warning fire for these per-request sessions too, and the changeset describes the change.

Tested. test_sessionless_http_calls_without_a_client_id_get_their_own_sessions now runs with anchoring on and off, and asserts distinct sessions, an isolated $set and the warning. The off rows fail before.

Comment thread posthog/mcp/README.md Outdated
Comment on lines +51 to +52
`$mcp_session_source`: `client_metadata`, `conversation`, `transport`, or `generated`. Custom events
from `McpAnalytics.capture()` carry the instance's own source. The rules are the sdk-specs "Session

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: This sentence became stale after commits 4b103b5 and cd5fb1d bound in-tool McpAnalytics.capture() to the active tool call's settled session and source (_instrumentation.py:684-685). Consider updating it to:

Custom events from McpAnalytics.capture() called inside a tool handler carry that call's session and $mcp_session_source; calls outside a tool handler carry the instance's own session and source.

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.

Updated in 60e836e. The README now says custom events from McpAnalytics.capture() inside a tool call carry that call's session, source and identity, and are sent when the call ends, like the call's own event. Outside a tool they carry the instance's own session and source.

Comment thread posthog/mcp/asgi.py
Comment on lines +54 to +58
from .session import ( # noqa: F401 - handshake_session_id is public API
handshake_session,
handshake_session_id,
new_session_id,
)

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: Importing handshake_session without a leading underscore here causes references/public_api_snapshot.txt:363 to export posthog.mcp.asgi.handshake_session as public API, even though neither handshake_session nor its ResolvedSession return type is in session.__all__ (SDK guidelines: "Design APIs for forward compatibility" — avoid accidentally expanding public API).

Consider importing handshake_session as _handshake_session (keeping handshake_session_id as-is for backwards compatibility) and regenerating references/public_api_snapshot.txt.

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.

Done in 761c508: imported as _handshake_session, with handshake_session_id still public. The public API snapshot is regenerated and no longer lists posthog.mcp.asgi.handshake_session.

@dustinbyrne
dustinbyrne requested a review from a team November 23, 2026 23:53
…n with anchoring off

A ChatGPT call with no usable openai/session got a fresh request session only
when a handle was minted for it. With enable_conversation_id off (the setup of
PostHog/posthog#119784), or a tool that owns its conversation_id, it fell back
to the shared process session, so two callers shared one $session_id and Bob
inherited Alice's $set (Dustin's finding; it predates this PR). posthog-js and
sdk-specs rule 4 give it a fresh session whenever the client is handle-free.

Tested: the sessionless ChatGPT test now runs with anchoring on and off; the
off rows fail before.
…that records nothing keeps its conversation

Letting analytics.flush() settle running calls caused round 7's findings: it
ran identify outside the call's own context, so a ContextVar identity read the
flusher's and a concurrent flush on a shared stateless server cached one
caller's identity on the shared session; and reading settle_early twice raced
under a cross-thread flush (Dustin's and veria-ai's findings). Separately, a
cancelled call settled its held events with its primed session, dropping a
client conversation id or echoed handle and its identity.

flush() no longer settles running calls. Custom events captured during a call
go out when it ends, like the call's own event; a server that stops while a
call runs loses both, which the README now says. A call that records nothing
settles with its client id or echoed handle when it has one, else its primed
session. The README sentence on custom-event sessions is updated.

Tested: a cancelled call with a client id or an echoed handle keeps that
session, its source and identity (fails before); a flush during a call leaves
its custom events to the call. The flush-settle tests are removed with the
feature. pytest posthog/test/mcp: 962 passed.
asgi.py imported handshake_session without an underscore, so the public API
snapshot exported posthog.mcp.asgi.handshake_session though session.__all__
does not (Dustin's suggestion). It is now imported as _handshake_session;
handshake_session_id stays public.

Tested: check_public_api.py --write drops the alias; the check passes.
…nts, and the middleware warning covers ChatGPT

Review of the previous commits found that a call that recorded nothing
(cancelled, empty tool name) sent its held custom events in the right session
but anonymous, since recording is what runs identify. And a ChatGPT call with
no usable openai/session now gets a per-request session, which no longer
tripped the "middleware never attached" warning that names the fix.

Settling left-over events now runs identify first, in a task of its own so a
cancelled call can still do it, with the call's context. The warning also
fires for those per-request sessions. The changeset now covers custom events
going out with their call, not on flush(), and the ChatGPT session change.

Tested: the record-nothing test no longer warms the session with an earlier
identified call (fails before); the sessionless ChatGPT test asserts the
warning (fails before). pytest posthog/test/mcp: 962 passed.

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

The earlier 7fc8fc88 threads (removing settle_early from flush(), handling ChatGPT with enable_conversation_id=False, updating posthog/mcp/README.md, and keeping handshake_session out of posthog.mcp.asgi's public exports) are addressed.

Three verified Breaking regressions remain on f84fefb0, each reproduced with like-for-like base (97b4e45d) vs head (f84fefb0) HTTP tests on both MCP SDK v1 (1.30.0) and v2 (2.3.0):

  1. resolve_session_id_with_source() still mutates shared data.session_id / data.session_source (posthog/mcp/session.py:335–336): leaks a ChatGPT caller's identity and $set properties onto subsequent out-of-tool McpAnalytics.capture() calls under default enable_conversation_id=True, and clobbers sticky "mcp" sessions.
  2. settle_left_over_custom_events() invokes identify() spuriously on zero-event cancelled/empty-name calls and duplicates identify() when cancelled during recording (posthog/mcp/_instrumentation.py:664–668): also causes test_a_cancelled_call_still_sends_its_custom_event[while the call records] to sleep 10.01s inside analytics.flush().
  3. McpAnalytics.flush() returns before identify_then_settle()'s spawned custom-event captures finish when both identify and before_send are async (posthog/mcp/_instrumentation.py:669–675): can drop custom events on the documented await analytics.flush(); posthog.shutdown() exit path.

Details, executed base/head evidence, and regression tests are inline, along with two optional Suggestion items (PostHogMCP.prepare_tool_list docstring and derive_session_id_from_client_conversation export visibility).

Non-blocking cross-repo follow-ups (outside this PR):

  • PostHog/posthog.com: update contents/docs/mcp-analytics/{events,conversation-id,custom-events,installation/python}.mdx for client conversation IDs, $mcp_session_source, ChatGPT handle-free behavior, Python custom-event deferral, and the new PostHogMCP parameters.
  • PostHog/posthog: register $mcp_session_source in posthog/taxonomy/taxonomy.py.

AI-assisted review.

Comment thread posthog/mcp/session.py
Comment on lines +332 to +336
if request_session_id:
# Stored only so an in-tool custom event lands in this request's
# session. No later request reuses a "request" session.
data.session_id = request_session_id
data.session_source = "request"

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: resolve_session_id_with_source() persists the per-request request_session_id onto shared data.session_id and data.session_source = "request", leaking a ChatGPT caller's session and identity to subsequent out-of-tool McpAnalytics.capture() calls and clobbering sticky "mcp" sessions.

Why this matters: On a shared stateless HTTP server with default enable_conversation_id=True and identify=..., when Alice calls a tool from ChatGPT without a usable openai/session, resolve_session_id_with_source() writes Alice's single-request request_session_id into shared data.session_id and handle_identify() caches Alice's UserIdentity under that ID. Any subsequent out-of-tool await analytics.capture("server_heartbeat") (e.g., background job, lifecycle hook, webhook) reads current_session(data) → data.session_id and is emitted with Alice's single-request $session_id, distinct_id="alice", and Alice's $set properties. Additionally, overwriting data.session_source = "request" defeats the sticky "mcp" check at line 341 (if data.session_source == "mcp" and data.last_mcp_session_id:), fragmenting subsequent headerless requests (even when a ChatGPT/Codex/VS Code call does carry a client conversation ID, because prime_session() still passes request_session_id without client_conversation).

The inline comment (# Stored only so an in-tool custom event lands in this request's session) became obsolete once bind_in_tool_session() (session.py:123–146) bound primed in _in_tool_session (which addressed #discussion_r4556322336); no in-tool path reads data.session_id anymore.

Governing contract & peer parity:

  • sdk-specs (6cf0374b, openspec/specs/mcp-analytics/spec.md, "Session identity", lines 387–388): "A custom event captured outside any call carries the session the server instance last held, which is never one a session resolver, a client conversation id, or a handle produced."
  • posthog-js (9d286015, packages/mcp/src/extensions/session.ts:192–194) returns { sessionId: newSessionId(), source: 'generated' } without mutating data.sessionId or data.sessionSource.

Executed base (97b4e45d) vs head (f84fefb0) evidence (Python 3.11.13, pytest==9.2.0, real HTTP ASGI transport):

  • enable_conversation_id=True (default), ChatGPT call as alice followed by out-of-tool await analytics.capture("server_heartbeat"):
    • Base v1 (mcp 1.30.0) & Base v2 (mcp 2.3.0): PASSED — server_heartbeat uses the server's own anonymous session ($set absent, distinct from the tool call's minted-handle session).
    • Head v1 (mcp 1.30.0) & Head v2 (mcp 2.3.0): FAILED (assert 'alice' != 'alice') — server_heartbeat shares Alice's single-request $session_id, distinct_id="alice", and $set={"alice_only": "present"}.
  • enable_conversation_id=False: fails on both base (pre-existing shared process session) and head (lines 335–336 still overwrite shared data.session_id despite b3edcb1's per-request session isolation for #discussion_r4673627641).
  • Sticky "mcp" session unit check (head-only API request_session_id): FAILED on both v1 and v2 — after a request_session_id call, a headerless resolve_session_id_with_source(data, None) rotates to "generated" instead of keeping "mcp".

Consider returning ResolvedSession(request_session_id, "request") without mutating shared data:

if request_session_id:
    return ResolvedSession(request_session_id, "request")

and adding regression coverage in posthog/test/mcp/test_client_conversation_session.py:

async def test_out_of_tool_capture_does_not_leak_chatgpt_request_identity():
    client = FakeClient()
    server = FastMCP("t", stateless_http=True, json_response=True)

    @server.tool()
    def add(a: int, b: int) -> int:
        return a + b

    def identify(request, extra):
        user = (get_request_headers(extra) or {}).get("x-user")
        if not user:
            return None
        return UserIdentity(distinct_id=user, properties={f"{user}_only": "present"})

    analytics = instrument(
        server,
        client,
        MCPAnalyticsOptions(enable_conversation_id=True, identify=identify),
    )
    app = server.streamable_http_app()
    async with server.session_manager.run():
        async with httpx.AsyncClient(
            transport=httpx.ASGITransport(app=app), base_url="http://127.0.0.1:8000"
        ) as http:
            resp = await http.post(
                "/mcp",
                json={
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "tools/call",
                    "params": {"name": "add", "arguments": {"a": 1, "b": 2}},
                },
                headers={
                    "accept": "application/json, text/event-stream",
                    "content-type": "application/json",
                    "mcp-protocol-version": "2025-06-18",
                    "user-agent": "openai-mcp/1.0.0 (ChatGPT)",
                    "x-user": "alice",
                },
            )
            assert resp.status_code == 200
    await analytics.flush()
    await flush_background()

    await analytics.capture("server_heartbeat")
    await analytics.flush()
    await flush_background()

    (call,) = events_named(client, "$mcp_tool_call")
    (heartbeat,) = events_named(client, "server_heartbeat")
    assert heartbeat["distinct_id"] != "alice"
    assert "alice_only" not in (heartbeat["properties"].get("$set") or {})
    assert heartbeat["properties"]["$session_id"] != call["properties"]["$session_id"]


async def test_request_session_does_not_clobber_sticky_mcp_session():
    data = MCPAnalyticsData(options=MCPAnalyticsOptions(), session_id="ses_init")
    mcp_session = await resolve_session_id_with_source(data, "mcp-1")
    assert mcp_session.source == "mcp"

    req_session = await resolve_session_id_with_source(
        data, None, request_session_id="ses_one_request"
    )
    assert req_session == ("ses_one_request", "request")

    after = await resolve_session_id_with_source(data, None)
    assert after == mcp_session

Comment on lines +664 to +668
pending = self.pending_custom_events
fallback = pending.fallback
if pending.settled is not None or fallback is None:
return

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: settle_left_over_custom_events() invokes identify() in a background task on cancelled or empty-tool-name calls with zero custom events, and re-invokes identify() a second time when a call is cancelled while recording (introduced in f84fefb0 while addressing #discussion_r4673627625).

Why this matters:

  1. Spurious identify() on zero-event calls: When a normal tool call that never called analytics.capture() is cancelled (client disconnect, timeout, shutdown) — or when tools/call arrives with name="" (record_if_unknown_tool returns True without settling pending) — finally: lifecycle.settle_left_over_custom_events() spawns identify_then_settle() and runs the host's identify(request, extra) callback even though zero events exist to emit. That runs host auth/DB/network logic after request teardown, populates identified_sessions, and delays analytics.flush().
  2. Duplicate identify() when cancelled during recording: record_result() and record_error() await prepare_session() (which runs handle_identify()) before calling _settle_custom_events(). If the call is cancelled while identify() is awaiting (e.g., a slow/hung callback timed out by the server), pending.settled is still None, so finally: launches handle_identify() a second time in _BACKGROUND_TASKS. This is already happening in test_a_cancelled_call_still_sends_its_custom_event[while the call records] (posthog/test/mcp/test_minted_handle_custom_events.py:30–66), which invokes identify() twice and stalls for 10.01s inside await analytics[0].flush() (measured via pytest --durations=5).

Governing contract: Merge base (97b4e45d) never invoked identify() on zero-event cancelled/empty-name calls and never re-ran a cancelled identify(). sdk-specs (6cf0374b, "Optional events") specifies that a call naming no tool emits nothing.

Executed base (97b4e45d) vs head (f84fefb0) evidence (Python 3.11.13, pytest==9.2.0, real HTTP ASGI transport on both mcp 1.30.0 and mcp 2.3.0):

  • Cancelled tool call with zero custom events: Base v1 & v2 PASSED (identify_calls == 0) → Head v1 & v2 FAILED (identify_calls == 1).
  • Empty tool name "" with zero custom events: Base v1 & v2 PASSED (identify_calls == 0) → Head v1 & v2 FAILED (identify_calls == 1).
  • Cancelled while awaiting identify() inside record_result: Base v1 & v2 PASSED (identify_calls == 1) → Head v1 & v2 FAILED (identify_calls == 2).

Consider:

  1. Adding a lock-protected settle_if_empty(fallback) -> bool on PendingCustomEvents (under self.lock: if self.settled is not None return True; if not self.events, set self.settled = fallback and return True; else False) and returning early in settle_left_over_custom_events() when no events were buffered.
  2. Tracking identify_attempted: bool = False on PendingCustomEvents (set right before prepare_session invokes prepare_request → handle_identify), so if recording already entered identify(), settle_left_over_custom_events() settles directly without re-running handle_identify().
  3. Adding regression tests for all three cases in posthog/test/mcp/test_minted_handle_custom_events.py (and replacing the 10s sleep in test_a_cancelled_call_still_sends_its_custom_event with an asyncio.Event plus assert identify_calls == 1):
async def test_cancelled_call_without_custom_events_does_not_call_identify():
    client = FakeClient()
    server = FastMCP("t")
    entered = asyncio.Event()
    identify_calls = 0

    async def identify(request, extra):
        nonlocal identify_calls
        identify_calls += 1
        return UserIdentity(distinct_id="u1")

    @server.tool()
    async def slow() -> str:
        entered.set()
        await asyncio.sleep(10)
        return "ok"

    analytics = instrument(server, client, MCPAnalyticsOptions(identify=identify))
    task = asyncio.create_task(
        server._tool_manager.call_tool(
            "slow", {}, context=server.get_context(), convert_result=True
        )
    )
    await entered.wait()
    task.cancel()
    with pytest.raises(asyncio.CancelledError):
        await task
    await analytics.flush()
    await flush_background()

    assert identify_calls == 0


async def test_empty_tool_name_without_custom_events_does_not_call_identify():
    client = FakeClient()
    server = FastMCP("t")
    identify_calls = 0

    async def identify(request, extra):
        nonlocal identify_calls
        identify_calls += 1
        return UserIdentity(distinct_id="u1")

    @server.tool()
    async def add(a: int, b: int) -> int:
        return a + b

    analytics = instrument(server, client, MCPAnalyticsOptions(identify=identify))
    with pytest.raises(Exception):
        await server._tool_manager.call_tool(
            "", {}, context=server.get_context(), convert_result=True
        )
    await analytics.flush()
    await flush_background()

    assert identify_calls == 0


async def test_cancelled_during_identify_does_not_reinvoke_identify():
    client = FakeClient()
    server = FastMCP("t")
    in_identify = asyncio.Event()
    identify_calls = 0

    async def identify(request, extra):
        nonlocal identify_calls
        identify_calls += 1
        in_identify.set()
        await asyncio.sleep(10 if identify_calls == 1 else 0.01)
        return UserIdentity(distinct_id="u1")

    @server.tool()
    async def quick() -> str:
        await analytics.capture("inside_tool")
        return "ok"

    analytics = instrument(server, client, MCPAnalyticsOptions(identify=identify))
    task = asyncio.create_task(
        server._tool_manager.call_tool(
            "quick", {}, context=server.get_context(), convert_result=True
        )
    )
    await in_identify.wait()
    task.cancel()
    with pytest.raises(asyncio.CancelledError):
        await task
    await analytics.flush()
    await flush_background()

    assert identify_calls == 1

Comment on lines +669 to +675
async def identify_then_settle() -> None:
await handle_identify(
self.data, fallback.session_id, self.request, self.extra
)
self._settle_custom_events(fallback)

fire_and_forget(identify_then_settle(), self.data)

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: McpAnalytics.flush() returns before identify_then_settle()'s spawned custom-event captures finish when both identify and before_send are async, dropping custom events on the documented await analytics.flush(); posthog.shutdown() shutdown path (introduced in f84fefb0 while addressing #discussion_r4673627625).

Why this happens (two-stage background task chain):

  1. settle_left_over_custom_events() registers Task A (identify_then_settle()) in _BACKGROUND_TASKS via fire_and_forget().
  2. Task A suspends inside await handle_identify(...) (async identify).
  3. await analytics.flush() calls drain_pending(data) (_instrumentation.py:198–212), which takes a single snapshot of _BACKGROUND_TASKS ([Task A]) and awaits asyncio.gather(Task A).
  4. Task A finishes handle_identify(), calls self._settle_custom_events(fallback) → context.run(fire_and_forget, capture, self.data) (registering Task B in _BACKGROUND_TASKS), and returns immediately without awaiting Task B.
  5. Task B hits await before_send(capture) (_sink.py:79) and suspends; drain_pending() returns immediately with self._posthog.capture(...) still unexecuted.

Governing contract: McpAnalytics.flush() (posthog/mcp/__init__.py:200–203) documents: "Await this server's in-flight auto-captures on the current event loop. Call this before posthog.shutdown() on exit so trailing tool-call events aren't dropped." Async before_send hooks are supported (posthog/mcp/types.py:86–91) and covered by test_fastmcp.py:test_analytics_flush_drains_its_own_captures. test_minted_handle_custom_events.py:63–64 masked this by calling the test-only 10-pass await flush_background() after await analytics[0].flush() and not configuring an async before_send.

Executed base (97b4e45d) vs head (f84fefb0) evidence (Python 3.11.13, pytest==9.2.0, real HTTP ASGI transport on both mcp 1.30.0 and mcp 2.3.0):

  • Cancelled tool call with async identify + async before_send, asserting immediately after await analytics.flush() (no flush_background()):
    • Base v1 (mcp 1.30.0) & Base v2 (mcp 2.3.0): PASSED (count == 1).
    • Head v1 (mcp 1.30.0) & Head v2 (mcp 2.3.0): FAILED (count == 0 — analytics.flush() returned before inside_tool finished before_send).
  • Controls (executed on both v1 & v2): non-cancelled calls (normal-control) and identify=None + async before_send pass on both base and head (confirming Task A must suspend before _settle_custom_events for drain_pending to snapshot before Task B is registered).

Consider having fire_and_forget() return the scheduled task/future (or None) and _settle_custom_events() return its scheduled asyncio.Tasks so identify_then_settle() awaits asyncio.gather(*tasks, return_exceptions=True) before completing. That keeps Task A alive in _BACKGROUND_TASKS until its settled captures finish without looping drain_pending() under live traffic. Consider also adding this regression test to posthog/test/mcp/test_minted_handle_custom_events.py (calling await analytics.flush() alone):

async def test_flush_drains_cancelled_call_custom_event_with_async_identify_and_before_send():
    client = FakeClient()
    server = FastMCP("t")
    analytics: list[McpAnalytics] = []
    reached = asyncio.Event()

    async def slow_before_send(event):
        await asyncio.sleep(0.05)
        return event

    async def async_identify(request, extra):
        await asyncio.sleep(0.01)
        return UserIdentity(distinct_id="u1")

    @server.tool()
    async def slow() -> str:
        await analytics[0].capture("inside_tool")
        reached.set()
        await asyncio.sleep(10)
        return "ok"

    analytics.append(
        instrument(
            server,
            client,
            MCPAnalyticsOptions(
                enable_conversation_id=True,
                identify=async_identify,
                before_send=slow_before_send,
            ),
        )
    )
    task = asyncio.create_task(
        server._tool_manager.call_tool(
            "slow", {}, context=server.get_context(), convert_result=True
        )
    )
    await reached.wait()
    task.cancel()
    with pytest.raises(asyncio.CancelledError):
        await task

    await analytics[0].flush()
    assert len(events_named(client, "inside_tool")) == 1

context: Union[bool, MCPAnalyticsContextOptions] = True,
report_missing: bool = False,
collect_feedback: bool = False,
headers: Any = 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.

Suggestion: PostHogMCP.prepare_tool_call (lines 640–645) and PostHogMCP.capture_tool_call (lines 233–236) both document their newly added headers / client_info / request_meta parameters in their docstrings, while prepare_tool_list's docstring (lines 492–517) does not mention the new headers parameter (SDK guidelines: "Treat docs and examples as part of the SDK" — Python docstrings feed IDE tooltips and generated SDK reference docs).

Consider adding a short note to prepare_tool_list's docstring explaining that passing the listing request's HTTP headers keeps handle-free clients (such as ChatGPT) free of conversation_id and _mcp_instructions.

Comment thread posthog/mcp/session.py
__all__ = [
"derive_session_id_from_mcp_session",
"derive_session_id_from_conversation",
"derive_session_id_from_client_conversation",

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: derive_session_id_from_client_conversation is added to posthog.mcp.session.__all__ (expanding references/public_api_snapshot.txt:1640), even though it is not re-exported in posthog.mcp.__all__ (unlike derive_session_id_from_mcp_session and derive_session_id_from_conversation), PostHogMCP methods now derive client-conversation sessions internally from headers/client_info/request_meta, and peer posthog-js (packages/mcp/src/index.ts) keeps deriveSessionIdFromClientConversation internal (SDK guidelines: "Design APIs for forward compatibility").

Consider either removing derive_session_id_from_client_conversation from posthog.mcp.session.__all__ (and regenerating references/public_api_snapshot.txt) if it is internal-only, or re-exporting it from posthog.mcp.__init__ if direct caller use is an intended public contract.

@dustinbyrne
dustinbyrne requested a review from a team November 25, 2026 00:02

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

Note

🤖 Automated comment by QA Swarm — not written by a human

QA Swarm review complete. See the inline comments and the summary comment.

Comment thread posthog/mcp/session.py
if request_session_id:
# Stored only so an in-tool custom event lands in this request's
# session. No later request reuses a "request" session.
data.session_id = request_session_id

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.

Note

🤖 Automated comment by QA Swarm — not written by a human

[convergent: code-review + engineering-systems-thinking] 🟡 MEDIUM

The request_session_id branch writes a temporary session for one request into the shared data.session_id and data.session_source = "request". Line 349 starts a new session when the source is not "generated". On a shared HTTP instance, a sessionless ChatGPT call therefore starts a new fallback session for all other clients. It also removes the "mcp" session that stays the same (lines 341–343). A capture() outside a tool then gets the ChatGPT request's id, which no other event uses. main does not have this branch.

The write is not necessary, because each adapter already holds the call's session through in_tool and bind_in_tool_session. The comment at line 333 is out of date.

Suggested fix: return ResolvedSession(request_session_id, "request") and do not change data. Add a test: a sessionless non-ChatGPT call, then a sessionless ChatGPT call, then a sessionless non-ChatGPT call and a capture outside a tool.

tool
# The framework validates the next result against the latest listing, so
# a listing that declares nothing turns mirroring off until one declares.
data.tool_output_instructions[tool.name] = (

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.

Note

🤖 Automated comment by QA Swarm — not written by a human

[convergent: code-review + router + engineering-systems-thinking + security-audit/integrity] 🟡 MEDIUM

All clients share tool_output_instructions[name], and the last listing sets it. After one ChatGPT tools/list, the SDK stops copying the handle into structuredContent for all other clients' calls. This continues until a non-ChatGPT client lists again. Clients that read only structuredContent then lose the handle, and their sessions break up. main always copied it.

On mcp 1.x, setting it to False is required, because the SDK checks results against a tool cache that all clients share. test_a_chatgpt_listing_keeps_an_ordinary_strict_result_valid shows that the result stays valid, but it does not check that the handle copy is present. A spoofed ChatGPT User-Agent can also cause this.

Suggested fix: always declare the optional _mcp_instructions output property, which does not change anything for ChatGPT. Control only the input conversation_id for each client. mirrors_output_instructions already excludes handle-free calls.

)
request = params_to_request_dict(_LIST_METHOD, params, by_alias=True)
extra: Dict[str, Any] = {"session_id": mcp_session_id, "ctx": ctx}
advertise_conversation_id = lists_conversation_id(extra, client_name)

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.

Note

🤖 Automated comment by QA Swarm — not written by a human

[engineering-systems-thinking] 🟢 LOW

Part of the tool_output_instructions finding. The PR description says "the internal tool-cache pass still injects". This is true for lowlevel and FastMCP, but not for v2. Here, the internal tools/list dispatch gets advertise_conversation_id from the User-Agent of the tools/call that started it. So each ChatGPT call on the 2026-07-28 path turns off handle copying for all tools.

Suggested fix: use advertise=True for the internal dispatch, as the other adapters do. Add a test for two eras: a ChatGPT call, then a non-ChatGPT call that checks that _mcp_instructions is copied.

Comment thread posthog/mcp/session.py
self.dropped += 1
if self.dropped == 1:
log(
f"Warning: a tool call captured more than {MAX_DEFERRED_CUSTOM_EVENTS} "

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.

Note

🤖 Automated comment by QA Swarm — not written by a human

[code-review + engineering-systems-thinking] 🟡 MEDIUM

After 1000 deferred events in one call, the SDK drops all other events. It logs only one line, and capture() still returns as if it worked. main sent each event immediately, with no limit. A long batch tool that sends one event per item loses data with no error.

Suggested fix: when the call reaches the limit, send the events that it holds with the session it has now and send the rest immediately. Or make the limit configurable. Add a test.

Comment thread posthog/mcp/session.py
try:
snapshot = {
**event_input,
"properties": _top_level_copy(event_input.get("properties")),

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.

Note

🤖 Automated comment by QA Swarm — not written by a human

[code-review + engineering-systems-thinking] 🟢 LOW

defer() copies only the top level of properties and event_options. If a tool changes a nested value after capture(), the event has the new value:

props = {"items": items}
await analytics.capture("x", props)
items.append(y)  # the deferred event is sent with y

This is a regression, because main sent each event immediately.

Suggested fix: use copy.deepcopy and, if it fails, use the top-level copy.

return

async def identify_then_settle() -> None:
await handle_identify(

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.

Note

🤖 Automated comment by QA Swarm — not written by a human

[router + engineering-systems-thinking] 🟢 LOW

identify_then_settle waits for the host's identify callback, and there is no timeout. If identify hangs, the events of a cancelled call wait forever. drain_pending uses asyncio.gather with no timeout, so McpAnalytics.flush() also hangs. The hang in flush() is new.

Suggested fix: put asyncio.wait_for around identify, or send the events after a timeout. Add a test with an identify that hangs.

original_tool,
session_id,
recognize_manual_client(
headers, request_meta, (client_info or {}).get("name")

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.

Note

🤖 Automated comment by QA Swarm — not written by a human

[code-review + engineering-systems-thinking] 🟢 LOW

(client_info or {}).get("name") works only with a Mapping. The docstring says the value is the initialize clientInfo. An mcp-SDK host holds that value as a types.Implementation model (for example session.client_params.clientInfo), which has no .get, so this causes an AttributeError in prepare_tool_call. The tests pass only dicts.

Suggested fix: use .get for a Mapping, and getattr(client_info, "name", None) for other types. Add a test with mcp.types.Implementation.

vendor_client,
)
client_conversation = read_client_conversation(
recognize_client(client_user_agent, meta_client_name(request_meta)),

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.

Note

🤖 Automated comment by QA Swarm — not written by a human

[code-review + engineering-systems-thinking] 🟢 LOW

capture_tool_call recognizes a client only from the user agent and the _meta clientInfo. Assume a Codex or VS Code client that prepare_tool_call recognized only from the handshake client_info. That client gets the correct session id, but no $mcp_session_source. So prepare and capture do not agree.

Suggested fix: keep the resolved source on PreparedToolCall, or accept client_info in capture_tool_call.

previous.output_instructions and current.output_instructions,
)
if not advertise:
self._conversation_ownership.update(ownership)

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.

Note

🤖 Automated comment by QA Swarm — not written by a human

[code-review + engineering-systems-thinking] 🟢 LOW

(Plausible, not reproduced.) A listing that does not advertise records ownership from what the SDK can inject (can_inject/can_declare), not from what it actually injects. Assume ChatGPT lists first and one tool's output schema copy fails. A later non-ChatGPT prepare_tool_call with no original_tool then copies _mcp_instructions into a schema that never declared it. This fails with additionalProperties: false. A later advertising listing corrects the state.

Suggested fix: on a listing that does not advertise, do not create new True entries.

@posthog

posthog Bot commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Note

🤖 Automated comment by QA Swarm — not written by a human

Multi-perspective review: router (cheap-first pass) + delegated lenses (engineering-systems-thinking, security-audit), merged with a separate /code-review pass

Verdict: 💬 APPROVE WITH NITS (round 1 @ f84fefb)

There are 0 HIGH and 3 MEDIUM findings. The core design is sound: each call holds its own session in a context variable, custom events wait until the call has its session, and the recognition rules match posthog-js row for row. The main problem is that two places write one client's data into state that all clients on the server share.

Key findings

🟡 MEDIUM

  • session.py:335: the per-request session is written to the shared data. A sessionless ChatGPT call starts a new fallback session for other clients, and a capture() outside a tool gets an id that no other event uses.
  • _instrumentation.py:1415: tool_output_instructions is shared, and the last listing sets it. After a ChatGPT listing (or, on v2, any ChatGPT call through the internal dispatch at _instrument_v2.py:822), other clients lose the handle copy in structuredContent.
  • session.py:99: after 1000 deferred events in one call, the SDK drops all other events with only one log line.

🟢 LOW

  • session.py:84: only the top level is copied, so nested changes after capture() go into the event.
  • _instrumentation.py:670: a hanging identify holds the events forever and makes flush() hang.
  • posthog_mcp.py:664: a client_info that is an mcp.types.Implementation causes an AttributeError.
  • posthog_mcp.py:255: capture_tool_call cannot recognize a client from the handshake only, so $mcp_session_source is missing.
  • posthog_mcp.py:999 (plausible): a listing that does not advertise records ownership from what the SDK can inject, not from what it injects.

Notes (no inline comment)

  • capture() inside a tool now sends the event later, so await analytics.flush() in a tool does not send it. The changeset gives this information. Please also state it clearly in the changelog or README.
  • Small efficiency issues: on a tool call that the client groups itself, record_missing_capability/record_feedback take the session lock two times, and touch_connection_session takes it one more time. advertises_conversation_id runs the User-Agent regex two times for each listing.
  • Security: nothing exploitable. A spoofed User-Agent or client name changes only the caller's own telemetry. The regexes are linear. The session hash has no salt, so a known conversation id can be joined in the same project. This is LOW.
  • Test gaps: a mix of ChatGPT and other sessionless calls, the handle copy after a ChatGPT listing, v2 internal dispatch during a ChatGPT call, a hanging identify, the event limit, and nested changes.

Convergence

  • session.py:335 (shared write of the request session): code-review + engineering-systems-thinking. One reviewer reproduced it by calling resolve_session_id_with_source directly.
  • _instrumentation.py:1415 (shared output-instruction flag): code-review + router + engineering-systems-thinking + security-audit.

Reviewer summaries

Reviewer Assessment
🧭 router No HIGH or CRITICAL findings. Precedence and race handling are sound. Danger HIGH (large diff, session state, concurrency), so it delegated the session and listing state, and the recognition security.
🧠 engineering-systems-thinking Checked 8 hypotheses and refuted none. Root cause: per-client variation written into state that the whole server shares.
🔒 security-audit No exploitable issues. Two LOW integrity notes.
🔍 code-review Found the shared request-session write, the client_info type, the shallow copy, the event limit, the capture/prepare mismatch and some efficiency issues.

The tests were not run as part of this review.


Automated by QA Swarm — not a human review

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.

2 participants