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.

fix(ci): unblock test teardown flush from leaked temporal worker sessions (#62548)

Raúl Negrón-Oteroa8ab32175e1e
diff --git a/posthog/conftest.py b/posthog/conftest.py
index ddd313d2ee38..a8428c3b5281 100644
--- a/posthog/conftest.py
+++ b/posthog/conftest.py
@@ -1,5 +1,7 @@
import os
import subprocess
+from collections.abc import Callable
+from functools import partial
from typing import Any
from urllib.parse import quote_plus
@@ -13,6 +15,7 @@ from django.db import connections
from infi.clickhouse_orm import Database
from posthog.clickhouse.client import sync_execute
+from posthog.test import flush_lock_guard
def create_clickhouse_tables():
@@ -332,9 +335,31 @@ def django_db_setup(django_db_setup, django_db_keepdb, django_db_blocker):
yield from _django_db_setup(django_db_keepdb, django_db_blocker)
+def pytest_terminal_summary(terminalreporter: Any, exitstatus: int, config: Any) -> None:
+ # Drain rather than iterate: products/conftest.py star-imports this hook, so it can
+ # be invoked once per registering conftest.
+ while flush_lock_guard.reports:
+ terminalreporter.write_line(f"[flush-lock-guard] {flush_lock_guard.reports.pop(0)}", yellow=True)
+
+
+def _truncate_persons_db_tables(database: str) -> None:
+ conn = connections[database]
+ with conn.cursor() as cursor:
+ cursor.execute("""
+ SELECT tablename FROM pg_tables
+ WHERE schemaname = 'public'
+ AND tablename NOT LIKE 'pg_%'
+ AND tablename NOT LIKE '_sqlx_%'
+ AND tablename NOT LIKE '_persons_migrations'
+ """)
+ tables = [row[0] for row in cursor.fetchall()]
+ if tables:
+ cursor.execute(f"TRUNCATE TABLE {', '.join(tables)} RESTART IDENTITY CASCADE")
+
+
def _patched_flush_handle(self, **options: Any) -> None:
"""
- Patched Django flush command for two reasons:
+ Patched Django flush command for three reasons:
1. Persons database doesn't have Django's built-in tables (contenttypes,
permissions), so we skip post_migrate signals by truncating manually.
@@ -343,28 +368,24 @@ def _patched_flush_handle(self, **options: Any) -> None:
Django doesn't know about. CASCADE lets TRUNCATE succeed even when
unknown FK constraints reference a table being flushed.
+ 3. TRUNCATE waits on an ACCESS EXCLUSIVE lock, so one leaked idle-in-transaction
+ session (e.g. from a background worker thread) hangs teardown until the CI job
+ timeout. flush_lock_guard turns that silent hang into a loud, self-healing
+ terminate-and-retry.
+
Applied at module level (not via monkeypatch) so it stays active during
pytest-django's _post_teardown, which runs flush AFTER function-scoped
fixture teardown.
"""
- database = options.get("database")
+ database = options["database"]
if database in ("persons_db_writer", "persons_db_reader"):
- conn = connections[database]
- with conn.cursor() as cursor:
- cursor.execute("""
- SELECT tablename FROM pg_tables
- WHERE schemaname = 'public'
- AND tablename NOT LIKE 'pg_%'
- AND tablename NOT LIKE '_sqlx_%'
- AND tablename NOT LIKE '_persons_migrations'
- """)
- tables = [row[0] for row in cursor.fetchall()]
- if tables:
- cursor.execute(f"TRUNCATE TABLE {', '.join(tables)} RESTART IDENTITY CASCADE")
+ flush: Callable[[], None] = partial(_truncate_persons_db_tables, database)
else:
options["allow_cascade"] = True
- return _original_flush_handle(self, **options)
+ flush = partial(_original_flush_handle, self, **options)
+
+ flush_lock_guard.flush_with_lock_guard(database, flush)
_original_flush_handle = FlushCommand.handle
diff --git a/posthog/temporal/common/test_utils.py b/posthog/temporal/common/test_utils.py
index 917ae6984f36..9bdfe7002369 100644
--- a/posthog/temporal/common/test_utils.py
+++ b/posthog/temporal/common/test_utils.py
@@ -1,14 +1,21 @@
+import sys
import time
import asyncio
+import logging
import datetime as dt
import threading
from collections.abc import Callable, Sequence
from contextlib import contextmanager
+from django.db import connections
+
import temporalio.worker
+from asgiref.sync import sync_to_async
from temporalio.client import Client as TemporalClient
from temporalio.worker import Worker
+logger = logging.getLogger(__name__)
+
class ThreadedWorker(Worker):
"""A Temporal Worker that can run in a separate thread.
@@ -17,7 +24,7 @@ class ThreadedWorker(Worker):
"""
@contextmanager
- def run_in_thread(self, *, startup_timeout: float = 30.0):
+ def run_in_thread(self, *, startup_timeout: float = 30.0, shutdown_timeout: float = 60.0):
"""Run a Temporal Worker in a thread.
Don't use this outside of tests. Once PostHog is fully async we can get rid of this.
@@ -54,14 +61,27 @@ class ThreadedWorker(Worker):
time.sleep(0.1)
yield
finally:
- self._shutdown_event.set()
- # Give the worker a chance to shut down before exiting
- max_wait = 10.0
- while t.is_alive() and max_wait > 0:
- time.sleep(0.1)
- max_wait -= 0.1
+ try:
+ # asyncio primitives aren't thread-safe: set() can raise if the worker crashed
+ # and closed its loop, and the no-op callback forces a loop wakeup so run()
+ # observes the event (a cross-thread set() alone doesn't wake the selector).
+ self._shutdown_event.set()
+ loop.call_soon_threadsafe(lambda: None)
+ except RuntimeError:
+ pass # loop already closed: the worker thread finished (or crashed) on its own
+ # An abandoned worker thread can hold open database sessions (idle in transaction)
+ # that block the teardown TRUNCATE of the whole test database — fail loudly instead.
+ t.join(timeout=shutdown_timeout)
+ if t.is_alive():
+ message = f"Temporal test worker thread did not shut down within {shutdown_timeout:g}s"
+ if sys.exc_info()[0] is not None:
+ # Raising here would replace the in-flight exception (the likely root
+ # cause of the wedged worker) — report instead of masking it.
+ logger.error(message)
+ else:
+ raise RuntimeError(message)
- def run_using_loop(self, loop):
+ def run_using_loop(self, loop: asyncio.AbstractEventLoop) -> None:
"""Setup an event loop to run the Worker.
Using async_to_sync(Worker.run) causes a deadlock.
@@ -70,8 +90,23 @@ class ThreadedWorker(Worker):
try:
loop.run_until_complete(super().run())
finally:
- loop.run_until_complete(loop.shutdown_asyncgens())
- loop.close()
+ try:
+ loop.run_until_complete(loop.shutdown_asyncgens())
+ # Join the loop's default executor (asyncio.to_thread file/network work),
+ # bounded: a thread wedged on an uncancellable call must not hang shutdown.
+ # type-ignore: typeshed's AbstractEventLoop lacks the timeout param that
+ # the concrete BaseEventLoop has since Python 3.12.
+ loop.run_until_complete(loop.shutdown_default_executor(timeout=10)) # type: ignore[call-arg]
+ # Activity ORM code runs via thread-sensitive sync_to_async on asgiref's
+ # long-lived global executor thread; hop onto that same thread to close its
+ # Django connections — a session leaked idle-in-transaction there blocks
+ # the teardown TRUNCATE of the whole test database.
+ loop.run_until_complete(asyncio.wait_for(sync_to_async(connections.close_all)(), timeout=10))
+ except (TimeoutError, RuntimeError):
+ logger.exception("Could not fully clean up Temporal test worker executors/connections")
+ finally:
+ loop.close()
+ connections.close_all()
@contextmanager
diff --git a/posthog/test/flush_lock_guard.py b/posthog/test/flush_lock_guard.py
new file mode 100644
index 000000000000..8d9b3b919e07
--- /dev/null
+++ b/posthog/test/flush_lock_guard.py
@@ -0,0 +1,128 @@
+"""Self-healing lock guard for the teardown flush of test databases.
+
+TRUNCATE needs an ACCESS EXCLUSIVE lock on every flushed table, so a single leaked
+idle-in-transaction session (e.g. a background worker thread that never closed its
+transaction) blocks teardown forever and the CI job dies at its timeout with no
+diagnostics. Instead: time out quickly, name and terminate the blockers, retry once.
+
+Wired into Django's flush command by posthog/conftest.py, which also reports
+self-heal events (``reports``) at the end of the run.
+"""
+
+import logging
+import warnings
+from collections.abc import Callable
+
+from django.db import connections
+
+from psycopg import errors as psycopg_errors
+
+logger = logging.getLogger(__name__)
+
+# How long a teardown flush may wait on a Postgres lock before we terminate
+# idle-in-transaction blockers and retry. Generous: nothing legitimate holds a table lock
+# for anywhere near this long in tests.
+FLUSH_LOCK_TIMEOUT_SECONDS = 30
+
+# Self-heal events surfaced at the end of the run: pytest.ini ships `-p no:warnings`, so
+# warnings.warn alone would be invisible in CI for passing tests.
+reports: list[str] = []
+
+
+def _is_lock_timeout(exc: BaseException | None) -> bool:
+ # Walk both __cause__ and __context__: Django/management wrapping usually chains via
+ # __cause__, but a LockNotAvailable can sit on __context__ when both are set.
+ stack = [exc] if exc is not None else []
+ seen: set[int] = set()
+ while stack:
+ current = stack.pop()
+ if id(current) in seen:
+ continue
+ seen.add(id(current))
+ if isinstance(current, psycopg_errors.LockNotAvailable):
+ return True
+ stack.extend(linked for linked in (current.__cause__, current.__context__) if linked is not None)
+ return False
+
+
+def _snapshot_sessions(database: str) -> tuple[list[str], list[int]]:
+ """Describe other sessions on this connection's database (any state, for diagnostics —
+ an *active* blocker should still be named even though we never kill it) and identify
+ the leaked ones: idle in transaction since before our lock wait began, so provably
+ the blocker. A session merely *between* statements of an in-flight transaction
+ (idle-in-transaction for milliseconds, e.g. a concurrent background thread mid-INSERT)
+ is not considered leaked.
+ """
+ with connections[database].cursor() as cursor:
+ cursor.execute(
+ """
+ SELECT pid, usename, application_name, state, wait_event_type, wait_event,
+ now() - xact_start AS xact_age,
+ now() - state_change AS state_age,
+ COALESCE(state_change < now() - make_interval(secs => %s), FALSE) AS stale,
+ query
+ FROM pg_stat_activity
+ WHERE datname = current_database()
+ AND pid != pg_backend_pid()
+ AND backend_type = 'client backend'
+ """,
+ [FLUSH_LOCK_TIMEOUT_SECONDS],
+ )
+ sessions = cursor.fetchall()
+ descriptions = [
+ f"pid={pid} user={user} app={app!r} state={state!r} wait_event={wait_type}/{wait_event} "
+ f"xact_age={xact_age} state_age={state_age} last_query={query!r}"
+ for pid, user, app, state, wait_type, wait_event, xact_age, state_age, _stale, query in sessions
+ ]
+ leaked_pids = [row[0] for row in sessions if row[3] and row[3].startswith("idle in transaction") and row[8]]
+ return descriptions, leaked_pids
+
+
+def _terminate_leaked_sessions(database: str) -> tuple[list[str], int]:
+ descriptions, leaked_pids = _snapshot_sessions(database)
+ if leaked_pids:
+ with connections[database].cursor() as cursor:
+ cursor.execute("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE pid = ANY(%s)", [leaked_pids])
+ return descriptions, len(leaked_pids)
+
+
+def flush_with_lock_guard(database: str, flush: Callable[[], None]) -> None:
+ """Run a teardown flush with a session lock_timeout and a terminate-and-retry fallback."""
+ conn = connections[database]
+ with conn.cursor() as cursor:
+ cursor.execute("SELECT set_config('lock_timeout', %s, false)", [f"{FLUSH_LOCK_TIMEOUT_SECONDS}s"])
+ try:
+ flush()
+ except Exception as err:
+ if not _is_lock_timeout(err):
+ raise
+ sessions, terminated = _terminate_leaked_sessions(database)
+ sessions_desc = "; ".join(sessions)
+ message = (
+ f"Teardown flush of {database!r} timed out after {FLUSH_LOCK_TIMEOUT_SECONDS}s waiting for a "
+ f"table lock; terminated {terminated} idle-in-transaction session(s) of {len(sessions)} on the "
+ f"database, retrying once: {sessions_desc}"
+ )
+ logger.exception(message)
+ warnings.warn(message, stacklevel=2)
+ reports.append(message)
+ try:
+ flush()
+ except Exception as retry_err:
+ try:
+ current_sessions, _ = _snapshot_sessions(database)
+ except Exception:
+ current_sessions = ["<snapshot unavailable>"]
+ raise RuntimeError(
+ f"Teardown flush of {database!r} failed again after terminating {terminated} "
+ f"idle-in-transaction session(s); sessions now: {'; '.join(current_sessions)} | "
+ f"at first failure: {sessions_desc}"
+ ) from retry_err
+ finally:
+ try:
+ with conn.cursor() as cursor:
+ cursor.execute("RESET lock_timeout")
+ except Exception:
+ # The flush may have failed because the connection itself died; raising here
+ # would mask that original error, and a reconnect gets fresh session state anyway.
+ logger.warning("Could not reset lock_timeout after flushing %r", database, exc_info=True)
diff --git a/posthog/test/test_flush_lock_guard.py b/posthog/test/test_flush_lock_guard.py
new file mode 100644
index 000000000000..6c72a4fadf26
--- /dev/null
+++ b/posthog/test/test_flush_lock_guard.py
@@ -0,0 +1,36 @@
+import pytest
+
+from django.core.management import call_command
+from django.db import connections
+
+import psycopg
+
+from posthog.test import flush_lock_guard
+
+
[email protected]_db(transaction=True)
+def test_flush_terminates_idle_in_transaction_blocker(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(flush_lock_guard, "FLUSH_LOCK_TIMEOUT_SECONDS", 1)
+
+ blocker = psycopg.connect(**connections["default"].get_connection_params())
+ try:
+ # An open transaction holding ACCESS SHARE on a flushed table blocks TRUNCATE's
+ # ACCESS EXCLUSIVE lock — the state a leaked background-thread session leaves behind.
+ blocker.execute("SELECT 1 FROM posthog_organization")
+
+ with pytest.warns(UserWarning, match="idle-in-transaction"):
+ call_command(
+ "flush",
+ verbosity=0,
+ interactive=False,
+ database="default",
+ reset_sequences=False,
+ # pytest-django's own teardown flush re-runs post_migrate right after this
+ # test; skipping it here avoids a duplicate contenttypes/permissions re-sync.
+ inhibit_post_migrate=True,
+ )
+
+ with pytest.raises(psycopg.OperationalError):
+ blocker.execute("SELECT 1")
+ finally:
+ blocker.close()