Skip to content

fix(mcp): report the exception behind a FastMCP isError tool result - #1226

Open
lucasheriques wants to merge 9 commits into
mainfrom
lucas/mcp-fastmcp-tool-exception
Open

lucasheriques wants to merge 9 commits into
mainfrom
lucas/mcp-fastmcp-tool-exception

Conversation

@lucasheriques

@lucasheriques lucasheriques commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

💡 Motivation and Context

Part of #1223. On a standalone FastMCP server, every failed tool call reached PostHog as $mcp_error_type: "Error" with one synthetic $exception_list entry and no stack frames, so MCP failure views and error tracking could not tell one failure from another.

FastMCP's tools/call handler turns whatever its public call_tool raised into CallToolResult(isError=True) and keeps only the message text. Our wrapper sits around that handler, so it only ever saw the text.

instrument() now wraps the server's tool dispatch, which still raises (ToolError chained from the tool's exception). That's call_tool on fastmcp 3 and later, and _call_tool_middleware on fastmcp 2, which has no public call_tool. The wrapper hands the outermost call's outcome to the enclosing handler through a context variable, and the handler records the exception next to the result. The slot names the server whose handler opened it, so a tool that calls another server's call_tool and handles the failure never gets that exception on its own event. fastmcp's Error calling tool ... wrapper joins the dispatch wrappers the scalars already step past, so $mcp_error_type names the tool's own exception, the same as on the official SDK path.

Before After
$mcp_error_type Error RuntimeError
$exception_list Error (generic, 0 frames) ToolError -> RuntimeError -> ConnectionError, each with frames

Frames now leave the process on this path, so the MCP sanitizer also redacts each frame's pre_context, context_line and post_context, not just the exception value. That also closes the same gap on the official SDK path, which already sent frames.

With mask_error_details=True, the client still sees the masked text, but PostHog now gets the real exception and message. Masking controls what the MCP client sees. The official SDK path already sends the raised exception to PostHog, and error tracking needs it.

Not included: $mcp_error_status, which the issue also asks for. The taxonomy defines it as the upstream status of PostHog's own server calls, and no SDK sets it today. Setting it from the SDKs is a cross-SDK contract change, so it gets its own discussion. #1223 stays open for it.

