: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(cohorts): persist disaster-recovery boundary on backfill runs (#71144)
Matheus Batista9815b3480cec
diff --git a/products/cohorts/backend/backfill/runs.py b/products/cohorts/backend/backfill/runs.pyindex f0802dd1eb38..2cd704502e78 100644--- a/products/cohorts/backend/backfill/runs.py+++ b/products/cohorts/backend/backfill/runs.py@@ -1,9 +1,11 @@from collections.abc import Iterable+from datetime import UTC, datetimefrom typing import Anyfrom django.conf import settingsfrom django.db import transactionfrom django.db.models.functions import Now+from django.utils import timezone as django_timezonefrom posthog.models.team.team import Team@@ -16,6 +18,7 @@ from products.cohorts.backend.models.backfill import (CohortBackfillRunCohort,CohortBackfillRunStatus,CohortBackfillScope,+ CohortBackfillTrigger,)from products.cohorts.backend.models.cohort import Cohort, CohortTypefrom products.cohorts.backend.models.leaf_shape import walk_filter_leaves@@ -122,10 +125,21 @@ def create_team_backfill_run(trigger_kind: str,cohort_ids: Iterable[int] | None = None,created_by_id: int | None = None,+ boundary_at: datetime | None = None,) -> CohortBackfillRun:if not is_realtime_cohort_team(team_id):raise ValueError(f"Team {team_id} is not in the realtime cohort allowlist")+ if boundary_at is not None:+ if trigger_kind != CohortBackfillTrigger.DISASTER_RECOVERY:+ raise ValueError("boundary_at is only valid for disaster recovery runs")+ if django_timezone.is_naive(boundary_at):+ raise ValueError("boundary_at must include a UTC offset")+ try:+ boundary_at = boundary_at.astimezone(UTC)+ except OverflowError as error:+ raise ValueError("boundary_at falls outside the supported UTC range") from error+requested_ids = set(cohort_ids) if cohort_ids is not None else Nonewith transaction.atomic():team = Team.objects.get(id=team_id)@@ -161,6 +175,7 @@ def create_team_backfill_run(trigger_kind=trigger_kind,scope=CohortBackfillScope.TEAM,status=status,+ boundary_at=boundary_at,timezone=team.timezone,pinned=_pinned_payload(cohorts),preconditions=preconditions,diff --git a/products/cohorts/backend/backfill/test/test_management_command.py b/products/cohorts/backend/backfill/test/test_management_command.pyindex 494ea96b3347..6a7e5cc1bb5b 100644--- a/products/cohorts/backend/backfill/test/test_management_command.py+++ b/products/cohorts/backend/backfill/test/test_management_command.py@@ -1,3 +1,4 @@+from datetime import UTC, datetimefrom io import StringIOfrom posthog.test.base import BaseTest@@ -7,7 +8,9 @@ from django.core.management import call_commandfrom django.core.management.base import CommandErrorfrom django.test import override_settings-from products.cohorts.backend.models.backfill import CohortBackfillRun, CohortBackfillRunCohort+from parameterized import parameterized++from products.cohorts.backend.models.backfill import CohortBackfillRun, CohortBackfillRunCohort, CohortBackfillRunStatusfrom products.cohorts.backend.models.cohort import Cohort, CohortType@@ -95,6 +98,54 @@ class TestCreateCohortBackfillRunCommand(BaseTest):[selected.id],)+ def test_disaster_recovery_boundary_is_persisted_without_promoting_the_run(self) -> None:+ self._cohort("$pageview")++ call_command(+ "create_cohort_backfill_run",+ team_id=self.team.id,+ trigger="disaster_recovery",+ boundary_at="2026-07-14T09:45:12-03:00",+ )++ run = CohortBackfillRun.objects.for_team(self.team.id).get()+ self.assertEqual(run.boundary_at, datetime(2026, 7, 14, 12, 45, 12, tzinfo=UTC))+ self.assertIsNone(run.boundary_established_at)+ self.assertEqual(run.status, CohortBackfillRunStatus.AWAITING_BOUNDARY)++ @parameterized.expand(+ [+ ("missing_offset", "disaster_recovery", "2026-07-14T09:45:12", "must include a UTC offset"),+ ("invalid", "disaster_recovery", "not-a-timestamp", "must be a valid ISO 8601 timestamp"),+ (+ "utc_overflow",+ "disaster_recovery",+ "0001-01-01T00:00:00+23:59",+ "falls outside the supported UTC range",+ ),+ (+ "wrong_trigger",+ "team_enablement",+ "2026-07-14T09:45:12Z",+ "only valid with --trigger disaster_recovery",+ ),+ ]+ )+ def test_invalid_boundary_returns_clean_command_error(+ self, _name: str, trigger: str, boundary_at: str, error_message: str+ ) -> None:+ self._cohort("$pageview")++ with self.assertRaisesMessage(CommandError, error_message):+ call_command(+ "create_cohort_backfill_run",+ team_id=self.team.id,+ trigger=trigger,+ boundary_at=boundary_at,+ )++ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)+def test_active_team_run_returns_clean_command_error(self) -> None:first = self._cohort("$pageview")call_command(diff --git a/products/cohorts/backend/management/commands/create_cohort_backfill_run.py b/products/cohorts/backend/management/commands/create_cohort_backfill_run.pyindex f33a9bf12142..8e178170ed2c 100644--- a/products/cohorts/backend/management/commands/create_cohort_backfill_run.py+++ b/products/cohorts/backend/management/commands/create_cohort_backfill_run.py@@ -1,7 +1,10 @@+from datetime import datetimefrom typing import Anyfrom django.core.management.base import BaseCommand, CommandError, CommandParserfrom django.db import IntegrityError+from django.utils import timezone as django_timezone+from django.utils.dateparse import parse_datetimefrom posthog.models.team.team import Team@@ -19,6 +22,20 @@ def _has_behavioral_filters(cohort: Cohort) -> bool:)+def _parse_boundary_at(value: str | None) -> datetime | None:+ if value is None:+ return None+ try:+ boundary_at = parse_datetime(value)+ except ValueError as error:+ raise CommandError("--boundary-at must be a valid ISO 8601 timestamp with a UTC offset") from error+ if boundary_at is None:+ raise CommandError("--boundary-at must be a valid ISO 8601 timestamp with a UTC offset")+ if django_timezone.is_naive(boundary_at):+ raise CommandError("--boundary-at must include a UTC offset")+ return boundary_at++class Command(BaseCommand):help = "Create a coordinated behavioral cohort backfill run"@@ -30,10 +47,16 @@ class Command(BaseCommand):required=True,)parser.add_argument("--cohort-ids", type=int, nargs="+")+ parser.add_argument("--boundary-at", help="ISO 8601 disaster recovery boundary with a UTC offset")parser.add_argument("--dry-run", action="store_true")def handle(self, *args: Any, **options: Any) -> None:team_id: int = options["team_id"]+ trigger: str = options["trigger"]+ boundary_at = _parse_boundary_at(options.get("boundary_at"))+ if boundary_at is not None and trigger != CohortBackfillTrigger.DISASTER_RECOVERY:+ raise CommandError("--boundary-at is only valid with --trigger disaster_recovery")+if not is_realtime_cohort_team(team_id):raise CommandError(f"Team {team_id} is not in the realtime cohort allowlist")@@ -62,7 +85,7 @@ class Command(BaseCommand):returntry:- run = create_team_backfill_run(team_id, options["trigger"], cohort_ids)+ run = create_team_backfill_run(team_id, trigger, cohort_ids, boundary_at=boundary_at)except (Team.DoesNotExist, ValueError) as error:raise CommandError(str(error)) from errorexcept IntegrityError as error: