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(data-modeling): batch reconcile teams onto tiers with a breaker (#75430)

Jovan Sakovice89544bff32b
diff --git a/products/data_modeling/backend/management/commands/batch_reconcile_teams.py b/products/data_modeling/backend/management/commands/batch_reconcile_teams.py
new file mode 100644
index 000000000000..3af687c06cfb
--- /dev/null
+++ b/products/data_modeling/backend/management/commands/batch_reconcile_teams.py
@@ -0,0 +1,187 @@
+import json
+import dataclasses
+from datetime import timedelta
+from pathlib import Path
+
+from django.core.management.base import BaseCommand, CommandError
+
+import structlog
+from asgiref.sync import async_to_sync
+
+from posthog.models.team import Team
+from posthog.temporal.common.client import async_connect
+from posthog.temporal.common.schedule import a_schedule_exists
+
+from products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_id
+from products.data_modeling.backend.logic.node_frequency import schedulable_nodes
+from products.data_modeling.backend.logic.schedule_reconcile import (
+ convert_dag_to_tiers,
+ delete_v1_saved_query_schedules,
+ null_saved_query_intervals,
+ preview_dag_schedules,
+ tiered_schedules_enabled,
+)
+from products.data_modeling.backend.models.dag import DAG
+
+logger = structlog.get_logger(__name__)
+
+REPORT_MARKER = "=== BATCH RECONCILE REPORT JSON ==="
+
+
+class Anomaly(Exception):
+ """The team's state diverged from what the plan predicted; halts the batch."""
+
+
+def _seconds(interval: timedelta) -> int:
+ return int(interval.total_seconds())
+
+
+@async_to_sync
+async def _verify_schedules(expected: list[str], deleted: list[str]) -> tuple[list[str], list[str]]:
+ """Point-read every id: planned schedules must exist, swept ones must be gone. Listing
+ would go through the eventually-consistent visibility store and can return a pre-apply
+ snapshot, halting the batch on a conversion that actually succeeded."""
+ temporal = await async_connect()
+ missing = [sid for sid in expected if not await a_schedule_exists(temporal, sid)]
+ lingering = [sid for sid in deleted if await a_schedule_exists(temporal, sid)]
+ return missing, lingering
+
+
+class Command(BaseCommand):
+ help = (
+ "Reconcile a batch of teams onto tiered schedules with a built-in circuit breaker. "
+ "Each team is planned read-only first (predicted tier set, clamps, invalid targets); "
+ "with --apply the plan is executed and the live Temporal schedule set is verified "
+ "against the prediction. Any divergence or error halts the batch before the next "
+ "team. Emits a JSON report (after the marker line, and to --output when given) for "
+ "the rollout tracker."
+ )
+
+ def add_arguments(self, parser):
+ parser.add_argument("--team-ids", type=str, required=True, help="Comma-separated team ids, processed in order")
+ parser.add_argument(
+ "--apply", action="store_true", default=False, help="Execute the plan; default is plan-only"
+ )
+ parser.add_argument("--output", type=str, default=None, help="Also write the JSON report to this path")
+
+ def handle(self, *args, **options):
+ try:
+ team_ids = [int(part) for part in options["team_ids"].split(",") if part.strip()]
+ except ValueError:
+ raise CommandError(f"--team-ids must be comma-separated integers, got {options['team_ids']!r}")
+ if not team_ids:
+ raise CommandError("--team-ids is empty")
+
+ apply = options["apply"]
+ report: dict = {"apply": apply, "halted": False, "halt_reason": None, "teams": []}
+ halted = False
+ for team_id in team_ids:
+ if halted:
+ report["teams"].append({"team_id": team_id, "status": "skipped", "anomalies": [], "dags": []})
+ continue
+ record: dict = {"team_id": team_id, "status": "planned", "dags": [], "anomalies": []}
+ report["teams"].append(record)
+ try:
+ self._process_team(team_id, record, apply=apply)
+ if apply:
+ record["status"] = "applied"
+ self.stdout.write(f"team {team_id}: {record['status']}")
+ except Anomaly as err:
+ record["status"] = "anomaly"
+ record["anomalies"].append(str(err))
+ report["halted"] = True
+ report["halt_reason"] = f"team {team_id}: {err}"
+ halted = True
+ self.stderr.write(self.style.ERROR(f"HALT: team {team_id}: {err}"))
+ except Exception as err:
+ logger.exception("Unexpected error reconciling team", team_id=team_id)
+ record["status"] = "anomaly"
+ record["anomalies"].append(f"unexpected error: {err!r}")
+ report["halted"] = True
+ report["halt_reason"] = f"team {team_id}: unexpected error: {err!r}"
+ halted = True
+ self.stderr.write(self.style.ERROR(f"HALT: team {team_id}: unexpected error: {err!r}"))
+
+ payload = json.dumps(report, indent=1)
+ if options["output"]:
+ Path(options["output"]).write_text(payload)
+ self.stdout.write(REPORT_MARKER)
+ self.stdout.write(payload)
+
+ def _process_team(self, team_id: int, record: dict, *, apply: bool) -> None:
+ team = Team.objects.filter(id=team_id).first()
+ if team is None:
+ raise Anomaly("team does not exist")
+ record["organization_id"] = str(team.organization_id)
+ if apply and not tiered_schedules_enabled(team):
+ raise Anomaly("team's org is not on the tiered-schedules flag")
+
+ dag_list = list(DAG.objects.filter(team_id=team_id))
+ if not dag_list:
+ record["note"] = "no DAGs"
+ return
+
+ plans = []
+ for dag in dag_list:
+ preview = preview_dag_schedules(dag, seed=True)
+ dag_record: dict = {
+ "dag_id": str(dag.id),
+ "name": dag.name,
+ "planned_tiers": sorted(_seconds(t) for t in preview.desired_tiers),
+ "tier_node_counts": {str(_seconds(t)): len(nodes) for t, nodes in preview.desired_tiers.items()},
+ "to_create": sorted(preview.plan.to_create),
+ "to_update": sorted(preview.plan.to_update),
+ "to_delete": sorted(preview.plan.to_delete),
+ "clamped": [
+ {
+ **dataclasses.asdict(c),
+ "demanded": _seconds(c.demanded),
+ "source_floor": _seconds(c.source_floor),
+ "clamped_to": _seconds(c.clamped_to),
+ }
+ for c in preview.clamped
+ ],
+ # pre-existing declared-target drift is common and non-blocking (the effective
+ # cadence wins; floor violations clamp at schedule time), so it is reported for
+ # review rather than halting the batch
+ "invalid_targets": [
+ {
+ "node_id": c.node_id,
+ "declared": _seconds(c.declared),
+ "source_floor": _seconds(c.source_floor),
+ "consumer_ceiling": _seconds(c.consumer_ceiling) if c.consumer_ceiling is not None else None,
+ }
+ for c in preview.invalid_targets
+ ],
+ "unsupported_tiers": [_seconds(t) for t in preview.unsupported_tiers],
+ }
+ record["dags"].append(dag_record)
+ plans.append((dag, preview, dag_record))
+ if preview.unsupported_tiers:
+ raise Anomaly(f"DAG {dag.name}: unsupported tier(s) {[_seconds(t) for t in preview.unsupported_tiers]}")
+
+ if not apply:
+ return
+
+ # Seed every DAG before sweeping any intervals: a query in two DAGs seeds from the shared
+ # interval, so sweeping/nulling mid-loop would corrupt the other DAG's seed.
+ for dag, _preview, dag_record in plans:
+ dag_record["seeded"] = convert_dag_to_tiers(dag)
+ for dag, _preview, dag_record in plans:
+ nodes = list(schedulable_nodes(dag).select_related("saved_query"))
+ sq_ids = [str(node.saved_query_id) for node in nodes if node.saved_query_id is not None]
+ failed = delete_v1_saved_query_schedules(nodes, team_id=dag.team_id, dag_id=str(dag.id))
+ swept = [sq_id for sq_id in sq_ids if sq_id not in failed]
+ dag_record["v1_swept"] = len(swept)
+ dag_record["intervals_cleared"] = null_saved_query_intervals(dag, only_saved_query_ids=swept)
+ if failed:
+ raise Anomaly(f"DAG {dag.name}: {len(failed)} v1 schedule(s) failed to delete")
+
+ for dag, preview, dag_record in plans:
+ expected = sorted(tier_schedule_id(str(dag.id), interval) for interval in preview.desired_tiers)
+ missing, lingering = _verify_schedules(expected, sorted(preview.plan.to_delete))
+ dag_record["verified"] = not missing and not lingering
+ if missing or lingering:
+ raise Anomaly(
+ f"DAG {dag.name}: missing planned schedule(s) {missing}; lingering swept schedule(s) {lingering}"
+ )
diff --git a/products/data_modeling/backend/test/test_batch_reconcile_teams.py b/products/data_modeling/backend/test/test_batch_reconcile_teams.py
new file mode 100644
index 000000000000..bc6e99408f94
--- /dev/null
+++ b/products/data_modeling/backend/test/test_batch_reconcile_teams.py
@@ -0,0 +1,153 @@
+import json
+from datetime import timedelta
+from io import StringIO
+
+import pytest
+from posthog.test.base import BaseTest
+from unittest import mock
+
+from django.core.management import call_command
+
+from posthog.models.team import Team
+
+from products.data_modeling.backend.logic.cohort_scheduling import tier_schedule_id
+from products.data_modeling.backend.logic.node_frequency import get_declared_target, set_declared_target
+from products.data_modeling.backend.management.commands.batch_reconcile_teams import REPORT_MARKER
+from products.data_modeling.backend.models.dag import DAG
+from products.data_modeling.backend.models.datawarehouse_saved_query import DataWarehouseSavedQuery
+from products.data_modeling.backend.models.node import Node, NodeType
+from products.data_modeling.backend.test.helpers import temporal_listing as _temporal_listing
+
+H6 = timedelta(hours=6)
+
+RECONCILE = "products.data_modeling.backend.logic.schedule_reconcile"
+BATCH = "products.data_modeling.backend.management.commands.batch_reconcile_teams"
+
+
+class TestBatchReconcileTeams(BaseTest):
+ def _legacy_dag(self, team) -> tuple[DAG, Node]:
+ dag = DAG.objects.create(team=team, name="Default", sync_frequency_interval=H6)
+ saved_query = DataWarehouseSavedQuery.objects.create(
+ name=f"v_{team.pk}",
+ team=team,
+ query={"query": "SELECT 1", "kind": "HogQLQuery"},
+ sync_frequency_interval=H6,
+ )
+ node = Node.objects.create(team=team, dag=dag, saved_query=saved_query, type=NodeType.VIEW)
+ return dag, node
+
+ def _run(self, team_ids: str, *extra_args, existing=(), verify_listing=None):
+ out = StringIO()
+ with (
+ mock.patch(f"{BATCH}.tiered_schedules_enabled", return_value=True),
+ mock.patch(f"{RECONCILE}.sync_connect"),
+ mock.patch(f"{RECONCILE}.delete_schedule"),
+ mock.patch(
+ f"{RECONCILE}.async_connect", new=mock.AsyncMock(return_value=_temporal_listing(list(existing)))
+ ),
+ mock.patch(f"{RECONCILE}.a_create_schedule", new=mock.AsyncMock()) as create,
+ mock.patch(f"{RECONCILE}.a_delete_schedule", new=mock.AsyncMock()) as delete,
+ mock.patch(f"{BATCH}.async_connect", new=mock.AsyncMock()),
+ mock.patch(
+ f"{BATCH}.a_schedule_exists",
+ new=mock.AsyncMock(side_effect=lambda _t, sid: sid in (verify_listing or set())),
+ ),
+ ):
+ call_command("batch_reconcile_teams", "--team-ids", team_ids, *extra_args, stdout=out, stderr=StringIO())
+ report = json.loads(out.getvalue().split(REPORT_MARKER, 1)[1])
+ return report, create, delete
+
+ def test_breaker_halts_batch_and_skips_remaining_teams(self):
+ # an unsupported tier on the first team must stop the batch before the second team
+ # is even planned, let alone applied
+ dag_a, node_a = self._legacy_dag(self.team)
+ set_declared_target(node_a, timedelta(minutes=7))
+ node_a.save()
+ team_b = Team.objects.create(organization=self.organization, name="second")
+ dag_b, node_b = self._legacy_dag(team_b)
+
+ report, create, _delete = self._run(f"{self.team.pk},{team_b.pk}", "--apply", existing=[str(dag_a.id)])
+
+ assert report["halted"] is True
+ assert "unsupported tier" in report["halt_reason"]
+ statuses = {t["team_id"]: t["status"] for t in report["teams"]}
+ assert statuses[self.team.pk] == "anomaly"
+ assert statuses[team_b.pk] == "skipped"
+ create.assert_not_called()
+ node_b.refresh_from_db()
+ assert get_declared_target(node_b) is None
+
+ def test_apply_creates_planned_tier_and_verifies(self):
+ dag, node = self._legacy_dag(self.team)
+ legacy_id = str(dag.id)
+ expected_tier = tier_schedule_id(legacy_id, H6)
+
+ report, create, _delete = self._run(
+ str(self.team.pk), "--apply", existing=[legacy_id], verify_listing={expected_tier}
+ )
+
+ assert report["halted"] is False
+ team_record = report["teams"][0]
+ assert team_record["status"] == "applied"
+ assert team_record["dags"][0]["planned_tiers"] == [int(H6.total_seconds())]
+ assert team_record["dags"][0]["verified"] is True
+ create.assert_called_once()
+ assert create.call_args.kwargs["id"] == expected_tier
+ assert node.saved_query is not None
+ node.saved_query.refresh_from_db()
+ assert node.saved_query.sync_frequency_interval is None
+
+ def test_verify_mismatch_halts(self):
+ # if the live schedule set after apply is not exactly the planned tier set, the batch
+ # must halt instead of reporting success
+ dag, _node = self._legacy_dag(self.team)
+
+ report, _create, _delete = self._run(str(self.team.pk), "--apply", existing=[str(dag.id)], verify_listing=set())
+
+ assert report["halted"] is True
+ assert "missing planned schedule" in report["halt_reason"]
+ assert report["teams"][0]["status"] == "anomaly"
+
+ def test_invalid_declared_targets_are_reported_but_do_not_halt(self):
+ # pre-existing declared-target drift is fleet-common (team 2 alone has 18) and does not
+ # affect scheduling correctness; halting on it would block the rollout
+ from products.data_modeling.backend.models.edge import Edge
+
+ dag, parent = self._legacy_dag(self.team)
+ child_query = DataWarehouseSavedQuery.objects.create(
+ name="child",
+ team=self.team,
+ query={"query": "SELECT 1", "kind": "HogQLQuery"},
+ )
+ child = Node.objects.create(team=self.team, dag=dag, saved_query=child_query, type=NodeType.VIEW)
+ Edge.objects.create(team=self.team, dag=dag, source=parent, target=child)
+ set_declared_target(parent, timedelta(days=1))
+ parent.save()
+ set_declared_target(child, timedelta(hours=1))
+ child.save()
+
+ report, _create, _delete = self._run(str(self.team.pk), existing=[str(dag.id)])
+
+ assert report["halted"] is False
+ team_record = report["teams"][0]
+ assert team_record["status"] == "planned"
+ invalid = team_record["dags"][0]["invalid_targets"]
+ assert [t["node_id"] for t in invalid] == [str(parent.id)]
+ assert invalid[0]["consumer_ceiling"] == int(timedelta(hours=1).total_seconds())
+
+ def test_plan_only_writes_nothing(self):
+ dag, node = self._legacy_dag(self.team)
+
+ report, create, delete = self._run(str(self.team.pk), existing=[str(dag.id)])
+
+ assert report["halted"] is False
+ assert report["teams"][0]["status"] == "planned"
+ assert report["teams"][0]["dags"][0]["planned_tiers"] == [int(H6.total_seconds())]
+ create.assert_not_called()
+ delete.assert_not_called()
+ node.refresh_from_db()
+ assert get_declared_target(node) is None
+ assert node.saved_query is not None
+ node.saved_query.refresh_from_db()
+ assert node.saved_query.sync_frequency_interval == H6