💚 How did you test it?

  • posthog/test/mcp/test_fastmcp_tool_errors.py lands in its own commit first and fails on both stacks ('Error' == 'RuntimeError'), then passes with the fix. Cases: a chained exception with mask_error_details off and on, a tool raising ToolError itself (including one worded like fastmcp's wrapper), and a tool that handles a failed call_tool and succeeds. That last case covers a failure from the same server, from another server, and on a server instrumented only through _mcp_server, and it must report no error.
  • test_secrets_in_frame_source_lines_are_redacted fails without the sanitizer change and passes with it.
  • pytest posthog/test/mcp: 698 passed on mcp 1.30 + fastmcp 3.2, 579 on mcp 2.3 + fastmcp 4.1.8, and 689 on mcp 1.30 + fastmcp 2.14.7. CI gains a v1-fastmcp2 leg for the last combination; review caught that this PR had broken fastmcp 2.x, and nothing in CI ran it.
  • The issue's repro script on both stacks prints $mcp_error_type RuntimeError and the three-entry chain with frames.
  • ruff format --check, ruff check, mypy | mypy-baseline filter clean.

📝 Checklist

  • All commits are signed (see Commit signing)
  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Claude Code (Opus) reproduced the issue on both fastmcp majors, traced the conversion to fastmcp's _call_tool_mcp, and wrote the fix test-first. The issue suggested registering a FastMCP middleware; wrapping call_tool was chosen instead because it sits outside every middleware no matter when the application adds its own, and needs no ordering against them. A pre-merge adversarial review (Opus and Sonnet subagents) found the cross-server leak and the over-broad wrapper match. Both are fixed in the last commit, with tests.

…exception

Standalone FastMCP converts a raised tool exception into an isError result
before our wrapped handler returns, so the failure is reported as a generic
"Error" with no frames (posthog-python#1223). Fails on fastmcp 3/mcp 1 and
fastmcp 4/mcp 2.
Standalone FastMCP converts a raised tool exception into
CallToolResult(isError=True) inside the tools/call handler we wrap, so
every failure was captured from the result text: $mcp_error_type "Error",
one generic $exception_list entry, no frames (posthog-python#1223).

instrument() now wraps the server's public call_tool, which still raises
(ToolError chained from the tool's exception). The wrapper hands the
outermost call's outcome to the enclosing handler through a context
variable, and the handler records it next to the result. fastmcp's
"Error calling tool" ToolError joins the dispatch wrappers the scalars
step past, so $mcp_error_type names the tool's own exception.

Tested:
- test_fastmcp_tool_errors.py fails before, passes after, on fastmcp 3.2 +
  mcp 1.30 and fastmcp 4.1.8 + mcp 2.3
- pytest posthog/test/mcp: 694 passed (mcp 1.x), 575 passed (mcp 2.x)
- issue repro: $mcp_error_type RuntimeError, chain ToolError ->
  RuntimeError -> ConnectionError with frames
- ruff format/check, mypy clean

Not included: $mcp_error_status. The taxonomy defines it as the upstream
status of PostHog's own server calls and no SDK sets it today; setting it
from the SDK is a cross-SDK contract change.
@lucasheriques lucasheriques self-assigned this Nov 10, 2026
@github-actions

github-actions Bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-11-12T13:52:31.482364+00:00
Duration: 254578ms

✅ All Tests Passed!

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

Capture_Ai Tests

✅ 5/5 tests passed

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

Feature_Flags Tests

✅ 17/17 tests passed

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

Feature_Flags_V4 Tests

✅ 149/149 tests passed

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

Feature_Flags_Local_Evaluation Tests

✅ 4/4 tests passed

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

@github-actions

github-actions Bot commented Nov 10, 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 113.54 KiB/op 113.53 KiB/op <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Allocations per operation 1,096.58 count/op 1,096.55 count/op <0.1% fewer Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Time per operation 49.16 µs/op 48.31 µs/op 1.7% less time Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Idle process memory (RSS) 36.04 MiB 36.02 MiB <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 37.78 MiB 37.77 MiB <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 37.78 MiB 37.77 MiB <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, burst)
Shard: capture
Process CPU time per operation 50.43 µs/op 49.54 µs/op 1.8% less 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 166.1 KiB/op 166.1 KiB/op <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Allocations per operation 1,089.59 count/op 1,089.59 count/op <0.1% more Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Time per operation 69.11 µs/op 71.62 µs/op 3.6% more time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Idle process memory (RSS) 40.87 MiB 40.88 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Observed peak process memory (RSS) 45.95 MiB 45.98 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process memory after settling (RSS) 45.95 MiB 45.98 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Process CPU time per operation 64.96 µs/op 65.54 µs/op 0.9% more time Not flagged
Capture and deliver events (4,096-byte payload, burst)
Shard: capture
Lifetime peak process memory (RSS) 50.81 MiB 50.79 MiB <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocated memory per operation 117.68 KiB/op 117.68 KiB/op <0.1% less memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Allocations per operation 1,136.59 count/op 1,136.59 count/op <0.1% more Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Time per operation 58.29 µs/op 56.5 µs/op 3.1% less time Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Idle process memory (RSS) 35.77 MiB 35.83 MiB 0.2% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 35.87 MiB 35.93 MiB 0.2% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 35.87 MiB 35.93 MiB 0.2% more memory Not flagged
Capture and deliver events (32-byte payload, steady)
Shard: capture
Process CPU time per operation 58.48 µs/op 56.3 µs/op 3.7% 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 170.57 KiB/op 170.57 KiB/op <0.1% less memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Allocations per operation 1,129.48 count/op 1,129.47 count/op <0.1% fewer Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Time per operation 73.83 µs/op 72.59 µs/op 1.7% less time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Idle process memory (RSS) 40.7 MiB 40.73 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Observed peak process memory (RSS) 40.7 MiB 40.73 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process memory after settling (RSS) 40.7 MiB 40.73 MiB <0.1% more memory Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Process CPU time per operation 71.63 µs/op 70.01 µs/op 2.3% less time Not flagged
Capture and deliver events (4,096-byte payload, steady)
Shard: capture
Lifetime peak process memory (RSS) 40.99 MiB 41.01 MiB <0.1% more memory Not flagged
Queue an event (32-byte payload)
Shard: capture
Caller-thread CPU time per operation 32.63 µs/op 33.36 µs/op 2.2% more time Not flagged
Queue an event (32-byte payload)
Shard: capture
Time per operation 34.64 µs/op 33.36 µs/op 3.7% less time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Caller-thread CPU time per operation 34.26 µs/op 33.08 µs/op 3.4% less time Not flagged
Queue an event (4,096-byte payload)
Shard: capture
Time per operation 35.07 µs/op 33.74 µs/op 3.8% less time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocated memory per operation 200.98 KiB/op 200.98 KiB/op No observed change Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Allocations per operation 2,339.33 count/op 2,339.33 count/op No observed change Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Time per operation 129.57 µs/op 129.6 µs/op <0.1% more time Not flagged
Evaluate all 10 flags
Shard: flags-scaling
Process CPU time per operation 129.57 µs/op 129.59 µs/op <0.1% more time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocated memory per operation 1.93 MiB/op 1.93 MiB/op No observed change Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Allocations per operation 23,013.56 count/op 23,013.56 count/op No observed change Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Time per operation 1.21 ms/op 1.21 ms/op 0.2% more time Not flagged
Evaluate all 100 flags
Shard: flags-scaling
Process CPU time per operation 1.21 ms/op 1.21 ms/op 0.2% more time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocated memory per operation 19.24 MiB/op 19.24 MiB/op No observed change Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Allocations per operation 229,654.94 count/op 229,654.94 count/op No observed change Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Time per operation 11.85 ms/op 11.94 ms/op 0.7% more time Not flagged
Evaluate all 1,000 flags
Shard: flags-scaling
Process CPU time per operation 11.85 ms/op 11.94 ms/op 0.7% more time Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Idle process memory (RSS) 41.64 MiB 42.35 MiB 1.7% more memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Observed peak process memory (RSS) 41.94 MiB 42.67 MiB 1.7% more memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Process memory after settling (RSS) 41.94 MiB 42.67 MiB 1.7% more memory Not flagged
Evaluate 1,000 flags under concurrent load
Shard: flags-memory
Lifetime peak process memory (RSS) 42.53 MiB 42.51 MiB <0.1% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Idle process memory (RSS) 41.83 MiB 42.08 MiB 0.6% more memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Observed peak process memory (RSS) 42.56 MiB 42.15 MiB 1% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Process memory after settling (RSS) 42.56 MiB 41.83 MiB 1.7% less memory Not flagged
Refresh 1,000 flag definitions
Shard: flags-memory
Lifetime peak process memory (RSS) 42.84 MiB 42.53 MiB 0.7% less memory Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocated memory per operation 15.05 KiB/op 15.05 KiB/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Allocations per operation 173.76 count/op 173.76 count/op No observed change Not flagged
Evaluate one boolean flag
Shard: flags-single
Time per operation 7.05 µs/op 6.9 µs/op 2.2% less time Not flagged
Evaluate one boolean flag
Shard: flags-single
Process CPU time per operation 7.05 µs/op 6.9 µs/op 2.2% less time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocated memory per operation 23.12 KiB/op 23.12 KiB/op No observed change Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Allocations per operation 270.27 count/op 270.27 count/op No observed change Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Time per operation 9.03 µs/op 8.99 µs/op 0.4% less time Not flagged
Evaluate a cohort-filtered flag
Shard: flags-single
Process CPU time per operation 9.03 µs/op 8.99 µs/op 0.4% less time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocated memory per operation 35.71 KiB/op 35.71 KiB/op No observed change Not flagged
Evaluate a flag (early match)
Shard: flags-single
Allocations per operation 387.27 count/op 387.27 count/op No observed change Not flagged
Evaluate a flag (early match)
Shard: flags-single
Time per operation 12.96 µs/op 13.05 µs/op 0.8% more time Not flagged
Evaluate a flag (early match)
Shard: flags-single
Process CPU time per operation 12.96 µs/op 13.05 µs/op 0.8% more time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocated memory per operation 53.59 KiB/op 53.59 KiB/op No observed change Not flagged
Evaluate a flag (late match)
Shard: flags-single
Allocations per operation 576.27 count/op 576.27 count/op No observed change Not flagged
Evaluate a flag (late match)
Shard: flags-single
Time per operation 18.72 µs/op 18.93 µs/op 1.1% more time Not flagged
Evaluate a flag (late match)
Shard: flags-single
Process CPU time per operation 18.72 µs/op 18.93 µs/op 1.1% more time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocated memory per operation 52.14 KiB/op 52.14 KiB/op No observed change Not flagged
Evaluate a flag (no match)
Shard: flags-single
Allocations per operation 556.77 count/op 556.77 count/op No observed change Not flagged
Evaluate a flag (no match)
Shard: flags-single
Time per operation 17.83 µs/op 17.68 µs/op 0.8% less time Not flagged
Evaluate a flag (no match)
Shard: flags-single
Process CPU time per operation 17.83 µs/op 17.68 µs/op 0.8% less time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocated memory per operation 17.84 KiB/op 17.84 KiB/op No observed change Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Allocations per operation 198.27 count/op 198.27 count/op No observed change Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Time per operation 7.63 µs/op 7.56 µs/op 0.9% less time Not flagged
Evaluate a property-filtered flag
Shard: flags-single
Process CPU time per operation 7.63 µs/op 7.56 µs/op 0.9% less time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocated memory per operation 19.23 KiB/op 19.23 KiB/op No observed change Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Allocations per operation 210.77 count/op 210.77 count/op No observed change Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Time per operation 8.14 µs/op 8.13 µs/op 0.2% less time Not flagged
Evaluate a regex-filtered flag
Shard: flags-single
Process CPU time per operation 8.14 µs/op 8.13 µs/op 0.2% less time Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocated memory per operation 14.04 KiB/op 14.04 KiB/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Allocations per operation 160.76 count/op 160.76 count/op No observed change Not flagged
Evaluate a rollout flag
Shard: flags-single
Time per operation 6.43 µs/op 6.54 µs/op 1.7% more time Not flagged
Evaluate a rollout flag
Shard: flags-single
Process CPU time per operation 6.43 µs/op 6.54 µs/op 1.7% more time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocated memory per operation 15.21 KiB/op 15.21 KiB/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Allocations per operation 177.77 count/op 177.77 count/op No observed change Not flagged
Evaluate a multivariate flag
Shard: flags-single
Time per operation 7.19 µs/op 7.24 µs/op 0.6% more time Not flagged
Evaluate a multivariate flag
Shard: flags-single
Process CPU time per operation 7.19 µs/op 7.24 µs/op 0.7% more 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 ae8f0bd2caa2f562da57127b31601aa35147d9d7 → f9832ccf34b33d4e5a6feb20d3e866b08afc825d.

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.

Pre-PR gate findings on the previous commit:

- The error slot was shared across servers. A tool that called another
  instrumented FastMCP's call_tool and handled its failure got that
  exception on its own successful event, whenever its own server's
  call_tool was not wrapped (a raw low-level server, or a FastMCP
  instrumented only through _mcp_server). The slot now names the server
  whose handler opened it, and only that server's call_tool writes to it.
- The "Error calling tool" wrapper match also unwrapped a tool's own
  ToolError worded that way. It now requires fastmcp's quoted tool name.

Tested: both repros added to test_fastmcp_tool_errors.py; pytest
posthog/test/mcp 697 passed (mcp 1.30 + fastmcp 3.2), 578 passed
(mcp 2.3 + fastmcp 4.1.8); ruff and mypy clean.
@lucasheriques
lucasheriques marked this pull request as ready for review November 10, 2026 23:47
@lucasheriques
lucasheriques requested a review from a team as a code owner November 10, 2026 23:47
@veria-ai

veria-ai Bot commented Nov 10, 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: 2 · PR risk: 0/10

Reviews

@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 81b3170: 2 Must fix, 1 Should 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/_raised_tool_error.py Outdated


def wrap_call_tool(server: Any) -> None:
original = server.call_tool

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 · Preserve instrumentation for FastMCP 2.x

On standalone FastMCP 2.x (reproduced on 2.14.0), FastMCP exposes _call_tool and _call_tool_middleware, not call_tool. This access raises AttributeError before instrument() installs any handlers, so it returns _NoopAnalytics and captures no MCP events on a previously supported stack. Guard this hook or wrap the corresponding 2.x method.

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.

🤖 An AI agent wrote this on behalf of @ioannisj.

+1, on fastmcp 2.14.7 with mcp 1.30.0 instrument() returns _NoopAnalytics and captures nothing, and the same script on ae8f0bd captures all five events.

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 f5aea70. FastMCP 2.x dispatches tools/call through _call_tool_middleware, so that's the method wrapped there, and call_tool on 3.x and later. Before the fix, 63 MCP tests failed on fastmcp 2.14.7 + mcp 1.30. Now all 689 pass, and 2.x also reports the raised exception (the issue's repro gives RuntimeError with the full chain). I added a v1-fastmcp2 leg to the tests-mcp matrix so CI covers 2.x from now on.

allow_self_reported_model=self.allow_self_reported_model,
analytics_owned_parameters=self.analytics_owned_parameters,
result=result,
error=error,

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 · Sanitize source context before capturing recovered exceptions

On failed standalone FastMCP calls, record_result now forwards exceptions with source snippets in their stack frames. _sanitize_exception_values scrubs only exception value, leaving pre_context, context_line, and post_context untouched. URL passwords and PostHog tokens in those lines reach $exception verbatim, violating the MCP privacy contract; sanitize frame strings before capture.

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.

🤖 An AI agent wrote this on behalf of @ioannisj.

+1, on fastmcp 3.2.0 a phx_ token written in the raise line is redacted in value but shows up as-is in that frame's context_line. Base sent no frames here.

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 34fbaeb. The sanitizer now runs pre_context, context_line and post_context of every frame through sanitize_captured_value, the same pass value gets. That also covers the official SDK path, which already sent frames. test_secrets_in_frame_source_lines_are_redacted puts a database URL with a password on the line before the raise. It fails without the change and passes with it, on fastmcp 2.14.7, 3.2 and 4.1.8.

Comment thread posthog/mcp/_raised_tool_error.py Outdated
Comment on lines +54 to +55
if raised is not None and raised.server is server:
raised.error = error

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 · Prevent background calls from overwriting the settled exception

A same-server background call_tool inherits the parent's mutable RaisedToolError. If the parent raises and the child finishes during the handler's awaited registered_tool_exists, _settle overwrites the client's failure: an outer RuntimeError is reported as the child's ValueError. Freeze the outcome on context exit or restrict settlement to the outer call.

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 f5aea70. The slot now closes when the handler's dispatch returns, so a background task can no longer write to it afterwards. I couldn't reproduce the race: a tool that spawned a failing background call_tool and then raised kept its own RuntimeError across a 0-40 event-loop tick sweep on fastmcp 3.2 and 4.1.8. So there's no test for it. Closing the slot on exit makes the window impossible by construction.

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

🤖 An AI agent wrote this on behalf of @ioannisj.

The FastMCP 2.x and frame source context threads both reproduce for me on this head, so I'd want those two fixed before this merges. On the description: it opens with Fixes #1223, but the issue also asks for $mcp_error_status and that part isn't included here, so merging closes the issue with the status request still open and nothing tracking it. I think leaving it out is the right call, the spec only says MAY and posthog-js doesn't set it either. Worth switching to Part of #1223 so the issue stays open for that discussion?

Comment thread posthog/mcp/_raised_tool_error.py Outdated


def wrap_call_tool(server: Any) -> None:
original = server.call_tool

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.

🤖 An AI agent wrote this on behalf of @ioannisj.

+1, on fastmcp 2.14.7 with mcp 1.30.0 instrument() returns _NoopAnalytics and captures nothing, and the same script on ae8f0bd captures all five events.

allow_self_reported_model=self.allow_self_reported_model,
analytics_owned_parameters=self.analytics_owned_parameters,
result=result,
error=error,

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.

🤖 An AI agent wrote this on behalf of @ioannisj.

+1, on fastmcp 3.2.0 a phx_ token written in the raise line is redacted in value but shows up as-is in that frame's context_line. Base sent no frames here.

@ioannisj
ioannisj requested a review from a team November 11, 2026 09:20
Review on 81b3170 (PostHog Review, confirmed by ioannisj):

- FastMCP 2.x has no public call_tool, so wrapping it raised
  AttributeError and instrument() fell back to no-op analytics: no MCP
  events at all on a supported stack. 2.x dispatches tools/call through
  _call_tool_middleware, so that is the seam wrapped there. 2.x now also
  reports the raised exception.
- A background task holding the slot could settle it after the handler's
  dispatch returned. The slot now closes when the handler leaves it.
- CI gains a v1-fastmcp2 leg (mcp 1.x + fastmcp 2.x), which would have
  caught the first point.

Tested: pytest posthog/test/mcp passes on fastmcp 2.14.7 + mcp 1.30,
fastmcp 3.2 + mcp 1.30, fastmcp 4.1.8 + mcp 2.3 (at 81b3170, 63 tests
failed on fastmcp 2.14.7; at ae8f0bd all passed). The background race
did not reproduce in a 0-40 tick sweep on 3.2 or 4.1.8, so it has no
test; the close-on-exit makes it impossible by construction.
The MCP sanitizer scrubbed each exception's value but not its frames'
pre_context, context_line and post_context. A token written in the
source around a raise reached $exception verbatim. This was already true
on the official SDK path; #1223's fix made it reachable on standalone
FastMCP too, where frames were never sent before. Those three keys now
pass through the same sanitize_captured_value as the value.

Tested: test_secrets_in_frame_source_lines_are_redacted fails without
the sanitizer change and passes with it; full MCP suites pass on fastmcp
2.14.7, 3.2 and 4.1.8.

@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 34fbaeb: 1 Should fix.

Comment thread posthog/mcp/_raised_tool_error.py Outdated
Comment on lines +73 to +74
raised.open = False
_current.reset(token)

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 · Release recovered exceptions after recording the outcome

When a failing tool starts a long-lived background task, that task inherits the mutable RaisedToolError. Setting open=False leaves error attached, retaining its traceback and all tool-frame locals after the request finishes. Repeated failures retain request payloads for the background tasks' lifetimes; clear the shared exception after recording the outcome.

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 52fc421. The slot a background task can reach is now emptied on exit, and the handler reads the outcome from a separate object only it holds. test_a_background_task_does_not_keep_the_failure_alive holds a weakref to a tool local while the tool's background task is still pending. It fails before and passes after, on fastmcp 2.14.7, 3.2 and 4.1.8.

@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 .github/workflows/ci.yml as infra/CI-CD (it adds a new v1-fastmcp2 matrix leg). The tier gate classified the change as T2-never: it is a cross-cutting fix spanning 10 files and 319 lines, including the instrumentation, sanitizer, and event-building code under posthog/mcp/.

A human reviewer needs to look at this one. To make that easier, you could move the CI workflow change into its own pull request, so the posthog/mcp changes are smaller and no longer touch CI config. Either way, please ask a maintainer to review it.

  • posthog[bot] reviewed the current head.
Gate mechanics and policy version
Gate Result
prerequisites ✓ all clear
deny-list ✗ matches: infra_cicd
size ✓ 154L, 8F substantive, 319L/10F incl. docs/generated/snapshots — within ceiling
tier ✗ classified as T2-never: T2-never (319L, 10F, cross-cutting, fix)
stamphog 2.7.0 .stamphog/policy.yml @ unknown · reviewed head 34fbaeb

…ck alive

PostHog Review on 34fbaeb: a background task started by a failing tool
copies the request's context, and with it the slot holding the raised
exception. Closing the slot left the exception attached, so its traceback
and every frame's locals lived as long as the task. The slot the context
can reach is now emptied on exit; the handler reads the outcome from a
separate object only it holds.

Tested: test_a_background_task_does_not_keep_the_failure_alive holds a
weakref to a tool local while the tool's background task is still
pending. It fails before and passes after on fastmcp 2.14.7, 3.2 and
4.1.8. The test turns logging off, because pytest's log capture keeps
fastmcp's error records and their exc_info would retain the traceback by
itself. Full MCP suites: 690 / 699 / 580 passed.

@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 52fc421: 1 Must fix.

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

return {
**frame,
**{
key: sanitize_captured_value(frame[key])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 · Redact sensitive members embedded in captured source lines

When a failed FastMCP tool has a source line containing {"password": "hunter2"}, _sanitize_frame sends the credential unchanged: sanitize_captured_value redacts dictionary keys but does not recognize sensitive members embedded in strings. Newly captured source therefore violates the MCP payload privacy contract; redact embedded sensitive members before sending frame context.

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 d8a7a55. The root cause was wider than frames: posthog-python never implemented the spec's JSON-member pass, so {"password": "hunter2"} also passed through response text and error messages. I ported posthog-go's and posthog-rs's pattern into _redact_credentials, so every captured string gets it, frame source included. posthog-go's JSON-member test table is ported as a parameterized test, plus a source-line case: 13 redaction cases failed before and all pass after. The frame test now has a JSON credential next to "account": "reader", which must survive. Full MCP suites pass on fastmcp 2.14.7, 3.2 and 4.1.8.

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

Native FastMCP exception recovery and the latest traceback-lifetime correction are verified. The earlier compatibility, URL/token source-redaction, parent-outcome and retention cases now pass.

One credential-redaction gap remains in newly captured source context: sensitive JSON-member values can be transmitted unchanged. The independently executed public-client/HTTP regression fails on reviewed head 52fc4216becdfa410b5615d87ab3de4fc22278f8; reproduction and requested correction are in the inline finding.

AI-assisted review.

return {
**frame,
**{
key: sanitize_captured_value(frame[key])

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.

1. [P1] Redact sensitive JSON members in captured source context

IMPORTANT · REQUIRED · Exposes/amplifies an existing sanitizer omission
Location: posthog/mcp/_sanitization.py:709, RIGHT.

A normal failed FastMCP tool can now transmit a password from nearby source text even when its exception message contains no credential. With readable source and default exception autocapture, a line such as credentials = {"password": "hunter2"} appears unchanged in $exception frame pre_context; the expected value is "[redacted]".

_sanitize_frame() delegates source strings to sanitize_captured_value(). Sensitive-key redaction handles dictionary objects, while its string path applies token/entropy/URL passes but not sensitive JSON-member redaction. The pinned MCP Payload privacy requirement explicitly requires that redaction inside any string, including this member shape. The rationale mentions structured responses, but does not limit the rule to them.

This executed repository-style regression uses synthetic data:

import json
from fastmcp import Client, FastMCP
from posthog.mcp import MCPAnalyticsOptions, instrument
from posthog.test.mcp._helpers import FakeClient, events_named, flush_background

async def test_sensitive_json_members_in_frame_source_are_redacted():
    server = FastMCP("json-source-regression")

    @server.tool
    def fail() -> str:
        credentials = {"password": "hunter2"}  # Synthetic fixture.
        raise RuntimeError("synthetic failure")

    sink = FakeClient()
    instrument(server, sink, MCPAnalyticsOptions())
    async with Client(server) as client:
        result = await client.call_tool("fail", {}, raise_on_error=False)
    await flush_background()

    assert result.is_error
    [exception] = events_named(sink, "$exception")
    assert "hunter2" not in json.dumps(exception["properties"]["$exception_list"])

I separately verified actual HTTP transmission through public Client(server), instrument(server, real_posthog_client), the SDK queue and /batch/ transport, mock-service inspection, flush and shutdown. That fixture also confirms the scalar error message has no password and ordinary source text ("account": "reader") remains present.

Equivalent Python 3.11.13 / MCP 1.28.1 / FastMCP 3.2.0 comparisons:

Observation Merge base ae8f0bd2 Previous 34fbaeb2 Reviewed 52fc4216
Application frames 0 1 1
Password literal transmitted in source No Yes Yes
HTTP privacy assertion Pass, exit 0 Fail, exit 1 Fail, exit 1
Pytest regression above Pass Fail Fail

Both current failures are privacy assertions, not setup/import failures. The HTTP assertion reports Sensitive JSON member leaked in captured source context.

The generic string omission predates the latest memory fix, but the original PR newly emits these source frames on this standalone path; identical base calls send frameless generic errors and do not transmit the literal. This demonstrates credential-shaped source transmission, not an actual customer-secret incident, arbitrary-local-variable capture or deployed backend disclosure. Disabling the exception sibling or repairing it in before_send can mitigate exposure, but does not satisfy the default privacy contract.

Consider adding the required embedded-member redaction to the string path used by source context and retaining this regression and its benign-source control. Preserve ordinary source text and frame shapes. No proposed correction was applied or tested.

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 d8a7a55. The root cause was wider than frames: posthog-python never implemented the spec's JSON-member pass, so {"password": "hunter2"} also passed through response text and error messages. I ported posthog-go's and posthog-rs's pattern into _redact_credentials, so every captured string gets it, frame source included. posthog-go's JSON-member test table is ported as a parameterized test, plus a source-line case: 13 redaction cases failed before and all pass after. The frame test now has a JSON credential next to "account": "reader", which must survive. Full MCP suites pass on fastmcp 2.14.7, 3.2 and 4.1.8.

@dustinbyrne
dustinbyrne requested a review from a team November 11, 2026 18:22
Review on 52fc421 (PostHog Review, dustinbyrne): a failed FastMCP tool
whose source has `credentials = {"password": "hunter2"}` sent the
password in its frame's source context. The cause is wider than frames:
the MCP Payload privacy spec requires redacting, inside any captured
string, the value of a JSON member whose key is on the credential list,
and posthog-python never implemented it. posthog-go and posthog-rs do.
This ports their pattern into _redact_credentials, so it covers response
text, error messages and frame source alike.

Tested: posthog-go's TestSanitizeStringRedactsSensitiveJSONMembers table
ported as a parameterized test, plus a source-line case; 13 redaction
cases failed before, all 17 pass after. The frame test now also carries
a JSON credential next to a benign member that must survive. Full MCP
suites pass: 716 (fastmcp 3.2 + mcp 1.30), 597 (fastmcp 4.1.8 + mcp 2.3),
707 (fastmcp 2.14.7 + mcp 1.30). Ruff and mypy clean.

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

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

Comment thread posthog/mcp/_sanitization.py Outdated
Comment on lines +47 to +49
+ r"|\[(?:\s*(?:"
+ _JSON_SCALAR
+ r"|null)\s*,?)*\s*(?:\]|$))"

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 · Require separators between numeric array elements

A captured string containing "note":[ followed by 30 digits and ! makes sanitize_captured_value run for over three seconds. The optional comma lets the repeated numeric alternative partition those digits exponentially when matching fails. Sanitization blocks the MCP event loop, allowing request-driven denial of service; require separators and eliminate ambiguous repetition.

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 9c1cb4f. The array part made every comma optional. Go and Rust run this pattern on linear-time engines, but Python's re backtracks, so a run of digits split into array items in exponentially many ways. Every item after the first now needs its comma, plus an optional trailing one so an array cut off mid-list still matches. That leaves each input exactly one parse. test_json_member_redaction_runs_in_linear_time_on_malformed_arrays timed out at 5 s on the digit inputs before and passes after. I also probed ten adversarial 100k-character shapes (open arrays, lone quotes, unclosed strings, escapes, number characters), and each finishes in under 10 ms.

Comment thread posthog/mcp/_sanitization.py Resolved
Review on d8a7a55 (PostHog Review, veria-ai): the array part of the
JSON-member pattern made every comma optional. Go and Rust run that
pattern on linear-time engines; Python's re backtracks, so a caller's
`{"note":[` + 40 digits + `!` split the digits into array items in
exponentially many ways and blocked the event loop. Every item after the
first now needs its comma, with an optional trailing one so an array cut
off mid-list still matches, which leaves each input one parse.

Tested: test_json_member_redaction_runs_in_linear_time_on_malformed_arrays
timed out at 5 s on two of three inputs before and passes after. Ten
adversarial 100k-character shapes (open arrays, lone quotes, unclosed
strings, escapes, number characters) each finish under 10 ms. All
JSON-member cases still pass. Full MCP suites: 719 / 600 / 710 passed on
fastmcp 3.2 / 4.1.8 / 2.14.7.

@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 9c1cb4f: 1 Must fix.

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

Comment thread posthog/mcp/_sanitization.py Outdated
r"\[\s*(?:" + _JSON_ITEM + r"(?:,\s*" + _JSON_ITEM + r")*(?:,\s*)?)?(?:\]|$)"
)
_JSON_MEMBER_PATTERN = re.compile(
r'("((?:[^"\\\n]|\\.)*)"\s*:\s*)(?:' + _JSON_SCALAR + "|" + _JSON_ARRAY + ")"

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 · Scan escaped quotes without repeatedly rescanning the remaining text

A captured string containing 16,000 backslash–quote pairs (32 KB) takes about 2.4 seconds through process_mcp_event. _JSON_MEMBER_PATTERN retries at every escaped quote and rescans the remaining suffix, producing quadratic work. Request-controlled arguments therefore block the MCP event loop before truncation; scan strings once without restarting inside escaped sequences.

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 f9832cc. This is the second performance finding in the same regex, so I replaced it rather than patching it again. Go and Rust run the pattern on linear-time engines, but Python's re restarts at every quote and rescans the rest of the text: 16,000 escaped quote pairs took about 3 s here, and 64,000 took 49 s. The new scanner tries the same key starts but caches where each string body ends and what follows each closing quote, so overlapping candidates share their work. Ten adversarial inputs of 100k to 200k characters, including both of the ones reported here, each finish in under 60 ms. A differential test keeps the reference pattern as an oracle and checks the scanner against it on 30,000 random texts, so the redaction rules stay the same as in Go and Rust. A one-off run of 200,000 longer texts found no mismatch.

Comment thread posthog/mcp/_sanitization.py Resolved
…ry quote

Review on 9c1cb4f (PostHog Review, veria-ai): with no member to match,
the JSON-member regex restarted at every quote and rescanned the rest of
the text, so 16,000 escaped quote pairs took about 3 s and 64,000 took
49 s on the server's event loop. This is the second performance finding
in that regex: Go and Rust run it on linear-time engines, and Python's re
does not. It is replaced by a scanner that tries the same key starts but
caches where a string body ends and what follows each closing quote, so
overlapping candidates share their work.

Tested: the linear-time test gains escaped-quote and JSON-encoded-quote
inputs at 32,000 pairs, which timed out at 5 s before and pass after; ten
adversarial 100k-200k-character shapes each finish under 60 ms. A
differential test keeps the reference pattern as an oracle and checks the
scanner against it on 30,000 random texts (a one-off run of 200,000
longer ones found no mismatch). Full MCP suites: 722 / 603 / 713 passed
on fastmcp 3.2 / 4.1.8 / 2.14.7; ruff and mypy clean.

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.

3 participants