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(tests): clean up committed-row leaks from async temporal tests (#70285)

Paul D'Ambra576c2261538d
diff --git a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.py b/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.py
index 4dda4f9402b0..14e2966bd0e0 100644
--- a/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.py
+++ b/posthog/temporal/messaging/test/test_backfill_precalculated_person_properties_workflow.py
@@ -263,7 +263,7 @@ class TestBackfillPrecalculatedPersonPropertiesActivity:
# fragment. argmax_select wraps the chain in an ``ast.Field``, keeping the key parameterized.
assert select_fields == {"prop_0": ["properties", malicious_property]}
- @pytest.mark.django_db
+ @pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_activity_parameterizes_property_keys_in_clickhouse_query(self):
from asgiref.sync import sync_to_async
@@ -360,7 +360,7 @@ class TestBackfillPrecalculatedPersonPropertiesActivity:
prop_chains = _collect_field_chains(property_aliases[0])
assert any(chain[-2:] == ["properties", malicious_property] for chain in prop_chains)
- @pytest.mark.django_db
+ @pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test_activity_falls_back_to_full_properties_for_percent_keys(self):
from asgiref.sync import sync_to_async
diff --git a/posthog/temporal/messaging/test/test_hogql_compile.py b/posthog/temporal/messaging/test/test_hogql_compile.py
index 1e209c881ee8..92f68a53aa12 100644
--- a/posthog/temporal/messaging/test/test_hogql_compile.py
+++ b/posthog/temporal/messaging/test/test_hogql_compile.py
@@ -10,7 +10,7 @@ from posthog.models.team.team import Team
from posthog.temporal.messaging.hogql_compile import compile_hogql_for_streaming
[email protected]_db(transaction=True)
class TestCompileHogqlForStreaming:
@pytest.mark.asyncio
async def test_bypasses_property_restrictions(self):
diff --git a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py b/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py
index 519918b162c1..77b44015463a 100644
--- a/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py
+++ b/posthog/temporal/messaging/test/test_realtime_cohort_calculation_workflow.py
@@ -1473,7 +1473,7 @@ class TestBatchUpdateCohortMetrics:
"""Tests for _batch_update_cohort_metrics timestamp handling regression."""
@pytest.mark.asyncio
- @pytest.mark.django_db
+ @pytest.mark.django_db(transaction=True)
async def test_batch_update_cohort_metrics_timestamp_fix(self):
"""
Regression test for timestamp bug fix.
@@ -1555,7 +1555,7 @@ class TestBatchUpdateCohortMetrics:
assert duration_updates_count == 1 # Only cohort2 should have had duration updated
@pytest.mark.asyncio
- @pytest.mark.django_db
+ @pytest.mark.django_db(transaction=True)
async def test_batch_update_cohort_metrics_first_calculation(self):
"""Test that first calculation always updates duration regardless of threshold."""
from asgiref.sync import sync_to_async
@@ -1598,7 +1598,7 @@ class TestBatchUpdateCohortMetrics:
assert duration_updates_count == 1
@pytest.mark.asyncio
- @pytest.mark.django_db
+ @pytest.mark.django_db(transaction=True)
async def test_batch_update_cohort_metrics_zero_previous_duration(self):
"""Test that cohorts with zero previous duration always get updated."""
from asgiref.sync import sync_to_async
diff --git a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
index d8ec0e621676..185cd079d0ba 100644
--- a/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
+++ b/posthog/temporal/tests/data_modeling/test_materialize_view_activities.py
@@ -404,13 +404,18 @@ class TestShouldPauseScheduleForTimeout:
async def test_streak_ignores_jobs_from_other_engines(self, ateam, asaved_query):
from posthog.temporal.data_modeling.activities.fail_materialization import should_pause_schedule_for_timeout
- for _ in range(5):
+ jobs = [
await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="Timeout exceeded")
+ for _ in range(5)
+ ]
# a more recent duckgres failure must not break the clickhouse timeout streak
- await _make_job(
- ateam, asaved_query, DataModelingJob.Status.FAILED, engine=DataModelingJobEngine.DUCKGRES, error="boom"
+ jobs.append(
+ await _make_job(
+ ateam, asaved_query, DataModelingJob.Status.FAILED, engine=DataModelingJobEngine.DUCKGRES, error="boom"
+ )
)
current_job = await _make_job(ateam, asaved_query, DataModelingJob.Status.RUNNING)
+ jobs.append(current_job)
should_pause, count = await database_sync_to_async(should_pause_schedule_for_timeout)(
asaved_query.id, current_job.id
@@ -418,6 +423,10 @@ class TestShouldPauseScheduleForTimeout:
assert should_pause is True
assert count == 5
+ # DataModelingJob.team is SET_NULL, so it survives the ateam fixture's team teardown.
+ for job in jobs:
+ await database_sync_to_async(job.delete)()
+
class TestNodeSuspension:
async def test_suspends_for_engine_after_consecutive_failures(self, ateam, anode, asaved_query, adag):
@@ -427,9 +436,12 @@ class TestNodeSuspension:
maybe_suspend_node_for_engine,
)
- for _ in range(CONSECUTIVE_FAILURES_TO_SUSPEND):
+ jobs = [
await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom")
+ for _ in range(CONSECUTIVE_FAILURES_TO_SUSPEND)
+ ]
job = await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom")
+ jobs.append(job)
suspended = await maybe_suspend_node_for_engine(
node_id=str(anode.id),
@@ -448,12 +460,17 @@ class TestNodeSuspension:
await database_sync_to_async(job.refresh_from_db)()
assert "has been suspended" in job.error
+ # DataModelingJob.team is SET_NULL, so it survives the ateam fixture's team teardown.
+ for j in jobs:
+ await database_sync_to_async(j.delete)()
+
async def test_does_not_suspend_when_latest_run_succeeded(self, ateam, anode, asaved_query, adag):
from posthog.temporal.data_modeling.activities.utils import is_node_suspended, maybe_suspend_node_for_engine
- for _ in range(4):
- await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom")
- await _make_job(ateam, asaved_query, DataModelingJob.Status.COMPLETED)
+ jobs = [await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom") for _ in range(4)]
+ jobs.append(await _make_job(ateam, asaved_query, DataModelingJob.Status.COMPLETED))
+ last_job = await _make_job(ateam, asaved_query, DataModelingJob.Status.COMPLETED)
+ jobs.append(last_job)
suspended = await maybe_suspend_node_for_engine(
node_id=str(anode.id),
@@ -462,19 +479,23 @@ class TestNodeSuspension:
saved_query_id=asaved_query.id,
engine=DataModelingJobEngine.CLICKHOUSE,
reason="boom",
- job_id=str((await _make_job(ateam, asaved_query, DataModelingJob.Status.COMPLETED)).id),
+ job_id=str(last_job.id),
)
assert suspended is False
await database_sync_to_async(anode.refresh_from_db)()
assert is_node_suspended(anode, DataModelingJobEngine.CLICKHOUSE) is False
+ # DataModelingJob.team is SET_NULL, so it survives the ateam fixture's team teardown.
+ for job in jobs:
+ await database_sync_to_async(job.delete)()
+
async def test_does_not_restamp_when_already_suspended(self, ateam, anode, asaved_query, adag):
from posthog.temporal.data_modeling.activities.utils import maybe_suspend_node_for_engine
- for _ in range(5):
- await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom")
+ jobs = [await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom") for _ in range(5)]
first_job = await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom")
+ jobs.append(first_job)
assert await maybe_suspend_node_for_engine(
node_id=str(anode.id),
team_id=ateam.pk,
@@ -486,6 +507,7 @@ class TestNodeSuspension:
)
next_job = await _make_job(ateam, asaved_query, DataModelingJob.Status.FAILED, error="boom again")
+ jobs.append(next_job)
suspended_again = await maybe_suspend_node_for_engine(
node_id=str(anode.id),
team_id=ateam.pk,
@@ -500,16 +522,23 @@ class TestNodeSuspension:
await database_sync_to_async(next_job.refresh_from_db)()
assert next_job.error == "boom again"
+ # DataModelingJob.team is SET_NULL, so it survives the ateam fixture's team teardown.
+ for job in jobs:
+ await database_sync_to_async(job.delete)()
+
async def test_engine_suspension_is_independent(self, ateam, anode, asaved_query, adag):
from posthog.temporal.data_modeling.activities.utils import is_node_suspended, maybe_suspend_node_for_engine
- for _ in range(5):
+ jobs = [
await _make_job(
ateam, asaved_query, DataModelingJob.Status.FAILED, engine=DataModelingJobEngine.DUCKGRES, error="boom"
)
+ for _ in range(5)
+ ]
job = await _make_job(
ateam, asaved_query, DataModelingJob.Status.FAILED, engine=DataModelingJobEngine.DUCKGRES, error="boom"
)
+ jobs.append(job)
kwargs = {
"node_id": str(anode.id),
@@ -529,6 +558,10 @@ class TestNodeSuspension:
await database_sync_to_async(job.refresh_from_db)()
assert job.error == "boom"
+ # DataModelingJob.team is SET_NULL, so it survives the ateam fixture's team teardown.
+ for j in jobs:
+ await database_sync_to_async(j.delete)()
+
async def test_clear_suspension_only_affects_one_engine(self, ateam, anode, adag):
from posthog.temporal.data_modeling.activities.utils import (
clear_node_suspension_for_engine,
diff --git a/posthog/temporal/tests/data_modeling/test_run_workflow.py b/posthog/temporal/tests/data_modeling/test_run_workflow.py
index 267ad917f5b4..572088f828da 100644
--- a/posthog/temporal/tests/data_modeling/test_run_workflow.py
+++ b/posthog/temporal/tests/data_modeling/test_run_workflow.py
@@ -57,7 +57,7 @@ from products.data_modeling.backend.facade.modeling import DataWarehouseModelPat
from products.data_modeling.backend.facade.models import DataModelingJob, DataWarehouseSavedQuery
from products.warehouse_sources.backend.facade.models import DataWarehouseTable
-pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
+pytestmark = [pytest.mark.asyncio, pytest.mark.django_db(transaction=True)]
TEST_TIME = dt.datetime.now(dt.UTC)
diff --git a/posthog/temporal/tests/test_alerts_activities.py b/posthog/temporal/tests/test_alerts_activities.py
index 93de2221fd7e..c05396fd0c6b 100644
--- a/posthog/temporal/tests/test_alerts_activities.py
+++ b/posthog/temporal/tests/test_alerts_activities.py
@@ -109,7 +109,7 @@ async def alert(ateam):
@pytest_asyncio.fixture
async def alert_with_user(ateam, aorganization):
@sync_to_async
- def _create() -> AlertConfiguration:
+ def _create() -> tuple[AlertConfiguration, User]:
user = User.objects.create_and_join(
organization=aorganization, email=f"alerts-{uuid.uuid4().hex[:6]}@posthog.com", password=None
)
@@ -130,9 +130,15 @@ async def alert_with_user(ateam, aorganization):
threshold=threshold,
)
a.subscribed_users.add(user)
- return a
+ return a, user
- return await _create()
+ alert, user = await _create()
+ yield alert
+
+ # User.current_organization is SET_NULL, so deleting the org/team (via the
+ # ateam/aorganization fixtures) does not cascade-delete this user; the executor-thread
+ # write above committed for real, so it must be cleaned up explicitly.
+ await sync_to_async(user.delete)()
async def _create_alert_check(
diff --git a/posthog/temporal/tests/test_shutdown.py b/posthog/temporal/tests/test_shutdown.py
index bd97c891e441..cfa2f2f3a3cc 100644
--- a/posthog/temporal/tests/test_shutdown.py
+++ b/posthog/temporal/tests/test_shutdown.py
@@ -53,7 +53,9 @@ async def test_shutdown_monitor_async(temporal_client: Client):
wait_for_shutdown_task = asyncio.create_task(waiter.shutdown_monitor.wait_for_worker_shutdown())
shutdown_task = asyncio.create_task(worker.shutdown())
- _ = await asyncio.wait([wait_for_shutdown_task], timeout=5)
+ # Generous bound: shutdown propagation is the thing under test and can take
+ # longer than a few seconds on loaded CI runners.
+ _ = await asyncio.wait([wait_for_shutdown_task], timeout=15)
assert waiter.shutdown_monitor.is_worker_shutdown()
_ = await asyncio.wait([shutdown_task, worker_run_task], timeout=5)
@@ -135,10 +137,13 @@ async def test_shutdown_monitor_sync(temporal_client: Client, task_queue: str, w
_ = await asyncio.to_thread(waiter.is_waiting_sync.wait)
shutdown_task = asyncio.create_task(worker.shutdown())
- _ = await asyncio.wait([shutdown_task], timeout=5)
-
assert waiter.shutdown_monitor is not None
- assert waiter.shutdown_monitor.is_worker_shutdown()
+ # Wait on the monitor's own event: worker.shutdown() completing within a fixed
+ # window is neither necessary nor sufficient for the sync event to be set, and
+ # propagation can take longer than a few seconds on loaded CI runners.
+ assert await asyncio.to_thread(waiter.shutdown_monitor.wait_for_worker_shutdown_sync, 15)
+
+ _ = await asyncio.wait([shutdown_task], timeout=5)
with ThreadPoolExecutor(max_workers=50) as executor:
# Need to start a new worker to pick-up the workflow again and set the failure.
diff --git a/posthog/temporal/tests/usage_report/test_aggregate_activity.py b/posthog/temporal/tests/usage_report/test_aggregate_activity.py
index c7862285f980..574876b4ddad 100644
--- a/posthog/temporal/tests/usage_report/test_aggregate_activity.py
+++ b/posthog/temporal/tests/usage_report/test_aggregate_activity.py
@@ -180,7 +180,7 @@ def _read_json(key: str) -> Any:
return json.loads(body)
[email protected]_db(transaction=True)
@pytest.mark.asyncio
async def test_aggregate_writes_chunks_and_manifest(minio_workflow_ctx: WorkflowContext, activity_environment) -> None:
org_a = await _make_org("Org A")
@@ -250,7 +250,7 @@ async def test_aggregate_writes_chunks_and_manifest(minio_workflow_ctx: Workflow
assert by_org[str(org_a.id)]["teams"][str(team_a.id)]["event_count_in_period"] == 100
[email protected]_db(transaction=True)
@pytest.mark.asyncio
async def test_aggregate_chunks_into_batches_of_ten_thousand(
minio_workflow_ctx: WorkflowContext, activity_environment
@@ -304,7 +304,7 @@ async def test_aggregate_chunks_into_batches_of_ten_thousand(
assert manifest["chunk_keys"] == result.chunk_keys
[email protected]_db(transaction=True)
@pytest.mark.asyncio
async def test_aggregate_drops_orgs_with_no_usage_from_chunks(
minio_workflow_ctx: WorkflowContext, activity_environment
@@ -358,7 +358,7 @@ async def test_aggregate_drops_orgs_with_no_usage_from_chunks(
assert {row["organization_id"] for row in rows} == {str(org_with_usage.id)}
[email protected]_db(transaction=True)
@pytest.mark.asyncio
async def test_aggregate_filters_by_organization_ids(minio_workflow_ctx: WorkflowContext, activity_environment) -> None:
org_a = await _make_org("A")