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(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.py
index 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, datetime
from typing import Any
from django.conf import settings
from django.db import transaction
from django.db.models.functions import Now
+from django.utils import timezone as django_timezone
from 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, CohortType
from 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 None
with 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.py
index 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, datetime
from io import StringIO
from posthog.test.base import BaseTest
@@ -7,7 +8,9 @@ from django.core.management import call_command
from django.core.management.base import CommandError
from 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, CohortBackfillRunStatus
from 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.py
index 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 datetime
from typing import Any
from django.core.management.base import BaseCommand, CommandError, CommandParser
from django.db import IntegrityError
+from django.utils import timezone as django_timezone
+from django.utils.dateparse import parse_datetime
from 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):
return
try:
- 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 error
except IntegrityError as error: