: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: New batch export on demand model (#58107)
Tomás Farías Santana0855746cee76
diff --git a/.semgrep/rules/idor-team-scoped-models.yaml b/.semgrep/rules/idor-team-scoped-models.yamlindex d37543e55e18..adb0ee09a1a8 100644--- a/.semgrep/rules/idor-team-scoped-models.yaml+++ b/.semgrep/rules/idor-team-scoped-models.yaml@@ -65,6 +65,7 @@ rules:|BatchExport|BatchExportBackfill|BatchExportFileDownload+ |BatchExportOnDemand|BatchImport|ButtonTile|ChangeRequest@@ -287,6 +288,7 @@ rules:|BatchExport|BatchExportBackfill|BatchExportFileDownload+ |BatchExportOnDemand|BatchImport|ButtonTile|ChangeRequestdiff --git a/posthog/batch_exports/debug/debugger.py b/posthog/batch_exports/debug/debugger.pyindex 33525e804570..072804cebd96 100644--- a/posthog/batch_exports/debug/debugger.py+++ b/posthog/batch_exports/debug/debugger.py@@ -343,7 +343,7 @@ class BatchExportsDebugger:self, batch_export_run: BatchExportRun) -> collections.abc.Generator[pa.RecordBatch, None, None]:folder = get_base_s3_staging_folder(- batch_export_run.batch_export.id,+ batch_export_run.parent.id,batch_export_run.data_interval_start.isoformat() if batch_export_run.data_interval_start else None,batch_export_run.data_interval_end.isoformat(),)@@ -390,14 +390,14 @@ class BatchExportsDebugger:self,batch_export_run: BatchExportRun,) -> collections.abc.Generator[pa.RecordBatch, None, None]:- team_id = batch_export_run.batch_export.team.id+ team_id = batch_export_run.parent.team.idfull_range = (batch_export_run.data_interval_start, batch_export_run.data_interval_end)parameters = {"team_id": team_id, "interval_end": full_range[1].strftime("%Y-%m-%d %H:%M:%S.%f")}if full_range[0]:parameters["interval_start"] = full_range[0].strftime("%Y-%m-%d %H:%M:%S.%f")extra_query_parameters: dict[str, str] = {}- filters = batch_export_run.batch_export.filters+ filters = batch_export_run.parent.filtersif filters is not None and len(filters) > 0:filters_str, extra_query_parameters = compose_filters_clause(@@ -408,25 +408,29 @@ class BatchExportsDebugger:is_backfill = batch_export_run.backfill is not None- if batch_export_run.batch_export.model == BatchExport.Model.PERSONS:+ if batch_export_run.parent.model == BatchExport.Model.PERSONS:if is_backfill and full_range[0] is None:query = SELECT_FROM_PERSONS_BACKFILLelse:query = SELECT_FROM_PERSONSelse:- if batch_export_run.batch_export.destination.config.get("exclude_events", None):- parameters["exclude_events"] = list(batch_export_run.batch_export.destination.config["exclude_events"])+ if batch_export_run.parent.destination.config.get("exclude_events", None):+ parameters["exclude_events"] = list(batch_export_run.parent.destination.config["exclude_events"])else:parameters["exclude_events"] = []- if batch_export_run.batch_export.destination.config.get("include_events", None):- parameters["include_events"] = list(batch_export_run.batch_export.destination.config["include_events"])+ if batch_export_run.parent.destination.config.get("include_events", None):+ parameters["include_events"] = list(batch_export_run.parent.destination.config["include_events"])else:parameters["include_events"] = []# for 5 min batch exports we query the events_recent table, which is known to have zero replication lag, but# may not be able to handle the load from all batch exports- if batch_export_run.batch_export.interval == "every 5 minutes" and not is_backfill:+ if (+ isinstance(batch_export_run.parent, BatchExport)+ and batch_export_run.parent.interval == "every 5 minutes"+ and not is_backfill+ ):query_template = SELECT_FROM_EVENTS_VIEW_RECENT# for other batch exports that should use `events_recent` we use the `distributed_events_recent` table# which is a distributed table that sits in front of the `events_recent` table@@ -445,7 +449,7 @@ class BatchExportsDebugger:)parameters["lookback_days"] = lookback_days- match batch_export_run.batch_export.destination.type:+ match batch_export_run.parent.destination.type:case BatchExportDestination.Destination.S3:fields = s3_default_fields()case BatchExportDestination.Destination.SNOWFLAKE:diff --git a/posthog/batch_exports/models.py b/posthog/batch_exports/models.pyindex 0e15118ad6ae..2baa29716300 100644--- a/posthog/batch_exports/models.py+++ b/posthog/batch_exports/models.py@@ -1,3 +1,4 @@+import typingimport datetime as dtfrom datetime import timedeltafrom enum import IntEnum@@ -5,6 +6,7 @@ from math import ceilfrom zoneinfo import ZoneInfofrom django.db import models+from django.db.models import Qimport pytz@@ -15,6 +17,7 @@ import pytzfrom posthog.clickhouse.client import sync_execute # noqa: F401from posthog.helpers.encrypted_fields import EncryptedJSONFieldfrom posthog.models.activity_logging.model_activity import ModelActivityMixin+from posthog.models.scoping.root_mixin import TeamScopedRootMixinfrom posthog.models.utils import UUIDTModel# this is what is used by the Team model@@ -111,13 +114,23 @@ class BatchExportDestination(UUIDTModel):class BatchExportRun(UUIDTModel):- """A model of a single run of a PostHog BatchExport given a time interval.+ """A single run of a PostHog batch export defined by its data interval bounds.- It is used to keep track of the status and progress of the export- between the specified time interval, as well as communicating any errors- that may have occurred during the process.+ It is used to keep track of the status of the export and once it finishes to+ store any result metadata, and errors that may have occurred during the process."""+ class Meta:+ constraints = [+ models.CheckConstraint(+ check=(+ Q(batch_export__isnull=False, batch_export_on_demand__isnull=True)+ | Q(batch_export__isnull=True, batch_export_on_demand__isnull=False)+ ),+ name="run_has_exactly_one_parent_batch_export_or_batch_export_on_demand",+ )+ ]+class Status(models.TextChoices):"""Possible states of the BatchExportRun."""@@ -135,7 +148,14 @@ class BatchExportRun(UUIDTModel):batch_export = models.ForeignKey("BatchExport",on_delete=models.CASCADE,- help_text="The BatchExport this run belongs to.",+ null=True,+ help_text="The `BatchExport` this run belongs to.",+ )+ batch_export_on_demand = models.ForeignKey(+ "BatchExportOnDemand",+ on_delete=models.CASCADE,+ null=True,+ help_text="The `BatchExportOnDemand` this run belongs to.",)status = models.CharField(choices=Status, max_length=64, help_text="The status of this run.")records_completed = models.IntegerField(null=True, help_text="The number of records that have been exported.")@@ -177,8 +197,33 @@ class BatchExportRun(UUIDTModel):@propertydef workflow_id(self) -> str:- """Return the Workflow id that corresponds to this BatchExportRun model."""- return f"{self.batch_export.id}-{self.data_interval_end:%Y-%m-%dT%H:%M:%S}Z"+ """Return the Workflow id that corresponds to this model."""+ parent = self.parent++ if isinstance(parent, BatchExport):+ return f"{parent.id}-{self.data_interval_end:%Y-%m-%dT%H:%M:%S}Z"++ if isinstance(parent, BatchExportOnDemand):+ return (+ f"{parent.id}-{self.data_interval_start:%Y-%m-%dT%H:%M:%S}Z-{self.data_interval_end:%Y-%m-%dT%H:%M:%S}Z"+ )++ typing.assert_never(parent)++ @property+ def parent(self) -> "BatchExport | BatchExportOnDemand":+ """Get this run's parent batch export.++ It is enforced by a check constraint that either a `BatchExport` or a+ `BatchExportOnDemand` must be defined in this run, but we must communicate that+ to the Python type checker too via this property.+ """+ if self.batch_export is not None:+ return self.batch_export+ if self.batch_export_on_demand is not None:+ return self.batch_export_on_demand++ raise ValueError("One of batch export or batch export on demand must always be defined")BATCH_EXPORT_INTERVALS = [@@ -197,15 +242,21 @@ BATCH_EXPORT_INTERVAL_TO_START_JITTER = {class BatchExport(ModelActivityMixin, UUIDTModel):- """- Defines the configuration of PostHog to export data to a destination,- either on a schedule (via the interval parameter), or manually by a- "backfill". Specific instances of a unit process of exporting data is called- a BatchExportRun.+ """A model for a PostHog batch export that runs on a schedule.++ A batch export exports data from PostHog to the configured destination on a+ schedule given by its `interval`, `interval_offset`, and `timezone`.++ An instance of a batch export for a particular period of the schedule is called a+ "run", and runs are modelled by the `BatchExportRun` model.++ Old periods of time can be re-exported by executing a "backfill", even periods from+ before the batch export was created. Backfills are modelled via the+ `BatchExportBackfill` model."""class Model(models.TextChoices):- """Possible models that this BatchExport can export."""+ """Possible data models that this BatchExport can export."""EVENTS = "events"PERSONS = "persons"@@ -526,3 +577,43 @@ class BatchExportFileDownload(ModelActivityMixin, UUIDTModel):threshold_delta = thresholdreturn threshold_delta > delta+++class BatchExportOnDemand(TeamScopedRootMixin, ModelActivityMixin, UUIDTModel):+ """A model for a PostHog batch export triggered on demand.++ Shares a lot of similarities with a `BatchExport`, with the big difference that+ an on demand batch export does not run on a schedule.+ """++ class Model(models.TextChoices):+ """Possible data models that this BatchExport can export."""++ EVENTS = "events"+ PERSONS = "persons"+ SESSIONS = "sessions"++ team = models.ForeignKey("Team", on_delete=models.CASCADE, help_text="The team this belongs to.")+ destination = models.ForeignKey(+ "BatchExportDestination",+ on_delete=models.CASCADE,+ help_text="The destination to export data to.",+ )+ deleted = models.BooleanField(default=False, help_text="Whether this is deleted or not.")+ created_at = models.DateTimeField(+ auto_now_add=True,+ help_text="The timestamp at which this was created.",+ )+ last_updated_at = models.DateTimeField(+ auto_now=True,+ help_text="The timestamp at which this was last updated.",+ )+ model = models.CharField(+ max_length=64,+ null=True,+ blank=True,+ choices=Model,+ default=Model.EVENTS,+ help_text="Which model this batch export is exporting.",+ )+ filters = models.JSONField(null=True, blank=True)diff --git a/posthog/migrations/1163_alter_batchexportrun_batch_export_and_more.py b/posthog/migrations/1163_alter_batchexportrun_batch_export_and_more.pynew file mode 100644index 000000000000..baf01ef8bf6f--- /dev/null+++ b/posthog/migrations/1163_alter_batchexportrun_batch_export_and_more.py@@ -0,0 +1,119 @@+# Generated by Django 5.2.13 on 2026-05-08 10:03++import django.db.models.deletion+from django.db import migrations, models++import posthog.models.utils+++class Migration(migrations.Migration):+ dependencies = [+ ("posthog", "1162_drop_hourly_from_subscription_frequency_choices"),+ ]++ operations = [+ migrations.AlterField(+ model_name="batchexportrun",+ name="batch_export",+ field=models.ForeignKey(+ help_text="The `BatchExport` this run belongs to.",+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.batchexport",+ ),+ ),+ migrations.CreateModel(+ name="BatchExportOnDemand",+ fields=[+ (+ "id",+ models.UUIDField(+ default=posthog.models.utils.UUIDT,+ editable=False,+ primary_key=True,+ serialize=False,+ ),+ ),+ (+ "deleted",+ models.BooleanField(default=False, help_text="Whether this is deleted or not."),+ ),+ (+ "created_at",+ models.DateTimeField(+ auto_now_add=True,+ help_text="The timestamp at which this was created.",+ ),+ ),+ (+ "last_updated_at",+ models.DateTimeField(+ auto_now=True,+ help_text="The timestamp at which this was last updated.",+ ),+ ),+ (+ "model",+ models.CharField(+ blank=True,+ choices=[+ ("events", "Events"),+ ("persons", "Persons"),+ ("sessions", "Sessions"),+ ],+ default="events",+ help_text="Which model this batch export is exporting.",+ max_length=64,+ null=True,+ ),+ ),+ ("filters", models.JSONField(blank=True, null=True)),+ (+ "destination",+ models.ForeignKey(+ help_text="The destination to export data to.",+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.batchexportdestination",+ ),+ ),+ (+ "team",+ models.ForeignKey(+ help_text="The team this belongs to.",+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.team",+ ),+ ),+ ],+ options={+ "abstract": False,+ },+ ),+ migrations.AddField(+ model_name="batchexportrun",+ name="batch_export_on_demand",+ field=models.ForeignKey(+ help_text="The `BatchExportOnDemand` this run belongs to.",+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ to="posthog.batchexportondemand",+ ),+ ),+ migrations.AddConstraint(+ model_name="batchexportrun",+ constraint=models.CheckConstraint(+ condition=models.Q(+ models.Q(+ ("batch_export__isnull", False),+ ("batch_export_on_demand__isnull", True),+ ),+ models.Q(+ ("batch_export__isnull", True),+ ("batch_export_on_demand__isnull", False),+ ),+ _connector="OR",+ ),+ name="run_has_exactly_one_parent_batch_export_or_batch_export_on_demand",+ ),+ ),+ ]diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txtindex e7107eb61b34..61423a7dba77 100644--- a/posthog/migrations/max_migration.txt+++ b/posthog/migrations/max_migration.txt@@ -1 +1 @@-1162_drop_hourly_from_subscription_frequency_choices+1163_alter_batchexportrun_batch_export_and_morediff --git a/posthog/models/__init__.py b/posthog/models/__init__.pyindex 497aeafa7b80..5ddfec733dde 100644--- a/posthog/models/__init__.py+++ b/posthog/models/__init__.py@@ -1,9 +1,14 @@# Need to skip autoimporting because this file is severely prone to circular imports errors# You should try and make them alphabetically sorted manually if possible# isort: skip_file--from ..batch_exports.models import BatchExport, BatchExportBackfill, BatchExportDestination, BatchExportRun-+from ..batch_exports.models import (+ BatchExport,+ BatchExportBackfill,+ BatchExportFileDownload,+ BatchExportDestination,+ BatchExportRun,+ BatchExportOnDemand,+)from ..session_recordings.models.session_recording import SessionRecordingfrom ..session_recordings.models.session_recording_playlist import SessionRecordingPlaylistfrom ..session_recordings.models.session_recording_playlist_item import SessionRecordingPlaylistItem@@ -123,7 +128,9 @@ __all__ = ["BatchExport","BatchExportBackfill","BatchExportDestination",+ "BatchExportFileDownload","BatchExportRun",+ "BatchExportOnDemand","BatchImport","CIMDVerificationToken","Cohort",diff --git a/posthog/tasks/email.py b/posthog/tasks/email.pyindex 888002dec44d..036021d1f41b 100644--- a/posthog/tasks/email.py+++ b/posthog/tasks/email.py@@ -13,7 +13,7 @@ import posthoganalyticsfrom celery import shared_taskfrom posthoganalytics import new_context, tag-from posthog.batch_exports.models import BatchExportRun+from posthog.batch_exports.models import BatchExport, BatchExportRunfrom posthog.caching.login_device_cache import check_and_cache_login_devicefrom posthog.cloud_utils import is_cloudfrom posthog.constants import AUTH_BACKEND_DISPLAY_NAMES, INVITE_DAYS_VALIDITY@@ -558,10 +558,11 @@ def send_batch_export_run_failure(logger.warning("Email service is not available")return None- batch_export_run: BatchExportRun = BatchExportRun.objects.select_related("batch_export__team").get(- id=batch_export_run_id- )- team: Team = batch_export_run.batch_export.team+ batch_export_run: BatchExportRun = BatchExportRun.objects.select_related(+ "batch_export__team", "batch_export_on_demand__team"+ ).get(id=batch_export_run_id)+ batch_export = batch_export_run.parent+ team: Team = batch_export.teammemberships_to_email = get_members_to_notify_for_pipeline_error(team, failure_rate)if not memberships_to_email:@@ -572,19 +573,22 @@ def send_batch_export_run_failure(# NOTE: We are taking only the date component to cap the number of emails at one per day per batch export.last_updated_at_date = batch_export_run.last_updated_at.strftime("%Y-%m-%d")- campaign_key: str = (- f"batch_export_run_email_batch_export_{batch_export_run.batch_export.id}_last_updated_at_{last_updated_at_date}"- )+ campaign_key: str = f"batch_export_run_email_batch_export_{batch_export.id}_last_updated_at_{last_updated_at_date}"+ subject = (+ f"PostHog: {batch_export.name} batch export run failure"+ if isinstance(batch_export, BatchExport)+ else "PostHog: batch export on demand run failure"+ )message = EmailMessage(campaign_key=campaign_key,- subject=f"PostHog: {batch_export_run.batch_export.name} batch export run failure",+ subject=subject,template_name="batch_export_run_failure",template_context={"time": batch_export_run.last_updated_at.strftime("%I:%M%p %Z on %B %d"),"team": team,- "id": batch_export_run.batch_export.id,- "name": batch_export_run.batch_export.name,+ "id": batch_export.id,+ "name": batch_export.name if isinstance(batch_export, BatchExport) else "",},)logger.info("Prepared notification email for campaign %s", campaign_key)diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.pyindex cf68e8983f81..e137bd991bd1 100644--- a/products/batch_exports/backend/temporal/batch_exports.py+++ b/products/batch_exports/backend/temporal/batch_exports.py@@ -14,7 +14,7 @@ from structlog.contextvars import bind_contextvarsfrom temporalio import activity, exceptions, workflowfrom temporalio.common import RetryPolicy-from posthog.batch_exports.models import BatchExportRun+from posthog.batch_exports.models import BatchExport, BatchExportRunfrom posthog.kafka_client.routing import async_producer_scopefrom posthog.kafka_client.topics import KAFKA_APP_METRICS2from posthog.models.team.team import Team@@ -100,16 +100,16 @@ def _dispatch_batch_export_failure_realtime(batch_export_run_id: str | UUIDT) ->"""try:run = BatchExportRun.objects.select_related("batch_export__team").get(id=batch_export_run_id)- team = run.batch_export.team+ team = run.parent.team# failure_rate=1.0 mirrors the email path (send_batch_export_run_failure default) — a fully# failed run is treated as 100%, so users are filtered only by their data_pipeline_error_threshold.memberships = get_members_to_notify_for_pipeline_error(team, failure_rate=1.0)if not memberships:return- name = (run.batch_export.name or "")[:80]+ name = (run.parent.name if isinstance(run.parent, BatchExport) else "on demand")[:80]title = f"Batch export {name} failed"body = f"Last failure at {run.last_updated_at.strftime('%I:%M%p %Z on %B %d, %Y')}"- source_url = f"/project/{team.project_id}/pipeline/batch-exports/{run.batch_export.id}"+ source_url = f"/project/{team.project_id}/pipeline/batch-exports/{run.parent.id}"for membership in memberships:try:create_notification(@@ -122,7 +122,7 @@ def _dispatch_batch_export_failure_realtime(batch_export_run_id: str | UUIDT) ->target_type=TargetType.USER,target_id=str(membership.user_id),resource_type=NotificationOnlyResourceType.PIPELINE,- resource_id=str(run.batch_export.id),+ resource_id=str(run.parent.id),source_url=source_url,))diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.tsindex 51dbc1ce80e5..744da007b6e8 100644--- a/products/batch_exports/frontend/generated/api.schemas.ts+++ b/products/batch_exports/frontend/generated/api.schemas.ts@@ -334,8 +334,16 @@ export interface BatchExportRunApi {* @nullable*/bytes_exported?: number | null- /** The BatchExport this run belongs to. */- readonly batch_export: string+ /**+ * The `BatchExport` this run belongs to.+ * @nullable+ */+ readonly batch_export: string | null+ /**+ * The `BatchExportOnDemand` this run belongs to.+ * @nullable+ */+ batch_export_on_demand?: string | null/*** The backfill this run belongs to.* @nullablediff --git a/products/batch_exports/frontend/generated/api.zod.ts b/products/batch_exports/frontend/generated/api.zod.tsindex 65630d987513..995a35b94e47 100644--- a/products/batch_exports/frontend/generated/api.zod.ts+++ b/products/batch_exports/frontend/generated/api.zod.ts@@ -347,6 +347,7 @@ export const BatchExportsRunsCancelCreateBody = /* @__PURE__ */ zod.max(batchExportsRunsCancelCreateBodyBytesExportedMax).nullish().describe('The number of bytes that have been exported in this BatchExportRun.'),+ batch_export_on_demand: zod.uuid().nullish().describe('The `BatchExportOnDemand` this run belongs to.'),backfill: zod.uuid().nullish().describe('The backfill this run belongs to.'),}).describe('Serializer for a BatchExportRun model.')@@ -422,6 +423,7 @@ export const BatchExportsRunsRetryCreateBody = /* @__PURE__ */ zod.max(batchExportsRunsRetryCreateBodyBytesExportedMax).nullish().describe('The number of bytes that have been exported in this BatchExportRun.'),+ batch_export_on_demand: zod.uuid().nullish().describe('The `BatchExportOnDemand` this run belongs to.'),backfill: zod.uuid().nullish().describe('The backfill this run belongs to.'),}).describe('Serializer for a BatchExportRun model.')diff --git a/products/data_warehouse/backend/api/data_warehouse.py b/products/data_warehouse/backend/api/data_warehouse.pyindex 44633f0c4f17..309e3cf46c39 100644--- a/products/data_warehouse/backend/api/data_warehouse.py+++ b/products/data_warehouse/backend/api/data_warehouse.py@@ -662,13 +662,13 @@ class DataWarehouseViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):for run in failed_runs:results.append({- "id": str(run.batch_export.id),- "name": run.batch_export.name,+ "id": str(run.parent.id),+ "name": getattr(run.parent, "name", "Batch export on demand"),"type": "destination","status": "failed","error": run.latest_error,"failed_at": run.finished_at.isoformat() if run.finished_at else None,- "url": f"/pipeline/batch-exports/{run.batch_export.id}",+ "url": f"/pipeline/batch-exports/{run.parent.id}",})diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex af6401b4e57e..c1d36bc74006 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -5378,8 +5378,16 @@ export namespace Schemas {* @nullable*/bytes_exported?: number | null;- /** The BatchExport this run belongs to. */- readonly batch_export: string;+ /**+ * The `BatchExport` this run belongs to.+ * @nullable+ */+ readonly batch_export: string | null;+ /**+ * The `BatchExportOnDemand` this run belongs to.+ * @nullable+ */+ batch_export_on_demand?: string | null;/*** The backfill this run belongs to.* @nullable