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.

test(batch-exports): speed up the batch exports python tests (#108385)

Rossc191e569b464
diff --git a/posthog/temporal/common/test_utils.py b/posthog/temporal/common/test_utils.py
index 9bdfe7002369..630cba99125d 100644
--- a/posthog/temporal/common/test_utils.py
+++ b/posthog/temporal/common/test_utils.py
@@ -116,6 +116,7 @@ def start_test_worker(
task_queue: str,
workflows: Sequence[type],
activities: Sequence[Callable],
+ graceful_shutdown_timeout: dt.timedelta = dt.timedelta(seconds=5),
):
with ThreadedWorker(
client=temporal,
@@ -123,6 +124,6 @@ def start_test_worker(
workflows=workflows,
activities=activities,
workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
- graceful_shutdown_timeout=dt.timedelta(seconds=5),
+ graceful_shutdown_timeout=graceful_shutdown_timeout,
).run_in_thread():
yield
diff --git a/products/batch_exports/backend/tests/api/backfills/test_cancel.py b/products/batch_exports/backend/tests/api/backfills/test_cancel.py
index 0fd2afcff1a2..a172dfb14dc3 100644
--- a/products/batch_exports/backend/tests/api/backfills/test_cancel.py
+++ b/products/batch_exports/backend/tests/api/backfills/test_cancel.py
@@ -21,9 +21,11 @@ pytestmark = [
pytest.mark.usefixtures("temporal_worker", "cleanup"),
]
+POLL_INTERVAL = 0.2
+
def wait_for_backfill_creation(client: HttpClient, team_id: int, batch_export_id: str):
- total = 0
+ total = 0.0
# The backfill appears when the Temporal worker processes the workflow. On a
# shard that also runs the temporal suites the worker can lag well past 30s,
# so give it headroom; the green path returns as soon as it shows up.
@@ -32,8 +34,8 @@ def wait_for_backfill_creation(client: HttpClient, team_id: int, batch_export_id
response = list_batch_export_backfills_ok(client, team_id, batch_export_id)
backfills = response["results"]
if len(backfills) == 0:
- time.sleep(1)
- total += 1
+ time.sleep(POLL_INTERVAL)
+ total += POLL_INTERVAL
else:
return backfills[0]
@@ -41,13 +43,13 @@ def wait_for_backfill_creation(client: HttpClient, team_id: int, batch_export_id
def wait_for_backfill_runs(backfill_id: str, timeout: int = 120) -> list[BatchExportRun]:
- total = 0
+ total = 0.0
while total < timeout:
runs = list(BatchExportRun.objects.filter(backfill_id=backfill_id))
if runs:
return runs
- time.sleep(1)
- total += 1
+ time.sleep(POLL_INTERVAL)
+ total += POLL_INTERVAL
raise Exception("No runs found for backfill")
diff --git a/products/batch_exports/backend/tests/api/operations.py b/products/batch_exports/backend/tests/api/operations.py
index b01612d203a7..4f2094763804 100644
--- a/products/batch_exports/backend/tests/api/operations.py
+++ b/products/batch_exports/backend/tests/api/operations.py
@@ -1,4 +1,5 @@
import asyncio
+import datetime as dt
from contextlib import contextmanager
from django.conf import settings
@@ -22,6 +23,9 @@ def start_test_worker(temporal: TemporalClient):
task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,
workflows=WORKFLOWS,
activities=ACTIVITIES,
+ # The worker stops after the last test that needs it. Cancellation tests leave mocked
+ # activities that never finish, so a grace period only delays the shutdown.
+ graceful_shutdown_timeout=dt.timedelta(0),
):
yield
@@ -192,12 +196,12 @@ def cancel_batch_export_backfill_ok(client: TestClient, team_id: int, batch_expo
@async_to_sync
async def wait_for_workflow_executions(
- temporal: temporalio.client.Client, query: str, timeout: int = 30, sleep: int = 1
+ temporal: temporalio.client.Client, query: str, timeout: float = 30, sleep: float = 0.2
):
"""Wait for Workflow Executions matching query."""
workflows = [workflow async for workflow in temporal.list_workflows(query=query)]
- total = 0
+ total = 0.0
while not workflows:
if total > timeout:
raise TimeoutError(f"No backfill Workflow Executions after {timeout} seconds")
diff --git a/products/batch_exports/backend/tests/api/test_delete.py b/products/batch_exports/backend/tests/api/test_delete.py
index 3de0b53256ea..406a8b9b34a2 100644
--- a/products/batch_exports/backend/tests/api/test_delete.py
+++ b/products/batch_exports/backend/tests/api/test_delete.py
@@ -52,14 +52,14 @@ async def wait_for_workflow_in_status(
temporal: temporalio.client.Client,
workflow_id: str,
status: temporalio.client.WorkflowExecutionStatus,
- sleep: int = 1,
- timeout: int = 30,
+ sleep: float = 0.2,
+ timeout: float = 30,
):
"""Wait for a Workflow to be in a given status."""
handle = temporal.get_workflow_handle(workflow_id)
workflow = await handle.describe()
- total = 0
+ total = 0.0
while workflow.status != status:
total += sleep
diff --git a/products/batch_exports/backend/tests/temporal/backfills/conftest.py b/products/batch_exports/backend/tests/temporal/backfills/conftest.py
index c59d6dcc8db0..add8e2742f95 100644
--- a/products/batch_exports/backend/tests/temporal/backfills/conftest.py
+++ b/products/batch_exports/backend/tests/temporal/backfills/conftest.py
@@ -28,9 +28,9 @@ async def wait_for_workflows(
timeout: Wait for at most this amount of seconds.
"""
query = f'TemporalScheduledById="{schedule_id}" order by StartTime asc'
- workflows: list[temporalio.client.WorkflowExecution] = []
+ workflows = [workflow async for workflow in temporal_client.list_workflows(query=query)]
elapsed = 0.0
- delay = 0.5
+ delay = 0.2
while len(workflows) < expected_count:
if elapsed > timeout:
@@ -41,7 +41,6 @@ async def wait_for_workflows(
await asyncio.sleep(delay)
elapsed += delay
- delay = min(delay * 2, 5)
workflows = [workflow async for workflow in temporal_client.list_workflows(query=query)]
if assert_exact:
diff --git a/products/batch_exports/backend/tests/temporal/conftest.py b/products/batch_exports/backend/tests/temporal/conftest.py
index 5cab201dd380..c005102b9d56 100644
--- a/products/batch_exports/backend/tests/temporal/conftest.py
+++ b/products/batch_exports/backend/tests/temporal/conftest.py
@@ -30,11 +30,7 @@ from posthog.temporal.tests.utils.events import generate_test_events_in_clickhou
from products.batch_exports.backend.facade.api import delete_batch_exports_for_teams
from products.batch_exports.backend.temporal import ACTIVITIES, WORKFLOWS
from products.batch_exports.backend.temporal.metrics import BatchExportsMetricsInterceptor
-from products.batch_exports.backend.tests.temporal.utils.clickhouse import (
- truncate_events,
- truncate_persons,
- truncate_sessions,
-)
+from products.batch_exports.backend.tests.temporal.utils.clickhouse import truncate_all
from products.batch_exports.backend.tests.temporal.utils.persons import (
PersonDistinctId2Values,
PersonValues,
@@ -47,9 +43,7 @@ from products.batch_exports.backend.tests.temporal.utils.persons import (
@pytest_asyncio.fixture
async def truncate_clickhouse_tables(clickhouse_client):
yield
- await truncate_events(clickhouse_client)
- await truncate_persons(clickhouse_client)
- await truncate_sessions(clickhouse_client)
+ await truncate_all(clickhouse_client)
@pytest.fixture(scope="package", autouse=True)
diff --git a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_workflow_error_states.py b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_workflow_error_states.py
index 4a42b41e7502..d882ee07387d 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_workflow_error_states.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/azure_blob/test_workflow_error_states.py
@@ -1,4 +1,3 @@
-import asyncio
import datetime as dt
import pytest
@@ -25,7 +24,10 @@ from products.batch_exports.backend.temporal.pipeline.internal_stage import (
BatchExportInsertIntoInternalStageInputs,
InternalStageResult,
)
-from products.batch_exports.backend.tests.temporal.utils.workflow import mocked_start_batch_export_run
+from products.batch_exports.backend.tests.temporal.utils.workflow import (
+ NeverFinishingActivity,
+ mocked_start_batch_export_run,
+)
pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
@@ -245,11 +247,7 @@ async def test_workflow_sets_cancelled_on_cancellation(
async def insert_into_internal_stage_activity_mocked(_: BatchExportInsertIntoInternalStageInputs):
return InternalStageResult(stage_folder="test-stage-folder", records_total=None)
- @activity.defn(name="insert_into_azure_blob_activity_from_stage")
- async def never_finish_activity(_):
- while True:
- activity.heartbeat()
- await asyncio.sleep(1)
+ never_finish = NeverFinishingActivity("insert_into_azure_blob_activity_from_stage")
async with await WorkflowEnvironment.start_time_skipping() as activity_environment:
async with Worker(
@@ -259,7 +257,7 @@ async def test_workflow_sets_cancelled_on_cancellation(
activities=[
mocked_start_batch_export_run,
insert_into_internal_stage_activity_mocked,
- never_finish_activity,
+ never_finish.defn,
finish_batch_export_run,
],
workflow_runner=UnsandboxedWorkflowRunner(),
@@ -271,7 +269,7 @@ async def test_workflow_sets_cancelled_on_cancellation(
task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,
retry_policy=RetryPolicy(maximum_attempts=1),
)
- await asyncio.sleep(5)
+ await never_finish.wait_until_started()
await handle.cancel()
with pytest.raises(WorkflowFailureError):
diff --git a/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_workflow.py
index 917a82bddfa3..19e4dd25713f 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_workflow.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/bigquery/test_workflow.py
@@ -1,7 +1,6 @@
"""Test module covering the workflow used for batch exporting to BigQuery."""
import uuid
-import asyncio
import datetime as dt
import pytest
@@ -10,7 +9,6 @@ import unittest.mock
from django.conf import settings
import pytest_asyncio
-from temporalio import activity
from temporalio.client import WorkflowFailureError
from temporalio.common import RetryPolicy
from temporalio.testing import WorkflowEnvironment
@@ -27,7 +25,6 @@ from products.batch_exports.backend.service import (
from products.batch_exports.backend.temporal.batch_exports import finish_batch_export_run, start_batch_export_run
from products.batch_exports.backend.temporal.destinations.bigquery_batch_export import (
BigQueryBatchExportWorkflow,
- BigQueryInsertInputs,
insert_into_bigquery_activity_from_stage,
)
from products.batch_exports.backend.temporal.pipeline.internal_stage import insert_into_internal_stage_activity
@@ -37,7 +34,10 @@ from products.batch_exports.backend.tests.temporal.destinations.bigquery.utils i
TEST_TIME,
assert_clickhouse_records_in_bigquery,
)
-from products.batch_exports.backend.tests.temporal.utils.workflow import mocked_start_batch_export_run
+from products.batch_exports.backend.tests.temporal.utils.workflow import (
+ NeverFinishingActivity,
+ mocked_start_batch_export_run,
+)
pytestmark = [
SKIP_IF_MISSING_GOOGLE_APPLICATION_CREDENTIALS,
@@ -483,11 +483,7 @@ async def test_bigquery_export_workflow_handles_cancellation(
**bigquery_batch_export.destination.config,
)
- @activity.defn(name="insert_into_bigquery_activity_from_stage")
- async def never_finish_activity(_: BigQueryInsertInputs) -> str:
- while True:
- activity.heartbeat()
- await asyncio.sleep(1)
+ never_finish = NeverFinishingActivity("insert_into_bigquery_activity_from_stage")
async with await WorkflowEnvironment.start_time_skipping() as activity_environment:
async with Worker(
@@ -496,7 +492,7 @@ async def test_bigquery_export_workflow_handles_cancellation(
workflows=[BigQueryBatchExportWorkflow],
activities=[
mocked_start_batch_export_run,
- never_finish_activity,
+ never_finish.defn,
insert_into_internal_stage_activity,
finish_batch_export_run,
],
@@ -510,7 +506,7 @@ async def test_bigquery_export_workflow_handles_cancellation(
retry_policy=RetryPolicy(maximum_attempts=1),
)
- await asyncio.sleep(5)
+ await never_finish.wait_until_started()
await handle.cancel()
with pytest.raises(WorkflowFailureError):
diff --git a/products/batch_exports/backend/tests/temporal/destinations/conftest.py b/products/batch_exports/backend/tests/temporal/destinations/conftest.py
index e11e745ca621..7206c9629633 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/conftest.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/conftest.py
@@ -4,9 +4,7 @@ import pytest_asyncio
from products.batch_exports.backend.tests.temporal.utils.clickhouse import (
create_clickhouse_tables_and_views,
- truncate_events,
- truncate_persons,
- truncate_sessions,
+ truncate_all,
)
@@ -32,6 +30,4 @@ async def truncate(clickhouse_client):
This is useful if during the test setup we insert a lot of data we wish to clean-up.
"""
yield
- await truncate_events(clickhouse_client)
- await truncate_persons(clickhouse_client)
- await truncate_sessions(clickhouse_client)
+ await truncate_all(clickhouse_client)
diff --git a/products/batch_exports/backend/tests/temporal/destinations/postgres/test_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/postgres/test_workflow.py
index 7a1bed3646bd..1a790b4e109e 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/postgres/test_workflow.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/postgres/test_workflow.py
@@ -10,7 +10,6 @@ import unittest.mock
from django.conf import settings
from django.test import override_settings
-from temporalio import activity
from temporalio.client import WorkflowFailureError
from temporalio.common import RetryPolicy
from temporalio.testing import WorkflowEnvironment
@@ -23,7 +22,6 @@ from products.batch_exports.backend.temporal.batch_exports import finish_batch_e
from products.batch_exports.backend.temporal.destinations.postgres_batch_export import (
PostgresBatchExportInputs,
PostgresBatchExportWorkflow,
- PostgresInsertInputs,
insert_into_postgres_activity_from_stage,
)
from products.batch_exports.backend.temporal.pipeline.internal_stage import insert_into_internal_stage_activity
@@ -33,6 +31,7 @@ from products.batch_exports.backend.tests.temporal.destinations.postgres.utils i
)
from products.batch_exports.backend.tests.temporal.utils.workflow import (
WORKFLOW_REAL_TIME_LIMIT_SECONDS,
+ NeverFinishingActivity,
mocked_start_batch_export_run,
)
@@ -538,11 +537,7 @@ async def test_postgres_export_workflow_handles_cancellation(ateam, postgres_bat
**postgres_batch_export.destination.config,
)
- @activity.defn(name="insert_into_postgres_activity_from_stage")
- async def never_finish_activity(_: PostgresInsertInputs) -> str:
- while True:
- activity.heartbeat()
- await asyncio.sleep(1)
+ never_finish = NeverFinishingActivity("insert_into_postgres_activity_from_stage")
async with await WorkflowEnvironment.start_time_skipping() as activity_environment:
async with Worker(
@@ -551,7 +546,7 @@ async def test_postgres_export_workflow_handles_cancellation(ateam, postgres_bat
workflows=[PostgresBatchExportWorkflow],
activities=[
mocked_start_batch_export_run,
- never_finish_activity,
+ never_finish.defn,
insert_into_internal_stage_activity,
finish_batch_export_run,
],
@@ -564,7 +559,7 @@ async def test_postgres_export_workflow_handles_cancellation(ateam, postgres_bat
task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,
retry_policy=RetryPolicy(maximum_attempts=1),
)
- await asyncio.sleep(5)
+ await never_finish.wait_until_started()
await handle.cancel()
with pytest.raises(WorkflowFailureError):
diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_error_handling.py b/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_error_handling.py
index d2b40c9e6279..beb037715a6f 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_error_handling.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_error_handling.py
@@ -1,6 +1,5 @@
import uuid
import typing as t
-import asyncio
import datetime as dt
import contextlib
@@ -34,7 +33,10 @@ from products.batch_exports.backend.temporal.pipeline.internal_stage import (
insert_into_internal_stage_activity,
)
from products.batch_exports.backend.tests.temporal.destinations.s3.utils import assert_clickhouse_records_in_s3
-from products.batch_exports.backend.tests.temporal.utils.workflow import mocked_start_batch_export_run
+from products.batch_exports.backend.tests.temporal.utils.workflow import (
+ NeverFinishingActivity,
+ mocked_start_batch_export_run,
+)
pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
@@ -192,11 +194,7 @@ async def test_s3_export_workflow_handles_cancellation(ateam, s3_compatible_batc
async def insert_into_internal_stage_activity_mocked(_: BatchExportInsertIntoInternalStageInputs):
return InternalStageResult(stage_folder="test-stage-folder", records_total=None)
- @activity.defn(name="insert_into_s3_activity_from_stage")
- async def never_finish_activity_from_stage(_):
- while True:
- activity.heartbeat()
- await asyncio.sleep(1)
+ never_finish = NeverFinishingActivity("insert_into_s3_activity_from_stage")
async with await WorkflowEnvironment.start_time_skipping() as activity_environment:
async with Worker(
@@ -206,7 +204,7 @@ async def test_s3_export_workflow_handles_cancellation(ateam, s3_compatible_batc
activities=[
mocked_start_batch_export_run,
insert_into_internal_stage_activity_mocked,
- never_finish_activity_from_stage,
+ never_finish.defn,
finish_batch_export_run,
],
workflow_runner=UnsandboxedWorkflowRunner(),
@@ -218,7 +216,7 @@ async def test_s3_export_workflow_handles_cancellation(ateam, s3_compatible_batc
task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,
retry_policy=RetryPolicy(maximum_attempts=1),
)
- await asyncio.sleep(5)
+ await never_finish.wait_until_started()
await handle.cancel()
with pytest.raises(WorkflowFailureError):
diff --git a/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_workflow.py
index 9ab35baccb4b..4be4449df606 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_workflow.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/snowflake/test_workflow.py
@@ -14,7 +14,6 @@ import unittest.mock
from django.conf import settings
from django.test import override_settings
-from temporalio import activity
from temporalio.client import WorkflowFailureError
from temporalio.common import RetryPolicy
from temporalio.exceptions import ActivityError, ApplicationError
@@ -29,7 +28,6 @@ from products.batch_exports.backend.temporal.batch_exports import finish_batch_e
from products.batch_exports.backend.temporal.destinations.snowflake_batch_export import (
SnowflakeBatchExportInputs,
SnowflakeBatchExportWorkflow,
- SnowflakeInsertInputs,
insert_into_snowflake_activity_from_stage,
)
from products.batch_exports.backend.temporal.pipeline.internal_stage import insert_into_internal_stage_activity
@@ -39,6 +37,7 @@ from products.batch_exports.backend.tests.temporal.destinations.snowflake.utils
)
from products.batch_exports.backend.tests.temporal.utils.workflow import (
WORKFLOW_REAL_TIME_LIMIT_SECONDS,
+ NeverFinishingActivity,
mocked_start_batch_export_run,
)
@@ -379,11 +378,7 @@ async def test_snowflake_export_workflow_handles_cancellation_mocked(ateam, snow
**snowflake_batch_export.destination.config,
)
- @activity.defn(name="insert_into_snowflake_activity_from_stage")
- async def never_finish_activity_from_stage(_: SnowflakeInsertInputs) -> str:
- while True:
- activity.heartbeat()
- await asyncio.sleep(1)
+ never_finish = NeverFinishingActivity("insert_into_snowflake_activity_from_stage")
async with (
await WorkflowEnvironment.start_time_skipping() as activity_environment,
@@ -394,7 +389,7 @@ async def test_snowflake_export_workflow_handles_cancellation_mocked(ateam, snow
activities=[
mocked_start_batch_export_run,
insert_into_internal_stage_activity,
- never_finish_activity_from_stage,
+ never_finish.defn,
finish_batch_export_run,
],
workflow_runner=UnsandboxedWorkflowRunner(),
@@ -407,7 +402,7 @@ async def test_snowflake_export_workflow_handles_cancellation_mocked(ateam, snow
task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,
retry_policy=RetryPolicy(maximum_attempts=1),
)
- await asyncio.sleep(5)
+ await never_finish.wait_until_started()
await handle.cancel()
with pytest.raises(WorkflowFailureError):
diff --git a/products/batch_exports/backend/tests/temporal/destinations/test_http_batch_export_workflow.py b/products/batch_exports/backend/tests/temporal/destinations/test_http_batch_export_workflow.py
index 965574838269..131ef02a879d 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/test_http_batch_export_workflow.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/test_http_batch_export_workflow.py
@@ -1,5 +1,4 @@
import json
-import asyncio
import datetime as dt
from random import randint
from uuid import uuid4
@@ -40,7 +39,10 @@ from products.batch_exports.backend.temporal.destinations.http_batch_export impo
insert_into_http_activity,
)
from products.batch_exports.backend.temporal.filters import compose_filters_clause
-from products.batch_exports.backend.tests.temporal.utils.workflow import mocked_start_batch_export_run
+from products.batch_exports.backend.tests.temporal.utils.workflow import (
+ NeverFinishingActivity,
+ mocked_start_batch_export_run,
+)
pytestmark = [
pytest.mark.asyncio,
@@ -820,11 +822,7 @@ async def test_http_export_workflow_handles_cancellation(ateam, http_batch_expor
**http_batch_export.destination.config,
)
- @activity.defn(name="insert_into_http_activity")
- async def never_finish_activity(_: HttpInsertInputs) -> str:
- while True:
- activity.heartbeat()
- await asyncio.sleep(1)
+ never_finish = NeverFinishingActivity("insert_into_http_activity")
async with await WorkflowEnvironment.start_time_skipping() as activity_environment:
async with Worker(
@@ -833,7 +831,7 @@ async def test_http_export_workflow_handles_cancellation(ateam, http_batch_expor
workflows=[HttpBatchExportWorkflow],
activities=[
mocked_start_batch_export_run,
- never_finish_activity,
+ never_finish.defn,
finish_batch_export_run,
],
workflow_runner=UnsandboxedWorkflowRunner(),
@@ -845,7 +843,7 @@ async def test_http_export_workflow_handles_cancellation(ateam, http_batch_expor
task_queue=settings.TEMPORAL_TASK_QUEUE,
retry_policy=RetryPolicy(maximum_attempts=1),
)
- await asyncio.sleep(5)
+ await never_finish.wait_until_started()
await handle.cancel()
with pytest.raises(WorkflowFailureError):
diff --git a/products/batch_exports/backend/tests/temporal/destinations/workflows/test_activity.py b/products/batch_exports/backend/tests/temporal/destinations/workflows/test_activity.py
index e7e4dc2805a2..ff8426eb2e5d 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/workflows/test_activity.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/workflows/test_activity.py
@@ -1,9 +1,11 @@
import uuid
+import functools
import urllib.parse
import pytest
from products.batch_exports.backend.service import BatchExportInsertInputs, BatchExportModel, BatchExportSchema
+from products.batch_exports.backend.temporal.destinations import workflows_batch_export
from products.batch_exports.backend.temporal.destinations.workflows_batch_export import (
WorkflowsInsertInputs,
insert_into_workflows_activity_from_stage,
@@ -13,6 +15,7 @@ from products.batch_exports.backend.temporal.pipeline.internal_stage import (
BatchExportInsertIntoInternalStageInputs,
insert_into_internal_stage_activity,
)
+from products.batch_exports.backend.temporal.utils import make_retryable_with_exponential_backoff
from products.batch_exports.backend.tests.temporal.destinations.workflows.utils import (
assert_clickhouse_records_were_handled,
)
@@ -23,6 +26,15 @@ pytestmark = [
]
+def no_retry_delay(monkeypatch):
+ monkeypatch.setattr(
+ workflows_batch_export,
+ "make_retryable_with_exponential_backoff",
+ functools.partial(make_retryable_with_exponential_backoff, initial_retry_delay=0, max_delay_jitter=0),
+ )
+
+
async def _run_activity(
activity_environment,
server,
@@ -196,6 +208,7 @@ async def test_insert_into_workflows_activity_from_stage_fails_on_non_retryable_
@pytest.mark.parametrize("error", [429, 500, 503], indirect=True)
[email protected]("no_retry_delay")
async def test_insert_into_workflows_activity_from_stage_retries_on_retryable_errors(
clickhouse_client,
activity_environment,
diff --git a/products/batch_exports/backend/tests/temporal/utils/clickhouse.py b/products/batch_exports/backend/tests/temporal/utils/clickhouse.py
index ca4daf14b800..89dc304dcdbd 100644
--- a/products/batch_exports/backend/tests/temporal/utils/clickhouse.py
+++ b/products/batch_exports/backend/tests/temporal/utils/clickhouse.py
@@ -1,4 +1,5 @@
import asyncio
+import collections.abc
import aiohttp.client_exceptions
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_random_exponential
@@ -70,22 +71,37 @@ async def create_clickhouse_tables_and_views(clickhouse_client):
return
+EVENTS_TABLES = (
+ "sharded_events",
+ "sharded_events_json",
+ "distributed_events_recent",
+ "events_recent",
+ "sharded_events_recent",
+)
+PERSONS_TABLES = ("person_distinct_id2", "person")
+SESSIONS_TABLES = ("sharded_raw_sessions", "raw_sessions")
+
+
+async def truncate_tables(clickhouse_client, tables: collections.abc.Iterable[str]) -> None:
+ async with asyncio.TaskGroup() as tg:
+ for table in tables:
+ tg.create_task(execute_query(clickhouse_client, f"TRUNCATE TABLE IF EXISTS {table}"))
+
+
async def truncate_events(clickhouse_client):
- await execute_query(clickhouse_client, "TRUNCATE TABLE IF EXISTS sharded_events")
- await execute_query(clickhouse_client, "TRUNCATE TABLE IF EXISTS sharded_events_json")
- await execute_query(clickhouse_client, "TRUNCATE TABLE IF EXISTS distributed_events_recent")
- await execute_query(clickhouse_client, "TRUNCATE TABLE IF EXISTS events_recent")
- await execute_query(clickhouse_client, "TRUNCATE TABLE IF EXISTS sharded_events_recent")
+ await truncate_tables(clickhouse_client, EVENTS_TABLES)
async def truncate_persons(clickhouse_client):
- await execute_query(clickhouse_client, "TRUNCATE TABLE IF EXISTS person_distinct_id2")
- await execute_query(clickhouse_client, "TRUNCATE TABLE IF EXISTS person")
+ await truncate_tables(clickhouse_client, PERSONS_TABLES)
async def truncate_sessions(clickhouse_client):
- await execute_query(clickhouse_client, "TRUNCATE TABLE IF EXISTS sharded_raw_sessions")
- await execute_query(clickhouse_client, "TRUNCATE TABLE IF EXISTS raw_sessions")
+ await truncate_tables(clickhouse_client, SESSIONS_TABLES)
+
+
+async def truncate_all(clickhouse_client):
+ await truncate_tables(clickhouse_client, EVENTS_TABLES + PERSONS_TABLES + SESSIONS_TABLES)
class FlakyClickHouseClient(ClickHouseClient):
diff --git a/products/batch_exports/backend/tests/temporal/utils/workflow.py b/products/batch_exports/backend/tests/temporal/utils/workflow.py
index eda6598ba82f..fb759b317711 100644
--- a/products/batch_exports/backend/tests/temporal/utils/workflow.py
+++ b/products/batch_exports/backend/tests/temporal/utils/workflow.py
@@ -1,4 +1,6 @@
import uuid
+import typing
+import asyncio
import contextlib
import pytest
@@ -32,6 +34,26 @@ async def mocked_start_batch_export_run(inputs: StartBatchExportRunInputs) -> st
return str(run.id)
+class NeverFinishingActivity:
+ """Mock an activity that runs until the workflow cancels it."""
+
+ def __init__(self, name: str) -> None:
+ self.started = asyncio.Event()
+
+ @activity.defn(name=name)
+ async def never_finish(_: typing.Any) -> None:
+ self.started.set()
+ while True:
+ # Temporal delivers the cancellation to the activity in the heartbeat response.
+ activity.heartbeat()
+ await asyncio.sleep(1)
+
+ self.defn = never_finish
+
+ async def wait_until_started(self, timeout: float = 30) -> None:
+ await asyncio.wait_for(self.started.wait(), timeout=timeout)
+
+
@contextlib.contextmanager
def fail_on_application_error():
"""Context manager to fail the test if an application error is raised.