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(devex): trim django_db(transaction=True) on temporal tests + drop per-test timeout (#59380)

Julian Bezefb6d1faf796
diff --git a/.github/workflows/ci-backend.yml b/.github/workflows/ci-backend.yml
index 5698369431da..2f08dc60531d 100644
--- a/.github/workflows/ci-backend.yml
+++ b/.github/workflows/ci-backend.yml
@@ -1623,12 +1623,13 @@ jobs:
MODAL_TOKEN_SECRET: ${{ needs.changes.outputs.tasks_temporal == 'true' && secrets.MODAL_TOKEN_SECRET || '' }}
run: |
set +e
- # Bumped from 900 → 1500: shards 1/4 consistently exceed 900s in the
- # package-scoped django_db_setup → migrate → create_clickhouse_tables
- # chain (the first package on those shards is heavier). 1500s gives
- # ample headroom while still catching genuine hangs before the
- # 30-minute job-level kill.
- pytest -v --tb=short --reuse-db -o junit_duration_report=call --timeout=1500 --timeout-method=thread posthog/temporal products/batch_exports/backend/tests/temporal products/tasks/backend/temporal -m "not async_migrations" \
+ # No per-test pytest --timeout; rely on the job-level timeout-minutes
+ # as the single safety net. The per-test guillotine added nothing
+ # over it (--timeout-method=thread os._exit()s the whole process
+ # anyway, so the shard dies either way) and was the reason the
+ # transaction=True overhead in async tests looked like "the
+ # timeout problem" instead of a per-test cost worth fixing.
+ pytest -v --tb=short --reuse-db -o junit_duration_report=call posthog/temporal products/batch_exports/backend/tests/temporal products/tasks/backend/temporal -m "not async_migrations" \
--splits ${{ matrix.concurrency }} --group ${{ matrix.group }} \
--durations=100 --durations-min=1.0 --store-durations \
--splitting-algorithm=duration_based_chunks \
diff --git a/posthog/temporal/llm_analytics/eval_reports/test/test_emit_signal.py b/posthog/temporal/llm_analytics/eval_reports/test/test_emit_signal.py
index 18df59483e3b..b34107df4e2a 100644
--- a/posthog/temporal/llm_analytics/eval_reports/test/test_emit_signal.py
+++ b/posthog/temporal/llm_analytics/eval_reports/test/test_emit_signal.py
@@ -138,7 +138,7 @@ async def _setup_org_not_ai_approved(ateam):
@pytest.mark.asyncio
[email protected]_db(transaction=True)
class TestEmitEvalReportSignalActivity:
@pytest.mark.parametrize(
"setup_fn",
diff --git a/posthog/temporal/llm_analytics/evaluation_clustering/tests/test_data.py b/posthog/temporal/llm_analytics/evaluation_clustering/tests/test_data.py
index 2f3d7e0e8b79..450b4da58f46 100644
--- a/posthog/temporal/llm_analytics/evaluation_clustering/tests/test_data.py
+++ b/posthog/temporal/llm_analytics/evaluation_clustering/tests/test_data.py
@@ -46,7 +46,7 @@ class TestCoerceBool:
class TestFetchEvaluationEmbeddings:
- @pytest.mark.django_db(transaction=True)
+ @pytest.mark.django_db
def test_filters_by_doc_type_and_job_suffix(self, mock_team):
with patch("posthog.temporal.llm_analytics.evaluation_clustering.data.execute_hogql_query") as mock_execute:
mock_execute.return_value.results = [
@@ -69,7 +69,7 @@ class TestFetchEvaluationEmbeddings:
assert placeholders["job_id_suffix"].value == "_job-abc"
assert placeholders["max_samples"].value == 100
- @pytest.mark.django_db(transaction=True)
+ @pytest.mark.django_db
def test_empty_results(self, mock_team):
with patch("posthog.temporal.llm_analytics.evaluation_clustering.data.execute_hogql_query") as mock_execute:
mock_execute.return_value.results = []
@@ -79,7 +79,7 @@ class TestFetchEvaluationEmbeddings:
class TestFetchEvaluationMetadata:
- @pytest.mark.django_db(transaction=True)
+ @pytest.mark.django_db
def test_empty_input_returns_empty(self, mock_team):
from datetime import datetime
@@ -91,7 +91,7 @@ class TestFetchEvaluationMetadata:
)
assert result == {}
- @pytest.mark.django_db(transaction=True)
+ @pytest.mark.django_db
def test_populates_all_fields_when_generation_present(self, mock_team):
"""Two-query metadata fetch: eval rows, then a second query for linked generations."""
from datetime import datetime
@@ -141,7 +141,7 @@ class TestFetchEvaluationMetadata:
assert meta.generation_model == "gpt-4o"
assert meta.generation_is_error is False
- @pytest.mark.django_db(transaction=True)
+ @pytest.mark.django_db
def test_degrades_when_linked_generation_missing(self, mock_team):
"""Missing generation (second query returns no rows) → None operational fields."""
from datetime import datetime
diff --git a/posthog/temporal/llm_analytics/evaluation_clustering/tests/test_event_emission.py b/posthog/temporal/llm_analytics/evaluation_clustering/tests/test_event_emission.py
index d8e095adc1a2..6d41a1b02fef 100644
--- a/posthog/temporal/llm_analytics/evaluation_clustering/tests/test_event_emission.py
+++ b/posthog/temporal/llm_analytics/evaluation_clustering/tests/test_event_emission.py
@@ -20,7 +20,7 @@ def mock_team(db):
class TestEmitEvaluationClusterEvents:
- @pytest.mark.django_db(transaction=True)
+ @pytest.mark.django_db
def test_emits_single_event_with_evaluation_level(self, mock_team):
items = [
ClusterItem(trace_id="e1", generation_id="e1"),
@@ -72,7 +72,7 @@ class TestEmitEvaluationClusterEvents:
# Clusters are serialized as dicts
assert props["$ai_clusters"][0]["title"] == "Factuality failures"
- @pytest.mark.django_db(transaction=True)
+ @pytest.mark.django_db
def test_metrics_flow_through_to_cluster_payload(self, mock_team):
items = [ClusterItem(trace_id="e1", generation_id="e1")]
labels = [0]
diff --git a/posthog/temporal/proxy_service/test/test_send_proxy_email.py b/posthog/temporal/proxy_service/test/test_send_proxy_email.py
index d37708522e23..96472ea094b3 100644
--- a/posthog/temporal/proxy_service/test/test_send_proxy_email.py
+++ b/posthog/temporal/proxy_service/test/test_send_proxy_email.py
@@ -9,6 +9,18 @@ from posthog.models.user import User
from posthog.temporal.proxy_service.common import SendProxyCreatedEmailInputs, activity_send_proxy_created_email
[email protected](autouse=True)
+def _no_temporal_worker_reconnect(monkeypatch):
+ # The activity calls django.db.connection.connect() to recover from stale
+ # worker connections in production. Under test that drops the test's
+ # wrapping atomic transaction (and the freshly-opened connection can't see
+ # data the test just wrote). Stub it out so tests can stay on fast
+ # transaction-rollback isolation instead of needing transaction=True.
+ from django.db import connection
+
+ monkeypatch.setattr(connection, "connect", lambda: None)
+
+
def _make_inputs(**overrides):
defaults = {
"organization_id": uuid.uuid4(),
@@ -19,7 +31,7 @@ def _make_inputs(**overrides):
return SendProxyCreatedEmailInputs(**defaults) # type: ignore
[email protected]_db(transaction=True)
class TestSendProxyCreatedEmail:
def test_sends_email_when_record_and_user_exist(self):
org = Organization.objects.create(name="Test Org")
diff --git a/posthog/temporal/tests/backfill_materialized_property/test_batched_activities.py b/posthog/temporal/tests/backfill_materialized_property/test_batched_activities.py
index 5f2a4efe04f8..b77944c32ef0 100644
--- a/posthog/temporal/tests/backfill_materialized_property/test_batched_activities.py
+++ b/posthog/temporal/tests/backfill_materialized_property/test_batched_activities.py
@@ -42,7 +42,7 @@ def _make_pending_slot(team, name: str) -> MaterializedColumnSlot:
)
[email protected]_db(transaction=True)
class TestPlanColumnAssignments:
def test_packs_two_teams_into_a_single_column(self, team, organization):
from posthog.models import Team
@@ -193,7 +193,7 @@ class TestCycleMarkerEmbedding:
assert 0 <= marker < 2**32
[email protected]_db(transaction=True)
class TestAssignPendingColumns:
def test_transitions_pending_slots_to_backfill_with_indexes(self, team, activity_environment):
slot_a = _make_pending_slot(team, "browser")
@@ -333,7 +333,7 @@ class TestAssignPendingColumns:
assert any(a.column_index == 3 for a in result.assignments)
[email protected]_db(transaction=True)
class TestActivateAndFailSlots:
def test_activate_slots_transitions_backfill_to_ready(self, team, activity_environment):
prop = PropertyDefinition.objects.create(
@@ -398,7 +398,7 @@ class TestActivateAndFailSlots:
assert slot.error_message == "ClickHouse OOM"
[email protected]_db(transaction=True)
class TestRunBatchedMutation:
@patch("posthog.temporal.backfill_materialized_property.activities.AlterTableMutationRunner")
@patch("posthog.temporal.backfill_materialized_property.activities.get_cluster")
@@ -442,7 +442,7 @@ class TestRunBatchedMutation:
runner_instance.run_on_shards.assert_called_once_with(mock_get_cluster.return_value)
[email protected]_db(transaction=True)
class TestPopulateSlotAssignments:
"""The activity reads READY+BACKFILL slots from Postgres and pushes them as a CH-side
table that the dmat_slot_assignments_dict reads from. The PENDING-allocation
diff --git a/posthog/temporal/tests/backfill_materialized_property/test_coercion_parity.py b/posthog/temporal/tests/backfill_materialized_property/test_coercion_parity.py
index a7e5f4102fb4..6532da137985 100644
--- a/posthog/temporal/tests/backfill_materialized_property/test_coercion_parity.py
+++ b/posthog/temporal/tests/backfill_materialized_property/test_coercion_parity.py
@@ -57,7 +57,7 @@ def _string_cases():
yield pytest.param(case, id=f"string_cases::{case['name']}")
[email protected]_db(transaction=True)
class TestCoercionParity:
@pytest.mark.parametrize("case", list(_string_cases()))
def test_extraction_sql_matches_fixture(self, team, case):
@@ -123,7 +123,7 @@ def _dict_backed_dispatch_sql(column_index: int, fallback_value: str = "NULL") -
)
[email protected]_db(transaction=True)
class TestDictBackedDispatchCoercion:
"""The dict-based mutation reads property names out of `dmat_slot_assignments_dict`
via `dictGetString` instead of a query parameter. Same wrapper, different way of
diff --git a/posthog/temporal/tests/data_imports/test_bigquery_source.py b/posthog/temporal/tests/data_imports/test_bigquery_source.py
index c4c41b796a47..52dd89bc9728 100644
--- a/posthog/temporal/tests/data_imports/test_bigquery_source.py
+++ b/posthog/temporal/tests/data_imports/test_bigquery_source.py
@@ -319,7 +319,7 @@ async def setup_bigquery(
@SKIP_IF_MISSING_GOOGLE_APPLICATION_CREDENTIALS
[email protected]_db(transaction=True)
@pytest.mark.asyncio
async def test_bigquery_source_full_refresh_table(
activity_environment,
@@ -385,7 +385,7 @@ async def test_bigquery_source_full_refresh_table(
@SKIP_IF_MISSING_GOOGLE_APPLICATION_CREDENTIALS
[email protected]_db(transaction=True)
@pytest.mark.asyncio
async def test_bigquery_source_full_refresh_view(
activity_environment,
@@ -451,7 +451,7 @@ async def test_bigquery_source_full_refresh_view(
@SKIP_IF_MISSING_GOOGLE_APPLICATION_CREDENTIALS
[email protected]_db(transaction=True)
@pytest.mark.asyncio
async def test_bigquery_source_incremental_integer(
activity_environment,
@@ -570,7 +570,7 @@ async def test_bigquery_source_incremental_integer(
@SKIP_IF_MISSING_GOOGLE_APPLICATION_CREDENTIALS
[email protected]_db(transaction=True)
@pytest.mark.asyncio
async def test_bigquery_source_incremental_timestamp(
activity_environment,
@@ -695,7 +695,7 @@ async def test_bigquery_source_incremental_timestamp(
@SKIP_IF_MISSING_GOOGLE_APPLICATION_CREDENTIALS
[email protected]_db(transaction=True)
@pytest.mark.parametrize("bigquery_table_primary_key", ["test_pk"], indirect=True)
@pytest.mark.asyncio
async def test_bigquery_source_incremental_custom_primary_key(
diff --git a/posthog/temporal/tests/session_replay/summarization_sweep/test_session_candidates.py b/posthog/temporal/tests/session_replay/summarization_sweep/test_session_candidates.py
index d79db2200322..bf7b081c21b7 100644
--- a/posthog/temporal/tests/session_replay/summarization_sweep/test_session_candidates.py
+++ b/posthog/temporal/tests/session_replay/summarization_sweep/test_session_candidates.py
@@ -76,7 +76,7 @@ def _enable_source(team) -> None:
class TestSamplingPushdown(ClickhouseTestMixin):
- @pytest.mark.django_db(transaction=True)
+ @pytest.mark.django_db
def test_full_rate_returns_all(self, team) -> None:
_enable_source(team)
sessions = self._produce_sessions(team.id, count=10)
@@ -84,7 +84,7 @@ class TestSamplingPushdown(ClickhouseTestMixin):
ids = fetch_recent_session_ids(team=team, lookback_minutes=30, sample_rate=1.0)
assert sorted(ids) == sorted(sessions)
- @pytest.mark.django_db(transaction=True)
+ @pytest.mark.django_db
def test_zero_rate_returns_none(self, team) -> None:
_enable_source(team)
self._produce_sessions(team.id, count=10)
@@ -92,7 +92,7 @@ class TestSamplingPushdown(ClickhouseTestMixin):
ids = fetch_recent_session_ids(team=team, lookback_minutes=30, sample_rate=0.0)
assert ids == []
- @pytest.mark.django_db(transaction=True)
+ @pytest.mark.django_db
def test_partial_rate_is_stable_across_calls(self, team) -> None:
_enable_source(team)
self._produce_sessions(team.id, count=40)
diff --git a/posthog/temporal/tests/sync_person_distinct_ids/test_activities.py b/posthog/temporal/tests/sync_person_distinct_ids/test_activities.py
index f08b928eeb4b..a632a4273483 100644
--- a/posthog/temporal/tests/sync_person_distinct_ids/test_activities.py
+++ b/posthog/temporal/tests/sync_person_distinct_ids/test_activities.py
@@ -33,7 +33,7 @@ from posthog.temporal.tests.sync_person_distinct_ids.conftest import (
)
[email protected]_db(transaction=True)
class TestFindOrphanedPersons:
@pytest.fixture(autouse=True)
def setup(self, team, test_prefix, activity_environment):
@@ -121,7 +121,7 @@ class TestFindOrphanedPersons:
assert len(result.orphaned_persons) == 2
[email protected]_db(transaction=True)
class TestLookupPgDistinctIds:
@pytest.fixture(autouse=True)
def setup(self, team, test_prefix, activity_environment):
@@ -245,7 +245,7 @@ class TestLookupPgDistinctIds:
assert len(result.persons_not_found) == 0
[email protected]_db(transaction=True)
class TestSyncDistinctIdsToCh:
@pytest.fixture(autouse=True)
def setup(self, team, test_prefix, activity_environment):
@@ -357,7 +357,7 @@ class TestSyncDistinctIdsToCh:
assert str(ch_did2["person_id"]) == person_uuid
[email protected]_db(transaction=True)
class TestMarkChOnlyOrphansDeleted:
@pytest.fixture(autouse=True)
def setup(self, team, test_prefix, activity_environment):
@@ -449,7 +449,7 @@ class TestMarkChOnlyOrphansDeleted:
)
[email protected]_db(transaction=True)
class TestEndToEndOrphanCategories:
"""Test the complete flow of finding and categorizing all orphan types."""
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index dd57c0a1733a..967fe36a2ed0 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -136,7 +136,7 @@ async def _create_alert_check(
@pytest.mark.asyncio
[email protected]_db(transaction=True)
class TestPrepareAlert:
async def test_skip_when_alert_not_found(self) -> None:
env = ActivityEnvironment()
@@ -265,7 +265,7 @@ class TestPrepareAlert:
@pytest.mark.asyncio
[email protected]_db(transaction=True)
class TestEvaluateAlert:
async def test_evaluate_not_firing_no_breaches(self, alert) -> None:
with patch(
@@ -350,7 +350,7 @@ class TestEvaluateAlert:
@pytest.mark.asyncio
[email protected]_db(transaction=True)
class TestNotifyAlert:
async def test_noop_when_not_firing(self, alert_with_user) -> None:
check = await _create_alert_check(alert_with_user, state=AlertState.NOT_FIRING)
@@ -572,7 +572,7 @@ class TestNotifyAlert:
@pytest.mark.asyncio
[email protected]_db(transaction=True)
class TestCleanupAlertChecks:
async def test_delegates_to_model_classmethod(self) -> None:
with patch.object(AlertCheck, "clean_up_old_checks", return_value=7) as mock_cleanup:
diff --git a/posthog/temporal/tests/usage_report/test_parity.py b/posthog/temporal/tests/usage_report/test_parity.py
index 44db901bfdbb..ed857d7522df 100644
--- a/posthog/temporal/tests/usage_report/test_parity.py
+++ b/posthog/temporal/tests/usage_report/test_parity.py
@@ -256,7 +256,7 @@ def test_end_to_end_parity_celery_task_vs_temporal_activity(
assert temporal_per_org[str(org_b.id)]["team_count"] == 1
[email protected]_db(transaction=True)
def test_temporal_build_org_reports_does_not_run_per_org_membership_queries() -> None:
"""The Temporal-local `aggregator.build_org_reports` must fetch
organization membership counts in bulk. The legacy Celery facade still