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..ec4531a7a 100644 --- a/posthog/mcp/_sink.py +++ b/posthog/mcp/_sink.py @@ -13,9 +13,15 @@ from __future__ import annotations +import asyncio +import concurrent.futures +import contextlib 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 @@ -27,6 +33,57 @@ 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) + 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 + + +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.""" @@ -116,3 +173,21 @@ 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: + # 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: + with _client_flushes_lock: + running = _client_flushes.get(self._posthog) + if running is not None: + # 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) + ) + 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..8b56b08c4 100644 --- a/posthog/test/mcp/test_fastmcp.py +++ b/posthog/test/mcp/test_fastmcp.py @@ -1,6 +1,11 @@ """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 import pytest @@ -8,7 +13,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 +177,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 +196,185 @@ 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)] + + +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(), client_class(), MCPAnalyticsOptions(logger=lines.append) + ) + await analytics.flush() + finally: + set_logger(None) + + 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(): + 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_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) + + +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 + + +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()) + 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():