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(managed-warehouse): stop full-backfill from re-running the current month (#68273)

James Greenhill35fddac40f42
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.py
index abcc6207fe0d..7172172d6d26 100644
--- a/posthog/dags/events_backfill_to_duckling.py
+++ b/posthog/dags/events_backfill_to_duckling.py
@@ -2704,6 +2704,14 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
session.close()
+# Cap on current-month CATCH-UP partitions (every day older than yesterday) emitted in one
+# tick. Yesterday is always emitted on top of this so freshness never starves; the cap only
+# bounds the backlog a burst of newly enabled teams can create, which then drains over the
+# following hourly ticks. Execution is throttled independently by the duckling_events_v1
+# concurrency limit, so this only bounds sensor-eval work and Dagster queue depth.
+DAILY_BACKFILL_MAX_CATCHUP_PARTITIONS_PER_TICK = 1000
+
+
@sensor(
name="duckling_events_daily_backfill_sensor",
minimum_interval_seconds=3600, # Run hourly
@@ -2712,73 +2720,106 @@ def duckling_persons_backfill(context: AssetExecutionContext, config: DucklingBa
def duckling_events_daily_backfill_sensor(
context: SensorEvaluationContext,
) -> SensorResult:
- """Discover teams with backfills enabled (DuckgresServerTeam) and create daily backfill partitions.
-
- This sensor runs periodically to:
- 1. Find all teams with backfills enabled (DuckgresServerTeam)
- 2. Create partitions for yesterday's data (if not already exists)
- 3. Trigger backfill runs for new partitions
- 4. Retry failed partitions that already exist
+ """Discover teams with backfills enabled (DuckgresServerTeam) and keep the current month's
+ daily backfill partitions filled.
+
+ This sensor owns the CURRENT month; the full-backfill sensor owns every complete prior
+ month. The two are disjoint by day, so they never write the same team-day (which is what
+ used to make the current-month monthly partition race the daily runs).
+
+ Each tick it, per enabled team:
+ 1. Creates a daily partition for every day from the 1st of the current month through
+ yesterday that doesn't exist yet. In steady state only yesterday is new; for a team
+ enabled partway through the month this catches up the earlier days the full-backfill
+ sensor won't touch, closing the gap between its history and daily coverage. Yesterday
+ is always emitted; the older catch-up days are bounded per tick
+ (DAILY_BACKFILL_MAX_CATCHUP_PARTITIONS_PER_TICK) so a burst of newly enabled teams
+ can't flood one tick — the remainder drains over the following ticks.
+ 2. Retries yesterday's partition if its last run failed (bounding the per-tick run lookup
+ to one query per team — older caught-up days are left as-is once they've run).
+
+ On the 1st of the month there are no current-month days on or before yesterday, so the
+ sensor is a no-op; yesterday (last month's final day) is covered by last month's now-complete
+ monthly partition from the full-backfill sensor.
"""
- yesterday = (timezone.now() - timedelta(days=1)).strftime("%Y-%m-%d")
+ today = timezone.now().date()
+ yesterday_date = today - timedelta(days=1)
+ first_of_month = today.replace(day=1)
+
+ # Current-month days up to yesterday (empty on the 1st — see docstring).
+ current_month_dates: list[date] = []
+ day = first_of_month
+ while day <= yesterday_date:
+ current_month_dates.append(day)
+ day += timedelta(days=1)
# Get existing partitions
existing = set(context.instance.get_dynamic_partitions("duckling_events_backfill"))
new_partitions: list[str] = []
run_requests: list[RunRequest] = []
+ catchup_emitted = 0 # older-than-yesterday days created this tick, bounded below
for backfill in DuckgresServerTeam.objects.filter(backfill_enabled=True):
- partition_key = f"{backfill.team_id}_{yesterday}"
-
- if partition_key not in existing:
- # New partition - create and trigger run
- new_partitions.append(partition_key)
- run_requests.append(
- RunRequest(
- partition_key=partition_key,
- run_key=f"{partition_key}_new",
+ for partition_date in current_month_dates:
+ date_str = partition_date.strftime("%Y-%m-%d")
+ partition_key = f"{backfill.team_id}_{date_str}"
+ is_yesterday = partition_date == yesterday_date
+
+ if partition_key not in existing:
+ # Yesterday is always emitted (freshness); older catch-up days are bounded per
+ # tick so a burst of newly enabled teams can't emit tens of thousands of run
+ # requests at once — the remainder drains over subsequent hourly ticks.
+ if not is_yesterday and catchup_emitted >= DAILY_BACKFILL_MAX_CATCHUP_PARTITIONS_PER_TICK:
+ continue
+ new_partitions.append(partition_key)
+ run_requests.append(
+ RunRequest(
+ partition_key=partition_key,
+ run_key=f"{partition_key}_new",
+ )
)
- )
- context.log.info(f"Creating partition for team_id={backfill.team_id}, date={yesterday}")
- else:
- # Existing partition - check if the last run failed and needs retry
- # Query for runs with this partition key (stored in dagster/partition tag)
- runs = context.instance.get_runs(
- filters=RunsFilter(
- job_name="duckling_events_backfill_job",
- tags={"dagster/partition": partition_key},
- ),
- limit=1,
- )
- if runs:
- latest_run = runs[0]
- # Only retry if failed - skip if in progress or succeeded
- if latest_run.status == DagsterRunStatus.FAILURE:
- # Failed run - trigger retry with unique run_key
- run_requests.append(
- RunRequest(
- partition_key=partition_key,
- run_key=f"{partition_key}_retry_{latest_run.run_id[:8]}",
+ if not is_yesterday:
+ catchup_emitted += 1
+ context.log.info(f"Creating partition for team_id={backfill.team_id}, date={date_str}")
+ elif is_yesterday:
+ # Existing freshest partition - check if the last run failed and needs retry.
+ # Only yesterday is retried, so the run lookup stays at one query per team.
+ runs = context.instance.get_runs(
+ filters=RunsFilter(
+ job_name="duckling_events_backfill_job",
+ tags={"dagster/partition": partition_key},
+ ),
+ limit=1,
+ )
+ if runs:
+ latest_run = runs[0]
+ # Only retry if failed - skip if in progress or succeeded
+ if latest_run.status == DagsterRunStatus.FAILURE:
+ # Failed run - trigger retry with unique run_key
+ run_requests.append(
+ RunRequest(
+ partition_key=partition_key,
+ run_key=f"{partition_key}_retry_{latest_run.run_id[:8]}",
+ )
+ )
+ context.log.info(
+ f"Retrying failed partition team_id={backfill.team_id}, date={date_str} "
+ f"(previous run: {latest_run.run_id[:8]})"
+ )
+ logger.info(
+ "duckling_sensor_retry_failed_partition",
+ team_id=backfill.team_id,
+ date=date_str,
+ previous_run_id=latest_run.run_id,
+ )
+ elif latest_run.status in (
+ DagsterRunStatus.STARTED,
+ DagsterRunStatus.QUEUED,
+ ):
+ context.log.debug(
+ f"Skipping partition team_id={backfill.team_id}, date={date_str} - run in progress"
)
- )
- context.log.info(
- f"Retrying failed partition team_id={backfill.team_id}, date={yesterday} "
- f"(previous run: {latest_run.run_id[:8]})"
- )
- logger.info(
- "duckling_sensor_retry_failed_partition",
- team_id=backfill.team_id,
- date=yesterday,
- previous_run_id=latest_run.run_id,
- )
- elif latest_run.status in (
- DagsterRunStatus.STARTED,
- DagsterRunStatus.QUEUED,
- ):
- context.log.debug(
- f"Skipping partition team_id={backfill.team_id}, date={yesterday} - run in progress"
- )
if new_partitions:
context.log.info(f"Discovered {len(new_partitions)} new partitions to backfill")
@@ -2866,7 +2907,9 @@ def duckling_events_full_backfill_sensor(
"""Full historical events backfill — monthly partitions, enqueued round-robin under a bounded queue.
Monthly partitions (``{team_id}_{YYYY-MM}``) keep the partition count down; each one
- backfills all days in its month.
+ backfills all days in its month. Only COMPLETE historical months are enqueued — the
+ current, in-progress month is left to the daily backfill sensor, so a team whose earliest
+ event is only in the current month gets no full-backfill partition at all.
Enqueue strategy, decoupled from execution (which the duckling_events_v1 concurrency
limit throttles to a handful of concurrent runs to protect ClickHouse):
@@ -2886,7 +2929,13 @@ def duckling_events_full_backfill_sensor(
the partition key, so re-ticks and restarts never double-enqueue. Any cursor written by
the previous serial implementation is simply ignored (safe rollback either way).
"""
- yesterday = (timezone.now() - timedelta(days=1)).date()
+ # Full backfill covers only COMPLETE historical months, up to the end of last month. The
+ # current, in-progress month is owned by the daily backfill sensor (which fills it in
+ # day-by-day), so emitting a whole-month partition for it is redundant — it re-DELETEs and
+ # re-registers exactly the days the daily runs are handling, racing them under DuckLake's
+ # per-table OCC (that conflict is why the current-month monthly partition goes red while the
+ # daily partitions succeed).
+ last_month_end = timezone.now().date().replace(day=1) - timedelta(days=1)
backfills = list(DuckgresServerTeam.objects.filter(backfill_enabled=True).order_by("team_id"))
if not backfills:
@@ -2915,10 +2964,12 @@ def duckling_events_full_backfill_sensor(
per_team_remaining: list[list[str]] = []
for bf in backfills:
earliest = bf.earliest_event_date
- if earliest is None or earliest > yesterday:
- # Unresolved this tick, or no-history sentinel / brand-new team (nothing historical yet).
+ if earliest is None or earliest > last_month_end:
+ # Unresolved this tick, no-history sentinel, or a team whose earliest event is only
+ # in the current month — no complete month to full-backfill (the daily sensor owns
+ # the current month), so skip it.
continue
- keys = [f"{bf.team_id}_{m}" for m in get_months_in_range(earliest, yesterday)]
+ keys = [f"{bf.team_id}_{m}" for m in get_months_in_range(earliest, last_month_end)]
remaining = [k for k in keys if k not in existing]
if remaining:
per_team_remaining.append(remaining)
diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.py
index 922ec3326b36..f90c37addd3c 100644
--- a/posthog/dags/test_events_backfill_to_duckling.py
+++ b/posthog/dags/test_events_backfill_to_duckling.py
@@ -45,6 +45,7 @@ from posthog.dags.events_backfill_to_duckling import (
_validate_identifier,
delete_events_partition_data,
duckling_events_backfill_job,
+ duckling_events_daily_backfill_sensor,
duckling_events_full_backfill_sensor,
duckling_persons_backfill_job,
export_events_to_duckling_s3,
@@ -772,15 +773,38 @@ class TestFullBackfillSensorEarliestDate:
def test_round_robin_interleaves_teams(self):
# Two teams with the same range → emission alternates team by month index, so the
# FIFO queue drains both fairly rather than finishing team 1's whole history first.
+ # The current month (2020-03) is excluded — it's the daily sensor's job.
backfills = [self._bf(1), self._bf(2)]
result, _ = self._run_full_sensor(
backfills, now=datetime(2020, 3, 10, 12, 0, 0), get_earliest=datetime(2020, 1, 1)
)
keys = [rr.partition_key for rr in result.run_requests]
- assert keys == ["1_2020-01", "2_2020-01", "1_2020-02", "2_2020-02", "1_2020-03", "2_2020-03"]
+ assert keys == ["1_2020-01", "2_2020-01", "1_2020-02", "2_2020-02"]
# Every full-backfill run is tagged so the next tick's in-flight count excludes daily runs.
assert all(rr.tags.get("duckling_backfill_type") == "full" for rr in result.run_requests)
+ def test_excludes_current_in_progress_month(self):
+ # The full backfill stops at the end of last month; the current, in-progress month
+ # (2020-03) is owned by the daily sensor and must never be emitted as a monthly
+ # partition (it would race the daily runs for the same team-days).
+ result, _ = self._run_full_sensor(
+ [self._bf(1, earliest=date(2020, 1, 1))],
+ now=datetime(2020, 3, 10, 12, 0, 0),
+ get_earliest=None,
+ )
+ keys = [rr.partition_key for rr in result.run_requests]
+ assert keys == ["1_2020-01", "1_2020-02"]
+
+ def test_team_with_only_current_month_history_gets_nothing(self):
+ # A team whose earliest event is in the current month has no complete month to
+ # full-backfill, so the sensor emits nothing for it — the daily sensor covers it.
+ result, _ = self._run_full_sensor(
+ [self._bf(1, earliest=date(2020, 3, 2))],
+ now=datetime(2020, 3, 10, 12, 0, 0),
+ get_earliest=None,
+ )
+ assert result.run_requests == []
+
def test_skips_existing_partitions(self):
result, _ = self._run_full_sensor(
[self._bf(1, earliest=date(2020, 1, 1))],
@@ -790,7 +814,7 @@ class TestFullBackfillSensorEarliestDate:
)
keys = [rr.partition_key for rr in result.run_requests]
assert "1_2020-01" not in keys
- assert keys == ["1_2020-02", "1_2020-03"]
+ assert keys == ["1_2020-02"]
def test_does_not_requery_cached_earliest(self):
result, mock_ge = self._run_full_sensor(
@@ -799,7 +823,7 @@ class TestFullBackfillSensorEarliestDate:
get_earliest=None,
)
mock_ge.assert_not_called()
- assert [rr.partition_key for rr in result.run_requests] == ["1_2020-01", "1_2020-02"]
+ assert [rr.partition_key for rr in result.run_requests] == ["1_2020-01"]
def test_caps_earliest_lookups_per_tick(self):
# 7 unresolved teams, cap is 5 → only 5 ClickHouse lookups this tick; the other two
@@ -853,6 +877,105 @@ class TestFullBackfillSensorEarliestDate:
assert runs_filter.tags == {"duckling_backfill_type": "full"}
+class TestDailyBackfillSensor:
+ @staticmethod
+ def _team(team_id: int):
+ m = MagicMock()
+ m.team_id = team_id
+ return m
+
+ @staticmethod
+ def _daily_keys(team_id: int, start: date, end: date) -> list[str]:
+ # Build expected partition keys the same way prod does (strftime), so a formatting bug
+ # (e.g. a hand-rolled zero-pad that breaks on two-digit days) would be caught.
+ keys = []
+ d = start
+ while d <= end:
+ keys.append(f"{team_id}_{d.strftime('%Y-%m-%d')}")
+ d += timedelta(days=1)
+ return keys
+
+ def _run_daily(self, backfills, *, now, existing=None, get_runs=None):
+ from dagster import DagsterInstance, build_sensor_context
+
+ with (
+ patch("posthog.dags.events_backfill_to_duckling.timezone") as mock_tz,
+ patch("posthog.dags.events_backfill_to_duckling.DuckgresServerTeam") as mock_cls,
+ ):
+ mock_tz.now.return_value = now
+ mock_cls.objects.filter.return_value = backfills
+
+ instance = DagsterInstance.ephemeral()
+ if existing:
+ instance.add_dynamic_partitions("duckling_events_backfill", list(existing))
+
+ context = build_sensor_context(instance=instance)
+ if get_runs is not None:
+ with patch.object(instance, "get_runs", return_value=get_runs):
+ return duckling_events_daily_backfill_sensor(context)
+ return duckling_events_daily_backfill_sensor(context)
+
+ def test_steady_state_creates_only_yesterday(self):
+ # Established team already has every current-month day except yesterday → only
+ # yesterday (2020-03-09) is new, matching the pre-catch-up behavior.
+ existing = [f"1_2020-03-0{d}" for d in range(1, 9)] # 2020-03-01 .. 2020-03-08
+ result = self._run_daily([self._team(1)], now=datetime(2020, 3, 10, 12, 0, 0), existing=existing)
+ assert [rr.partition_key for rr in result.run_requests] == ["1_2020-03-09"]
+
+ def test_catches_up_current_month_for_newly_enabled_team(self):
+ # A team with no existing partitions (just enabled) gets every current-month day from
+ # the 1st through yesterday, closing the gap the full-backfill sensor won't cover.
+ # now=the 15th so the range crosses the single/two-digit day boundary (01..14).
+ result = self._run_daily([self._team(1)], now=datetime(2020, 3, 15, 12, 0, 0))
+ keys = [rr.partition_key for rr in result.run_requests]
+ assert keys == self._daily_keys(1, date(2020, 3, 1), date(2020, 3, 14))
+
+ def test_first_of_month_is_noop(self):
+ # On the 1st, yesterday is in the previous month (owned by that month's now-complete
+ # full-backfill partition), so the daily sensor creates nothing.
+ result = self._run_daily([self._team(1)], now=datetime(2020, 3, 1, 12, 0, 0))
+ assert result.run_requests == []
+
+ def test_retries_only_yesterday_not_older_days(self):
+ # All current-month days already exist and their last run failed, but only yesterday
+ # (2020-03-09) is retried — older caught-up days are left alone, keeping the per-tick
+ # run lookup to one query per team.
+ from dagster import DagsterRunStatus
+
+ existing = [f"1_2020-03-0{d}" for d in range(1, 10)] # 2020-03-01 .. 2020-03-09
+ failed = MagicMock()
+ failed.status = DagsterRunStatus.FAILURE
+ failed.run_id = "deadbeefcafef00d"
+ result = self._run_daily(
+ [self._team(1)], now=datetime(2020, 3, 10, 12, 0, 0), existing=existing, get_runs=[failed]
+ )
+ keys = [rr.partition_key for rr in result.run_requests]
+ assert keys == ["1_2020-03-09"]
+ assert result.run_requests[0].run_key == "1_2020-03-09_retry_deadbeef"
+
+ def test_catchup_is_bounded_per_tick_but_yesterday_always_emitted(self):
+ # With the catch-up cap at 3 and two freshly enabled teams on 2020-03-05 (older days
+ # 01/02/03, yesterday 04): the first team exhausts the cap with its three older days,
+ # the second team's older days are dropped this tick, but BOTH teams still get
+ # yesterday so freshness never starves behind the backlog.
+ with patch(
+ "posthog.dags.events_backfill_to_duckling.DAILY_BACKFILL_MAX_CATCHUP_PARTITIONS_PER_TICK",
+ 3,
+ ):
+ result = self._run_daily(
+ [self._team(1), self._team(2)],
+ now=datetime(2020, 3, 5, 12, 0, 0),
+ )
+ keys = [rr.partition_key for rr in result.run_requests]
+ assert keys == [
+ "1_2020-03-01",
+ "1_2020-03-02",
+ "1_2020-03-03",
+ "1_2020-03-04",
+ "2_2020-03-04",
+ ]
+
+
class TestGetClusterRetry:
@patch("tenacity.nap.time.sleep")
@patch("posthog.dags.events_backfill_to_duckling.get_cluster")