From de7c30e3b4b89327649ccd25b0487f49fc2916ca Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 12:07:22 -0300 Subject: [PATCH 1/6] feat(mcp): make McpAnalytics.flush() send captured events 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. --- .../changesets/mcp-analytics-flush-sends.md | 5 ++++ posthog/mcp/__init__.py | 14 +++++++---- posthog/mcp/_sink.py | 7 ++++++ posthog/test/mcp/_helpers.py | 4 ++++ posthog/test/mcp/test_fastmcp.py | 24 +++++++++++++++++-- 5 files changed, 47 insertions(+), 7 deletions(-) create mode 100644 .sampo/changesets/mcp-analytics-flush-sends.md diff --git a/.sampo/changesets/mcp-analytics-flush-sends.md b/.sampo/changesets/mcp-analytics-flush-sends.md new file mode 100644 index 000000000..bc143c0ea --- /dev/null +++ b/.sampo/changesets/mcp-analytics-flush-sends.md @@ -0,0 +1,5 @@ +--- +pypi/posthog: minor +--- + +`McpAnalytics.flush()`, on the handle `instrument()` returns, now flushes the posthog client after it waits for in-flight MCP captures, so the captured events are sent. It never raises: a failed client flush is logged. On a per-request runtime, `await analytics.flush()` alone is enough; you no longer need a separate `posthog.flush()`. diff --git a/posthog/mcp/__init__.py b/posthog/mcp/__init__.py index 927f41be7..24617481f 100644 --- a/posthog/mcp/__init__.py +++ b/posthog/mcp/__init__.py @@ -186,12 +186,16 @@ async def capture( await coro async def flush(self) -> None: - """Await this server's in-flight auto-captures on the current event loop. - Call this before ``posthog.shutdown()`` on exit so trailing tool-call events - aren't dropped. (Then call ``posthog.flush()``/``shutdown()`` to send them.)""" + """Await this server's in-flight auto-captures on the current event loop, + then flush the posthog client, which sends every event queued on it. On a + per-request runtime (serverless, edge), await this before the request ends. + Never raises: a failed client flush is logged.""" data = get_server_tracking_data(self._key) - if data is not None: - await drain_pending(data) + if data is None: + return + await drain_pending(data) + if data.sink is not None: + await data.sink.flush() class _NoopAnalytics(McpAnalytics): diff --git a/posthog/mcp/_sink.py b/posthog/mcp/_sink.py index 15a5e789a..c1b192777 100644 --- a/posthog/mcp/_sink.py +++ b/posthog/mcp/_sink.py @@ -13,6 +13,7 @@ from __future__ import annotations +import asyncio import inspect from dataclasses import dataclass from typing import List, Optional, Tuple @@ -116,3 +117,9 @@ async def capture(self, event: McpEvent, options: McpCaptureOptions) -> None: ) except Exception as err: log(f"Failed to capture PostHog event {full_event.get('id')}: {err}") + + async def flush(self) -> None: + try: + await asyncio.to_thread(self._posthog.flush) + except Exception as err: + log(f"Failed to flush PostHog events: {err}") diff --git a/posthog/test/mcp/_helpers.py b/posthog/test/mcp/_helpers.py index adf5c537f..0806c15c2 100644 --- a/posthog/test/mcp/_helpers.py +++ b/posthog/test/mcp/_helpers.py @@ -18,6 +18,7 @@ class FakeClient: def __init__(self): self.events = [] + self.event_counts_at_flush = [] def capture( self, @@ -38,6 +39,9 @@ def capture( ) return None + def flush(self, timeout_seconds=10): + self.event_counts_at_flush.append(len(self.events)) + async def flush_background(): """Let fire-and-forget capture tasks run to completion.""" diff --git a/posthog/test/mcp/test_fastmcp.py b/posthog/test/mcp/test_fastmcp.py index 632850d60..1696a8119 100644 --- a/posthog/test/mcp/test_fastmcp.py +++ b/posthog/test/mcp/test_fastmcp.py @@ -8,7 +8,7 @@ import mcp.types as mcp_types from mcp.server.fastmcp import FastMCP -from posthog.mcp import instrument +from posthog.mcp import instrument, set_logger from posthog.mcp.types import MCPAnalyticsOptions, UserIdentity from posthog.test.mcp._helpers import ( FakeClient, @@ -172,7 +172,7 @@ async def test_tool_call_captures_client_model_without_prior_listing(): assert "llm_model" not in props["$mcp_parameters"]["request"]["params"]["arguments"] -async def test_analytics_flush_drains_its_own_captures(): +async def test_analytics_flush_sends_its_captures(): async def slow_before_send(event): await asyncio.sleep(0.05) return event @@ -191,6 +191,26 @@ async def slow_before_send(event): await analytics.flush() assert len(_events(client, "$mcp_tool_call")) == 1 + assert client.event_counts_at_flush == [len(client.events)] + + +async def test_analytics_flush_logs_a_failed_client_flush(): + class FailingFlushClient(FakeClient): + def flush(self, timeout_seconds=10): + raise RuntimeError("network down") + + lines = [] + try: + analytics = instrument( + make_server(), + FailingFlushClient(), + MCPAnalyticsOptions(logger=lines.append), + ) + await analytics.flush() + finally: + set_logger(None) + + assert any("network down" in line for line in lines) async def test_initialize_emitted_once_per_session(): From f319f6a73e5a408fec5760921e640e4ab45d254c Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 12:12:21 -0300 Subject: [PATCH 2/6] fix(mcp): run McpAnalytics.flush() on its own thread pool 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. --- posthog/mcp/_sink.py | 9 ++++++++- posthog/test/mcp/test_fastmcp.py | 21 +++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/posthog/mcp/_sink.py b/posthog/mcp/_sink.py index c1b192777..b8d81a9e7 100644 --- a/posthog/mcp/_sink.py +++ b/posthog/mcp/_sink.py @@ -15,6 +15,7 @@ import asyncio import inspect +from concurrent.futures import ThreadPoolExecutor from dataclasses import dataclass from typing import List, Optional, Tuple @@ -27,6 +28,10 @@ from ._truncation import truncate_event from .types import BeforeSendFn, Event, McpEvent +# Flushes block for up to their timeout when ingest stalls, so they get their own +# threads instead of filling the loop's default executor (which also serves DNS). +_flush_executor = ThreadPoolExecutor(thread_name_prefix="posthog-mcp-flush") + @dataclass class McpCaptureOptions: @@ -120,6 +125,8 @@ async def capture(self, event: McpEvent, options: McpCaptureOptions) -> None: async def flush(self) -> None: try: - await asyncio.to_thread(self._posthog.flush) + await asyncio.get_running_loop().run_in_executor( + _flush_executor, self._posthog.flush + ) except Exception as err: log(f"Failed to flush PostHog events: {err}") diff --git a/posthog/test/mcp/test_fastmcp.py b/posthog/test/mcp/test_fastmcp.py index 1696a8119..80159071f 100644 --- a/posthog/test/mcp/test_fastmcp.py +++ b/posthog/test/mcp/test_fastmcp.py @@ -1,6 +1,8 @@ """End-to-end tests for the FastMCP adapter (Milestone 2).""" import asyncio +import threading +from concurrent.futures import ThreadPoolExecutor from types import SimpleNamespace import pytest @@ -213,6 +215,25 @@ def flush(self, timeout_seconds=10): assert any("network down" in line for line in lines) +async def test_analytics_flush_leaves_the_default_executor_free(): + release = threading.Event() + + class StalledFlushClient(FakeClient): + def flush(self, timeout_seconds=10): + release.wait(timeout=5) + + loop = asyncio.get_running_loop() + loop.set_default_executor(ThreadPoolExecutor(max_workers=1)) + analytics = instrument(make_server(), StalledFlushClient()) + flushing = asyncio.ensure_future(analytics.flush()) + await asyncio.sleep(0.05) + try: + assert await asyncio.wait_for(loop.run_in_executor(None, lambda: 1), 1) == 1 + finally: + release.set() + await flushing + + async def test_initialize_emitted_once_per_session(): server = make_server() client = FakeClient() From 3fed2339235ba8fa5473ea49fb0547ea6c46e61d Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 21:10:15 -0300 Subject: [PATCH 3/6] fix(mcp): flush on a short-lived thread instead of a shared pool 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/mcp/_sink.py | 24 ++++++++++++++------- posthog/test/mcp/test_fastmcp.py | 37 ++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 8 deletions(-) diff --git a/posthog/mcp/_sink.py b/posthog/mcp/_sink.py index b8d81a9e7..7b730ec12 100644 --- a/posthog/mcp/_sink.py +++ b/posthog/mcp/_sink.py @@ -14,8 +14,9 @@ from __future__ import annotations import asyncio +import concurrent.futures import inspect -from concurrent.futures import ThreadPoolExecutor +import threading from dataclasses import dataclass from typing import List, Optional, Tuple @@ -28,10 +29,6 @@ from ._truncation import truncate_event from .types import BeforeSendFn, Event, McpEvent -# Flushes block for up to their timeout when ingest stalls, so they get their own -# threads instead of filling the loop's default executor (which also serves DNS). -_flush_executor = ThreadPoolExecutor(thread_name_prefix="posthog-mcp-flush") - @dataclass class McpCaptureOptions: @@ -124,9 +121,20 @@ async def capture(self, event: McpEvent, options: McpCaptureOptions) -> None: log(f"Failed to capture PostHog event {full_event.get('id')}: {err}") async def flush(self) -> None: + # Client.flush() blocks for up to its timeout when ingest stalls. A thread + # per call keeps it out of any shared pool, so a stalled flush never delays + # another flush or the loop's default executor, and no pool outlives a fork. + done: concurrent.futures.Future[None] = concurrent.futures.Future() + + def run() -> None: + try: + self._posthog.flush() + done.set_result(None) + except BaseException as err: + done.set_exception(err) + + threading.Thread(target=run, name="posthog-mcp-flush", daemon=True).start() try: - await asyncio.get_running_loop().run_in_executor( - _flush_executor, self._posthog.flush - ) + await asyncio.wrap_future(done) except Exception as err: log(f"Failed to flush PostHog events: {err}") diff --git a/posthog/test/mcp/test_fastmcp.py b/posthog/test/mcp/test_fastmcp.py index 80159071f..7a57d0147 100644 --- a/posthog/test/mcp/test_fastmcp.py +++ b/posthog/test/mcp/test_fastmcp.py @@ -1,6 +1,7 @@ """End-to-end tests for the FastMCP adapter (Milestone 2).""" import asyncio +import os import threading from concurrent.futures import ThreadPoolExecutor from types import SimpleNamespace @@ -234,6 +235,42 @@ def flush(self, timeout_seconds=10): await flushing +async def test_analytics_flush_does_not_queue_behind_stalled_flushes(): + release = threading.Event() + + class StalledFlushClient(FakeClient): + def flush(self, timeout_seconds=10): + release.wait(timeout=5) + + stalled = [instrument(make_server(), StalledFlushClient()) for _ in range(64)] + healthy_client = FakeClient() + healthy = instrument(make_server(), healthy_client) + flushing = [asyncio.ensure_future(analytics.flush()) for analytics in stalled] + await asyncio.sleep(0.05) + try: + await asyncio.wait_for(healthy.flush(), 1) + assert healthy_client.event_counts_at_flush == [0] + finally: + release.set() + await asyncio.gather(*flushing) + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs os.fork") +async def test_analytics_flush_works_in_a_forked_child(): + analytics = instrument(make_server(), FakeClient()) + await analytics.flush() + + pid = os.fork() + if pid == 0: + try: + asyncio.run(asyncio.wait_for(analytics.flush(), 2)) + os._exit(0) + except BaseException: + os._exit(1) + _, status = os.waitpid(pid, 0) + assert os.waitstatus_to_exitcode(status) == 0 + + async def test_initialize_emitted_once_per_session(): server = make_server() client = FakeClient() From 656a139a625530dc62be7f00e55a057da217c0b5 Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 21:13:23 -0300 Subject: [PATCH 4/6] fix(mcp): keep analytics.flush() quiet on cancellation and thread failure 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/mcp/_sink.py | 5 ++- posthog/test/mcp/test_fastmcp.py | 52 +++++++++++++++++++++++++++----- 2 files changed, 48 insertions(+), 9 deletions(-) diff --git a/posthog/mcp/_sink.py b/posthog/mcp/_sink.py index 7b730ec12..342a13212 100644 --- a/posthog/mcp/_sink.py +++ b/posthog/mcp/_sink.py @@ -125,6 +125,9 @@ async def flush(self) -> None: # per call keeps it out of any shared pool, so a stalled flush never delays # another flush or the loop's default executor, and no pool outlives a fork. done: concurrent.futures.Future[None] = concurrent.futures.Future() + # A running future ignores cancel(), so cancelling this await can't make + # the worker's set_result() raise. + done.set_running_or_notify_cancel() def run() -> None: try: @@ -133,8 +136,8 @@ def run() -> None: except BaseException as err: done.set_exception(err) - threading.Thread(target=run, name="posthog-mcp-flush", daemon=True).start() try: + threading.Thread(target=run, name="posthog-mcp-flush", daemon=True).start() await asyncio.wrap_future(done) except Exception as err: log(f"Failed to flush PostHog events: {err}") diff --git a/posthog/test/mcp/test_fastmcp.py b/posthog/test/mcp/test_fastmcp.py index 7a57d0147..6994f7130 100644 --- a/posthog/test/mcp/test_fastmcp.py +++ b/posthog/test/mcp/test_fastmcp.py @@ -197,23 +197,59 @@ async def slow_before_send(event): assert client.event_counts_at_flush == [len(client.events)] -async def test_analytics_flush_logs_a_failed_client_flush(): - class FailingFlushClient(FakeClient): - def flush(self, timeout_seconds=10): - raise RuntimeError("network down") +class _FailingFlushClient(FakeClient): + def flush(self, timeout_seconds=10): + raise RuntimeError("network down") + + +def _fail_thread_start(self): + raise RuntimeError("can't start new thread") + +@pytest.mark.parametrize( + "client_class, thread_start, expected_log", + [ + (_FailingFlushClient, None, "network down"), + (FakeClient, _fail_thread_start, "can't start new thread"), + ], + ids=["client flush raises", "thread start raises"], +) +async def test_analytics_flush_logs_instead_of_raising( + monkeypatch, client_class, thread_start, expected_log +): + if thread_start is not None: + monkeypatch.setattr(threading.Thread, "start", thread_start) lines = [] try: analytics = instrument( - make_server(), - FailingFlushClient(), - MCPAnalyticsOptions(logger=lines.append), + make_server(), client_class(), MCPAnalyticsOptions(logger=lines.append) ) await analytics.flush() finally: set_logger(None) - assert any("network down" in line for line in lines) + assert any(expected_log in line for line in lines) + + +async def test_cancelled_analytics_flush_leaves_the_worker_quiet(monkeypatch): + release = threading.Event() + finished = threading.Event() + thread_errors = [] + monkeypatch.setattr(threading, "excepthook", thread_errors.append) + + class StalledFlushClient(FakeClient): + def flush(self, timeout_seconds=10): + release.wait(timeout=5) + finished.set() + + analytics = instrument(make_server(), StalledFlushClient()) + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for(analytics.flush(), 0.05) + release.set() + assert finished.wait(timeout=2) + await asyncio.sleep(0.05) + + assert thread_errors == [] async def test_analytics_flush_leaves_the_default_executor_free(): From d98ec75d2dc1674d7429d79298bf855a862128f6 Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 21:19:39 -0300 Subject: [PATCH 5/6] fix(mcp): coalesce overlapping analytics.flush() calls per client 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/mcp/_sink.py | 79 ++++++++++++++++++++++++-------- posthog/test/mcp/test_fastmcp.py | 28 +++++++++++ 2 files changed, 89 insertions(+), 18 deletions(-) diff --git a/posthog/mcp/_sink.py b/posthog/mcp/_sink.py index 342a13212..bc8bd0442 100644 --- a/posthog/mcp/_sink.py +++ b/posthog/mcp/_sink.py @@ -16,9 +16,11 @@ import asyncio import concurrent.futures import inspect +import os import threading +import weakref from dataclasses import dataclass -from typing import List, Optional, Tuple +from typing import Any, List, Optional, Tuple from posthog.client import Client @@ -30,6 +32,53 @@ from .types import BeforeSendFn, Event, McpEvent +# The client flush running on each client's flush thread, so overlapping +# analytics.flush() calls share one blocked thread instead of starting their own. +_client_flushes: "weakref.WeakKeyDictionary[Any, concurrent.futures.Future[None]]" = ( + weakref.WeakKeyDictionary() +) +_client_flushes_lock = threading.Lock() + + +def _forget_client_flushes_after_fork() -> None: + global _client_flushes_lock + _client_flushes_lock = threading.Lock() + _client_flushes.clear() + + +if hasattr(os, "register_at_fork"): + os.register_at_fork(after_in_child=_forget_client_flushes_after_fork) + + +def _start_client_flush(client: Any) -> "concurrent.futures.Future[None]": + done: concurrent.futures.Future[None] = concurrent.futures.Future() + # A running future ignores cancel(), so cancelling an await on it can't make + # the worker's set_result() raise. + done.set_running_or_notify_cancel() + + def run() -> None: + try: + client.flush() + done.set_result(None) + except BaseException as err: + done.set_exception(err) + + threading.Thread(target=run, name="posthog-mcp-flush", daemon=True).start() + return done + + +def _client_flush_started_after( + client: Any, earlier: "Optional[concurrent.futures.Future[None]]" +) -> "concurrent.futures.Future[None]": + with _client_flushes_lock: + current = _client_flushes.get(client) + if current is not None and current is not earlier and not current.done(): + return current + current = _start_client_flush(client) + _client_flushes[client] = current + return current + + @dataclass class McpCaptureOptions: """Per-event toggles consulted by the sink when fanning out an event.""" @@ -121,23 +170,17 @@ async def capture(self, event: McpEvent, options: McpCaptureOptions) -> None: log(f"Failed to capture PostHog event {full_event.get('id')}: {err}") async def flush(self) -> None: - # Client.flush() blocks for up to its timeout when ingest stalls. A thread - # per call keeps it out of any shared pool, so a stalled flush never delays - # another flush or the loop's default executor, and no pool outlives a fork. - done: concurrent.futures.Future[None] = concurrent.futures.Future() - # A running future ignores cancel(), so cancelling this await can't make - # the worker's set_result() raise. - done.set_running_or_notify_cancel() - - def run() -> None: - try: - self._posthog.flush() - done.set_result(None) - except BaseException as err: - done.set_exception(err) - + # Client.flush() blocks for up to its timeout when ingest stalls, so it runs + # on its own thread, never a shared pool. A flush already running when we + # were called may have missed our events: wait for it, then join or start + # one that began after. try: - threading.Thread(target=run, name="posthog-mcp-flush", daemon=True).start() - await asyncio.wrap_future(done) + with _client_flushes_lock: + running = _client_flushes.get(self._posthog) + if running is not None: + await asyncio.wait({asyncio.wrap_future(running)}) + await asyncio.wrap_future( + _client_flush_started_after(self._posthog, running) + ) except Exception as err: log(f"Failed to flush PostHog events: {err}") diff --git a/posthog/test/mcp/test_fastmcp.py b/posthog/test/mcp/test_fastmcp.py index 6994f7130..d229fdf87 100644 --- a/posthog/test/mcp/test_fastmcp.py +++ b/posthog/test/mcp/test_fastmcp.py @@ -291,6 +291,34 @@ def flush(self, timeout_seconds=10): await asyncio.gather(*flushing) +async def test_overlapping_analytics_flushes_run_one_client_flush_at_a_time(): + release = threading.Event() + lock = threading.Lock() + + class StalledFlushClient(FakeClient): + def __init__(self): + super().__init__() + self.running = 0 + self.most_running = 0 + + def flush(self, timeout_seconds=10): + with lock: + self.running += 1 + self.most_running = max(self.most_running, self.running) + release.wait(timeout=5) + with lock: + self.running -= 1 + + client = StalledFlushClient() + handles = [instrument(make_server(), client) for _ in range(20)] + flushing = [asyncio.ensure_future(analytics.flush()) for analytics in handles] + await asyncio.sleep(0.05) + release.set() + await asyncio.wait_for(asyncio.gather(*flushing), 2) + + assert client.most_running == 1 + + @pytest.mark.skipif(not hasattr(os, "fork"), reason="needs os.fork") async def test_analytics_flush_works_in_a_forked_child(): analytics = instrument(make_server(), FakeClient()) From 24c11845abd61987c95539095d813e98def4fd97 Mon Sep 17 00:00:00 2001 From: Lucas Faria Date: Wed, 25 Nov 2026 21:25:45 -0300 Subject: [PATCH 6/6] fix(mcp): drop finished client flushes and consume earlier failures 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/mcp/_sink.py | 9 ++++++- posthog/test/mcp/test_fastmcp.py | 42 ++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/posthog/mcp/_sink.py b/posthog/mcp/_sink.py index bc8bd0442..ec4531a7a 100644 --- a/posthog/mcp/_sink.py +++ b/posthog/mcp/_sink.py @@ -15,6 +15,7 @@ import asyncio import concurrent.futures +import contextlib import inspect import os import threading @@ -62,6 +63,10 @@ def run() -> None: done.set_result(None) except BaseException as err: done.set_exception(err) + finally: + with _client_flushes_lock: + if _client_flushes.get(client) is done: + del _client_flushes[client] threading.Thread(target=run, name="posthog-mcp-flush", daemon=True).start() return done @@ -178,7 +183,9 @@ async def flush(self) -> None: with _client_flushes_lock: running = _client_flushes.get(self._posthog) if running is not None: - await asyncio.wait({asyncio.wrap_future(running)}) + # Its failure is logged by the caller that started it. + with contextlib.suppress(Exception): + await asyncio.wrap_future(running) await asyncio.wrap_future( _client_flush_started_after(self._posthog, running) ) diff --git a/posthog/test/mcp/test_fastmcp.py b/posthog/test/mcp/test_fastmcp.py index d229fdf87..8b56b08c4 100644 --- a/posthog/test/mcp/test_fastmcp.py +++ b/posthog/test/mcp/test_fastmcp.py @@ -1,7 +1,9 @@ """End-to-end tests for the FastMCP adapter (Milestone 2).""" import asyncio +import gc import os +import weakref import threading from concurrent.futures import ThreadPoolExecutor from types import SimpleNamespace @@ -319,6 +321,46 @@ def flush(self, timeout_seconds=10): assert client.most_running == 1 +async def test_a_failed_analytics_flush_lets_the_client_be_collected(): + client = _FailingFlushClient() + analytics = instrument(make_server(), client) + await analytics.flush() + client_ref = weakref.ref(client) + for thread in threading.enumerate(): + if thread.name == "posthog-mcp-flush": + thread.join(timeout=2) + await asyncio.sleep(0) + + del client, analytics + gc.collect() + + assert client_ref() is None + + +async def test_a_failed_earlier_flush_does_not_reach_the_loop_exception_handler(): + loop_errors = [] + loop = asyncio.get_running_loop() + loop.set_exception_handler(lambda _loop, context: loop_errors.append(context)) + release = threading.Event() + + class StalledFailingClient(FakeClient): + def flush(self, timeout_seconds=10): + release.wait(timeout=5) + raise RuntimeError("network down") + + client = StalledFailingClient() + first = asyncio.ensure_future(instrument(make_server(), client).flush()) + await asyncio.sleep(0.05) + second = asyncio.ensure_future(instrument(make_server(), client).flush()) + await asyncio.sleep(0.05) + release.set() + await asyncio.wait_for(asyncio.gather(first, second), 2) + gc.collect() + await asyncio.sleep(0) + + assert loop_errors == [] + + @pytest.mark.skipif(not hasattr(os, "fork"), reason="needs os.fork") async def test_analytics_flush_works_in_a_forked_child(): analytics = instrument(make_server(), FakeClient())