: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(data-warehouse): dual-write earliest event date to duckgres CP (#72598)
Benjamin Knofe-Vider060045a8b4f7
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.pyindex 0b01e7969c1b..f1f6f8478151 100644--- a/posthog/dags/events_backfill_to_duckling.py+++ b/posthog/dags/events_backfill_to_duckling.py@@ -72,7 +72,13 @@ from posthog.clickhouse.query_tagging import tags_contextfrom posthog.cloud_utils import is_cloudfrom posthog.dags.common import JobOwners, dagster_tags, settings_with_log_commentfrom posthog.ducklake.client import make_duckgres_conninfo-from posthog.ducklake.common import DUCKGRES_BUCKET_REGION, _get_org_id_for_team, get_duckgres_server_for_organization+from posthog.ducklake.common import (+ DUCKGRES_BUCKET_REGION,+ NO_HISTORY_SENTINEL,+ _get_org_id_for_team,+ get_duckgres_server_for_organization,+ resolve_team_earliest_event_date,+)from posthog.ducklake.models import DuckgresServerTeamfrom products.data_warehouse.backend.facade.backfill_status import (@@ -915,46 +921,6 @@ def get_s3_url_for_clickhouse(bucket: str, region: str, path_without_scheme: strreturn f"https://{bucket}.s3.{region}.amazonaws.com/{path_without_scheme}"-def get_earliest_event_date_for_team(team_id: int) -> datetime | None:- """Query ClickHouse to find the earliest event date for a team.-- This is used by the full backfill sensor to determine the historical range- of data to backfill.-- Returns:- The date of the earliest event, or None if no events exist for this team.- """- cluster = _get_cluster()- workload = Workload.OFFLINE if is_cloud() else Workload.DEFAULT-- def query_earliest(client: Client) -> datetime | None:- # Filter timestamp >= '1970-01-01' to avoid toDate() overflow on pre-epoch timestamps.- # ClickHouse's Date type is UInt16 (days since 1970-01-01), so negative timestamps- # overflow to the max date (2149-06-06), breaking the backfill sensor logic.- result = client.execute(- """- SELECT toDate(min(timestamp)) as earliest_date- FROM events- WHERE team_id = %(team_id)s- AND timestamp >= '1970-01-01'- """,- {"team_id": team_id},- )- if result and result[0][0]:- # ClickHouse returns a date object, convert to datetime- date_val = result[0][0]- if isinstance(date_val, datetime):- return date_val- return datetime.combine(date_val, datetime.min.time())- return None-- return cluster.any_host_by_role(- fn=query_earliest,- workload=workload,- node_role=NodeRole.DATA,- ).result()--def get_earliest_person_date_for_team(team_id: int) -> datetime | None:"""Query ClickHouse to find the earliest person modification date for a team.@@ -2982,9 +2948,6 @@ def duckling_events_daily_backfill_sensor(# Still used by the persons full-backfill sensor below.BACKFILL_MONTHS_PER_TICK = 3-# Ignore events before this date — pre-2015 data is typically junk timestamps-EARLIEST_BACKFILL_DATE = datetime(2015, 1, 1)-# Full EVENTS-backfill sensor (round-robin, bounded top-up). Execution is throttled# separately by the duckling_events_v1 managed concurrency limit (charts) — kept small so# ClickHouse only ever sees a few concurrent exports. These knobs govern how the sensor@@ -3004,16 +2967,29 @@ EVENTS_BACKFILL_MAX_EARLIEST_LOOKUPS_PER_TICK = 5# Existing installations predate the durable UI projection. Reconcile a bounded# number of historical partitions per tick so the sensor stays within its budget.EVENTS_BACKFILL_STATUS_RECONCILE_LIMIT = 25-# Stored in DuckgresServerTeam.earliest_event_date for a team with no events, so the sensor-# caches "nothing to backfill" instead of re-querying every tick. Far enough in the future-# that the generated months range is always empty.-_NO_HISTORY_SENTINEL = date(9999, 12, 31)# Run tag stamped on full-backfill runs only. The full and daily events sensors share one# job (duckling_events_backfill_job), so the top-up's in-flight count filters on this tag to# count its OWN queued runs — otherwise a burst of daily runs could zero out its slots._FULL_BACKFILL_RUN_TAG = {"duckling_backfill_type": "full"}+def _push_earliest_event_date_to_cp(bf: DuckgresServerTeam) -> None:+ """Mirror a freshly resolved earliest_event_date onto the team's duckgres control-plane row.++ Dual-write while per-team backfill state moves into the control plane: the Django row+ stays the sensor's read source. Best-effort — any failure (resolving the org, the CP+ call itself) is logged and swallowed so it can never 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++ managed_warehouse.push_team_earliest_event_date(bf.server.organization_id, bf.team_id, bf.earliest_event_date)+ except Exception:+ logger.exception("duckling_earliest_event_date_cp_push_failed", team_id=bf.team_id)++def _reconcile_events_backfill_statuses(context: SensorEvaluationContext, partition_keys: list[str]) -> None:"""Backfill the status projection for partitions that ran before it existed.@@ -3133,13 +3109,11 @@ def duckling_events_full_backfill_sensor(if lookups >= EVENTS_BACKFILL_MAX_EARLIEST_LOOKUPS_PER_TICK:breaklookups += 1- earliest_dt = get_earliest_event_date_for_team(bf.team_id)- if earliest_dt is None:- bf.earliest_event_date = _NO_HISTORY_SENTINEL+ bf.earliest_event_date = resolve_team_earliest_event_date(bf.team_id)+ if bf.earliest_event_date == NO_HISTORY_SENTINEL:context.log.info(f"No events for team_id={bf.team_id}; caching no-history sentinel")- else:- bf.earliest_event_date = max(earliest_dt, EARLIEST_BACKFILL_DATE).date()bf.save(update_fields=["earliest_event_date"])+ _push_earliest_event_date_to_cp(bf)# 2. Per-team remaining months (oldest first), skipping already-registered partitions.existing = set(context.instance.get_dynamic_partitions("duckling_events_backfill"))diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.pyindex fbedc0e8a3c9..547cb5121020 100644--- a/posthog/dags/test_events_backfill_to_duckling.py+++ b/posthog/dags/test_events_backfill_to_duckling.py@@ -14,7 +14,6 @@ from posthog.dags.events_backfill_to_duckling import (_DUCKLAKE_FILE_PARTITION_VALUE_FIXUP_ENV_VAR,DUCKLAKE_ALIAS,DUCKLING_BACKFILL_CONCURRENCY_TAG,- EARLIEST_BACKFILL_DATE,EVENTS_COLUMNS,EVENTS_CONCURRENCY_TAG,EVENTS_TABLE_DDL,@@ -60,6 +59,7 @@ from posthog.dags.events_backfill_to_duckling import (register_persons_files_with_duckling,table_exists,)+from posthog.ducklake.common import EARLIEST_BACKFILL_DATE, NO_HISTORY_SENTINELfrom products.data_warehouse.backend.facade.backfill_status import BackfillOutcome, get_months_in_range@@ -672,7 +672,7 @@ class TestFullBackfillSensorEarliestDate:("post-2015 unchanged", datetime(2020, 6, 15), "2020-06"),])- @patch("posthog.dags.events_backfill_to_duckling.get_earliest_event_date_for_team")+ @patch("posthog.ducklake.common.get_earliest_event_date_for_team")@patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam")@patch("posthog.dags.events_backfill_to_duckling.timezone")@patch("posthog.dags.events_backfill_to_duckling.stale_running_partitions", new=MagicMock(return_value=[]))@@ -709,7 +709,7 @@ class TestFullBackfillSensorEarliestDate:# Earliest date is cached on the row so later ticks never re-query ClickHouse.assert backfill.earliest_event_date == max(earliest_dt, datetime(2015, 1, 1)).date()- @patch("posthog.dags.events_backfill_to_duckling.get_earliest_event_date_for_team")+ @patch("posthog.ducklake.common.get_earliest_event_date_for_team")@patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam")@patch("posthog.dags.events_backfill_to_duckling.timezone")@patch("posthog.dags.events_backfill_to_duckling.stale_running_partitions", new=MagicMock(return_value=[]))@@ -732,9 +732,7 @@ class TestFullBackfillSensorEarliestDate:assert len(result.run_requests) == 0# No events → cache the sentinel so the team isn't re-queried every tick.- from posthog.dags.events_backfill_to_duckling import _NO_HISTORY_SENTINEL-- assert backfill.earliest_event_date == _NO_HISTORY_SENTINEL+ assert backfill.earliest_event_date == NO_HISTORY_SENTINELdef test_earliest_backfill_date_is_2015(self):assert EARLIEST_BACKFILL_DATE == datetime(2015, 1, 1)@@ -756,7 +754,7 @@ class TestFullBackfillSensorEarliestDate:patch("posthog.dags.events_backfill_to_duckling.ManagedWarehouseBackfillPartition") as mock_projection,patch("posthog.dags.events_backfill_to_duckling.record_backfill_outcome"),patch("posthog.dags.events_backfill_to_duckling.stale_running_partitions", return_value=[]),- patch("posthog.dags.events_backfill_to_duckling.get_earliest_event_date_for_team") as mock_ge,+ patch("posthog.ducklake.common.get_earliest_event_date_for_team") as mock_ge,):mock_tz.now.return_value = nowmock_cls.objects.filter.return_value.order_by.return_value = backfills@@ -873,7 +871,7 @@ class TestFullBackfillSensorEarliestDate:patch("posthog.dags.events_backfill_to_duckling.timezone") as mock_tz,patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam") as mock_cls,patch("posthog.dags.events_backfill_to_duckling.stale_running_partitions", return_value=[]),- patch("posthog.dags.events_backfill_to_duckling.get_earliest_event_date_for_team"),+ 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))]@@ -885,6 +883,37 @@ class TestFullBackfillSensorEarliestDate:runs_filter = mock_get_runs.call_args.kwargs["filters"]assert runs_filter.tags == {"duckling_backfill_type": "full"}+ @parameterized.expand(+ [+ ("resolved_date", datetime(2020, 6, 15), date(2020, 6, 15)),+ ("no_events_pushes_sentinel", None, NO_HISTORY_SENTINEL),+ ]+ )+ def test_pushes_freshly_resolved_earliest_date_to_control_plane(self, _name, earliest_dt, expected_pushed):+ # Dual-write: the resolved date (or the no-history sentinel) lands on the Django row+ # AND is mirrored onto the duckgres control-plane team row.+ backfill = self._bf(1)+ with patch(+ "products.data_warehouse.backend.presentation.views.managed_warehouse.push_team_earliest_event_date"+ ) as mock_push:+ self._run_full_sensor([backfill], now=datetime(2020, 8, 10, 12, 0, 0), get_earliest=earliest_dt)+ mock_push.assert_called_once_with(backfill.server.organization_id, 1, expected_pushed)++ def test_control_plane_push_failure_does_not_fail_tick(self):+ # The CP mirror is best-effort: a push blowing up must lose neither the Django+ # write nor the tick's run requests.+ backfill = self._bf(1)+ with patch(+ "products.data_warehouse.backend.presentation.views.managed_warehouse.push_team_earliest_event_date",+ side_effect=Exception("cp down"),+ ):+ result, _ = self._run_full_sensor(+ [backfill], now=datetime(2020, 8, 10, 12, 0, 0), get_earliest=datetime(2020, 6, 15)+ )+ assert backfill.earliest_event_date == date(2020, 6, 15)+ backfill.save.assert_called_once_with(update_fields=["earliest_event_date"])+ assert len(result.run_requests) > 0+class TestStaleRunOutcome:# A stuck-RUNNING row may only be resolved from a run that provably ended — resolving a livediff --git a/posthog/ducklake/common.py b/posthog/ducklake/common.pyindex 5a9aefd008b0..477867cc2e70 100644--- a/posthog/ducklake/common.py+++ b/posthog/ducklake/common.py@@ -19,14 +19,19 @@ from __future__ import annotationsimport osimport reimport logging+from datetime import date, datetimefrom typing import TYPE_CHECKING, TypedDictfrom uuid import UUIDimport duckdbimport psycopgfrom psycopg import sql+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_fixedif TYPE_CHECKING:+ from clickhouse_driver import Client++ from posthog.clickhouse.cluster import ClickhouseClusterfrom posthog.ducklake.models import DuckgresServerfrom products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema@@ -711,11 +716,100 @@ def get_team_backfill_state(team_id: int) -> dict[str, object]:return {"has_backfill": True, "table_suffix": backfill["table_suffix"]}+# Ignore events before this date — pre-2015 data is typically junk timestamps.+EARLIEST_BACKFILL_DATE = datetime(2015, 1, 1)++# Stored in DuckgresServerTeam.earliest_event_date (and mirrored to the duckgres control+# plane) for a team with no events, so callers cache "nothing to backfill" instead of+# re-querying ClickHouse. Far enough in the future that any generated backfill months+# range is always empty.+NO_HISTORY_SENTINEL = date(9999, 12, 31)+++@retry(+ stop=stop_after_attempt(3),+ wait=wait_fixed(5),+ retry=retry_if_exception_type((TimeoutError, OSError)),+ reraise=True,+)+def _get_clickhouse_cluster() -> ClickhouseCluster:+ """get_cluster() with retry for transient bootstrap timeouts.++ Retries the cluster discovery query only — does not affect subsequent per-host+ query execution, avoiding stacked retries with callers' own retry decorators.+ """+ # Deferred: this module stays importable without Django settings configured (see module+ # docstring); the cluster helpers pull posthog.settings in at import.+ from posthog.clickhouse.cluster import get_cluster # noqa: PLC0415++ return get_cluster()+++def get_earliest_event_date_for_team(team_id: int) -> datetime | None:+ """Query ClickHouse to find the earliest event date for a team.++ This is used to determine the historical range of data a duckling backfill covers+ (by the Dagster full-backfill sensor and the provisioning-time sync task).++ Returns:+ The date of the earliest event, or None if no events exist for this team.+ """+ # Deferred for the same Django-less-import reason as _get_clickhouse_cluster.+ from posthog.clickhouse.client.connection import NodeRole, Workload # noqa: PLC0415+ from posthog.cloud_utils import is_cloud # noqa: PLC0415++ cluster = _get_clickhouse_cluster()+ workload = Workload.OFFLINE if is_cloud() else Workload.DEFAULT++ def query_earliest(client: Client) -> datetime | None:+ # Filter timestamp >= '1970-01-01' to avoid toDate() overflow on pre-epoch timestamps.+ # ClickHouse's Date type is UInt16 (days since 1970-01-01), so negative timestamps+ # overflow to the max date (2149-06-06), breaking the backfill sensor logic.+ result = client.execute(+ """+ SELECT toDate(min(timestamp)) as earliest_date+ FROM events+ WHERE team_id = %(team_id)s+ AND timestamp >= '1970-01-01'+ """,+ {"team_id": team_id},+ )+ if result and result[0][0]:+ # ClickHouse returns a date object, convert to datetime+ date_val = result[0][0]+ if isinstance(date_val, datetime):+ return date_val+ return datetime.combine(date_val, datetime.min.time())+ return None++ return cluster.any_host_by_role(+ fn=query_earliest,+ workload=workload,+ node_role=NodeRole.DATA,+ ).result()+++def resolve_team_earliest_event_date(team_id: int) -> date:+ """Resolve the date a team's historical duckling backfill should start from.++ Clamps to EARLIEST_BACKFILL_DATE and returns NO_HISTORY_SENTINEL for a team with no+ events, so callers can cache the result and never re-query ClickHouse for the team.+ """+ earliest_dt = get_earliest_event_date_for_team(team_id)+ if earliest_dt is None:+ return NO_HISTORY_SENTINEL+ return max(earliest_dt, EARLIEST_BACKFILL_DATE).date()++__all__ = [+ "EARLIEST_BACKFILL_DATE",+ "NO_HISTORY_SENTINEL","DucklingBackfillEnableError","attach_catalog","check_team_backfill_enable","default_bucket_region",+ "get_earliest_event_date_for_team",+ "resolve_team_earliest_event_date","duckgres_data_imports_schema","duckgres_data_imports_table_name","duckgres_data_modeling_schema",diff --git a/products/data_warehouse/backend/facade/tasks.py b/products/data_warehouse/backend/facade/tasks.pyindex 722a84e5510d..75dd958e69bf 100644--- a/products/data_warehouse/backend/facade/tasks.py+++ b/products/data_warehouse/backend/facade/tasks.py@@ -7,6 +7,7 @@ Re-export of the beat-scheduled task that core registers (posthog/tasks/schedulefrom products.data_warehouse.backend.tasks import (reconcile_all_managed_warehouse_tables_task,send_external_data_failure_digest_catchup,+ sync_team_earliest_event_date,)from products.data_warehouse.backend.tasks.tasks import schedule_external_data_failure_digest@@ -14,4 +15,5 @@ __all__ = ["reconcile_all_managed_warehouse_tables_task","schedule_external_data_failure_digest","send_external_data_failure_digest_catchup",+ "sync_team_earliest_event_date",]diff --git a/products/data_warehouse/backend/presentation/views/managed_warehouse.py b/products/data_warehouse/backend/presentation/views/managed_warehouse.pyindex 11723d3f530c..1867bd18f714 100644--- a/products/data_warehouse/backend/presentation/views/managed_warehouse.py+++ b/products/data_warehouse/backend/presentation/views/managed_warehouse.py@@ -11,10 +11,12 @@ per organization (not per team)."""import re+from datetime import datefrom typing import TypedDict, castfrom uuid import UUIDfrom django.conf import settings+from django.db import transactionimport requests as http_requestsimport structlog@@ -358,6 +360,7 @@ def _register_provisioning_team(organization_id: UUID | str, team_id: int, schemtry:enable_team_backfill(team_id=team_id, organization_id=organization_id, table_name=schema_name)+ _schedule_earliest_event_date_sync(team_id)except Exception:logger.exception("Failed to register provisioning team after provision", team_id=team_id)@@ -444,6 +447,74 @@ def create_team(return _request("POST", organization_id, "/teams", json_body=body, require_enabled=require_enabled)+def update_team(+ organization_id: UUID | str,+ team_id: int,+ *,+ require_enabled: bool = True,+ **fields: object,+) -> Response:+ """Update fields on an existing duckgres team row via the admin PUT endpoint.++ Presence-aware on the duckgres side: only the fields present in the body change, so+ callers pass exactly what they want written (e.g. just ``earliest_event_date``).+ """+ return _request(+ "PUT", organization_id, f"/teams/{team_id}", json_body=dict(fields), require_enabled=require_enabled+ )+++def push_team_earliest_event_date(organization_id: UUID | str, team_id: int, earliest: date | None) -> bool:+ """Best-effort mirror of a team's cached earliest event date onto its duckgres team row.++ Part of the dual-write moving per-team backfill state into the control plane: the+ Django ``DuckgresServerTeam.earliest_event_date`` (including the no-history sentinel)+ stays the read source for now, so a failure here is logged and swallowed — a later+ push (the provisioning-time task or the full-backfill sensor) converges the CP row.+ Returns True when the control plane accepted the value.+ """+ if earliest is None:+ return False+ try:+ resp = update_team(organization_id, team_id, require_enabled=False, earliest_event_date=earliest.isoformat())+ except Exception:+ logger.exception(+ "Failed to push earliest event date to duckgres",+ organization_id=str(organization_id),+ team_id=team_id,+ )+ return False+ if not status.is_success(resp.status_code):+ logger.warning(+ "Duckgres rejected earliest event date push",+ organization_id=str(organization_id),+ team_id=team_id,+ status_code=resp.status_code,+ )+ return False+ return True+++def _schedule_earliest_event_date_sync(team_id: int) -> None:+ """Dispatch the earliest-event-date resolution task once the membership row commits.++ ``transaction.on_commit`` so the task never races a rollback of the row it reads (it+ runs immediately in autocommit). Best-effort: a dispatch failure is logged, not+ raised — the full-backfill sensor resolves the date lazily regardless.+ """+ # Keep the Celery task module (and its import graph) off the API import path; the+ # facade is the allowed boundary for presentation -> tasks.+ from products.data_warehouse.backend.facade.tasks import sync_team_earliest_event_date # noqa: PLC0415++ def dispatch() -> None:+ try:+ sync_team_earliest_event_date.delay(team_id)+ except Exception:+ logger.exception("Failed to schedule earliest event date sync", team_id=team_id)++ transaction.on_commit(dispatch)++def delete_team(organization_id: UUID | str, team_id: int, require_enabled: bool = True) -> Response:"""Delete a team row from the org's duckgres warehouse.@@ -501,6 +572,7 @@ def onboard_team(# duckgres upsert is idempotent, so a retry after the user picks another name is safe.return Response({"error": str(exc)}, status=status.HTTP_400_BAD_REQUEST)+ _schedule_earliest_event_date_sync(team_id)return Response({"onboarded": True, "schema_name": suffix}, status=status.HTTP_200_OK)diff --git a/products/data_warehouse/backend/tasks/__init__.py b/products/data_warehouse/backend/tasks/__init__.pyindex 9982e473bb54..4e09dc81bc1a 100644--- a/products/data_warehouse/backend/tasks/__init__.py+++ b/products/data_warehouse/backend/tasks/__init__.py@@ -5,4 +5,5 @@ from products.data_warehouse.backend.tasks.tasks import ( # noqa: F401schedule_managed_warehouse_tables_reconcile,send_external_data_failure_digest_catchup,send_external_data_failure_digest_task,+ sync_team_earliest_event_date,)diff --git a/products/data_warehouse/backend/tasks/tasks.py b/products/data_warehouse/backend/tasks/tasks.pyindex 9e4ca2c48cf7..91d8fbe8ddc0 100644--- a/products/data_warehouse/backend/tasks/tasks.py+++ b/products/data_warehouse/backend/tasks/tasks.py@@ -143,6 +143,37 @@ def send_external_data_failure_digest_task(team_id: int) -> None:logger.info("External data failure digest already in flight for team, skipping", team_id=team_id)+@shared_task(ignore_result=True, name="products.data_warehouse.backend.tasks.sync_team_earliest_event_date")+@skip_team_scope_audit # DuckgresServerTeam is on the default Django manager+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.+ 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.+ """+ # 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.models import DuckgresServerTeam # noqa: PLC0415++ from products.data_warehouse.backend.presentation.views.managed_warehouse import ( # noqa: PLC0415+ push_team_earliest_event_date,+ )++ bf = DuckgresServerTeam.objects.select_related("server").filter(team_id=team_id).first()+ if bf is 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)+ bf.save(update_fields=["earliest_event_date"])+ push_team_earliest_event_date(bf.server.organization_id, team_id, bf.earliest_event_date)++@shared_task(ignore_result=True, name="products.data_warehouse.backend.tasks.send_external_data_failure_digest_catchup")@skip_team_scope_auditdef send_external_data_failure_digest_catchup() -> None:diff --git a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py b/products/data_warehouse/backend/tests/api/test_managed_warehouse.pyindex 1a1084f3316f..a465906d8e22 100644--- a/products/data_warehouse/backend/tests/api/test_managed_warehouse.py+++ b/products/data_warehouse/backend/tests/api/test_managed_warehouse.py@@ -1077,3 +1077,65 @@ def test_block_team_deletion_lets_unonboarded_team_through_on_control_plane_erromock_delete.return_value = Response({"error": "unreachable"}, status=502)assert managed_warehouse.block_team_deletion(team.id, org.id) is None+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.internal_requests")+@override_settings(DUCKGRES_API_URL="http://duckgres.invalid", DUCKGRES_INTERNAL_SECRET="s")+def test_update_team_puts_only_passed_fields_to_org_team_route(mock_internal: MagicMock) -> None:+ # The earliest-event-date mirror uses the admin PUT: only the passed fields may appear+ # in the body, so the presence-aware CP update can't clobber schema/table names.+ org_id = uuid4()+ mock_internal.request.return_value = MagicMock(status_code=200, **{"json.return_value": {}})++ resp = managed_warehouse.update_team(org_id, 42, require_enabled=False, earliest_event_date="2020-06-15")++ assert resp.status_code == 200+ method, url = mock_internal.request.call_args.args+ assert method == "PUT"+ assert url == f"http://duckgres.invalid/api/v1/orgs/{org_id}/teams/42"+ assert mock_internal.request.call_args.kwargs["json"] == {"earliest_event_date": "2020-06-15"}+++@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse.is_enabled", return_value=True)+@patch("products.data_warehouse.backend.facade.tasks.sync_team_earliest_event_date")+def test_onboard_team_schedules_earliest_event_date_sync_after_commit(+ mock_task: MagicMock,+ _mock_enabled: MagicMock,+ mock_request: MagicMock,+ django_capture_on_commit_callbacks,+) -> None:+ # The resolve task must only fire once the DuckgresServerTeam row is committed,+ # or it could run against a rolled-back membership row.+ org, team, _ = _provisioned_org()+ mock_request.return_value = Response({"team_id": team.id, "schema_name": "my_events"}, status=200)++ with django_capture_on_commit_callbacks(execute=True) as callbacks:+ resp = managed_warehouse.onboard_team(org.id, team.id, "my_events")++ assert resp.status_code == 200+ assert len(callbacks) == 1+ mock_task.delay.assert_called_once_with(team.id)+++@override_settings(CLOUD_DEPLOYMENT="US", DUCKGRES_PG_PORT=5432)+@patch("products.data_warehouse.backend.presentation.views.managed_warehouse._request")+@patch("products.data_warehouse.backend.facade.tasks.sync_team_earliest_event_date")+def test_provision_schedules_earliest_event_date_sync_after_commit(+ mock_task: MagicMock,+ mock_request: MagicMock,+ django_capture_on_commit_callbacks,+) -> None:+ org = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=org)+ mock_request.return_value = Response(+ {"status": "provisioning started", "org": str(org.id), "username": "root", "password": "secret"},+ status=202,+ )++ with django_capture_on_commit_callbacks(execute=True):+ managed_warehouse.provision(org.id, "my-warehouse", team.id, "prod_events")++ mock_task.delay.assert_called_once_with(team.id)diff --git a/products/data_warehouse/backend/tests/test_tasks.py b/products/data_warehouse/backend/tests/test_tasks.pynew file mode 100644index 000000000000..312e0c5fcd9b--- /dev/null+++ b/products/data_warehouse/backend/tests/test_tasks.py@@ -0,0 +1,103 @@+from datetime import date, datetime++import pytest+from unittest.mock import MagicMock, patch++from parameterized import parameterized+from rest_framework.response import Response++from posthog.ducklake.models import DuckgresServer, DuckgresServerTeam+from posthog.models import Organization, Team++from products.data_warehouse.backend.tasks.tasks import sync_team_earliest_event_date+++def _onboarded_team(earliest: date | None = None) -> tuple[Organization, Team]:+ org = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=org)+ server = DuckgresServer.objects.create(+ organization=org, host="h", port=5432, database="ducklake", username="root", password="x"+ )+ DuckgresServerTeam.objects.create(server=server, team=team, table_suffix="env", earliest_event_date=earliest)+ return org, 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)),+ ]+)+@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_resolves_and_dual_writes(+ _name: str,+ earliest_dt: datetime | None,+ expected: date,+ 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.+ org, team = _onboarded_team()+ mock_get_earliest.return_value = earliest_dt+ mock_update.return_value = Response({}, status=200)++ sync_team_earliest_event_date(team.id)++ assert DuckgresServerTeam.objects.get(team=team).earliest_event_date == expected+ mock_update.assert_called_once_with(+ org.id, team.id, require_enabled=False, earliest_event_date=expected.isoformat()+ )+++@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_skips_clickhouse_when_date_already_cached(+ mock_get_earliest: MagicMock, mock_update: MagicMock+) -> None:+ # Idempotent re-runs (dispatch retries, re-onboards) must not re-query ClickHouse,+ # but still converge the control-plane row from the cached value.+ org, team = _onboarded_team(earliest=date(2019, 5, 1))+ mock_update.return_value = Response({}, status=200)++ sync_team_earliest_event_date(team.id)++ mock_get_earliest.assert_not_called()+ mock_update.assert_called_once_with(org.id, team.id, require_enabled=False, earliest_event_date="2019-05-01")+++@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_control_plane_failure_keeps_django_write(+ mock_get_earliest: MagicMock, mock_update: MagicMock+) -> None:+ # Best-effort CP side: a control-plane error must neither raise nor lose the Django+ # write — the sensor keeps reading the Django row either way.+ _, team = _onboarded_team()+ mock_get_earliest.return_value = datetime(2020, 6, 15)+ mock_update.return_value = Response({"error": "boom"}, status=502)++ sync_team_earliest_event_date(team.id)++ assert DuckgresServerTeam.objects.get(team=team).earliest_event_date == date(2020, 6, 15)+++@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_without_membership_row_is_a_noop(mock_get_earliest: MagicMock, mock_update: MagicMock) -> None:+ # A dispatch can race a deleted membership row — the task must skip quietly instead+ # of querying ClickHouse or pushing to the control plane for a de-onboarded team.+ org = Organization.objects.create(name="Org")+ team = Team.objects.create(organization=org)++ sync_team_earliest_event_date(team.id)++ mock_get_earliest.assert_not_called()+ mock_update.assert_not_called()