:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
perf(warehouse-sources): speed up backend test suite ~12x (#69665)
Tom Owersbc40f23be231
diff --git a/conftest.py b/conftest.pyindex 7a41afc825a2..9b3ab84b1117 100644--- a/conftest.py+++ b/conftest.py@@ -22,6 +22,11 @@ def _end_gc_boot_window() -> None:# reclaims only ~1MB, so the garbage gets frozen along with the survivors.gc.freeze()gc.enable()+ # Collect far less often than the default (700, 10, 10): test runs allocate heavily and+ # cyclic garbage is reclaimed fine at these thresholds, while frequent young-gen sweeps+ # over a large frozen heap cost real wall time (~10% of a unit-heavy suite; measured on+ # products/warehouse_sources with peak RSS within 1% of the default thresholds).+ gc.set_threshold(50_000, 20, 20)# gc.get_referrers() cannot see referrers in the frozen permanent generation,# which turns hypothesis's register_random() liveness check into a false positive# for Randoms registered after the freeze (e.g. trio's module-level instance,diff --git a/posthog/personhog_client/fake_client.py b/posthog/personhog_client/fake_client.pyindex 56f5b1185b57..5f8f674c8dee 100644--- a/posthog/personhog_client/fake_client.py+++ b/posthog/personhog_client/fake_client.py@@ -763,14 +763,25 @@ def activate_personhog_fake():persons-DB ORM access so a stray Person.objects.* call fails loudly. Testhelpers in posthog.test.persons seed the fake explicitly when creating data."""+ import posthog.personhog_client.client as personhog_client_module # noqa: PLC0415from posthog.person_db_router import block_persons_orm, unblock_persons_orm # noqa: PLC0415fake = FakePersonHogClient()set_active_fake(fake)block_persons_orm()- with patch("posthog.personhog_client.client.get_personhog_client", return_value=fake):- try:- yield fake- finally:- unblock_persons_orm()- set_active_fake(None)++ # Plain attribute swap instead of mock.patch: this context manager wraps every test in the+ # repo, and mock.patch's MagicMock construction is measurable at that volume. The swap is+ # equivalent — both replace the same module attribute — and tests that patch the client+ # themselves still layer over it and restore this one on exit.+ def _get_fake_client() -> Any:+ return fake++ original_get_client = personhog_client_module.get_personhog_client+ personhog_client_module.get_personhog_client = _get_fake_client # ty: ignore[invalid-assignment]+ try:+ yield fake+ finally:+ personhog_client_module.get_personhog_client = original_get_client+ unblock_persons_orm()+ set_active_fake(None)diff --git a/products/warehouse_sources/backend/conftest.py b/products/warehouse_sources/backend/conftest.pynew file mode 100644index 000000000000..9135316a1d50--- /dev/null+++ b/products/warehouse_sources/backend/conftest.py@@ -0,0 +1,62 @@+import os+import sys+import subprocess+from collections.abc import Generator++import pytest++# Runs in a clean interpreter — the pytest process imports the google-ads SDK itself (via the+# google_ads test modules), so we can't inspect this process's sys.modules.+_SDK_LEAK_CHECK = """+import os, sys+os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")+import django+django.setup()+from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+SourceRegistry._ensure_loaded()+print("\\n".join(sorted(m for m in sys.modules if m.startswith("google.ads"))))+"""++_LEAK_TEST_NAME = "test_source_registration_does_not_import_google_ads_sdk"+++class SdkLeakCheck:+ """Handle for the leak-check subprocess; caches the result so reruns see the same outcome."""++ def __init__(self, proc: subprocess.Popen) -> None:+ self._proc = proc+ self._result: tuple[int, str, str] | None = None++ def result(self, timeout: float) -> tuple[int, str, str]:+ if self._result is None:+ stdout, stderr = self._proc.communicate(timeout=timeout)+ self._result = (self._proc.returncode, stdout, stderr)+ return self._result++[email protected](scope="session", autouse=True)+def google_ads_sdk_leak_check(request: pytest.FixtureRequest) -> Generator[SdkLeakCheck | None]:+ """Start the SDK-leak-check subprocess at session start so its ~15s of interpreter boot+ (django.setup + full source registry import) overlaps the rest of the suite instead of+ blocking the test that asserts on it. Only launched when that test is actually selected+ (it may live in a different shard).++ Hand the child our import paths so `import posthog` / `products.*` resolves regardless of+ the working directory (the product test job runs pytest from products/warehouse_sources/,+ not the repo root, so a bare `python -c` wouldn't find the repo packages on cwd alone).+ """+ if not any(item.name.startswith(_LEAK_TEST_NAME) for item in request.session.items):+ yield None+ return++ env = {**os.environ, "PYTHONPATH": os.pathsep.join(p for p in sys.path if p)}+ proc = subprocess.Popen(+ [sys.executable, "-c", _SDK_LEAK_CHECK],+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ text=True,+ env=env,+ )+ yield SdkLeakCheck(proc)+ if proc.poll() is None:+ proc.kill()diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/test_consumer.pyindex b66c26979764..74528b89c207 100644--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/test_consumer.py+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/kafka/test_consumer.py@@ -370,10 +370,12 @@ class TestProcessBatchPersistentRetry:assert call_order == ["increment", "process"]+ # The in-process retry loop sleeps its real exponential backoff between attempts; skip it.+ @patch("time.sleep", return_value=None)@patch(f"{RETRY_TRACKER_PATH}.update_retry_error_type")@patch(f"{RETRY_TRACKER_PATH}.increment_retry_count", return_value=RetryInfo(count=1))@patch(f"{RETRY_TRACKER_PATH}.get_retry_info", return_value=RetryInfo(count=0))- def test_transient_error_classified_correctly(self, mock_get, mock_inc, mock_update):+ def test_transient_error_classified_correctly(self, mock_get, mock_inc, mock_update, _sleep):process_fn = MagicMock(side_effect=ConnectionError("reset"))service = self._setup_service(process_message=process_fn)msg = _make_message()diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/jsonpath_utils.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/jsonpath_utils.pyindex 0586b81d8dff..03e228a1e4e8 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/jsonpath_utils.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/rest_source/jsonpath_utils.py@@ -1,3 +1,4 @@+import functoolsfrom typing import Any, Unionfrom jsonpath_ng import JSONPath@@ -6,10 +7,18 @@ from jsonpath_ng.ext import parse as jsonpath_parseTJsonPath = Union[str, JSONPath]+# jsonpath_ng builds a fresh PLY LR parser table on every parse() call (~10ms each), and the+# same handful of path strings (results_path, next_url_path, ...) are re-compiled for every+# page of every request. Compiled expressions are immutable, so cache by source string.[email protected]_cache(maxsize=1024)+def _compile_path_cached(path: str) -> JSONPath:+ return jsonpath_parse(path)++def compile_path(path: TJsonPath) -> JSONPath:if isinstance(path, JSONPath):return path- return jsonpath_parse(path)+ return _compile_path_cached(path)def find_values(path: TJsonPath, data: dict[str, Any]) -> list[Any]:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_webhook_s3.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_webhook_s3.pyindex f77d42ab71a5..e297993116e7 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_webhook_s3.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/test/test_webhook_s3.py@@ -1,6 +1,7 @@from __future__ import annotationsimport uuid+import asyncioimport functoolsimport contextlib@@ -15,6 +16,7 @@ import orjsonimport pyarrow as paimport aioboto3import pyarrow.parquet as pq+from aiobotocore.config import AioConfigfrom parameterized import parameterizedfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.webhook_s3 import (@@ -47,7 +49,13 @@ def _make_webhook_parquet_bytes(payloads: list[dict], team_id: int = 1, schema_iBUCKET_NAME = "test-webhook-s3"SESSION = aioboto3.Session()-create_test_client = functools.partial(SESSION.client, endpoint_url=settings.OBJECT_STORAGE_ENDPOINT)+# Fail fast against the local object store: it's either up (ops succeed first try) or absent+# (retry storms only slow the suite down before erroring anyway).+create_test_client = functools.partial(+ SESSION.client,+ endpoint_url=settings.OBJECT_STORAGE_ENDPOINT,+ config=AioConfig(connect_timeout=1, read_timeout=30, retries={"max_attempts": 1, "mode": "standard"}),+)def _make_inputs(**overrides) -> MagicMock:@@ -409,8 +417,35 @@ async def _minio_key_exists(minio_client, key: str) -> bool:return False[email protected](scope="session")+def _object_store_unreachable() -> str | None:+ """Probe the object store once per session; the error string when it's unreachable.++ Each MinIO-backed test otherwise pays the full connection timeout independently just to+ error with the same message when the store isn't running.+ """++ async def _probe() -> None:+ async with create_test_client(+ "s3",+ aws_access_key_id=settings.OBJECT_STORAGE_ACCESS_KEY_ID,+ aws_secret_access_key=settings.OBJECT_STORAGE_SECRET_ACCESS_KEY,+ ) as client:+ await client.list_buckets()++ try:+ asyncio.run(_probe())+ return None+ except Exception as exc:+ return f"{type(exc).__name__}: {exc}"++@pytest.fixture-async def minio_client():+async def minio_client(_object_store_unreachable):+ if _object_store_unreachable is not None:+ raise ConnectionError(+ f"object store at {settings.OBJECT_STORAGE_ENDPOINT} is unreachable: {_object_store_unreachable}"+ )async with create_test_client("s3",aws_access_key_id=settings.OBJECT_STORAGE_ACCESS_KEY_ID,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/conftest.py b/products/warehouse_sources/backend/temporal/data_imports/sources/conftest.pynew file mode 100644index 000000000000..2b2d29ffc9a4--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/conftest.py@@ -0,0 +1,32 @@+import time+from collections.abc import Generator+from typing import SupportsIndex++import pytest++_real_sleep = time.sleep+++def _capped_sleep(seconds: SupportsIndex | float, /) -> None:+ _real_sleep(min(float(seconds), 0.001))++[email protected](autouse=True)+def _cap_backoff_sleeps() -> Generator[None]:+ """Cap time.sleep so retry/backoff waits don't run at real duration.++ Nearly every source wraps its HTTP calls in tenacity retries (or hand-rolled+ loops) with multi-second exponential backoff, and time.sleep is the only wait+ primitive they use. Tests that exercise those retry paths otherwise spend real+ minutes asleep. Capping (rather than fully no-oping) keeps sleep()-based thread+ yields working. Tests that patch time.sleep themselves are unaffected: their+ patch layers over this one and restores it on exit.++ A plain attribute swap rather than mock.patch: this runs for every test in the+ sources tree, and MagicMock construction is measurable at that volume.+ """+ time.sleep = _capped_sleep # ty: ignore[invalid-assignment]+ try:+ yield+ finally:+ time.sleep = _real_sleepdiff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_google_ads_source.py b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_google_ads_source.pyindex 1846f28506bd..71e26aa324e4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_google_ads_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/e2e/test_google_ads_source.py@@ -1,7 +1,5 @@import os-import sysimport json-import subprocessfrom collections.abc import Iterablefrom dataclasses import dataclass@@ -629,32 +627,17 @@ class TestGoogleAdsClientStaleConnection:mock_close_old_connections.assert_not_called()-# Runs in a clean interpreter — this test module imports the google-ads SDK itself, so we can't-# inspect this process's sys.modules.-_SDK_LEAK_CHECK = """-import os, sys-os.environ.setdefault("DJANGO_SETTINGS_MODULE", "posthog.settings")-import django-django.setup()-from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry-SourceRegistry._ensure_loaded()-print("\\n".join(sorted(m for m in sys.modules if m.startswith("google.ads"))))-"""---def test_source_registration_does_not_import_google_ads_sdk() -> None:+def test_source_registration_does_not_import_google_ads_sdk(google_ads_sdk_leak_check) -> None:# google-ads has a circular module graph that is only safe to import single-threaded; importing# it from concurrent worker threads deadlocks or duplicate-registers its protobuf descriptors.# So registering sources (load_all_sources, which any sync triggers via SourceRegistry) must NOT# import the SDK — it loads lazily only when a google-ads sync actually runs. This guards the# split between configs.py (lightweight, registered) and google_ads.py (SDK, deferred).- # Hand the child our import paths so `import posthog` / `products.*` resolves regardless of the- # working directory (the product test job runs pytest from products/warehouse_sources/, not the- # repo root, so a bare `python -c` wouldn't find the repo packages on cwd alone).- env = {**os.environ, "PYTHONPATH": os.pathsep.join(p for p in sys.path if p)}- result = subprocess.run(- [sys.executable, "-c", _SDK_LEAK_CHECK], capture_output=True, text=True, timeout=120, env=env- )- assert result.returncode == 0, result.stderr[-2000:]- leaked = [m for m in result.stdout.splitlines() if m]+ # The clean-interpreter subprocess doing the check is launched at session start by the+ # google_ads_sdk_leak_check fixture (products/warehouse_sources/backend/conftest.py) so its+ # interpreter boot overlaps the rest of the suite; this test just collects its verdict.+ assert google_ads_sdk_leak_check is not None+ returncode, stdout, stderr = google_ads_sdk_leak_check.result(timeout=120)+ assert returncode == 0, stderr[-2000:]+ leaked = [m for m in stdout.splitlines() if m]assert not leaked, f"google-ads SDK imported during source registration: {leaked[:5]}"