: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
chore(tests): deflake backend test offenders (#68725)
Raúl Negrón-Otero2a3c22e7fc97
diff --git a/ee/api/test/test_admin_oauth2_middleware.py b/ee/api/test/test_admin_oauth2_middleware.pyindex 440e11a9ea63..10caddcc5a02 100644--- a/ee/api/test/test_admin_oauth2_middleware.py+++ b/ee/api/test/test_admin_oauth2_middleware.py@@ -5,6 +5,7 @@ import secretsfrom typing import Anyimport pytest+from freezegun import freeze_timefrom posthog.test.base import BaseTestfrom unittest.mock import MagicMock, patch@@ -97,6 +98,8 @@ class TestGetEmailFromIdToken(BaseTest):("30_seconds_future", 30, False),])+ # Freeze so the token iat and the validation now() share one instant.+ @freeze_time("2025-01-01T00:00:00Z")def test_iat_bounds_checking(self, name, iat_offset, expected_success):payload = {**self.base_payload, "iat": int(time.time()) + iat_offset}token = self.jwt_helper.create_id_token(payload)diff --git a/posthog/api/test/test_session.py b/posthog/api/test/test_session.pyindex 7a8f19690128..5ad5d99cbdbf 100644--- a/posthog/api/test/test_session.py+++ b/posthog/api/test/test_session.py@@ -95,20 +95,19 @@ def _set_session_table_version(team, version):class TestSessionsAPI(APIBaseTest):def setUp(self) -> None:super().setUp()- s1 = str(uuid7())-+ # Two distinct sessions: a single session's two utm_sources collapse to the argMin entry value once raw_sessions parts merge.create_event(team=self.team,event="$pageview",distinct_id="d1",- properties={"$session_id": s1, "utm_source": "google"},+ properties={"$session_id": str(uuid7()), "utm_source": "google"},event_uuid=(uuid.uuid4()),)create_event(team=self.team,event="$pageview",distinct_id="d1",- properties={"$session_id": s1, "utm_source": "youtube"},+ properties={"$session_id": str(uuid7()), "utm_source": "youtube"},event_uuid=(uuid.uuid4()),)diff --git a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.pyindex 4906dca96991..6dccc185cb4a 100644--- a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py+++ b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py@@ -1136,17 +1136,19 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):assert len(response.results) == 2- assert response.results[0]["label"] == "cohort p1"- assert response.results[0]["breakdown_value"] == cohort1.pk- assert response.results[0]["count"] == 0- assert len(response.results[0]["data"]) == 12- assert len(response.results[0]["days"]) == 12-- assert response.results[1]["label"] == "cohort p2"- assert response.results[1]["breakdown_value"] == cohort2.pk- assert response.results[1]["count"] == 0- assert len(response.results[1]["data"]) == 12- assert len(response.results[1]["days"]) == 12+ # Both cohorts aggregate to 0, so breakdown order is a nondeterministic tie — assert per-cohort.+ by_cohort = {r["breakdown_value"]: r for r in response.results}+ assert set(by_cohort) == {cohort1.pk, cohort2.pk}++ assert by_cohort[cohort1.pk]["label"] == "cohort p1"+ assert by_cohort[cohort1.pk]["count"] == 0+ assert len(by_cohort[cohort1.pk]["data"]) == 12+ assert len(by_cohort[cohort1.pk]["days"]) == 12++ assert by_cohort[cohort2.pk]["label"] == "cohort p2"+ assert by_cohort[cohort2.pk]["count"] == 0+ assert len(by_cohort[cohort2.pk]["data"]) == 12+ assert len(by_cohort[cohort2.pk]["days"]) == 12@parameterized.expand([diff --git a/posthog/hogql_queries/test/test_document_embeddings_query_runner.py b/posthog/hogql_queries/test/test_document_embeddings_query_runner.pyindex 4a3e214c4c67..97ffb81c7987 100644--- a/posthog/hogql_queries/test/test_document_embeddings_query_runner.py+++ b/posthog/hogql_queries/test/test_document_embeddings_query_runner.py@@ -53,7 +53,8 @@ def build_document_similarity_query(class TestDocumentEmbeddingsQueryRunner(ClickhouseTestMixin, APIBaseTest):- base_timestamp = datetime(2024, 1, 1, 12, 0, tzinfo=ZoneInfo("UTC"))+ # Must track real now(): the tables carry a 3-month real-clock TTL on timestamp, so a fixed past date seeds already-expired rows.+ base_timestamp = datetime.now(tz=ZoneInfo("UTC")) - timedelta(hours=1)product_documents = (("product_a", "document_a", "doc_product_a"),("product_b", "document_b", "doc_product_b"),diff --git a/posthog/management/commands/test/test_resave_hog_functions.py b/posthog/management/commands/test/test_resave_hog_functions.pyindex d6146dbf6051..ba183f65db57 100644--- a/posthog/management/commands/test/test_resave_hog_functions.py+++ b/posthog/management/commands/test/test_resave_hog_functions.py@@ -54,12 +54,13 @@ class TestResaveHogFunctions(BaseTest):call_command("resave_hog_functions")- # Verify that reload_hog_functions_on_workers was called for each function+ # any_order: the command applies no ORDER BY, so reload order isn't deterministic.mock_reload.assert_has_calls([call(team_id=self.team.id, hog_function_ids=[str(self.hog_function1.id)]),call(team_id=self.team.id, hog_function_ids=[str(self.hog_function2.id)]),- ]+ ],+ any_order=True,)assert mock_reload.call_count == 2@@ -90,11 +91,12 @@ class TestResaveHogFunctions(BaseTest):call_command("resave_hog_functions")- # Verify only the original enabled, non-deleted functions were reloaded+ # any_order: the command applies no ORDER BY, so reload order isn't deterministic.mock_reload.assert_has_calls([call(team_id=self.team.id, hog_function_ids=[str(self.hog_function1.id)]),call(team_id=self.team.id, hog_function_ids=[str(self.hog_function2.id)]),- ]+ ],+ any_order=True,)assert mock_reload.call_count == 2diff --git a/posthog/temporal/tests/test_clickhouse.py b/posthog/temporal/tests/test_clickhouse.pyindex dcb2c23f9579..d079b3163046 100644--- a/posthog/temporal/tests/test_clickhouse.py+++ b/posthog/temporal/tests/test_clickhouse.py@@ -38,6 +38,12 @@ async def _wait_for_query_status("""elapsed_time = 0.0while elapsed_time < max_wait_time:+ # Force query_log to materialize before reading (its async flush lags under CI load).+ # A transient flush failure is a retryable poll miss, so keep it out of the read's error handling.+ try:+ await client.execute_query("SYSTEM FLUSH LOGS")+ except ClickHouseError:+ passtry:status = await client.acheck_query_in_query_log(query_id, raise_on_error=raise_on_error)if status == expected_status:diff --git a/posthog/test/test_flush_lock_guard.py b/posthog/test/test_flush_lock_guard.pyindex 6c72a4fadf26..535b647d939a 100644--- a/posthog/test/test_flush_lock_guard.py+++ b/posthog/test/test_flush_lock_guard.py@@ -1,6 +1,5 @@import pytest-from django.core.management import call_commandfrom django.db import connectionsimport psycopg@@ -12,25 +11,28 @@ from posthog.test import flush_lock_guarddef 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())+ default = connections["default"]+ # Dedicated table so the guarded flush contends only with our blocker; Django's real flush+ # truncates every table and races unrelated transactions under the tight 1s timeout. (The+ # guard's wiring into Django's teardown flush is covered by conftest; here we isolate the retry.)+ with default.cursor() as cursor:+ cursor.execute("CREATE TABLE IF NOT EXISTS flush_lock_guard_probe (id integer)")++ blocker = psycopg.connect(**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")+ # Open transaction holds ACCESS SHARE, blocking TRUNCATE — the state a leaked session leaves behind.+ blocker.execute("SELECT 1 FROM flush_lock_guard_probe")++ def flush() -> None:+ with default.cursor() as cursor:+ cursor.execute("TRUNCATE flush_lock_guard_probe")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,- )+ flush_lock_guard.flush_with_lock_guard("default", flush)with pytest.raises(psycopg.OperationalError):blocker.execute("SELECT 1")finally:blocker.close()+ with default.cursor() as cursor:+ cursor.execute("DROP TABLE IF EXISTS flush_lock_guard_probe")