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(test): trim redundant batch export workflow matrix (#66400)

Georges-Antoine Assi42073979e00d
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 98878a79254b..b1519921b4db 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
@@ -42,7 +42,6 @@ pytestmark = [
@pytest.mark.parametrize("interval", ["hour", "day"], indirect=True)
@pytest.mark.parametrize("exclude_events", [None, ["test-exclude"]], indirect=True)
@pytest.mark.parametrize("model", TEST_MODELS)
[email protected]("integration", [True, False], indirect=True)
async def test_postgres_export_workflow(
clickhouse_client,
postgres_config,
@@ -56,7 +55,6 @@ async def test_postgres_export_workflow(
generate_test_data,
data_interval_start,
data_interval_end,
- integration,
):
"""Test Postgres Export Workflow end-to-end by using a local PG database.
@@ -77,13 +75,7 @@ async def test_postgres_export_workflow(
elif model is not None:
batch_export_schema = model
- if integration is not None:
- config = postgres_batch_export.destination.config.copy()
- for conn_param in ("host", "port", "user", "password"):
- # These should be present in the integration, so drop them to confirm
- config.pop(conn_param)
- else:
- config = postgres_batch_export.destination.config
+ config = postgres_batch_export.destination.config
workflow_id = str(uuid.uuid4())
inputs = PostgresBatchExportInputs(
@@ -93,7 +85,6 @@ async def test_postgres_export_workflow(
interval=interval,
batch_export_schema=batch_export_schema,
batch_export_model=batch_export_model,
- integration_id=integration.id if integration is not None else None,
**config,
)
@@ -156,6 +147,89 @@ async def test_postgres_export_workflow(
)
[email protected]("interval", ["hour"], indirect=True)
[email protected]("exclude_events", [None], indirect=True)
[email protected]("model", [BatchExportModel(name="events", schema=None)])
[email protected]("integration", [True], indirect=True)
+async def test_postgres_export_workflow_with_integration(
+ clickhouse_client,
+ postgres_config,
+ postgres_connection,
+ postgres_batch_export,
+ interval,
+ exclude_events,
+ ateam,
+ table_name,
+ model: BatchExportModel | None,
+ generate_test_data,
+ data_interval_start,
+ data_interval_end,
+ integration,
+):
+ """Test the workflow resolves destination connection params from an Integration end-to-end.
+
+ The connection params are dropped from the inline config and only reachable via the
+ integration, so a successful export proves the workflow plumbs ``integration_id`` through
+ to the insert activity (which is exercised across models in ``test_activity``).
+ """
+ assert integration is not None
+ config = postgres_batch_export.destination.config.copy()
+ for conn_param in ("host", "port", "user", "password"):
+ # These should be present in the integration, so drop them to confirm
+ config.pop(conn_param)
+
+ workflow_id = str(uuid.uuid4())
+ inputs = PostgresBatchExportInputs(
+ team_id=ateam.pk,
+ batch_export_id=str(postgres_batch_export.id),
+ data_interval_end=data_interval_end.isoformat(),
+ interval=interval,
+ batch_export_model=model,
+ integration_id=integration.id,
+ **config,
+ )
+
+ async with await WorkflowEnvironment.start_time_skipping() as activity_environment:
+ async with Worker(
+ activity_environment.client,
+ task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,
+ workflows=[PostgresBatchExportWorkflow],
+ activities=[
+ start_batch_export_run,
+ insert_into_internal_stage_activity,
+ insert_into_postgres_activity_from_stage,
+ finish_batch_export_run,
+ ],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ with override_settings(BATCH_EXPORT_POSTGRES_UPLOAD_CHUNK_SIZE_BYTES=5 * 1024**2):
+ await activity_environment.client.execute_workflow(
+ PostgresBatchExportWorkflow.run,
+ inputs,
+ id=workflow_id,
+ task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ execution_timeout=dt.timedelta(seconds=10),
+ )
+
+ runs = await afetch_batch_export_runs(batch_export_id=postgres_batch_export.id)
+ assert len(runs) == 1
+ assert runs[0].status == "Completed"
+
+ await assert_clickhouse_records_in_postgres(
+ postgres_connection=postgres_connection,
+ clickhouse_client=clickhouse_client,
+ schema_name=postgres_config["schema"],
+ table_name=table_name,
+ team_id=ateam.pk,
+ data_interval_start=data_interval_start,
+ data_interval_end=data_interval_end,
+ batch_export_model=model,
+ exclude_events=exclude_events,
+ sort_key="event",
+ )
+
+
@pytest.mark.parametrize("interval", ["hour"], indirect=True)
@pytest.mark.parametrize("exclude_events", [None], indirect=True)
@pytest.mark.parametrize("model", TEST_MODELS)
diff --git a/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_with_minio_bucket.py b/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_with_minio_bucket.py
index fdeb091e06a5..75dbf201c358 100644
--- a/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_with_minio_bucket.py
+++ b/products/batch_exports/backend/tests/temporal/destinations/s3/test_workflow_with_minio_bucket.py
@@ -18,12 +18,12 @@ pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
TEST_DATA_INTERVAL_END = dt.datetime.now(tz=dt.UTC).replace(hour=0, minute=0, second=0, microsecond=0)
[email protected]("interval", ["hour", "day", "every 5 minutes", "week"], indirect=True)
[email protected]("interval", ["hour"], indirect=True)
@pytest.mark.parametrize("model", TEST_S3_MODELS)
@pytest.mark.parametrize("compression", [None], indirect=True)
@pytest.mark.parametrize("exclude_events", [None], indirect=True)
@pytest.mark.parametrize("file_format", ["Parquet"], indirect=True)
-async def test_s3_export_workflow_with_minio_bucket_with_various_intervals_and_models(
+async def test_s3_export_workflow_with_minio_bucket_with_various_models(
clickhouse_client,
minio_client,
ateam,
diff --git a/products/batch_exports/backend/tests/temporal/test_metrics.py b/products/batch_exports/backend/tests/temporal/test_metrics.py
index 7d0b7c1bc866..6320f1d7d7c8 100644
--- a/products/batch_exports/backend/tests/temporal/test_metrics.py
+++ b/products/batch_exports/backend/tests/temporal/test_metrics.py
@@ -1,162 +1,29 @@
-import uuid
import asyncio
import datetime as dt
import pytest
-from unittest import mock
-from django.conf import settings
-
-import psycopg
-import pytest_asyncio
-import temporalio.client
from structlog.testing import capture_logs
-from temporalio.common import RetryPolicy
-
-from posthog.temporal.tests.utils.models import acreate_batch_export, adelete_batch_export
-from products.batch_exports.backend.service import BatchExportModel
-from products.batch_exports.backend.temporal.destinations.postgres_batch_export import PostgresBatchExportInputs
from products.batch_exports.backend.temporal.metrics import SLAWaiter
-pytestmark = [pytest.mark.asyncio, pytest.mark.django_db]
-
-
-def table_name(ateam, interval):
- return f"test_table_{ateam.pk}_{interval}"
-
-
-def postgres_config():
- return {
- "user": settings.PG_USER,
- "password": settings.PG_PASSWORD,
- "database": "exports_test_database",
- "schema": "exports_test_schema",
- "host": settings.PG_HOST,
- "port": int(settings.PG_PORT),
- }
-
-
-@pytest_asyncio.fixture
-async def postgres_connection(postgres_config, setup_postgres_test_db):
- connection = await psycopg.AsyncConnection.connect(
- user=postgres_config["user"],
- password=postgres_config["password"],
- dbname=postgres_config["database"],
- host=postgres_config["host"],
- port=postgres_config["port"],
- autocommit=True,
- )
-
- yield connection
-
- await connection.close()
-
-
-@pytest_asyncio.fixture
-async def postgres_batch_export(ateam, table_name, postgres_config, interval, exclude_events, temporal_client):
- destination_data = {
- "type": "Postgres",
- "config": {**postgres_config, "table_name": table_name, "exclude_events": exclude_events},
- }
- batch_export_data = {
- "name": "my-production-postgres-export",
- "destination": destination_data,
- "interval": interval,
- }
-
- batch_export = await acreate_batch_export(
- team_id=ateam.pk,
- name=batch_export_data["name"],
- destination_data=batch_export_data["destination"],
- interval=batch_export_data["interval"],
- )
-
- yield batch_export
-
- await adelete_batch_export(batch_export, temporal_client)
-
-
-async def test_interceptor_calls_histogram_metrics(
- ateam,
- data_interval_end,
- interval,
- postgres_batch_export,
- temporal_client: temporalio.client.Client,
- temporal_worker,
-):
- """Test metrics interceptor calls mocked histogram metrics."""
-
- workflow_id = str(uuid.uuid4())
- inputs = PostgresBatchExportInputs(
- team_id=ateam.pk,
- batch_export_id=str(postgres_batch_export.id),
- data_interval_end=data_interval_end.isoformat(),
- interval=interval,
- batch_export_model=BatchExportModel(name="events", schema=None),
- **postgres_batch_export.destination.config,
- )
-
- with mock.patch(
- "products.batch_exports.backend.temporal.metrics.get_metric_meter", mock.MagicMock()
- ) as mocked_meter:
- await temporal_client.execute_workflow(
- "postgres-export",
- inputs,
- id=workflow_id,
- task_queue=settings.BATCH_EXPORTS_TASK_QUEUE,
- execution_timeout=dt.timedelta(seconds=10),
- retry_policy=RetryPolicy(maximum_attempts=1),
- )
-
- mocked_meter.assert_any_call({"interval": "hour", "status": "COMPLETED", "exception": ""})
- mocked_meter.return_value.create_histogram_timedelta.assert_any_call(
- name="batch_exports_workflow_interval_execution_latency",
- description="Histogram tracking execution latency for batch export workflows by interval",
- unit="ms",
- )
- mocked_meter.return_value.create_histogram_timedelta.assert_any_call(
- name="batch_exports_activity_interval_execution_latency",
- description="Histogram tracking execution latency for critical batch export activities by interval",
- unit="ms",
- )
-
- mocked_meter.return_value.create_counter.assert_any_call(
- name="batch_exports_activity_attempts",
- description="Counter tracking every attempt at running an activity",
- )
- mocked_meter.return_value.create_counter.assert_any_call(
- name="batch_exports_activity_success_attempts",
- description="Counter tracking the attempts it took to complete activities",
- )
-
- number_of_record_calls = mocked_meter.return_value.create_histogram_timedelta.return_value.record.call_count
- assert number_of_record_calls == 3, (
- f"expected to have recorded three metrics: one for workflow and two for activity execution latency (insert_into_internal_stage_activity and insert_into_postgres_activity_from_stage), but found {number_of_record_calls}"
- )
-
- number_of_add_calls = mocked_meter.return_value.create_counter.return_value.add.call_count
- expected_calls = [mock.call(1)] * number_of_add_calls
-
- assert mocked_meter.return_value.create_counter.return_value.add.mock_calls == expected_calls
+pytestmark = [pytest.mark.asyncio]
async def test_sla_waiter():
with capture_logs() as cap_logs:
- async with SLAWaiter(batch_export_id="test", sla=dt.timedelta(seconds=1)) as detector:
- await asyncio.sleep(3)
+ async with SLAWaiter(batch_export_id="test", sla=dt.timedelta(seconds=0.25)) as detector:
+ await asyncio.sleep(0.75)
assert detector.is_over_sla()
assert "SLA breached" == cap_logs[0]["event"]
assert "test" == cap_logs[0]["batch_export_id"]
- assert 1 == cap_logs[0]["sla_seconds"]
+ assert 0.25 == cap_logs[0]["sla_seconds"]
with capture_logs() as cap_logs:
- async with SLAWaiter(batch_export_id="test", sla=dt.timedelta(seconds=3)) as detector:
- await asyncio.sleep(1)
+ async with SLAWaiter(batch_export_id="test", sla=dt.timedelta(seconds=0.75)) as detector:
+ await asyncio.sleep(0.25)
assert detector.is_over_sla() is False