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.

feat(batch-exports): Emit internal events on finish (#81242)

Tomás Farías Santanaa2c3e7563d3c
diff --git a/products/batch_exports/backend/service.py b/products/batch_exports/backend/service.py
index 472e72e23689..f8cc0b99644f 100644
--- a/products/batch_exports/backend/service.py
+++ b/products/batch_exports/backend/service.py
@@ -1031,7 +1031,7 @@ def update_batch_export_run(
run_id: The id of the BatchExportRun to update.
"""
# nosemgrep: idor-lookup-without-team (internal service, team_id passed as parameter)
- model = BatchExportRun.objects.filter(id=run_id)
+ model = BatchExportRun.objects.select_related("batch_export", "batch_export__destination").filter(id=run_id)
update_at = dt.datetime.now(dt.UTC)
updated = model.update(
diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.py
index 58aee05bafd9..0358bc9c3033 100644
--- a/products/batch_exports/backend/temporal/batch_exports.py
+++ b/products/batch_exports/backend/temporal/batch_exports.py
@@ -14,8 +14,9 @@ from structlog.contextvars import bind_contextvars
from temporalio import activity, exceptions, workflow
from temporalio.common import RetryPolicy
+from posthog.cdp.internal_events import InternalEventEvent, create_internal_event, internal_event_to_dict
from posthog.kafka_client.routing import async_producer_scope
-from posthog.kafka_client.topics import KAFKA_APP_METRICS2
+from posthog.kafka_client.topics import KAFKA_APP_METRICS2, KAFKA_CDP_INTERNAL_EVENTS
from posthog.models.team.team import Team
from posthog.models.utils import UUIDT
from posthog.settings.base_variables import TEST
@@ -67,6 +68,8 @@ RecordsGenerator = collections.abc.Generator[pa.RecordBatch]
AsyncBytesGenerator = collections.abc.AsyncGenerator[bytes]
AsyncRecordsGenerator = collections.abc.AsyncGenerator[pa.RecordBatch]
+KafkaPayload = dict[str, typing.Any]
+
def _notify_run_failure(batch_export_run_id: str | UUIDT) -> None:
"""Fan out failure notifications across every channel for a failed run.
@@ -525,17 +528,38 @@ async def start_batch_export_run(inputs: StartBatchExportRunInputs) -> BatchExpo
status=BatchExportRun.Status.FAILED_BILLING,
backfill_id=uuid.UUID(inputs.backfill_id) if inputs.backfill_id else None,
)
+ # Pre-fetch fields in async context, otherwise they would be lazily
+ # fetched below using blocking calls.
+ await run.arefresh_from_db(
+ from_queryset=BatchExportRun.objects.select_related("batch_export", "batch_export__destination")
+ )
logger.info("Over billing limit")
EXTERNAL_LOGGER.warning("Batch export run failed due to exceeding billing limits. No data has been exported.")
- await try_produce_app_metrics(
- status=BatchExportRun.Status.FAILED_BILLING,
- team_id=inputs.team_id,
- batch_export_id=inputs.batch_export_id,
- batch_export_run_id=str(run.id),
- rows_exported=0,
+ metric_payloads = make_app_metrics_payloads(
+ BatchExportRun.Status.FAILED_BILLING,
+ inputs.team_id,
+ inputs.batch_export_id,
+ str(run.id),
+ 0,
)
+ event_payloads = make_internal_events_payload(
+ BatchExportRun.Status.FAILED_BILLING,
+ inputs.team_id,
+ inputs.batch_export_id,
+ str(run.id),
+ run.batch_export.name if run.batch_export is not None else "Batch export on demand",
+ run.data_interval_start,
+ run.data_interval_end,
+ run.batch_export.destination.type if run.batch_export is not None else "On demand",
+ 0,
+ "Over billing limit",
+ # TODO: Should we auto-pause on billing limit exceeded?
+ False,
+ )
+ await try_produce(metric_payloads, topic=KAFKA_APP_METRICS2)
+ await try_produce(event_payloads, topic=KAFKA_CDP_INTERNAL_EVENTS)
raise OverBillingLimitError(inputs.team_id)
else:
@@ -616,9 +640,12 @@ async def finish_batch_export_run(inputs: FinishBatchExportRunInputs) -> None:
that's the case. Also, a notification is sent to users on every failure.
"""
bind_contextvars(
- team_id=inputs.team_id, batch_export_id=inputs.batch_export_id, status=inputs.status, on_demand=inputs.on_demand
+ team_id=inputs.team_id,
+ batch_export_id=inputs.batch_export_id,
+ status=inputs.status,
+ on_demand=inputs.on_demand,
+ batch_export_run_id=inputs.id,
)
- logger = LOGGER.bind()
external_logger = EXTERNAL_LOGGER.bind()
not_model_params = (
@@ -675,38 +702,29 @@ async def finish_batch_export_run(inputs: FinishBatchExportRunInputs) -> None:
failure_threshold=inputs.failure_threshold,
)
- if not is_over_failure_threshold:
- return
-
- try:
- was_paused = await pause_batch_export_over_failure_threshold(inputs.batch_export_id)
- except Exception:
- # Pausing could error if the underlying schedule is deleted.
- # Our application logic should prevent that, but I want to log it in case it ever happens
- # as that would indicate a bug.
- logger.exception("Batch export could not be automatically paused")
- else:
- if was_paused:
- external_logger.warning(
- "Batch export was automatically paused due to exceeding failure threshold and exhausting "
- "all automated retries."
- "The batch export can be unpaused after addressing any errors."
- )
+ was_paused = False
+ if is_over_failure_threshold:
+ was_paused = await try_pause_batch_export(inputs.batch_export_id)
+ await try_cancel_running_backfills(inputs.batch_export_id)
- try:
- total_cancelled = await cancel_running_backfills(
- inputs.batch_export_id,
- )
- except Exception:
- logger.exception("Ongoing backfills could not be automatically cancelled")
- else:
- if total_cancelled > 0:
- external_logger.warning(
- f"{total_cancelled} ongoing batch export backfill{'s' if total_cancelled > 1 else ''} "
- f"{'were' if total_cancelled > 1 else 'was'} cancelled due to exceeding failure threshold "
- " and exhausting all automated retries."
- "The backfill can be triggered again after addressing any errors."
- )
+ payloads = make_internal_events_payload(
+ batch_export_run.status,
+ inputs.team_id,
+ inputs.batch_export_id,
+ inputs.id,
+ batch_export_run.batch_export.name
+ if batch_export_run.batch_export is not None
+ else "Batch export on demand",
+ batch_export_run.data_interval_start,
+ batch_export_run.data_interval_end,
+ batch_export_run.batch_export.destination.type
+ if batch_export_run.batch_export is not None
+ else "On demand",
+ inputs.records_completed or 0,
+ batch_export_run.latest_error or "Unknown error",
+ was_paused,
+ )
+ await try_produce(payloads, topic=KAFKA_CDP_INTERNAL_EVENTS)
elif batch_export_run.status == BatchExportRun.Status.CANCELLED:
external_logger.warning(
@@ -723,19 +741,142 @@ async def finish_batch_export_run(inputs: FinishBatchExportRunInputs) -> None:
inputs.records_completed if inputs.records_completed is not None else "no",
)
- await try_produce_app_metrics(
- batch_export_run.status, inputs.team_id, inputs.batch_export_id, inputs.id, inputs.records_completed or 0
+ payloads = make_app_metrics_payloads(
+ batch_export_run.status,
+ inputs.team_id,
+ inputs.batch_export_id,
+ inputs.id,
+ inputs.records_completed or 0,
+ )
+ await try_produce(payloads, topic=KAFKA_APP_METRICS2)
+
+
+async def try_pause_batch_export(batch_export_id: str) -> bool:
+ was_paused = False
+
+ try:
+ was_paused = await pause_batch_export_over_failure_threshold(batch_export_id)
+ except Exception:
+ # Pausing could error if the underlying schedule is deleted.
+ # Our application logic should prevent that, but I want to log it in case it ever happens
+ # as that would indicate a bug.
+ LOGGER.exception("Batch export could not be automatically paused")
+ else:
+ if was_paused:
+ EXTERNAL_LOGGER.warning(
+ "Batch export was automatically paused due to exceeding failure threshold and exhausting "
+ "all automated retries."
+ "The batch export can be unpaused after addressing any errors."
+ )
+ return was_paused
+
+
+async def try_cancel_running_backfills(batch_export_id: str) -> int | None:
+ total_cancelled = None
+
+ try:
+ total_cancelled = await cancel_running_backfills(
+ batch_export_id,
+ )
+ except Exception:
+ LOGGER.exception("Ongoing backfills could not be automatically cancelled")
+ else:
+ if total_cancelled > 0:
+ EXTERNAL_LOGGER.warning(
+ f"{total_cancelled} ongoing batch export backfill{'s' if total_cancelled > 1 else ''} "
+ f"{'were' if total_cancelled > 1 else 'was'} cancelled due to exceeding failure threshold "
+ " and exhausting all automated retries."
+ "The backfill can be triggered again after addressing any errors."
+ )
+ return total_cancelled
+
+
+def make_internal_events_payload(
+ status: BatchExportRun.Status | str,
+ team_id: int,
+ batch_export_id: str,
+ batch_export_run_id: str,
+ batch_export_name: str,
+ data_interval_start: dt.datetime | None,
+ data_interval_end: dt.datetime,
+ destination_type: str,
+ rows_exported: int,
+ error: str | None,
+ was_paused: bool,
+) -> list[KafkaPayload]:
+ """Generate kafka payloads for internal events.
+
+ Internal events are generated for each batch export result status and when
+ a batch export is paused. Initially intended only to communicate failure
+ states, but with support for all possible batch export status.
+ """
+ base_properties = {
+ "batch_export_id": batch_export_id,
+ "batch_export_run_id": batch_export_run_id,
+ "batch_export_name": batch_export_name,
+ "data_interval_start": data_interval_start.isoformat() if data_interval_start is not None else None,
+ "data_interval_end": data_interval_end.isoformat(),
+ "destination_type": destination_type,
+ }
+
+ extra_properties: dict[str, str | int | None] = {}
+ match status:
+ case BatchExportRun.Status.COMPLETED:
+ event = "$batch_export_run_completed"
+ assert rows_exported is not None
+ extra_properties["rows_exported"] = rows_exported
+ case BatchExportRun.Status.CANCELLED:
+ event = "$batch_export_run_cancelled"
+ case BatchExportRun.Status.FAILED_BILLING:
+ event = "$batch_export_run_failed_billing"
+ assert error is not None
+ extra_properties["error"] = error
+ case _:
+ event = "$batch_export_run_failed"
+ assert error is not None
+ # Truncation roughly matching other products, realistically we shouldn't hit it
+ extra_properties["error"] = error[:1000]
+
+ properties = {**base_properties, **extra_properties}
+ payloads = [
+ internal_event_to_dict(
+ create_internal_event(
+ team_id,
+ event=InternalEventEvent(
+ event=event,
+ properties=properties,
+ distinct_id=f"team_{team_id}",
+ ),
+ )
+ )
+ ]
+
+ if not was_paused:
+ return payloads
+
+ payloads.append(
+ internal_event_to_dict(
+ create_internal_event(
+ team_id,
+ event=InternalEventEvent(
+ event="$batch_export_paused",
+ properties=properties,
+ distinct_id=f"team_{team_id}",
+ ),
+ )
+ )
)
+ return payloads
-async def try_produce_app_metrics(
+def make_app_metrics_payloads(
status: BatchExportRun.Status | str,
team_id: int,
batch_export_id: str,
batch_export_run_id: str,
rows_exported: int,
-):
- """Attempt to produce batch export run status to app_metrics2.
+) -> list[KafkaPayload]:
+ """Generate payloads with batch export run status for app_metrics2.
The metric name and kind will depend on the reported status.
"""
@@ -773,18 +914,20 @@ async def try_produce_app_metrics(
"metric_name": "rows_exported",
"timestamp": timestamp,
}
+ return [run_metric, rows_metric]
+
+
+async def try_produce(payloads: list[KafkaPayload], topic: str) -> None:
+ """Attempt to produce given payloads to kafka on topic."""
+ if not payloads:
+ return
try:
- async with async_producer_scope(topic=KAFKA_APP_METRICS2) as producer:
- await producer.produce(topic=KAFKA_APP_METRICS2, data=run_metric)
- await producer.produce(topic=KAFKA_APP_METRICS2, data=rows_metric)
+ async with async_producer_scope(topic=topic) as producer:
+ for payload in payloads:
+ await producer.produce(topic=topic, data=payload)
except Exception:
- LOGGER.exception(
- "Metrics production failed",
- team_id=team_id,
- batch_export_id=batch_export_id,
- metric_kind=metric_kind,
- )
+ LOGGER.exception("Producer failed", topic=topic)
async def check_if_over_failure_threshold(batch_export_id: str, check_window: int, failure_threshold: int):
diff --git a/products/batch_exports/backend/tests/temporal/test_internal_events.py b/products/batch_exports/backend/tests/temporal/test_internal_events.py
new file mode 100644
index 000000000000..f87ac80a84ab
--- /dev/null
+++ b/products/batch_exports/backend/tests/temporal/test_internal_events.py
@@ -0,0 +1,120 @@
+import datetime as dt
+
+import pytest
+import unittest.mock
+
+from products.batch_exports.backend.models.batch_export import BatchExportRun
+from products.batch_exports.backend.temporal.batch_exports import (
+ make_internal_events_payload,
+ try_cancel_running_backfills,
+ try_pause_batch_export,
+ try_produce,
+)
+
+TEAM_ID = 1
+BATCH_EXPORT_ID = "d0ec7b0c-6b3d-4a76-8ea4-6a5b2c0e1f5a"
+RUN_ID = "b3f5a9d1-2c4e-4f6a-8b7c-9d0e1f2a3b4c"
+BATCH_EXPORT_NAME = "test export"
+DESTINATION_TYPE = "S3"
+INTERVAL_START = dt.datetime(2023, 4, 24, tzinfo=dt.UTC)
+INTERVAL_END = dt.datetime(2023, 4, 25, tzinfo=dt.UTC)
+
+BASE_PROPERTIES = {
+ "batch_export_id": BATCH_EXPORT_ID,
+ "batch_export_run_id": RUN_ID,
+ "batch_export_name": BATCH_EXPORT_NAME,
+ "data_interval_start": INTERVAL_START.isoformat(),
+ "data_interval_end": INTERVAL_END.isoformat(),
+ "destination_type": DESTINATION_TYPE,
+}
+
+
+def make_payloads(status: BatchExportRun.Status, error: str | None = "Oh No!", was_paused: bool = False):
+ return make_internal_events_payload(
+ status,
+ TEAM_ID,
+ BATCH_EXPORT_ID,
+ RUN_ID,
+ BATCH_EXPORT_NAME,
+ INTERVAL_START,
+ INTERVAL_END,
+ DESTINATION_TYPE,
+ 10,
+ error,
+ was_paused,
+ )
+
+
+ "status,expected_event,expected_extra_properties",
+ [
+ (BatchExportRun.Status.COMPLETED, "$batch_export_run_completed", {"rows_exported": 10}),
+ (BatchExportRun.Status.CANCELLED, "$batch_export_run_cancelled", {}),
+ (BatchExportRun.Status.FAILED_BILLING, "$batch_export_run_failed_billing", {"error": "Oh No!"}),
+ (BatchExportRun.Status.FAILED, "$batch_export_run_failed", {"error": "Oh No!"}),
+ ],
+)
+def test_make_internal_events_payload_matches_status(status, expected_event, expected_extra_properties):
+ """Test 'make_internal_events_payload' generates the event matching each status."""
+ payloads = make_payloads(status)
+
+ assert len(payloads) == 1
+
+ payload = payloads[0]
+ assert payload["team_id"] == TEAM_ID
+ assert payload["event"]["event"] == expected_event
+ assert payload["event"]["distinct_id"] == f"team_{TEAM_ID}"
+ assert payload["event"]["properties"] == {**BASE_PROPERTIES, **expected_extra_properties}
+
+
+def test_make_internal_events_payload_truncates_error():
+ """Test 'make_internal_events_payload' truncates long error messages for failed runs."""
+ payloads = make_payloads(BatchExportRun.Status.FAILED, error="e" * 2000)
+
+ assert payloads[0]["event"]["properties"]["error"] == "e" * 1000
+
+
+def test_make_internal_events_payload_includes_paused_event_only_when_paused():
+ """Test the '$batch_export_paused' event is generated if and only if the batch export was paused."""
+ paused_payloads = make_payloads(BatchExportRun.Status.FAILED, was_paused=True)
+
+ assert [payload["event"]["event"] for payload in paused_payloads] == [
+ "$batch_export_run_failed",
+ "$batch_export_paused",
+ ]
+ assert paused_payloads[1]["event"]["properties"] == {**BASE_PROPERTIES, "error": "Oh No!"}
+ assert paused_payloads[1]["event"]["distinct_id"] == f"team_{TEAM_ID}"
+
+ not_paused_payloads = make_payloads(BatchExportRun.Status.FAILED, was_paused=False)
+
+ assert [payload["event"]["event"] for payload in not_paused_payloads] == ["$batch_export_run_failed"]
+
+
+async def test_try_pause_batch_export_returns_false_when_pausing_raises():
+ """Test 'try_pause_batch_export' swallows exceptions and reports no pause happened."""
+ with unittest.mock.patch(
+ "products.batch_exports.backend.temporal.batch_exports.pause_batch_export_over_failure_threshold",
+ side_effect=RuntimeError("Oh No!"),
+ ):
+ assert await try_pause_batch_export(BATCH_EXPORT_ID) is False
+
+
+async def test_try_cancel_running_backfills_returns_none_when_cancelling_raises():
+ """Test 'try_cancel_running_backfills' swallows exceptions and reports no cancellations."""
+ with unittest.mock.patch(
+ "products.batch_exports.backend.temporal.batch_exports.cancel_running_backfills",
+ side_effect=RuntimeError("Oh No!"),
+ ):
+ assert await try_cancel_running_backfills(BATCH_EXPORT_ID) is None
+
+
+async def test_try_produce_swallows_producer_errors():
+ """Test 'try_produce' does not raise when the underlying producer fails."""
+ with unittest.mock.patch(
+ "products.batch_exports.backend.temporal.batch_exports.async_producer_scope",
+ side_effect=RuntimeError("Oh No!"),
+ ):
+ await try_produce([{"key": "value"}], topic="some_topic")
diff --git a/products/batch_exports/backend/tests/temporal/test_run_updates.py b/products/batch_exports/backend/tests/temporal/test_run_updates.py
index 9363cb7e1a23..d4bdada5fa25 100644
--- a/products/batch_exports/backend/tests/temporal/test_run_updates.py
+++ b/products/batch_exports/backend/tests/temporal/test_run_updates.py
@@ -8,6 +8,7 @@ from django.test import override_settings
from asgiref.sync import sync_to_async
+from posthog.kafka_client.topics import KAFKA_APP_METRICS2, KAFKA_CDP_INTERNAL_EVENTS
from posthog.models import Organization, Team
from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportDestination, BatchExportRun
@@ -398,3 +399,192 @@ async def test_finish_batch_export_run_records_failed_none_when_not_set(activity
assert run.status == "Completed"
assert run.records_completed == 100
assert run.records_failed is None
+
+
+def get_produced_internal_event_payloads(mocked_try_produce: unittest.mock.AsyncMock) -> list:
+ """Extract payload lists produced to the internal events topic from a mocked 'try_produce'."""
+ return [
+ call.args[0]
+ for call in mocked_try_produce.call_args_list
+ if call.kwargs.get("topic") == KAFKA_CDP_INTERNAL_EVENTS
+ ]
+
+
+def get_produced_app_metrics_payloads(mocked_try_produce: unittest.mock.AsyncMock) -> list:
+ """Extract payload lists produced to the app metrics topic from a mocked 'try_produce'."""
+ return [
+ call.args[0] for call in mocked_try_produce.call_args_list if call.kwargs.get("topic") == KAFKA_APP_METRICS2
+ ]
+
+
[email protected]_db(transaction=True)
+async def test_finish_batch_export_run_produces_failed_internal_event(activity_environment, team, batch_export):
+ """Test 'finish_batch_export_run' produces a '$batch_export_run_failed' internal event on failure."""
+ start = dt.datetime(2023, 4, 24, tzinfo=dt.UTC)
+ end = dt.datetime(2023, 4, 25, tzinfo=dt.UTC)
+
+ run_id = await activity_environment.run(
+ start_batch_export_run,
+ StartBatchExportRunInputs(
+ team_id=team.id,
+ batch_export_id=str(batch_export.id),
+ data_interval_start=start.isoformat(),
+ data_interval_end=end.isoformat(),
+ ),
+ )
+
+ finish_inputs = FinishBatchExportRunInputs(
+ id=str(run_id),
+ batch_export_id=str(batch_export.id),
+ status=BatchExportRun.Status.FAILED,
+ team_id=team.id,
+ latest_error="Oh No!",
+ )
+
+ with unittest.mock.patch("products.batch_exports.backend.temporal.batch_exports.try_produce") as mocked_try_produce:
+ await activity_environment.run(finish_batch_export_run, finish_inputs)
+
+ internal_event_payloads = get_produced_internal_event_payloads(mocked_try_produce)
+ assert len(internal_event_payloads) == 1
+ assert [payload["event"]["event"] for payload in internal_event_payloads[0]] == ["$batch_export_run_failed"]
+ assert internal_event_payloads[0][0]["event"]["properties"] == {
+ "batch_export_id": str(batch_export.id),
+ "batch_export_name": batch_export.name,
+ "batch_export_run_id": str(run_id),
+ "data_interval_start": start.isoformat(),
+ "data_interval_end": end.isoformat(),
+ "destination_type": "S3",
+ "error": "Oh No!",
+ }
+
+ assert len(get_produced_app_metrics_payloads(mocked_try_produce)) == 1
+
+
[email protected]_db(transaction=True)
+async def test_finish_batch_export_run_produces_paused_internal_event(activity_environment, team, batch_export):
+ """Test 'finish_batch_export_run' produces a '$batch_export_paused' internal event when pausing."""
+ start = dt.datetime(2023, 4, 24, tzinfo=dt.UTC)
+ end = dt.datetime(2023, 4, 25, tzinfo=dt.UTC)
+
+ run_id = await activity_environment.run(
+ start_batch_export_run,
+ StartBatchExportRunInputs(
+ team_id=team.id,
+ batch_export_id=str(batch_export.id),
+ data_interval_start=start.isoformat(),
+ data_interval_end=end.isoformat(),
+ ),
+ )
+
+ finish_inputs = FinishBatchExportRunInputs(
+ id=str(run_id),
+ batch_export_id=str(batch_export.id),
+ status=BatchExportRun.Status.FAILED,
+ team_id=team.id,
+ latest_error="Oh No!",
+ )
+
+ with (
+ unittest.mock.patch(
+ "products.batch_exports.backend.temporal.batch_exports.check_if_over_failure_threshold",
+ return_value=True,
+ ),
+ unittest.mock.patch(
+ "products.batch_exports.backend.temporal.batch_exports.pause_batch_export_over_failure_threshold",
+ return_value=True,
+ ),
+ unittest.mock.patch(
+ "products.batch_exports.backend.temporal.batch_exports.cancel_running_backfills",
+ return_value=0,
+ ),
+ unittest.mock.patch("products.batch_exports.backend.temporal.batch_exports.try_produce") as mocked_try_produce,
+ ):
+ await activity_environment.run(finish_batch_export_run, finish_inputs)
+
+ internal_event_payloads = get_produced_internal_event_payloads(mocked_try_produce)
+ assert len(internal_event_payloads) == 1
+ assert [payload["event"]["event"] for payload in internal_event_payloads[0]] == [
+ "$batch_export_run_failed",
+ "$batch_export_paused",
+ ]
+
+
[email protected]("status", [BatchExportRun.Status.CANCELLED, BatchExportRun.Status.FAILED_RETRYABLE])
[email protected]_db(transaction=True)
+async def test_finish_batch_export_run_produces_no_internal_events(activity_environment, team, batch_export, status):
+ """Test 'finish_batch_export_run' produces no internal events for non-failure statuses, only app metrics."""
+ start = dt.datetime(2023, 4, 24, tzinfo=dt.UTC)
+ end = dt.datetime(2023, 4, 25, tzinfo=dt.UTC)
+
+ run_id = await activity_environment.run(
+ start_batch_export_run,
+ StartBatchExportRunInputs(
+ team_id=team.id,
+ batch_export_id=str(batch_export.id),
+ data_interval_start=start.isoformat(),
+ data_interval_end=end.isoformat(),
+ ),
+ )
+
+ finish_inputs = FinishBatchExportRunInputs(
+ id=str(run_id),
+ batch_export_id=str(batch_export.id),
+ status=status,
+ team_id=team.id,
+ latest_error="Oh No!",
+ )
+
+ with unittest.mock.patch("products.batch_exports.backend.temporal.batch_exports.try_produce") as mocked_try_produce:
+ await activity_environment.run(finish_batch_export_run, finish_inputs)
+
+ assert get_produced_internal_event_payloads(mocked_try_produce) == []
+ assert len(get_produced_app_metrics_payloads(mocked_try_produce)) == 1
+
+
[email protected]_db(transaction=True)
+async def test_start_batch_export_run_produces_failed_billing_internal_event(activity_environment, team, batch_export):
+ """Test 'start_batch_export_run' produces a '$batch_export_run_failed_billing' internal event when over limit."""
+ start = dt.datetime(2023, 4, 24, tzinfo=dt.UTC)
+ end = dt.datetime(2023, 4, 25, tzinfo=dt.UTC)
+
+ with override_settings(BATCH_EXPORTS_ENABLE_BILLING_CHECK=True):
+ inputs = StartBatchExportRunInputs(
+ team_id=team.id,
+ batch_export_id=str(batch_export.id),
+ data_interval_start=start.isoformat(),
+ data_interval_end=end.isoformat(),
+ )
+
+ fut: asyncio.Future[bool] = asyncio.Future()
+ fut.set_result(False)
+
+ with (
+ unittest.mock.patch(
+ "products.batch_exports.backend.temporal.batch_exports.check_is_over_limit", return_value=fut
+ ),
+ unittest.mock.patch("products.batch_exports.backend.temporal.batch_exports.try_produce") as mocked_try_produce,
+ pytest.raises(OverBillingLimitError),
+ ):
+ _ = await activity_environment.run(start_batch_export_run, inputs)
+
+ run = await sync_to_async(BatchExportRun.objects.filter(batch_export=batch_export).get)()
+ assert run.status == BatchExportRun.Status.FAILED_BILLING
+
+ internal_event_payloads = get_produced_internal_event_payloads(mocked_try_produce)
+ assert len(internal_event_payloads) == 1
+ assert [payload["event"]["event"] for payload in internal_event_payloads[0]] == ["$batch_export_run_failed_billing"]
+ assert internal_event_payloads[0][0]["event"]["properties"] == {
+ "batch_export_id": str(batch_export.id),
+ "batch_export_name": batch_export.name,
+ "batch_export_run_id": str(run.id),
+ "data_interval_start": start.isoformat(),
+ "data_interval_end": end.isoformat(),
+ "destination_type": "S3",
+ "error": "Over billing limit",
+ }
+
+ assert len(get_produced_app_metrics_payloads(mocked_try_produce)) == 1