Skip to content

fix(mcp): isolate pending capture tasks - #815

Merged
marandaneto merged 5 commits into
mainfrom
review-fix/38-mcp-pending-task-ownership
Aug 4, 2026
Merged

fix(mcp): isolate pending capture tasks#815
marandaneto merged 5 commits into
mainfrom
review-fix/38-mcp-pending-task-ownership

Conversation

@marandaneto

Copy link
Copy Markdown
Member

💡 Motivation and Context

MCP capture tasks were tracked globally, so flushing one analytics instance could wait for another instance's captures. Async drains could also encounter tasks created on another event loop.

Track each capture task by its lifecycle owner and event loop. Async analytics now drain only their own tasks on the current loop, while PostHogMCP consistently schedules and drains its captures on the shared background loop.

💚 How did you test it?

  • uv run --extra test pytest -q posthog/test/mcp (145 passed)
  • uv run ruff check posthog/mcp/__init__.py posthog/mcp/_instrumentation.py posthog/mcp/posthog_mcp.py posthog/test/mcp/_helpers.py posthog/test/mcp/test_review_fixes.py posthog/test/mcp/test_pending_tasks.py
  • uv run ruff format --check posthog/mcp/__init__.py posthog/mcp/_instrumentation.py posthog/mcp/posthog_mcp.py posthog/test/mcp/_helpers.py posthog/test/mcp/test_review_fixes.py posthog/test/mcp/test_pending_tasks.py
  • git diff --check

📝 Checklist

  • I reviewed the submitted code.
  • I added tests to verify the changes.
  • I updated the docs if needed.
  • No breaking change or entry added to the changelog.

If releasing new changes

  • Ran sampo add to generate a changeset file

🤖 Agent context

Autonomy: Human-driven (agent-assisted)

Pi implemented the human-directed fix from autoreview report 38. The selected approach scopes pending capture work by owner and event loop, and keeps the synchronous PostHogMCP lifecycle on the shared background loop so flush() and shutdown() can drain it safely. The generated patch changeset describes the user-visible fix.

This agent-assisted change requires human review before merge.

@marandaneto marandaneto self-assigned this Jul 30, 2026
@github-actions

github-actions Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

posthog-python Compliance Report

Date: 2026-08-04 09:13:11 UTC
Duration: 338836ms

✅ All Tests Passed!

111/111 tests passed


Capture_V1 Tests

94/94 tests passed

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

Feature_Flags Tests

17/17 tests passed

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

@marandaneto
marandaneto requested a review from a team July 31, 2026 08:08
@marandaneto
marandaneto marked this pull request as ready for review July 31, 2026 08:08
@marandaneto
marandaneto requested a review from a team as a code owner July 31, 2026 08:08
@marandaneto

Copy link
Copy Markdown
Member Author

@PostHog/team-mcp-analytics im not sure if this was intended or not, but i found out while reviewing some other stuff

@greptile-apps

greptile-apps Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Reviews (1): Last reviewed commit: "test(mcp): await background capture futu..." | Re-trigger Greptile

@gesh gesh left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good to me!
cc @lucasheriques as he might be more familiar with this implementation and whether it was intentional

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

approving. mechanism is sound.

verified: asyncio.Task isn't a concurrent.futures.Future subclass, so the two drain filters are disjoint. locking is deadlock free, _tasks_lock is released before both add_done_callback and concurrent.futures.wait. owner and loop identity match end to end through instrument(). background=True for PostHogMCP fixes a real gap, covered by test_posthog_mcp_sync_flush_drains_capture_from_async_host.

two non blocking comments below, neither changes behaviour.

the one that matters: flush() is what gets trailing captures over the line before the loop closes. if it silently stops draining, a host that does tool call, flush(), exit loses every event, and nothing in the suite would catch that.

Comment thread posthog/mcp/__init__.py Outdated
Comment thread posthog/mcp/_instrumentation.py Outdated
@marandaneto
marandaneto merged commit b16ec74 into main Aug 4, 2026
37 checks passed
@marandaneto
marandaneto deleted the review-fix/38-mcp-pending-task-ownership branch August 4, 2026 09:18
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