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(batch-exports): move the model enums into facade/enums.py (#108432)

Ross571d7eaea5e8
diff --git a/posthog/api/test/test_integration.py b/posthog/api/test/test_integration.py
index 7abdf9c1d7fa..8c65377241d8 100644
--- a/posthog/api/test/test_integration.py
+++ b/posthog/api/test/test_integration.py
@@ -80,7 +80,7 @@ from posthog.slack.channels import is_shared_channel
from products.access_control.backend.models.access_control import AccessControl
from products.batch_exports.backend.facade import testing as batch_exports_testing
-from products.batch_exports.backend.facade.contracts import DestinationType
+from products.batch_exports.backend.facade.enums import BatchExportDestinationType
from products.cdp.backend.models import HogFunction
from products.cdp.backend.models.hog_function_template import HogFunctionTemplate
from products.tasks.backend.facade.contracts import InProgressGithubRunsDTO
@@ -6880,7 +6880,7 @@ class TestIntegrationDeletionHogFunctionGuard:
batch_exports_testing.create_batch_export(
self.team.id,
name="Test batch export",
- destination_type=DestinationType.AWS_S3,
+ destination_type=BatchExportDestinationType.AWS_S3,
destination_config={},
integration_id=self.integration.id,
)
diff --git a/posthog/hogql/database/schema/test/test_system_tables.py b/posthog/hogql/database/schema/test/test_system_tables.py
index 46de9b159f71..8ce011fd16b3 100644
--- a/posthog/hogql/database/schema/test/test_system_tables.py
+++ b/posthog/hogql/database/schema/test/test_system_tables.py
@@ -46,10 +46,10 @@ from products.alerts.backend.models.alert import AlertConfiguration
from products.annotations.backend.models.annotation import Annotation
from products.autoresearch.backend.facade import testing as autoresearch_testing
from products.batch_exports.backend.facade import testing as batch_exports_testing
-from products.batch_exports.backend.facade.contracts import (
+from products.batch_exports.backend.facade.enums import (
BatchExportBackfillStatus,
+ BatchExportDestinationType,
BatchExportRunStatus,
- DestinationType,
)
from products.business_knowledge.backend.models import KnowledgeChunk, KnowledgeDocument, KnowledgeSource
from products.business_knowledge.backend.models.constants import SourceStatus, SourceType
@@ -215,7 +215,7 @@ class TestSystemTablesTeamScoping(BaseTest):
def _create_batch_export(team: Team, label: str) -> uuid.UUID:
return batch_exports_testing.create_batch_export(
- team.pk, name=f"export_{label}", destination_type=DestinationType.AWS_S3, destination_config={}
+ team.pk, name=f"export_{label}", destination_type=BatchExportDestinationType.AWS_S3, destination_config={}
)
@@ -231,7 +231,10 @@ def _create_data_deletion_request(team: Team, label: str) -> DataDeletionRequest
def _create_batch_export_backfill(team: Team, label: str) -> uuid.UUID:
batch_export_id = batch_exports_testing.create_batch_export(
- team.pk, name=f"export_for_backfill_{label}", destination_type=DestinationType.AWS_S3, destination_config={}
+ team.pk,
+ name=f"export_for_backfill_{label}",
+ destination_type=BatchExportDestinationType.AWS_S3,
+ destination_config={},
)
return batch_exports_testing.create_backfill(
batch_export_id, team_id=team.pk, status=BatchExportBackfillStatus.RUNNING
@@ -240,7 +243,10 @@ def _create_batch_export_backfill(team: Team, label: str) -> uuid.UUID:
def _create_batch_export_run(team: Team, label: str) -> uuid.UUID:
batch_export_id = batch_exports_testing.create_batch_export(
- team.pk, name=f"export_for_run_{label}", destination_type=DestinationType.AWS_S3, destination_config={}
+ team.pk,
+ name=f"export_for_run_{label}",
+ destination_type=BatchExportDestinationType.AWS_S3,
+ destination_config={},
)
return batch_exports_testing.create_batch_export_run(
batch_export_id=batch_export_id, status=BatchExportRunStatus.RUNNING, data_interval_end=timezone.now()
@@ -249,7 +255,7 @@ def _create_batch_export_run(team: Team, label: str) -> uuid.UUID:
def _create_batch_export_on_demand(team: Team, label: str) -> uuid.UUID:
return batch_exports_testing.create_batch_export_on_demand(
- team.pk, destination_type=DestinationType.AWS_S3, destination_config={}
+ team.pk, destination_type=BatchExportDestinationType.AWS_S3, destination_config={}
)
diff --git a/posthog/management/commands/migrate_team.py b/posthog/management/commands/migrate_team.py
index 545e63e60109..6596128a02b7 100644
--- a/posthog/management/commands/migrate_team.py
+++ b/posthog/management/commands/migrate_team.py
@@ -7,11 +7,8 @@ from django.core.management.base import BaseCommand, CommandError
from posthog.models import Team
from products.batch_exports.backend.facade import api as batch_exports_api
-from products.batch_exports.backend.facade.contracts import (
- BatchExportBackfillSummary,
- BatchExportDetail,
- DestinationType,
-)
+from products.batch_exports.backend.facade.contracts import BatchExportBackfillSummary, BatchExportDetail
+from products.batch_exports.backend.facade.enums import BatchExportDestinationType
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
@@ -98,7 +95,9 @@ class Command(BaseCommand):
)
try:
- existing_export = batch_exports_api.get_batch_export_by_name(team.id, EXPORT_NAME, DestinationType.HTTP)
+ existing_export = batch_exports_api.get_batch_export_by_name(
+ team.id, EXPORT_NAME, BatchExportDestinationType.HTTP
+ )
except batch_exports_api.MultipleBatchExportsError:
raise CommandError(
"More than one existing migration found! This should never happen if the management command is used, we don't know enough to proceed"
@@ -277,7 +276,7 @@ def create_migration(
batch_export = batch_exports_api.create_batch_export(
team_id,
name=EXPORT_NAME,
- destination_type=DestinationType.HTTP,
+ destination_type=BatchExportDestinationType.HTTP,
destination_config={
"url": url,
"token": dest_token,
diff --git a/posthog/management/commands/test/test_migrate_team.py b/posthog/management/commands/test/test_migrate_team.py
index 744f86b4ecdf..cbd0c8d49cec 100644
--- a/posthog/management/commands/test/test_migrate_team.py
+++ b/posthog/management/commands/test/test_migrate_team.py
@@ -5,7 +5,8 @@ import pytest
from posthog.management.commands.migrate_team import DATA_START_UNBOUNDED, get_migrated_data_start
-from products.batch_exports.backend.facade.contracts import BatchExportBackfillStatus, BatchExportBackfillSummary
+from products.batch_exports.backend.facade.contracts import BatchExportBackfillSummary
+from products.batch_exports.backend.facade.enums import BatchExportBackfillStatus
JAN_1 = dt.datetime(2026, 1, 1, tzinfo=dt.UTC)
JAN_2 = JAN_1 + dt.timedelta(days=1)
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 9833e052b849..d64031ee2ea8 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -598,8 +598,6 @@ SPECTACULAR_SETTINGS = {
"MetricsRecalculationStatusEnum": "products.experiments.backend.models.experiment.ExperimentMetricsRecalculation.Status",
# Matches tasks' LoopVisibility (personal/team).
"MCPAgentGrantScopeEnum": "products.mcp_store.backend.models.AGENT_GRANT_SCOPE_CHOICES",
- # BatchExport.Model and BatchExportOnDemand.Model are identical.
- "ModelEnum": "products.batch_exports.backend.models.batch_export.BatchExport.Model",
# Matches Subscription frequency (daily/weekly/monthly).
"RecurrenceIntervalEnum": "products.reminders.backend.models.reminder.Reminder.RecurrenceInterval",
# Matches the messaging email channel setup provider list.
diff --git a/posthog/tasks/test/test_email.py b/posthog/tasks/test/test_email.py
index 5ed0ea576340..db1022bca71b 100644
--- a/posthog/tasks/test/test_email.py
+++ b/posthog/tasks/test/test_email.py
@@ -60,7 +60,7 @@ from posthog.test.api_keys import create_project_secret_api_key
from products.access_control.backend.models.access_control import AccessControl
from products.batch_exports.backend.facade import testing as batch_exports_testing
-from products.batch_exports.backend.facade.contracts import BatchExportRunStatus, DestinationType
+from products.batch_exports.backend.facade.enums import BatchExportDestinationType, BatchExportRunStatus
from products.cdp.backend.models.hog_functions.hog_function import HogFunction
from products.cdp.backend.models.plugin import Plugin, PluginConfig
from products.data_modeling.backend.facade.api import mark_node_suspended, sync_saved_query_to_dag
@@ -71,7 +71,7 @@ def _create_failed_batch_export_run(team_id: int) -> tuple[uuid.UUID, uuid.UUID]
batch_export_id = batch_exports_testing.create_batch_export(
team_id,
name="A batch export",
- destination_type=DestinationType.AWS_S3,
+ destination_type=BatchExportDestinationType.AWS_S3,
destination_config={"bucket_name": "my_production_s3_bucket"},
)
now = dt.datetime.now()
@@ -640,7 +640,7 @@ class TestEmail(APIBaseTest, ClickhouseTestMixin):
mocked_email_messages = mock_email_messages(MockEmailMessage)
on_demand_id = batch_exports_testing.create_batch_export_on_demand(
self.team.pk,
- destination_type=DestinationType.AWS_S3,
+ destination_type=BatchExportDestinationType.AWS_S3,
destination_config={"bucket_name": "my_production_s3_bucket"},
)
now = dt.datetime.now()
diff --git a/posthog/tasks/test/test_usage_report.py b/posthog/tasks/test/test_usage_report.py
index d4fe2fa4dc63..6a92bd62be5c 100644
--- a/posthog/tasks/test/test_usage_report.py
+++ b/posthog/tasks/test/test_usage_report.py
@@ -81,7 +81,11 @@ from posthog.test.test_utils import create_group_type_mapping_without_created_at
from posthog.utils import get_previous_day
from products.batch_exports.backend.facade import testing as batch_exports_testing
-from products.batch_exports.backend.facade.contracts import BatchExportModel, BatchExportRunStatus, DestinationType
+from products.batch_exports.backend.facade.enums import (
+ BatchExportDestinationType,
+ BatchExportModel,
+ BatchExportRunStatus,
+)
from products.cdp.backend.models.plugin import Plugin, PluginConfig
from products.dashboards.backend.models.dashboard import Dashboard
from products.data_modeling.backend.facade.models import DataWarehouseSavedQuery
@@ -2821,7 +2825,7 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl
batch_exports_testing.create_batch_export(
team_id,
name="A batch export",
- destination_type=DestinationType.AWS_S3,
+ destination_type=BatchExportDestinationType.AWS_S3,
destination_config={"bucket_name": "my_production_s3_bucket"},
)
@@ -2854,13 +2858,13 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl
batch_export_id = batch_exports_testing.create_batch_export(
3,
name="Test export",
- destination_type=DestinationType.AWS_S3,
+ destination_type=BatchExportDestinationType.AWS_S3,
destination_config={"bucket_name": "test_bucket"},
model=BatchExportModel.EVENTS,
)
on_demand_id = batch_exports_testing.create_batch_export_on_demand(
3,
- destination_type=DestinationType.FILE_DOWNLOAD,
+ destination_type=BatchExportDestinationType.FILE_DOWNLOAD,
destination_config={"format": "Parquet"},
model=BatchExportModel.EVENTS,
)
@@ -2881,13 +2885,13 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl
hogql_batch_export_id = batch_exports_testing.create_batch_export(
3,
name="Test HogQL export",
- destination_type=DestinationType.AWS_S3,
+ destination_type=BatchExportDestinationType.AWS_S3,
destination_config={"bucket_name": "test_bucket"},
model=BatchExportModel.HOGQL,
)
hogql_on_demand_id = batch_exports_testing.create_batch_export_on_demand(
3,
- destination_type=DestinationType.FILE_DOWNLOAD,
+ destination_type=BatchExportDestinationType.FILE_DOWNLOAD,
destination_config={"format": "Parquet"},
model=BatchExportModel.HOGQL,
)
@@ -2926,12 +2930,15 @@ class TestExternalDataSyncUsageReport(ClickhouseDestroyTablesMixin, TestCase, Cl
batch_export_id = batch_exports_testing.create_batch_export(
3,
name="Test export",
- destination_type=DestinationType.WORKFLOWS,
+ destination_type=BatchExportDestinationType.WORKFLOWS,
destination_config={},
model=BatchExportModel.EVENTS,
)
on_demand_id = batch_exports_testing.create_batch_export_on_demand(
- 3, destination_type=DestinationType.WORKFLOWS, destination_config={}, model=BatchExportModel.EVENTS
+ 3,
+ destination_type=BatchExportDestinationType.WORKFLOWS,
+ destination_config={},
+ model=BatchExportModel.EVENTS,
)
for parent_id, parent_on_demand_id in ((batch_export_id, None), (None, on_demand_id)):
diff --git a/posthog/test/activity_log_utils.py b/posthog/test/activity_log_utils.py
index 9d776733a15a..ad86b9567b58 100644
--- a/posthog/test/activity_log_utils.py
+++ b/posthog/test/activity_log_utils.py
@@ -494,12 +494,12 @@ class ActivityLogTestHelper(APILicensedTest):
def create_batch_export(self, name: str = "Test Export", **kwargs) -> dict[str, Any]:
"""Create a batch export directly, without the API."""
from products.batch_exports.backend.facade import testing as batch_exports_testing
- from products.batch_exports.backend.facade.contracts import DestinationType
+ from products.batch_exports.backend.facade.enums import BatchExportDestinationType
batch_export_id = batch_exports_testing.create_batch_export(
self.team.id,
name=name,
- destination_type=DestinationType.HTTP,
+ destination_type=BatchExportDestinationType.HTTP,
destination_config={"url": "https://example.com"},
**kwargs,
)
diff --git a/products/batch_exports/backend/facade/contracts.py b/products/batch_exports/backend/facade/contracts.py
index e7650544d4ed..3acb2e519531 100644
--- a/products/batch_exports/backend/facade/contracts.py
+++ b/products/batch_exports/backend/facade/contracts.py
@@ -3,9 +3,8 @@ Contract types for batch_exports.
Stable, framework-free dataclasses defining what this product hands to the rest of the
codebase. No Django or DRF imports, and enums are flattened to their ``str`` value, so a
-consumer never needs a model class to read a batch export. The ``StrEnum`` classes name
-those values for a consumer that writes them. They copy the model's ``TextChoices``, and
-``tests/test_facade.py`` fails when the two copies differ.
+consumer never needs a model class to read a batch export. A consumer that writes one of
+those values imports the enum from ``facade/enums.py``.
The fields are the ones consumers read today and nothing more. An encrypted model field
never crosses whole, because reading one decrypts it; ``BatchExportDetail`` documents the
@@ -22,7 +21,6 @@ from dataclasses import (
dataclass as stdlib_dataclass,
field,
)
-from enum import StrEnum
from uuid import UUID
from pydantic.dataclasses import dataclass
@@ -31,55 +29,6 @@ from pydantic.dataclasses import dataclass
BATCH_EXPORT_MODEL_LABEL = "batch_exports.BatchExport"
-class DestinationType(StrEnum):
- AWS_S3 = "AwsS3"
- S3_COMPATIBLE = "S3Compatible"
- SNOWFLAKE = "Snowflake"
- POSTGRES = "Postgres"
- REDSHIFT = "Redshift"
- BIGQUERY = "BigQuery"
- DATABRICKS = "Databricks"
- AZURE_BLOB = "AzureBlob"
- WORKFLOWS = "Workflows"
- HTTP = "HTTP"
- NOOP = "NoOp"
- FILE_DOWNLOAD = "FileDownload"
-
-
-class BatchExportModel(StrEnum):
- """The data model an export reads, for scheduled and on-demand exports alike."""
-
- EVENTS = "events"
- PERSONS = "persons"
- SESSIONS = "sessions"
- HOGQL = "hogql"
-
-
-class BatchExportRunStatus(StrEnum):
- CANCELLED = "Cancelled"
- COMPLETED = "Completed"
- CONTINUED_AS_NEW = "ContinuedAsNew"
- FAILED = "Failed"
- FAILED_RETRYABLE = "FailedRetryable"
- FAILED_BILLING = "FailedBilling"
- TERMINATED = "Terminated"
- TIMEDOUT = "TimedOut"
- RUNNING = "Running"
- STARTING = "Starting"
-
-
-class BatchExportBackfillStatus(StrEnum):
- CANCELLED = "Cancelled"
- COMPLETED = "Completed"
- CONTINUED_AS_NEW = "ContinuedAsNew"
- FAILED = "Failed"
- FAILED_RETRYABLE = "FailedRetryable"
- TERMINATED = "Terminated"
- TIMEDOUT = "TimedOut"
- RUNNING = "Running"
- STARTING = "Starting"
-
-
@dataclass(frozen=True)
class BatchExportRef:
"""The bare identity of a batch export, for listing it by name."""
diff --git a/products/batch_exports/backend/facade/enums.py b/products/batch_exports/backend/facade/enums.py
new file mode 100644
index 000000000000..01c6d22a1ef7
--- /dev/null
+++ b/products/batch_exports/backend/facade/enums.py
@@ -0,0 +1,72 @@
+"""Enumerations the batch_exports models use.
+
+A consumer that writes one of these values reads the enum from here and does not need the
+model class. The models keep each enum as a class attribute (``BatchExportRun.Status``) so
+existing call sites are unchanged. In an annotation the class attribute is not a valid type, so
+annotate with the enum from this module directly.
+"""
+
+from posthog.enums import LabeledStrEnum
+
+
+class BatchExportDestinationType(LabeledStrEnum):
+ """Enumeration of supported destinations for PostHog BatchExports."""
+
+ AWS_S3 = "AwsS3"
+ S3_COMPATIBLE = "S3Compatible"
+ SNOWFLAKE = "Snowflake"
+ POSTGRES = "Postgres"
+ REDSHIFT = "Redshift"
+ BIGQUERY = "BigQuery"
+ DATABRICKS = "Databricks"
+ AZURE_BLOB = "AzureBlob"
+ WORKFLOWS = "Workflows"
+ HTTP = "HTTP"
+ NOOP = "NoOp"
+ FILE_DOWNLOAD = "FileDownload"
+
+
+class BatchExportModel(LabeledStrEnum):
+ """The data model an export reads, for scheduled and on-demand exports alike."""
+
+ EVENTS = "events"
+ PERSONS = "persons"
+ SESSIONS = "sessions"
+ HOGQL = "hogql"
+
+
+class BatchExportRunStatus(LabeledStrEnum):
+ """Possible states of the BatchExportRun."""
+
+ CANCELLED = "Cancelled"
+ COMPLETED = "Completed"
+ CONTINUED_AS_NEW = "ContinuedAsNew"
+ FAILED = "Failed"
+ FAILED_RETRYABLE = "FailedRetryable"
+ FAILED_BILLING = "FailedBilling"
+ TERMINATED = "Terminated"
+ TIMEDOUT = "TimedOut"
+ RUNNING = "Running"
+ STARTING = "Starting"
+
+
+class BatchExportBackfillStatus(LabeledStrEnum):
+ """Possible states of the BatchExportBackfill."""
+
+ CANCELLED = "Cancelled"
+ COMPLETED = "Completed"
+ CONTINUED_AS_NEW = "ContinuedAsNew"
+ FAILED = "Failed"
+ FAILED_RETRYABLE = "FailedRetryable"
+ TERMINATED = "Terminated"
+ TIMEDOUT = "TimedOut"
+ RUNNING = "Running"
+ STARTING = "Starting"
+
+
+class BatchExportInterval(LabeledStrEnum):
+ HOUR = "hour", "hour"
+ DAY = "day", "day"
+ WEEK = "week", "week"
+ EVERY_5_MINUTES = "every 5 minutes", "every 5 minutes"
+ EVERY_15_MINUTES = "every 15 minutes", "every 15 minutes"
diff --git a/products/batch_exports/backend/models/batch_export.py b/products/batch_exports/backend/models/batch_export.py
index 0de5f2d87130..539bcffb9a39 100644
--- a/products/batch_exports/backend/models/batch_export.py
+++ b/products/batch_exports/backend/models/batch_export.py
@@ -20,6 +20,8 @@ from posthog.models.activity_logging.model_activity import ModelActivityMixin
from posthog.models.scoping.root_mixin import TeamScopedRootMixin
from posthog.models.utils import UUIDTModel
+from products.batch_exports.backend.facade import enums
+
# this is what is used by the Team model
# (we could use common_timezones instead; this has 433 timezones vs 596 for all_timezones)
TIMEZONES = [(tz, tz) for tz in pytz.all_timezones]
@@ -70,21 +72,7 @@ class BatchExportDestination(UUIDTModel):
class Meta:
db_table = "posthog_batchexportdestination"
- class Destination(models.TextChoices):
- """Enumeration of supported destinations for PostHog BatchExports."""
-
- AWS_S3 = "AwsS3"
- S3_COMPATIBLE = "S3Compatible"
- SNOWFLAKE = "Snowflake"
- POSTGRES = "Postgres"
- REDSHIFT = "Redshift"
- BIGQUERY = "BigQuery"
- DATABRICKS = "Databricks"
- AZURE_BLOB = "AzureBlob"
- WORKFLOWS = "Workflows"
- HTTP = "HTTP"
- NOOP = "NoOp"
- FILE_DOWNLOAD = "FileDownload"
+ Destination = enums.BatchExportDestinationType
# S3-family exports read their credentials from an Integration, but rows migrated off inline
# credentials still hold them in `config`. These entries keep those stale values out of API
@@ -105,7 +93,7 @@ class BatchExportDestination(UUIDTModel):
}
type = models.CharField(
- choices=Destination,
+ choices=Destination.choices,
max_length=64,
help_text="A choice of supported BatchExportDestination types.",
)
@@ -195,19 +183,7 @@ class BatchExportRun(UUIDTModel):
)
]
- class Status(models.TextChoices):
- """Possible states of the BatchExportRun."""
-
- CANCELLED = "Cancelled"
- COMPLETED = "Completed"
- CONTINUED_AS_NEW = "ContinuedAsNew"
- FAILED = "Failed"
- FAILED_RETRYABLE = "FailedRetryable"
- FAILED_BILLING = "FailedBilling"
- TERMINATED = "Terminated"
- TIMEDOUT = "TimedOut"
- RUNNING = "Running"
- STARTING = "Starting"
+ Status = enums.BatchExportRunStatus
batch_export = models.ForeignKey(
"BatchExport",
@@ -221,7 +197,7 @@ class BatchExportRun(UUIDTModel):
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.")
+ status = models.CharField(choices=Status.choices, 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.")
records_failed = models.IntegerField(
null=True,
@@ -294,15 +270,7 @@ class BatchExportRun(UUIDTModel):
raise ValueError("One of batch export or batch export on demand must always be defined")
-class BatchExportInterval(models.TextChoices):
- HOUR = "hour", "hour"
- DAY = "day", "day"
- WEEK = "week", "week"
- EVERY_5_MINUTES = "every 5 minutes", "every 5 minutes"
- EVERY_15_MINUTES = "every 15 minutes", "every 15 minutes"
-
-
-BATCH_EXPORT_INTERVALS = BatchExportInterval.choices
+BATCH_EXPORT_INTERVALS = enums.BatchExportInterval.choices
BATCH_EXPORT_INTERVAL_TO_START_JITTER = {
"hour": timedelta(minutes=15),
@@ -328,13 +296,7 @@ class BatchExport(ModelActivityMixin, UUIDTModel):
class Meta:
db_table = "posthog_batchexport"
- class Model(models.TextChoices):
- """Possible data models that this BatchExport can export."""
-
- EVENTS = "events"
- PERSONS = "persons"
- SESSIONS = "sessions"
- HOGQL = "hogql"
+ Model = enums.BatchExportModel
team = models.ForeignKey(
"posthog.Team", on_delete=models.CASCADE, help_text="The team this belongs to.", related_name="+"
@@ -405,8 +367,8 @@ class BatchExport(ModelActivityMixin, UUIDTModel):
max_length=64,
null=True,
blank=True,
- choices=Model,
- default=Model.EVENTS,
+ choices=Model.choices,
+ default=Model.EVENTS.value,
help_text="Which model this BatchExport is exporting.",
)
filters = models.JSONField(null=True, blank=True)
@@ -548,18 +510,7 @@ class BatchExportBackfill(UUIDTModel):
class Meta:
db_table = "posthog_batchexportbackfill"
- class Status(models.TextChoices):
- """Possible states of the BatchExportBackfill."""
-
- CANCELLED = "Cancelled"
- COMPLETED = "Completed"
- CONTINUED_AS_NEW = "ContinuedAsNew"
- FAILED = "Failed"
- FAILED_RETRYABLE = "FailedRetryable"
- TERMINATED = "Terminated"
- TIMEDOUT = "TimedOut"
- RUNNING = "Running"
- STARTING = "Starting"
+ Status = enums.BatchExportBackfillStatus
team = models.ForeignKey("posthog.Team", on_delete=models.CASCADE, help_text="The team this belongs to.")
batch_export = models.ForeignKey(
@@ -569,7 +520,7 @@ class BatchExportBackfill(UUIDTModel):
)
start_at = models.DateTimeField(help_text="The start of the data interval.", null=True)
end_at = models.DateTimeField(help_text="The end of the data interval.", null=True)
- status = models.CharField(choices=Status, max_length=64, help_text="The status of this backfill.")
+ status = models.CharField(choices=Status.choices, max_length=64, help_text="The status of this backfill.")
created_at = models.DateTimeField(
auto_now_add=True,
help_text="The timestamp at which this BatchExportBackfill was created.",
@@ -716,13 +667,7 @@ class BatchExportOnDemand(TeamScopedRootMixin, ModelActivityMixin, UUIDTModel):
class Meta:
db_table = "posthog_batchexportondemand"
- class Model(models.TextChoices):
- """Possible data models that this BatchExport can export."""
-
- EVENTS = "events"
- PERSONS = "persons"
- SESSIONS = "sessions"
- HOGQL = "hogql"
+ Model = enums.BatchExportModel
team = models.ForeignKey(
"posthog.Team", on_delete=models.CASCADE, help_text="The team this belongs to.", related_name="+"
@@ -762,8 +707,8 @@ class BatchExportOnDemand(TeamScopedRootMixin, ModelActivityMixin, UUIDTModel):
max_length=64,
null=True,
blank=True,
- choices=Model,
- default=Model.EVENTS,
+ choices=Model.choices,
+ default=Model.EVENTS.value,
help_text="Which model this batch export is exporting.",
)
filters = models.JSONField(null=True, blank=True)
diff --git a/products/batch_exports/backend/temporal/batch_exports.py b/products/batch_exports/backend/temporal/batch_exports.py
index 2ddbba08c7e2..84b385339464 100644
--- a/products/batch_exports/backend/temporal/batch_exports.py
+++ b/products/batch_exports/backend/temporal/batch_exports.py
@@ -28,6 +28,7 @@ from posthog.temporal.common.logger import get_logger, get_write_only_logger
from posthog.usage_ingestion.client import UsageRecord, areport_usage
from products.batch_exports.backend.billing import is_billable_run
+from products.batch_exports.backend.facade.enums import BatchExportRunStatus
from products.batch_exports.backend.models.batch_export import BatchExport, BatchExportRun
from products.batch_exports.backend.service import (
BackfillDetails,
@@ -809,7 +810,7 @@ async def try_cancel_running_backfills(batch_export_id: str) -> int | None:
def make_internal_events_payload(
- status: BatchExportRun.Status | str,
+ status: BatchExportRunStatus | str,
team_id: int,
batch_export_id: str,
batch_export_run_id: str,
@@ -887,7 +888,7 @@ def make_internal_events_payload(
def make_app_metrics_payloads(
- status: BatchExportRun.Status | str,
+ status: BatchExportRunStatus | str,
team_id: int,
batch_export_id: str,
batch_export_run_id: str,
diff --git a/products/batch_exports/backend/temporal/pipeline/entrypoint.py b/products/batch_exports/backend/temporal/pipeline/entrypoint.py
index 8e0d9aa7544a..e4a89f4546e0 100644
--- a/products/batch_exports/backend/temporal/pipeline/entrypoint.py
+++ b/products/batch_exports/backend/temporal/pipeline/entrypoint.py
@@ -11,6 +11,7 @@ from posthog.dataclasses import frozen
from posthog.settings.base_variables import TEST
from posthog.temporal.common.logger import get_write_only_logger
+from products.batch_exports.backend.facade.enums import BatchExportRunStatus
from products.batch_exports.backend.models.batch_export import BatchExportRun
from products.batch_exports.backend.service import (
BackfillDetails,
@@ -160,7 +161,7 @@ def _get_config_for_interval(
raise ValueError(f"Unsupported interval: '{interval}'")
-def _get_status_for_activity_error(error: exceptions.ActivityError) -> BatchExportRun.Status:
+def _get_status_for_activity_error(error: exceptions.ActivityError) -> BatchExportRunStatus:
"""Decide what a failed run's status should be, given the error raised.
The error could be raised by either the `insert_into_internal_stage_activity` or the
diff --git a/products/batch_exports/backend/tests/temporal/test_internal_events.py b/products/batch_exports/backend/tests/temporal/test_internal_events.py
index f508fc15b421..615e7d0a2a17 100644
--- a/products/batch_exports/backend/tests/temporal/test_internal_events.py
+++ b/products/batch_exports/backend/tests/temporal/test_internal_events.py
@@ -3,6 +3,7 @@ import datetime as dt
import pytest
import unittest.mock
+from products.batch_exports.backend.facade.enums import BatchExportRunStatus
from products.batch_exports.backend.models.batch_export import BatchExportRun
from products.batch_exports.backend.temporal.batch_exports import (
make_internal_events_payload,
@@ -29,7 +30,7 @@ BASE_PROPERTIES = {
}
-def make_payloads(status: BatchExportRun.Status, error: str | None = "Oh No!", was_paused: bool = False):
+def make_payloads(status: BatchExportRunStatus, error: str | None = "Oh No!", was_paused: bool = False):
return make_internal_events_payload(
status,
TEAM_ID,
diff --git a/products/batch_exports/backend/tests/test_facade.py b/products/batch_exports/backend/tests/test_facade.py
index 4c3ef6d2683a..afc0abff0b71 100644
--- a/products/batch_exports/backend/tests/test_facade.py
+++ b/products/batch_exports/backend/tests/test_facade.py
@@ -16,7 +16,6 @@ from products.batch_exports.backend.models.batch_export import (
BatchExport,
BatchExportBackfill,
BatchExportDestination,
- BatchExportOnDemand,
BatchExportRun,
)
from products.batch_exports.backend.service import BatchExportServiceScheduleNotFound
@@ -71,21 +70,6 @@ def _create_run(*, finished_at, records=0, status=BatchExportRun.Status.COMPLETE
return run_id
- "contract_enum,model_choices",
- [
- (contracts.DestinationType, BatchExportDestination.Destination),
- (contracts.BatchExportModel, BatchExport.Model),
- (contracts.BatchExportModel, BatchExportOnDemand.Model),
- (contracts.BatchExportRunStatus, BatchExportRun.Status),
- (contracts.BatchExportBackfillStatus, BatchExportBackfill.Status),
- ],
- ids=["destination type", "model", "on-demand model", "run status", "backfill status"],
-)
-def test_contract_enums_match_the_model_choices(contract_enum, model_choices):
- assert {member.value for member in contract_enum} == set(model_choices.values)
-
-
def test_billable_rows_exported_sums_scheduled_and_on_demand_runs_per_team(team, organization):
scheduled = _create_export(team, name="scheduled")
on_demand = testing.create_batch_export_on_demand(team.pk, destination_type=FILE_DOWNLOAD, destination_config={})
diff --git a/products/batch_exports/frontend/generated/api.schemas.ts b/products/batch_exports/frontend/generated/api.schemas.ts
index e0c5bfb16d01..9be55908e032 100644
--- a/products/batch_exports/frontend/generated/api.schemas.ts
+++ b/products/batch_exports/frontend/generated/api.schemas.ts
@@ -13,9 +13,9 @@
* * `sessions` - Sessions
* * `hogql` - Hogql
*/
-export type ModelEnumApi = (typeof ModelEnumApi)[keyof typeof ModelEnumApi]
+export type BatchExportModelEnumApi = (typeof BatchExportModelEnumApi)[keyof typeof BatchExportModelEnumApi]
-export const ModelEnumApi = {
+export const BatchExportModelEnumApi = {
Events: 'events',
Persons: 'persons',
Sessions: 'sessions',
@@ -42,10 +42,10 @@ export const BlankEnumApi = {
* * `NoOp` - Noop
* * `FileDownload` - File Download
*/
-export type BatchExportDestinationDestinationEnumApi =
- (typeof BatchExportDestinationDestinationEnumApi)[keyof typeof BatchExportDestinationDestinationEnumApi]
+export type BatchExportDestinationTypeEnumApi =
+ (typeof BatchExportDestinationTypeEnumApi)[keyof typeof BatchExportDestinationTypeEnumApi]
-export const BatchExportDestinationDestinationEnumApi = {
+export const BatchExportDestinationTypeEnumApi = {
AwsS3: 'AwsS3',
S3Compatible: 'S3Compatible',
Snowflake: 'Snowflake',
@@ -471,7 +471,7 @@ export interface BatchExportDestinationApi {
* * `HTTP` - Http
* * `NoOp` - Noop
* * `FileDownload` - File Download */
- type: BatchExportDestinationDestinationEnumApi
+ type: BatchExportDestinationTypeEnumApi
/** Destination-specific configuration. Fields depend on `type`. Credentials for integration-backed destinations (Databricks, AzureBlob, BigQuery, Postgres, AwsS3, S3Compatible, Snowflake, Redshift) are NOT stored here — they live in the linked Integration. Secret fields are stripped from responses. */
config: BatchExportDestinationConfigApi
/**
@@ -886,7 +886,7 @@ export interface BatchExportApi {
* * `persons` - Persons
* * `sessions` - Sessions
* * `hogql` - Hogql */
- model?: ModelEnumApi | BlankEnumApi | null
+ model?: BatchExportModelEnumApi | BlankEnumApi | null
/** Destination configuration (type, config, and optional integration). */
destination: BatchExportDestinationApi
/** How often the batch export should run.
@@ -1716,7 +1716,7 @@ export interface BatchExportRequestApi {
* * `persons` - Persons
* * `sessions` - Sessions
* * `hogql` - Hogql */
- model?: ModelEnumApi
+ model?: BatchExportModelEnumApi
/** Destination configuration. Required integration_id is enforced per destination type. */
destination: BatchExportDestinationRequestApi
/** How often the batch export should run.
@@ -1882,7 +1882,7 @@ export interface PatchedBatchExportRequestApi {
* * `persons` - Persons
* * `sessions` - Sessions
* * `hogql` - Hogql */
- model?: ModelEnumApi
+ model?: BatchExportModelEnumApi
/** Destination configuration. Required integration_id is enforced per destination type. */
destination?: BatchExportDestinationRequestApi
/** How often the batch export should run.
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 4b4f6e237c7b..310c0435c52c 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -14491,10 +14491,10 @@ export namespace Schemas {
* * `sessions` - Sessions
* * `hogql` - Hogql
*/
- export type ModelEnum = typeof ModelEnum[keyof typeof ModelEnum];
+ export type BatchExportModelEnum = typeof BatchExportModelEnum[keyof typeof BatchExportModelEnum];
- export const ModelEnum = {
+ export const BatchExportModelEnum = {
Events: 'events',
Persons: 'persons',
Sessions: 'sessions',
@@ -14515,10 +14515,10 @@ export namespace Schemas {
* * `NoOp` - Noop
* * `FileDownload` - File Download
*/
- export type BatchExportDestinationDestinationEnum = typeof BatchExportDestinationDestinationEnum[keyof typeof BatchExportDestinationDestinationEnum];
+ export type BatchExportDestinationTypeEnum = typeof BatchExportDestinationTypeEnum[keyof typeof BatchExportDestinationTypeEnum];
- export const BatchExportDestinationDestinationEnum = {
+ export const BatchExportDestinationTypeEnum = {
AwsS3: 'AwsS3',
S3Compatible: 'S3Compatible',
Snowflake: 'Snowflake',
@@ -14811,7 +14811,7 @@ export namespace Schemas {
* * `HTTP` - Http
* * `NoOp` - Noop
* * `FileDownload` - File Download */
- type: BatchExportDestinationDestinationEnum;
+ type: BatchExportDestinationTypeEnum;
/** Destination-specific configuration. Fields depend on `type`. Credentials for integration-backed destinations (Databricks, AzureBlob, BigQuery, Postgres, AwsS3, S3Compatible, Snowflake, Redshift) are NOT stored here — they live in the linked Integration. Secret fields are stripped from responses. */
config: BatchExportDestinationConfig;
/**
@@ -14976,7 +14976,7 @@ export namespace Schemas {
* * `persons` - Persons
* * `sessions` - Sessions
* * `hogql` - Hogql */
- model?: ModelEnum | BlankEnum | null;
+ model?: BatchExportModelEnum | BlankEnum | null;
/** Destination configuration (type, config, and optional integration). */
destination: BatchExportDestination;
/** How often the batch export should run.
@@ -15846,7 +15846,7 @@ export namespace Schemas {
* * `persons` - Persons
* * `sessions` - Sessions
* * `hogql` - Hogql */
- model?: ModelEnum;
+ model?: BatchExportModelEnum;
/** Destination configuration. Required integration_id is enforced per destination type. */
destination: BatchExportDestinationRequest;
/** How often the batch export should run.
@@ -73301,7 +73301,7 @@ export namespace Schemas {
* * `persons` - Persons
* * `sessions` - Sessions
* * `hogql` - Hogql */
- model?: ModelEnum;
+ model?: BatchExportModelEnum;
/** Destination configuration. Required integration_id is enforced per destination type. */
destination?: BatchExportDestinationRequest;
/** How often the batch export should run.