Repository navigation
feat(mcp): make McpAnalytics.flush() send captured events - #1306
lucasheriques wants to merge 6 commits into
Conversation
McpAnalytics.flush() only waited for in-flight captures, so a host on a per-request runtime still had to call posthog.flush() itself or lose the events. It now waits, then flushes the client in a worker thread, and logs instead of raising when that flush fails. This matches the contract agreed for posthog-js (PostHog/posthog-js#5842). Tested: uv run pytest posthog/test/mcp (828 passed, 11 skipped); the two new flush tests fail without the change. ruff format/check, mypy baseline, public_api_check and `python -W error -c "import posthog"` pass.
A stalled ingest host holds each Client.flush() for up to its timeout. On the loop's default executor, concurrent flushes filled it and delayed unrelated work such as DNS lookups by ~9.5s. Flushes now use a dedicated executor. Tested: new test fails with asyncio.to_thread and passes now; a repro with 18 concurrent flushes against a host that never replies went from 9.5s to 0.0s for an unrelated getaddrinfo. pytest posthog/test/mcp: 829 passed.
There was a problem hiding this comment.
PostHog Review · Standard · reviewed f319f6a: 2 Should fix.
New pushes to this pull request won't start an automatic review. Comment @posthog review to review new changes.
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.
SDK performance: posthog-pythonBenchmarks 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
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 102 metric rows; 102 rows shown in all results. Omitted or shortened data remain in |
There was a problem hiding this comment.
Not approved — this change needs a human reviewer.
Add the stamphog label to request another review once you have addressed this.
Both of @PostHog's substantive concerns in posthog/mcp/_sink.py remain unaddressed, and its current-head review therefore provides no concern-free assurance. Address those threads and request review from Manoel Aranda Neto or another teammate before re-requesting automated approval.
- Author wrote 43% of the modified lines and has 9 merged PRs in these paths (familiarity MODERATE).
- PostHog Review (Standard) reviewed the current head: 2 findings, posted on the PR.
- posthog[bot] reviewed the current head.
- @PostHog on posthog/mcp/_sink.py: The fork-safety concern remains unresolved: the module-level executor is retained without a child-process reset, so inherited worker bookkeeping can leave a child's flush waiting indefinitely after the parent used the pool. Recreate the executor after fork and add a regression test before re-requesting.
- @PostHog on posthog/mcp/_sink.py: The scheduling-backlog concern remains unresolved: all clients share a finite executor, submissions have no scheduling deadline, and Client.flush() starts its timeout only after execution begins. Bound the scheduling wait and coalesce redundant per-client flushes before re-requesting; if this finding is incorrect, explain why in the review thread and resolve it.
Gate mechanics and policy version
| Gate | Result | |
|---|---|---|
| prerequisites | ✓ | all clear |
| deny-list | ✓ | no deny categories matched |
| every_file_attested | ✓ | not a bot PR |
| size | ✓ | 28L, 2F substantive, 82L/5F incl. docs/generated/snapshots — within ceiling |
| tier | ✓ | T1-agent / T1b-small (82L, 5F, two-areas, feat) |
| stamphog 2.9.1 | .stamphog/policy.yml @ f319f6a · reviewed head f319f6a |
PostHog Review flagged the module-level flush executor: it hangs a forked child's first flush, and when ingest stalls, flushes for healthy clients queue behind stalled ones with no deadline. Each flush now runs on its own daemon thread, so no pool state outlives a fork and no flush waits for a worker. The loop's default executor stays free. Tested: two new tests (a healthy flush finishes while 64 flushes stall; a forked child's flush completes) fail on the pool and pass now. pytest posthog/test/mcp: 831 passed. The stalled-host repro still shows 0.0s for an unrelated getaddrinfo; ruff, mypy baseline and import check pass.
|
@PostHog review |
|
@lucasheriques PostHog Review is reviewing this pull request. |
…lure PostHog Review found two holes in the per-flush thread. Cancelling flush() cancelled the worker's future, so its set_result() raised in the thread. A Thread.start() failure escaped flush(), which promises never to raise. The future is now marked running before the await (a running future ignores cancel()), and the thread start sits inside the guarded block. Tested: the cancellation test and the thread-start case of the parameterized never-raises test fail before and pass now. pytest posthog/test/mcp: 833 passed; ruff, mypy baseline, import check pass.
|
@PostHog review |
|
@lucasheriques PostHog Review is reviewing this pull request. |
There was a problem hiding this comment.
Not approved — this change needs a human reviewer.
Add the stamphog label to request another review once you have addressed this.
A current-head review supplies independent assurance for the risky changes, but @veria-ai's worker-exhaustion concern remains substantiated by the current code. Address that comment in posthog/mcp/_sink.py and request re-review before re-requesting approval; Manoel Aranda Neto is a suggested reviewer.
- Author wrote 43% of the modified lines and has 9 merged PRs in these paths (familiarity MODERATE).
- PostHog Review (Standard) reviewed the current head: no findings.
- posthog[bot] reviewed the current head.
- @veria-ai inline comment on posthog/mcp/_sink.py, reiterated by @veria-ai[bot] in discussion: unbounded flush worker creation remains unfixed. Lines 123–141 start a new native thread for every call without per-client coalescing or a concurrency bound; cancellation leaves the running client flush alive. Slow ingestion and per-request flush bursts can therefore exhaust thread or memory limits. Bound or coalesce overlapping flushes without using the shared executor, then request re-review; if the finding is incorrect, explain why in its thread and resolve it.
Gate mechanics and policy version
| Gate | Result | |
|---|---|---|
| prerequisites | ✓ | all clear |
| deny-list | ✓ | no deny categories matched |
| every_file_attested | ✓ | not a bot PR |
| size | ✓ | 39L, 2F substantive, 166L/5F incl. docs/generated/snapshots — within ceiling |
| tier | ✓ | T1-agent / T1c-medium (166L, 5F, two-areas, feat) |
| stamphog 2.9.1 | .stamphog/policy.yml @ 656a139 · reviewed head 656a139 |
veria-ai flagged that every flush() started its own thread, so a burst of per-request flushes during an ingest stall started one blocked thread per request. Overlapping flushes of the same client now share one client flush: a caller waits for a flush that was already running (it may have missed the caller's events), then joins or starts one that began after its call. At most one client flush runs per client. The per-client state is reset in a forked child. Tested: test_overlapping_analytics_flushes_run_one_client_flush_at_a_time (20 overlapping flushes on one stalled client) fails without coalescing and passes now. pytest posthog/test/mcp: 834 passed; the stalled-host and real-client repros still pass; ruff, mypy baseline, import check pass.
|
@PostHog review |
|
@lucasheriques PostHog Review is reviewing this pull request. |
There was a problem hiding this comment.
PostHog Review · Standard · reviewed d98ec75: 1 Should fix, 1 Consider.
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.
PostHog Review found that a failed client flush stayed in the per-client map, and its traceback kept the client alive. A caller that waited on an earlier failed flush also left that failure unretrieved, so asyncio sent it to the loop's exception handler instead of the MCP logger. The flush thread now removes its own entry when it ends, and the waiting caller suppresses the earlier failure, which the caller that started it logs. Tested: the collection test fails without the cleanup; the loop-handler test fails after the cleanup alone and passes with the suppression. pytest posthog/test/mcp: 836 passed in three runs; ruff, mypy pass.
|
@PostHog review |
|
@lucasheriques PostHog Review is reviewing this pull request. |
There was a problem hiding this comment.
Approved.
The public contract and telemetry delivery changes have independent assurance from a current-head agent review. The implementation matches the disclosed intent, with no outstanding substantive concerns or other refusal grounds found.
- Author wrote 50% of the modified lines and has 9 merged PRs in these paths (familiarity MODERATE).
- PostHog Review (Standard) reviewed the current head: no findings.
- posthog[bot] reviewed the current head.
Gate mechanics and policy version
| Gate | Result | |
|---|---|---|
| prerequisites | ✓ | all clear |
| deny-list | ✓ | no deny categories matched |
| every_file_attested | ✓ | not a bot PR |
| size | ✓ | 91L, 2F substantive, 288L/5F incl. docs/generated/snapshots — within ceiling |
| tier | ✓ | T1-agent / T1c-medium (288L, 5F, two-areas, feat) |
| stamphog 2.9.1 | .stamphog/policy.yml @ 24c1184 · reviewed head 24c1184 |
💡 Motivation and Context
McpAnalytics.flush(), on the handleinstrument()returns, only waited for in-flight MCP captures. A host on a per-request runtime (serverless, edge) had to callposthog.flush()after it too, or the events were lost. A method calledflushthat sends nothing is easy to misuse.It now waits for in-flight captures, then flushes the client, and it never raises: a failed client flush is logged. This is the contract agreed for posthog-js in PostHog/posthog-js#5842, so
await analytics.flush()means the same thing in both SDKs.Each client flush runs on its own short-lived thread, and overlapping flushes of one client share it, so at most one client flush runs per client.
Client.flush()blocks for up to its timeout when ingest stalls. On the loop's default executor, concurrent flushes held up unrelated work such as DNS lookups. A shared pool hung forked children and made healthy flushes queue behind stalled ones.Scope. This leaves out one case.
flush()still waits only for captures on the event loop it runs on, as before. A server that handles tool calls on one loop and awaitsflush()on another gets its client flushed before those captures are queued. Fixing that means changing the loop scoping indrain_pending, which is a separate change.Blast radius. Existing code that calls
await analytics.flush()and thenposthog.flush()orshutdown()keeps working: the second call finds an empty queue.flush()now flushes the whole client, so events the host captured itself on it are sent too.💚 How did you test it?
pytest posthog/test/mcp: 831 passed. The five new tests fail without the change: events are sent, a failed client flush is logged, the default executor stays free, a healthy flush doesn't wait behind stalled ones, and a forked child's flush completes.Clientand a local capture server. Same-loop flush sends$mcp_initializeand$mcp_tool_callbefore it returns. 50 concurrent flushes don't deadlock. With 18 concurrent flushes against a host that never replies, an unrelatedgetaddrinfodropped from 9.5s to 0.0s.ruff format --check,ruff check, the mypy baseline,make public_api_check, andpython -W error -c "import posthog"pass.📝 Checklist
If releasing new changes
sampo addto generate a changeset file🤖 Agent context
Autonomy: Human-driven (agent-assisted)
Written with Claude Code. Lucas chose "wait, then flush the client" while reviewing PostHog/posthog-js#5842. The alternative was wait-only, which is what Python's
McpAnalytics.flushdid. The pre-PR gate ran two adversarial reviewers (Opus and Sonnet). Both found the cross-loop gap above, which stays out of scope. Sonnet also found the executor starvation, which is fixed here. Later bot reviews flagged a shared pool's fork and backlog problems, cancellation and thread-start errors, and one thread per call. Flushes now run on their own threads, coalesced per client.