Skip to content

: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.

chore(ci): selective flush for transactional tests (#104784)

Raúl Negrón-Oterod94b3418adc0
diff --git a/posthog/conftest.py b/posthog/conftest.py
index 46c6c890c14a..2cff99706956 100644
--- a/posthog/conftest.py
+++ b/posthog/conftest.py
@@ -1,15 +1,16 @@
import os
import time
+import logging
import warnings
import subprocess
from collections.abc import Callable
from functools import partial
from pathlib import Path
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Any, cast
from urllib.parse import quote_plus
import pytest
-from posthog.test.base import PostHogTestCase, run_clickhouse_statement_in_parallel
+from posthog.test.base import PostHogTestCase, _selective_flush, run_clickhouse_statement_in_parallel
from _pytest.junitxml import ET, bin_xml_escape, mangle_test_address
@@ -23,6 +24,8 @@ except ImportError: # fail-open: runs without tools/hogli-commands on pythonpat
from django.conf import settings
from django.core.management.commands.flush import Command as FlushCommand
+from django.db import connections
+from django.test import TransactionTestCase
from infi.clickhouse_orm import Database
@@ -30,6 +33,8 @@ from posthog.clickhouse.client import sync_execute
from posthog.cloud_utils import is_ci
from posthog.test import flush_lock_guard
+logger = logging.getLogger(__name__)
+
def create_clickhouse_tables():
# Create clickhouse tables to default before running test
@@ -466,6 +471,40 @@ _original_flush_handle = FlushCommand.handle
FlushCommand.handle = _patched_flush_handle # type: ignore[method-assign]
+def _another_session_is_busy(db_name: str) -> bool:
+ with connections[db_name].cursor() as cursor:
+ cursor.execute(
+ "SELECT EXISTS (SELECT FROM pg_stat_activity WHERE datname = current_database()"
+ " AND pid <> pg_backend_pid() AND backend_type = 'client backend' AND state <> 'idle')"
+ )
+ return cursor.fetchone() == (True,)
+
+
+def _patched_fixture_teardown(self: TransactionTestCase) -> None:
+ """
+ Use the selective flush of NonAtomicBaseTest instead of the stock flush, which truncates every
+ table and re-seeds content types and permissions after each ``django_db(transaction=True)`` test.
+
+ Keep the stock flush while another session is busy, such as a Temporal worker thread: TRUNCATE
+ waits for that session's transaction, but the selective probe and DELETE do not, so rows it
+ commits later would leak into the next test.
+ """
+ db_names = cast(Any, self)._databases_names(include_mirrors=False)
+ if self.available_apps is not None or self.serialized_rollback or any(map(_another_session_is_busy, db_names)):
+ _original_fixture_teardown(self)
+ return
+ try:
+ for db_name in db_names:
+ _selective_flush(db_name, reset_sequences=False)
+ except Exception:
+ logger.exception("Selective flush failed; falling back to the stock teardown")
+ _original_fixture_teardown(self)
+
+
+_original_fixture_teardown = TransactionTestCase._fixture_teardown # type: ignore[attr-defined]
+TransactionTestCase._fixture_teardown = _patched_fixture_teardown # type: ignore[attr-defined]
+
+
@pytest.fixture
def base_test_mixin_fixture():
kls = PostHogTestCase()
diff --git a/posthog/temporal/README.md b/posthog/temporal/README.md
index 42c5cab07103..82c7c2d2945c 100644
--- a/posthog/temporal/README.md
+++ b/posthog/temporal/README.md
@@ -502,7 +502,8 @@ Per Temporal's own guidance: write the **majority** of tests as the cheapest har
Async tests that touch the Django ORM via `sync_to_async` / `database_sync_to_async` will fail without `@pytest.mark.django_db(transaction=True)`. asgiref dispatches the wrapped sync function to a separate thread, which gets its own DB connection, which can't see the test's wrapping atomic transaction. The test will create a row, the activity will fail to find it.
-`transaction=True` swaps fast transaction-rollback for slow TRUNCATE-everything between tests. This is the correct workaround — there's no clean way to share a Django connection across threads — but it's expensive, so **only use it when needed**:
+`transaction=True` swaps fast transaction-rollback for a flush between tests, which deletes the rows of every table the test wrote.
+The flush keeps `django_content_type` and `auth_permission`, so a test that changes those rows leaks the change to later tests. This is the correct workaround — there's no clean way to share a Django connection across threads — but it's slower, so **only use it when needed**:
```python
# Async test + Django ORM = needs transaction=True