: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(batch-exports): filter runs by status in the API (#89043)
Rossc10863ebb172
diff --git a/products/batch_exports/backend/api/batch_export.py b/products/batch_exports/backend/api/batch_export.pyindex 6bc9b29bd3a5..06bad0821010 100644--- a/products/batch_exports/backend/api/batch_export.py+++ b/products/batch_exports/backend/api/batch_export.py@@ -162,11 +162,58 @@ class BatchExportRunSerializer(serializers.ModelSerializer):read_only_fields = ["batch_export"]+class BatchExportRunListQuerySerializer(serializers.Serializer):+ """Query parameters accepted when listing the runs of a batch export."""++ status = serializers.ListField(+ required=False,+ child=serializers.ChoiceField(choices=BatchExportRun.Status.choices),+ help_text="Only return runs in these statuses. Repeat the parameter to pass more than one status.",+ )+ after = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text=(+ "Only return runs created at or after this point. "+ "Accepts an ISO-8601 datetime or a relative value like `-7d`. Defaults to `-7d`. "+ "Ignored when ordering by `data_interval_start`."+ ),+ )+ before = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text=(+ "Only return runs created at or before this point. "+ "Accepts an ISO-8601 datetime or a relative value like `-1d`. Defaults to now. "+ "Ignored when ordering by `data_interval_start`."+ ),+ )+ start = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text=(+ "Only return runs whose data interval starts at or after this point. "+ "Accepts an ISO-8601 datetime or a relative value like `-7d`. Defaults to `-7d`. "+ "Only applies when ordering by `data_interval_start`."+ ),+ )+ end = serializers.CharField(+ required=False,+ allow_blank=True,+ help_text=(+ "Only return runs whose data interval ends at or before this point. "+ "Accepts an ISO-8601 datetime or a relative value like `-1d`. Defaults to now. "+ "Only applies when ordering by `data_interval_start`."+ ),+ )++class RunsCursorPagination(CursorPagination):page_size = 100@extend_schema(tags=["batch_exports"])+@extend_schema_view(list=extend_schema(parameters=[BatchExportRunListQuerySerializer]))class BatchExportRunViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.ReadOnlyModelViewSet):scope_object = "batch_export"queryset = BatchExportRun.objects.select_related("batch_export__destination").all()@@ -182,12 +229,17 @@ class BatchExportRunViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.Readreturn cast(str, self.parents_query_dict["run_id"])def safely_get_queryset(self, queryset):- after = self.request.GET.get("after", None)- before = self.request.GET.get("before", None)- start = self.request.GET.get("start", None)- end = self.request.GET.get("end", None)- ordering = self.request.GET.get("ordering", None)+ query = BatchExportRunListQuerySerializer(data=self.request.GET)+ query.is_valid(raise_exception=True)+ params = query.validated_data+ after = params.get("after")+ before = params.get("before")+ start = params.get("start")+ end = params.get("end")++ # OrderingFilter applies the sort and declares this parameter, so it is not on the serializer.+ ordering = self.request.GET.get("ordering", None)# If we're ordering by data_interval_start, we need to filter by that otherwise we're ordering by created_atif ordering == "data_interval_start" or ordering == "-data_interval_start":start_timestamp = relative_date_parse(start if start else "-7d", self.team.timezone_info)@@ -199,6 +251,9 @@ class BatchExportRunViewSet(TeamAndOrgViewSetMixin, LogEntryMixin, viewsets.Readdate_range = (after_datetime, before_datetime)queryset = queryset.filter(created_at__range=date_range)+ if statuses := params.get("status"):+ queryset = queryset.filter(status__in=statuses)+queryset = queryset.filter(batch_export_id=self.kwargs["parent_lookup_batch_export_id"])return querysetdiff --git a/products/batch_exports/backend/tests/api/operations.py b/products/batch_exports/backend/tests/api/operations.pyindex 4142a9a46959..b01612d203a7 100644--- a/products/batch_exports/backend/tests/api/operations.py+++ b/products/batch_exports/backend/tests/api/operations.py@@ -74,15 +74,17 @@ def get_batch_export_ok(client: TestClient, team_id: int, batch_export_id: UUIDTreturn response.json()-def get_batch_export_runs(client: TestClient, team_id: int, batch_export_id: str):+def get_batch_export_runs(client: TestClient, team_id: int, batch_export_id: str, **query_params):return client.get(f"/api/projects/{team_id}/batch_exports/{batch_export_id}/runs",+ # List values are encoded as repeated parameters, matching how the API expects them.+ data=query_params or None,content_type="application/json",)-def get_batch_export_runs_ok(client: TestClient, team_id: int, batch_export_id: str):- response = get_batch_export_runs(client, team_id, batch_export_id)+def get_batch_export_runs_ok(client: TestClient, team_id: int, batch_export_id: str, **query_params):+ response = get_batch_export_runs(client, team_id, batch_export_id, **query_params)assert response.status_code == status.HTTP_200_OK, response.json()return response.json()diff --git a/products/batch_exports/backend/tests/api/test_runs.py b/products/batch_exports/backend/tests/api/test_runs.pyindex 8314cb642117..89f2ac42d173 100644--- a/products/batch_exports/backend/tests/api/test_runs.py+++ b/products/batch_exports/backend/tests/api/test_runs.py@@ -227,6 +227,109 @@ def test_cancelling_a_batch_export_run(client: HttpClient, temporal, organizatioassert run["status"] == "Cancelled"[email protected]("ordering", [None, "-data_interval_start"])+def test_get_batch_export_runs_filtered_by_status(client: HttpClient, team, user, ordering):+ batch_export = create_batch_export(team, create_destination())+ # Runs are only returned when their data interval falls inside the default window of the last 7 days.+ interval_end = dt.datetime.now(dt.UTC) - dt.timedelta(hours=1)+ runs = {}+ for hours, run_status in enumerate(+ [+ BatchExportRun.Status.COMPLETED,+ BatchExportRun.Status.FAILED,+ BatchExportRun.Status.FAILED_RETRYABLE,+ BatchExportRun.Status.RUNNING,+ ]+ ):+ runs[run_status] = create_run(+ batch_export,+ status=run_status,+ data_interval_start=interval_end - dt.timedelta(hours=hours + 1),+ data_interval_end=interval_end - dt.timedelta(hours=hours),+ )++ client.force_login(user)+ query_params = {"ordering": ordering} if ordering else {}++ # List runs filtered by failed statuses, asserting that only failed runs are returned+ data = get_batch_export_runs_ok(+ client,+ team.pk,+ batch_export.id,+ status=[BatchExportRun.Status.FAILED, BatchExportRun.Status.FAILED_RETRYABLE],+ **query_params,+ )+ assert {run["id"] for run in data["results"]} == {+ str(runs[BatchExportRun.Status.FAILED].id),+ str(runs[BatchExportRun.Status.FAILED_RETRYABLE].id),+ }++ # List all runs, without any status filter, asserting that all runs are returned+ data = get_batch_export_runs_ok(client, team.pk, batch_export.id, **query_params)+ assert {run["id"] for run in data["results"]} == {str(run.id) for run in runs.values()}+++def test_get_batch_export_runs_rejects_unknown_status(client: HttpClient, team, user):+ batch_export = create_batch_export(team, create_destination())+ client.force_login(user)++ response = get_batch_export_runs(client, team.pk, batch_export.id, status=["NotAStatus"])++ assert response.status_code == status.HTTP_400_BAD_REQUEST, response.json()+++def test_get_batch_export_runs_date_filter_depends_on_ordering(client: HttpClient, team, user):+ batch_export = create_batch_export(team, create_destination())+ now = dt.datetime.now(dt.UTC)++ def days_ago(days: float) -> dt.datetime:+ return now - dt.timedelta(days=days)++ # Backfilled today for a 40-day-old interval+ run_old_interval = create_run(+ batch_export,+ status=BatchExportRun.Status.COMPLETED,+ data_interval_start=days_ago(40) - dt.timedelta(hours=1),+ data_interval_end=days_ago(40),+ )++ # Backfilled 10 days ago for a 20-day-old interval.+ run_mid_interval = create_run(+ batch_export,+ status=BatchExportRun.Status.COMPLETED,+ data_interval_start=days_ago(20) - dt.timedelta(hours=1),+ data_interval_end=days_ago(20),+ )+ BatchExportRun.objects.filter(id=run_mid_interval.id).update(created_at=days_ago(10))++ # A normal, on-schedule run: created right as its 5-day-old interval ended.+ run_recent_interval = create_run(+ batch_export,+ status=BatchExportRun.Status.COMPLETED,+ data_interval_start=days_ago(5) - dt.timedelta(hours=1),+ data_interval_end=days_ago(5),+ )+ BatchExportRun.objects.filter(id=run_recent_interval.id).update(created_at=days_ago(5))++ client.force_login(user)++ # Default ordering sorts and filters by created_at: today (run_old_interval), then 5 days ago+ # (run_recent_interval); 10 days ago (run_mid_interval) falls outside the 8-day window.+ # `start` is passed too and must have no effect: applied, it would exclude run_old_interval's+ # 40-day-old interval.+ data = get_batch_export_runs_ok(client, team.pk, batch_export.id, after="-8d", start="-25d")+ assert [run["id"] for run in data["results"]] == [str(run_old_interval.id), str(run_recent_interval.id)]++ # Ordering by data_interval_start instead sorts and filters by the interval: 5 days ago+ # (run_recent_interval), then 20 days ago (run_mid_interval); 40 days ago (run_old_interval)+ # falls outside the 25-day window. `before` is passed too and must have no effect: applied, it+ # would exclude run_recent_interval, which was created only 5 days ago.+ data = get_batch_export_runs_ok(+ client, team.pk, batch_export.id, ordering="-data_interval_start", start="-25d", before="-8d"+ )+ assert [run["id"] for run in data["results"]] == [str(run_recent_interval.id), str(run_mid_interval.id)]++def test_cannot_cancel_completed_batch_export_run(client: HttpClient, team, user):destination = create_destination()batch_export = create_batch_export(team, destination)diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.tsindex 27297ec9312e..5bc7c1da8da1 100644--- a/products/batch_exports/frontend/generated/api.schemas.ts+++ b/products/batch_exports/frontend/generated/api.schemas.ts@@ -1937,16 +1937,64 @@ export type BatchExportsBackfillsListParams = {}export type BatchExportsRunsListParams = {+ /**+ * Only return runs created at or after this point. Accepts an ISO-8601 datetime or a relative value like `-7d`. Defaults to `-7d`. Ignored when ordering by `data_interval_start`.+ */+ after?: string+ /**+ * Only return runs created at or before this point. Accepts an ISO-8601 datetime or a relative value like `-1d`. Defaults to now. Ignored when ordering by `data_interval_start`.+ */+ before?: string/*** The pagination cursor value.*/cursor?: string+ /**+ * Only return runs whose data interval ends at or before this point. Accepts an ISO-8601 datetime or a relative value like `-1d`. Defaults to now. Only applies when ordering by `data_interval_start`.+ */+ end?: string/*** Which field to use when ordering the results.*/ordering?: string+ /**+ * Only return runs whose data interval starts at or after this point. Accepts an ISO-8601 datetime or a relative value like `-7d`. Defaults to `-7d`. Only applies when ordering by `data_interval_start`.+ */+ start?: string+ /**+ * Only return runs in these statuses. Repeat the parameter to pass more than one status.+ */+ status?: BatchExportsRunsListStatusItem[]}+/**+ * * `Cancelled` - Cancelled+ * * `Completed` - Completed+ * * `ContinuedAsNew` - Continued As New+ * * `Failed` - Failed+ * * `FailedRetryable` - Failed Retryable+ * * `FailedBilling` - Failed Billing+ * * `Terminated` - Terminated+ * * `TimedOut` - Timedout+ * * `Running` - Running+ * * `Starting` - Starting+ */+export type BatchExportsRunsListStatusItem =+ (typeof BatchExportsRunsListStatusItem)[keyof typeof BatchExportsRunsListStatusItem]++export const BatchExportsRunsListStatusItem = {+ Cancelled: 'Cancelled',+ Completed: 'Completed',+ ContinuedAsNew: 'ContinuedAsNew',+ Failed: 'Failed',+ FailedRetryable: 'FailedRetryable',+ FailedBilling: 'FailedBilling',+ Terminated: 'Terminated',+ TimedOut: 'TimedOut',+ Running: 'Running',+ Starting: 'Starting',+} as const+export type BatchExportsRunsLogsRetrieveParams = {/*** Only return entries after this ISO 8601 timestamp. Defaults to 7 days ago; pass an explicit value to read further back.diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 1a091b303e79..eaf539268907 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -88336,16 +88336,64 @@ export namespace Schemas {};export type BatchExportsRunsListParams = {+ /**+ * Only return runs created at or after this point. Accepts an ISO-8601 datetime or a relative value like `-7d`. Defaults to `-7d`. Ignored when ordering by `data_interval_start`.+ */+ after?: string;+ /**+ * Only return runs created at or before this point. Accepts an ISO-8601 datetime or a relative value like `-1d`. Defaults to now. Ignored when ordering by `data_interval_start`.+ */+ before?: string;/*** The pagination cursor value.*/cursor?: string;+ /**+ * Only return runs whose data interval ends at or before this point. Accepts an ISO-8601 datetime or a relative value like `-1d`. Defaults to now. Only applies when ordering by `data_interval_start`.+ */+ end?: string;/*** Which field to use when ordering the results.*/ordering?: string;+ /**+ * Only return runs whose data interval starts at or after this point. Accepts an ISO-8601 datetime or a relative value like `-7d`. Defaults to `-7d`. Only applies when ordering by `data_interval_start`.+ */+ start?: string;+ /**+ * Only return runs in these statuses. Repeat the parameter to pass more than one status.+ */+ status?: BatchExportsRunsListStatusItem[];};+ /**+ * * `Cancelled` - Cancelled+ * * `Completed` - Completed+ * * `ContinuedAsNew` - Continued As New+ * * `Failed` - Failed+ * * `FailedRetryable` - Failed Retryable+ * * `FailedBilling` - Failed Billing+ * * `Terminated` - Terminated+ * * `TimedOut` - Timedout+ * * `Running` - Running+ * * `Starting` - Starting+ */+ export type BatchExportsRunsListStatusItem = typeof BatchExportsRunsListStatusItem[keyof typeof BatchExportsRunsListStatusItem];+++ export const BatchExportsRunsListStatusItem = {+ Cancelled: 'Cancelled',+ Completed: 'Completed',+ ContinuedAsNew: 'ContinuedAsNew',+ Failed: 'Failed',+ FailedRetryable: 'FailedRetryable',+ FailedBilling: 'FailedBilling',+ Terminated: 'Terminated',+ TimedOut: 'TimedOut',+ Running: 'Running',+ Starting: 'Starting',+ } as const;+export type BatchExportsRunsLogsRetrieveParams = {/*** Only return entries after this ISO 8601 timestamp. Defaults to 7 days ago; pass an explicit value to read further back.