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.

fix(data-warehouse): defer empty-team sentinel and reconcile CP date mirror (#72827)

Benjamin Knofe-Vider03defd5a5506
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.py
index f1f6f8478151..7ea4d31a33d4 100644
--- a/posthog/dags/events_backfill_to_duckling.py
+++ b/posthog/dags/events_backfill_to_duckling.py
@@ -2990,6 +2990,44 @@ def _push_earliest_event_date_to_cp(bf: DuckgresServerTeam) -> None:
logger.exception("duckling_earliest_event_date_cp_push_failed", team_id=bf.team_id)
+def _reconcile_earliest_event_dates_with_cp(backfills: list[DuckgresServerTeam]) -> None:
+ """Re-push resolved earliest_event_dates whose control-plane mirror is missing or stale.
+
+ The per-row pushes (the provisioning Celery task, the sensor's resolve loop) are
+ best-effort one-shots: a transient control-plane failure would otherwise diverge the
+ two stores forever, because a row with a resolved date is never revisited. One
+ list-teams call per org per tick keeps this bounded; only teams the control plane
+ already knows are pushed (a missing row is the lazy grandfather's job, not this one's).
+ Best-effort in every direction — nothing here may fail the sensor tick.
+ """
+ try:
+ # Deferred like the other control-plane touchpoints: keeps the DRF-importing
+ # adapter off this module's import path.
+ from products.data_warehouse.backend.presentation.views import managed_warehouse # noqa: PLC0415
+ except Exception:
+ logger.exception("duckling_earliest_event_date_cp_reconcile_import_failed")
+ return
+
+ by_org: dict = {}
+ for bf in backfills:
+ if bf.earliest_event_date is not None:
+ by_org.setdefault(bf.server.organization_id, []).append(bf)
+
+ for org_id, rows in by_org.items():
+ try:
+ teams = managed_warehouse._teams_from_response(managed_warehouse.list_teams(org_id, require_enabled=False))
+ if teams is None:
+ continue
+ cp_dates = {row.get("team_id"): row.get("earliest_event_date") for row in teams}
+ for bf in rows:
+ if bf.team_id not in cp_dates:
+ continue
+ if cp_dates[bf.team_id] != bf.earliest_event_date.isoformat():
+ _push_earliest_event_date_to_cp(bf)
+ except Exception:
+ logger.exception("duckling_earliest_event_date_cp_reconcile_failed", organization_id=str(org_id))
+
+
def _reconcile_events_backfill_statuses(context: SensorEvaluationContext, partition_keys: list[str]) -> None:
"""Backfill the status projection for partitions that ran before it existed.
@@ -3095,7 +3133,9 @@ def duckling_events_full_backfill_sensor(
today = timezone.now().date()
last_month_end = today.replace(day=1) - timedelta(days=1)
- backfills = list(DuckgresServerTeam.objects.filter(backfill_enabled=True).order_by("team_id"))
+ backfills = list(
+ DuckgresServerTeam.objects.filter(backfill_enabled=True).select_related("server").order_by("team_id")
+ )
if not backfills:
context.log.info("No enabled DuckgresServerTeam entries found")
return SensorResult(run_requests=[])
@@ -3115,6 +3155,10 @@ def duckling_events_full_backfill_sensor(
bf.save(update_fields=["earliest_event_date"])
_push_earliest_event_date_to_cp(bf)
+ # Heal one-shot pushes that failed: re-mirror any resolved date the control plane
+ # is missing or has stale. Never fails the tick.
+ _reconcile_earliest_event_dates_with_cp(backfills)
+
# 2. Per-team remaining months (oldest first), skipping already-registered partitions.
existing = set(context.instance.get_dynamic_partitions("duckling_events_backfill"))
per_team_remaining: list[list[str]] = []
@@ -3318,7 +3362,9 @@ def duckling_persons_full_backfill_sensor(
To restart from scratch, reset the cursor in Dagster UI:
Sensors -> duckling_persons_full_backfill_sensor -> Reset cursor
"""
- backfills = list(DuckgresServerTeam.objects.filter(backfill_enabled=True).order_by("team_id"))
+ backfills = list(
+ DuckgresServerTeam.objects.filter(backfill_enabled=True).select_related("server").order_by("team_id")
+ )
if not backfills:
context.log.info("No enabled DuckgresServerTeam entries found")
return SensorResult(run_requests=[])
diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.py
index 547cb5121020..581d5c2e9f2e 100644
--- a/posthog/dags/test_events_backfill_to_duckling.py
+++ b/posthog/dags/test_events_backfill_to_duckling.py
@@ -693,7 +693,7 @@ class TestFullBackfillSensorEarliestDate:
backfill = MagicMock()
backfill.team_id = 1
backfill.earliest_event_date = None # unresolved → sensor resolves + caches it
- mock_backfill_cls.objects.filter.return_value.order_by.return_value = [backfill]
+ mock_backfill_cls.objects.filter.return_value.select_related.return_value.order_by.return_value = [backfill]
instance = DagsterInstance.ephemeral()
context = build_sensor_context(instance=instance)
@@ -722,7 +722,7 @@ class TestFullBackfillSensorEarliestDate:
backfill = MagicMock()
backfill.team_id = 1
backfill.earliest_event_date = None
- mock_backfill_cls.objects.filter.return_value.order_by.return_value = [backfill]
+ mock_backfill_cls.objects.filter.return_value.select_related.return_value.order_by.return_value = [backfill]
instance = DagsterInstance.ephemeral()
context = build_sensor_context(instance=instance)
@@ -757,7 +757,7 @@ class TestFullBackfillSensorEarliestDate:
patch("posthog.ducklake.common.get_earliest_event_date_for_team") as mock_ge,
):
mock_tz.now.return_value = now
- mock_cls.objects.filter.return_value.order_by.return_value = backfills
+ mock_cls.objects.filter.return_value.select_related.return_value.order_by.return_value = backfills
mock_projection.objects.unscoped.return_value.filter.return_value.values_list.return_value = []
if isinstance(get_earliest, list):
mock_ge.side_effect = get_earliest
@@ -874,7 +874,9 @@ class TestFullBackfillSensorEarliestDate:
patch("posthog.ducklake.common.get_earliest_event_date_for_team"),
):
mock_tz.now.return_value = datetime(2020, 2, 10, 12, 0, 0)
- mock_cls.objects.filter.return_value.order_by.return_value = [self._bf(1, earliest=date(2020, 1, 1))]
+ mock_cls.objects.filter.return_value.select_related.return_value.order_by.return_value = [
+ self._bf(1, earliest=date(2020, 1, 1))
+ ]
instance = DagsterInstance.ephemeral()
context = build_sensor_context(instance=instance)
with patch.object(instance, "get_runs", return_value=[]) as mock_get_runs:
@@ -915,6 +917,72 @@ class TestFullBackfillSensorEarliestDate:
assert len(result.run_requests) > 0
+class TestEarliestEventDateReconcile:
+ # The one-shot CP pushes are best-effort; this pass is what heals a transient failure.
+ @staticmethod
+ def _bf(team_id: int, org_id: str, earliest):
+ m = MagicMock()
+ m.team_id = team_id
+ m.server.organization_id = org_id
+ m.earliest_event_date = earliest
+ return m
+
+ @parameterized.expand(
+ [
+ # CP has no date for the team -> re-push
+ ("cp_missing_date", {"team_id": 1, "earliest_event_date": None}, True),
+ # CP has a stale date -> re-push
+ ("cp_stale_date", {"team_id": 1, "earliest_event_date": "2019-01-01"}, True),
+ # CP already converged -> nothing to do
+ ("cp_in_sync", {"team_id": 1, "earliest_event_date": "2020-06-15"}, False),
+ # CP doesn't know the team at all -> not this pass's job (lazy grandfather owns creation)
+ ("cp_missing_team", {"team_id": 999, "earliest_event_date": None}, False),
+ ]
+ )
+ def test_repushes_only_divergent_rows(self, _name, cp_row, expect_push):
+ from posthog.dags.events_backfill_to_duckling import _reconcile_earliest_event_dates_with_cp
+
+ bf = self._bf(1, "org-a", date(2020, 6, 15))
+ with (
+ patch("products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams") as mock_list,
+ patch(
+ "products.data_warehouse.backend.presentation.views.managed_warehouse._teams_from_response",
+ return_value=[cp_row],
+ ),
+ patch(
+ "products.data_warehouse.backend.presentation.views.managed_warehouse.push_team_earliest_event_date"
+ ) as mock_push,
+ ):
+ _reconcile_earliest_event_dates_with_cp([bf])
+
+ mock_list.assert_called_once_with("org-a", require_enabled=False)
+ if expect_push:
+ mock_push.assert_called_once_with("org-a", 1, date(2020, 6, 15))
+ else:
+ mock_push.assert_not_called()
+
+ def test_unresolved_rows_and_cp_failures_are_skipped_quietly(self):
+ from posthog.dags.events_backfill_to_duckling import _reconcile_earliest_event_dates_with_cp
+
+ unresolved = self._bf(1, "org-a", None)
+ resolved = self._bf(2, "org-b", date(2020, 6, 15))
+ with (
+ patch(
+ "products.data_warehouse.backend.presentation.views.managed_warehouse.list_teams",
+ side_effect=Exception("cp down"),
+ ) as mock_list,
+ patch(
+ "products.data_warehouse.backend.presentation.views.managed_warehouse.push_team_earliest_event_date"
+ ) as mock_push,
+ ):
+ # Must not raise: a CP outage can never fail the sensor tick.
+ _reconcile_earliest_event_dates_with_cp([unresolved, resolved])
+
+ # Unresolved rows contribute no org lookup; the failing org is logged and skipped.
+ mock_list.assert_called_once_with("org-b", require_enabled=False)
+ mock_push.assert_not_called()
+
+
class TestStaleRunOutcome:
# A stuck-RUNNING row may only be resolved from a run that provably ended — resolving a live
# or queued run would overwrite the terminal state its own process is about to write.
diff --git a/products/data_warehouse/backend/tasks/tasks.py b/products/data_warehouse/backend/tasks/tasks.py
index 91d8fbe8ddc0..7ec9862c0a75 100644
--- a/products/data_warehouse/backend/tasks/tasks.py
+++ b/products/data_warehouse/backend/tasks/tasks.py
@@ -148,16 +148,23 @@ def send_external_data_failure_digest_task(team_id: int) -> None:
def sync_team_earliest_event_date(team_id: int) -> None:
"""Resolve, cache, and mirror a team's earliest event date after provision/onboard.
- Dual-write: the clamped earliest event date (or the no-history sentinel for teams
- without events) is stored on the Django ``DuckgresServerTeam`` row — the full-backfill
- sensor's read source — and mirrored to the team's duckgres control-plane row.
+ Dual-write: the clamped earliest event date is stored on the Django
+ ``DuckgresServerTeam`` row — the full-backfill sensor's read source — and mirrored to
+ the team's duckgres control-plane row.
Idempotent: an already-cached date is never recomputed, and both writes are upserts.
Best-effort on the control-plane side: a failed push is logged and dropped — the
- sensor still works entirely off the Django row.
+ sensor's reconciliation pass re-pushes it on a later tick.
+
+ A team with no events yet is left unresolved (NULL), NOT cached as the no-history
+ sentinel: this task runs seconds after provision/onboard, when a brand-new project
+ plausibly hasn't ingested its first events. A cached date is final (nothing
+ re-resolves a non-NULL value), so persisting the sentinel here would permanently
+ exclude the team from historical backfill. The full-backfill sensor resolves it
+ later, when "no events" is a meaningful answer.
"""
# Deferred: ducklake.common pulls duckdb in, and posthog.models must not load while
# Celery imports task modules — keep both off this module's import path.
- from posthog.ducklake.common import resolve_team_earliest_event_date # noqa: PLC0415
+ from posthog.ducklake.common import NO_HISTORY_SENTINEL, resolve_team_earliest_event_date # noqa: PLC0415
from posthog.ducklake.models import DuckgresServerTeam # noqa: PLC0415
from products.data_warehouse.backend.presentation.views.managed_warehouse import ( # noqa: PLC0415
@@ -169,7 +176,11 @@ def sync_team_earliest_event_date(team_id: int) -> None:
logger.info("No duckling membership row for team; skipping earliest event date sync", team_id=team_id)
return
if bf.earliest_event_date is None:
- bf.earliest_event_date = resolve_team_earliest_event_date(team_id)
+ resolved = resolve_team_earliest_event_date(team_id)
+ if resolved == NO_HISTORY_SENTINEL:
+ logger.info("No events for team yet; leaving earliest event date unresolved", team_id=team_id)
+ return
+ bf.earliest_event_date = resolved
bf.save(update_fields=["earliest_event_date"])
push_team_earliest_event_date(bf.server.organization_id, team_id, bf.earliest_event_date)
diff --git a/products/data_warehouse/backend/tests/test_tasks.py b/products/data_warehouse/backend/tests/test_tasks.py
index 312e0c5fcd9b..9fb9ee7ca574 100644
--- a/products/data_warehouse/backend/tests/test_tasks.py
+++ b/products/data_warehouse/backend/tests/test_tasks.py
@@ -26,7 +26,6 @@ def _onboarded_team(earliest: date | None = None) -> tuple[Organization, Team]:
[
("pre_2015_clamped", datetime(2010, 3, 1), date(2015, 1, 1)),
("post_2015_kept", datetime(2020, 6, 15), date(2020, 6, 15)),
- ("no_events_sentinel", None, date(9999, 12, 31)),
]
)
@pytest.mark.django_db
@@ -39,9 +38,9 @@ def test_sync_task_resolves_and_dual_writes(
mock_get_earliest: MagicMock,
mock_update: MagicMock,
) -> None:
- # The provisioning-time task must apply the same clamp + no-history sentinel the
- # backfill sensor uses, and write the result to BOTH the Django row (the sensor's
- # read source) and the duckgres control-plane team row.
+ # The provisioning-time task must apply the same clamp the backfill sensor uses, and
+ # write the result to BOTH the Django row (the sensor's read source) and the duckgres
+ # control-plane team row.
org, team = _onboarded_team()
mock_get_earliest.return_value = earliest_dt
mock_update.return_value = Response({}, status=200)
@@ -54,6 +53,23 @@ def test_sync_task_resolves_and_dual_writes(
)
+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.update_team")
+@patch("posthog.ducklake.common.get_earliest_event_date_for_team")
+def test_sync_task_leaves_empty_team_unresolved(mock_get_earliest: MagicMock, mock_update: MagicMock) -> None:
+ # A just-provisioned project plausibly has no events YET. A cached date is final, so
+ # storing the no-history sentinel here would permanently exclude the team from
+ # historical backfill; the task must leave the row NULL for the sensor to resolve
+ # later, and push nothing to the control plane.
+ _, team = _onboarded_team()
+ mock_get_earliest.return_value = None
+
+ sync_team_earliest_event_date(team.id)
+
+ assert DuckgresServerTeam.objects.get(team=team).earliest_event_date is None
+ mock_update.assert_not_called()
+
+
@pytest.mark.django_db
@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.update_team")
@patch("posthog.ducklake.common.get_earliest_event_date_for_team")