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): round-robin + bounded top-up for the duckling full backfill (#65746)

Benjamin Knofe-Videra680c4e23f72
diff --git a/posthog/admin/admins/ducklake_backfill_admin.py b/posthog/admin/admins/ducklake_backfill_admin.py
index 2bb23daf9073..233fd05c35ad 100644
--- a/posthog/admin/admins/ducklake_backfill_admin.py
+++ b/posthog/admin/admins/ducklake_backfill_admin.py
@@ -12,6 +12,7 @@ class DuckLakeBackfillAdmin(admin.ModelAdmin):
"team_id",
"enabled",
"table_suffix",
+ "earliest_event_date",
"created_by",
"created_at",
"updated_at",
@@ -21,9 +22,12 @@ class DuckLakeBackfillAdmin(admin.ModelAdmin):
# `table_suffix` is write-once: it names a team's warehouse tables/schema, so changing it after
# data is written moves the target and orphans the old tables. It's set only through the
# validated enable flow (`enable_team_backfill`), never edited here.
- readonly_fields = ("id", "table_suffix", "created_at", "updated_at")
+ # `earliest_event_date` is the sensor's cached backfill floor — shown for visibility but
+ # not hand-edited (the sensor owns it; it resolves+caches it from ClickHouse once). To
+ # force re-discovery, use the "Reset earliest_event_date" action rather than a free-form edit.
+ readonly_fields = ("id", "table_suffix", "earliest_event_date", "created_at", "updated_at")
raw_id_fields = ("team", "created_by")
- actions = ("make_enabled", "make_disabled")
+ actions = ("make_enabled", "make_disabled", "reset_earliest_event_date")
# Toggling `enabled` drives the duckling sensors into expensive ClickHouse->S3
# backfills, so it goes through Django's action-confirmation flow rather than an
@@ -38,6 +42,15 @@ class DuckLakeBackfillAdmin(admin.ModelAdmin):
updated = queryset.update(enabled=False)
self.message_user(request, f"Disabled warehouse backfills for {updated} team(s).")
+ # The field is read-only in the form (the sensor owns it), but a team that previously had
+ # no events — and so cached the no-history sentinel — needs a way to re-trigger discovery
+ # after a historical import. Clearing it makes the sensor re-query ClickHouse and re-derive
+ # the backfill range on its next tick.
+ @admin.action(description="Reset earliest_event_date (re-discover backfill range)")
+ def reset_earliest_event_date(self, request: HttpRequest, queryset: QuerySet[DuckLakeBackfill]) -> None:
+ updated = queryset.update(earliest_event_date=None)
+ self.message_user(request, f"Reset backfill range for {updated} team(s); the sensor will re-discover it.")
+
fieldsets = (
(
None,
diff --git a/posthog/dags/events_backfill_to_duckling.py b/posthog/dags/events_backfill_to_duckling.py
index 72d658410252..74b6bcb8eddb 100644
--- a/posthog/dags/events_backfill_to_duckling.py
+++ b/posthog/dags/events_backfill_to_duckling.py
@@ -30,7 +30,6 @@ Partition Strategy:
"""
import os
-import json
import math
import time
import calendar
@@ -2367,12 +2366,38 @@ def duckling_events_daily_backfill_sensor(
)
-# Number of monthly partitions to create per sensor tick (to avoid timeout)
+# Number of monthly partitions to create per sensor tick (to avoid timeout).
+# 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
+# ENQUEUES into that limit; they never widen ClickHouse load.
+#
+# Standing depth of the run queue the sensor keeps topped up. Bounded so Dagster never
+# holds thousands of QUEUED runs: with the concurrency limit draining a few at a time, a
+# shallow queue keeps every slot busy while staying small. Fairness across orgs comes from
+# round-robin selection, not from depth.
+EVENTS_BACKFILL_TARGET_QUEUE_DEPTH = 100
+# Hard cap on RunRequests emitted in one tick, bounding the tick's work (and its 60s eval
+# budget) even when filling the queue from empty.
+EVENTS_BACKFILL_MAX_PARTITIONS_PER_TICK = 100
+# Cap on per-team earliest-event ClickHouse lookups per tick. This is the only expensive
+# sensor op; it runs once per team ever, then the result is cached on the model row.
+EVENTS_BACKFILL_MAX_EARLIEST_LOOKUPS_PER_TICK = 5
+# Stored in DuckLakeBackfill.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 get_months_in_range(start_date: date, end_date: date) -> list[str]:
"""Generate list of month strings (YYYY-MM) between start and end dates."""
@@ -2393,147 +2418,133 @@ def get_months_in_range(start_date: date, end_date: date) -> list[str]:
@sensor(
name="duckling_events_full_backfill_sensor",
- minimum_interval_seconds=600, # Run every 10 minutes
+ minimum_interval_seconds=60, # Cheap now (no per-month ClickHouse query) — tick often to keep the queue fed
job_name="duckling_events_backfill_job",
default_status=DefaultSensorStatus.RUNNING,
)
def duckling_events_full_backfill_sensor(
context: SensorEvaluationContext,
) -> SensorResult:
- """Full historical backfill sensor - creates MONTHLY partitions for efficiency.
-
- Uses monthly partitions (YYYY-MM) instead of daily to reduce partition count.
- Each monthly partition processes all days in that month.
-
- Cursor format: {"team_id": X, "next_month": "YYYY-MM", "earliest": "YYYY-MM"}
-
- Each tick creates up to BACKFILL_MONTHS_PER_TICK partitions (default 3)
- to stay within the 60-second timeout limit.
-
- Manual trigger:
- To restart from scratch, reset the cursor in Dagster UI:
- Sensors -> duckling_events_full_backfill_sensor -> Reset cursor
+ """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.
+
+ Enqueue strategy, decoupled from execution (which the duckling_events_v1 concurrency
+ limit throttles to a handful of concurrent runs to protect ClickHouse):
+
+ * ``earliest_event_date`` is resolved from ClickHouse ONCE per team and cached on the
+ ``DuckLakeBackfill`` row (bounded to EVENTS_BACKFILL_MAX_EARLIEST_LOOKUPS_PER_TICK
+ lookups per tick), so the hot path issues no ClickHouse queries and an org's whole
+ history can be enqueued in a few quick ticks instead of dripping 3 months / 10 min.
+ * Candidate months are interleaved ROUND-ROBIN across all enabled teams (each team
+ advances one month per round), so the FIFO run queue drains fairly — no org waits
+ for another's entire history to finish first.
+ * The sensor tops the queue up to EVENTS_BACKFILL_TARGET_QUEUE_DEPTH (counting
+ in-flight runs) rather than dumping the whole backlog, so Dagster holds a small
+ bounded queue while the concurrency limit does the actual throttling.
+
+ Idempotent and cursor-free: already-registered partitions are skipped and ``run_key`` is
+ 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()
- # Parse cursor - tracks where we left off
- cursor_data: dict = {}
- if context.cursor:
- try:
- cursor_data = json.loads(context.cursor)
- except json.JSONDecodeError:
- cursor_data = {}
-
backfills = list(DuckLakeBackfill.objects.filter(enabled=True).order_by("team_id"))
if not backfills:
context.log.info("No enabled DuckLakeBackfill entries found")
return SensorResult(run_requests=[])
- # Find where to resume from
- resume_team_id = cursor_data.get("team_id")
- resume_month = cursor_data.get("next_month")
- cached_earliest = cursor_data.get("earliest")
-
- # Find the backfill entry to resume from (or start from first)
- start_idx = 0
- if resume_team_id:
- for i, bf in enumerate(backfills):
- if bf.team_id == resume_team_id:
- start_idx = i
- break
-
- new_partitions: list[str] = []
- run_requests: list[RunRequest] = []
- existing_partitions = set(context.instance.get_dynamic_partitions("duckling_events_backfill"))
-
- # Process backfills starting from where we left off
- for bf_idx, bf in enumerate(backfills[start_idx:], start=start_idx):
- if len(new_partitions) >= BACKFILL_MONTHS_PER_TICK:
- context.log.info(f"Batch limit reached, will continue from team {bf.team_id}")
+ # 1. Resolve + cache earliest_event_date for teams that don't have it yet. This is the
+ # only expensive op (one ClickHouse query/team), bounded per tick and cached forever.
+ lookups = 0
+ for bf in backfills:
+ if bf.earliest_event_date is not None:
+ continue
+ if lookups >= EVENTS_BACKFILL_MAX_EARLIEST_LOOKUPS_PER_TICK:
break
-
- team_id = bf.team_id
-
- # Determine start month - use cached value if resuming same team
- if team_id == resume_team_id and cached_earliest:
- earliest_month = cached_earliest
- current_month = resume_month if resume_month else earliest_month
+ lookups += 1
+ earliest_dt = get_earliest_event_date_for_team(bf.team_id)
+ if earliest_dt is None:
+ bf.earliest_event_date = _NO_HISTORY_SENTINEL
+ context.log.info(f"No events for team_id={bf.team_id}; caching no-history sentinel")
else:
- # Query ClickHouse for earliest date (only once per team)
- earliest_dt = get_earliest_event_date_for_team(team_id)
- if earliest_dt is None:
- context.log.info(f"No events found for team_id={team_id}, skipping")
- continue
- earliest_dt = max(earliest_dt, EARLIEST_BACKFILL_DATE)
- earliest_month = earliest_dt.strftime("%Y-%m")
- current_month = earliest_month
-
- # Generate monthly partitions for this team
- end_month = yesterday.strftime("%Y-%m")
- all_months = get_months_in_range(datetime.strptime(current_month, "%Y-%m").date(), yesterday)
-
- for month in all_months:
- if len(new_partitions) >= BACKFILL_MONTHS_PER_TICK:
- break
+ bf.earliest_event_date = max(earliest_dt, EARLIEST_BACKFILL_DATE).date()
+ bf.save(update_fields=["earliest_event_date"])
- partition_key = f"{team_id}_{month}"
- current_month = month
-
- # Skip partitions that already exist — advance cursor past them
- if partition_key in existing_partitions:
- continue
-
- new_partitions.append(partition_key)
- run_requests.append(
- RunRequest(
- partition_key=partition_key,
- )
- )
+ # 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]] = []
+ 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).
+ continue
+ keys = [f"{bf.team_id}_{m}" for m in get_months_in_range(earliest, yesterday)]
+ remaining = [k for k in keys if k not in existing]
+ if remaining:
+ per_team_remaining.append(remaining)
+
+ # 3. Round-robin interleave by month index: round r takes each team's r-th remaining
+ # month, so the queue order is team0-m0, team1-m0, ..., team0-m1, ... — fair under FIFO.
+ candidates: list[str] = []
+ round_idx = 0
+ while True:
+ added = False
+ for team_keys in per_team_remaining:
+ if round_idx < len(team_keys):
+ candidates.append(team_keys[round_idx])
+ added = True
+ if not added:
+ break
+ round_idx += 1
- # Update cursor for next tick
- # Move to next month after the last one we processed
- last_processed = datetime.strptime(current_month, "%Y-%m").date()
- if last_processed.month == 12:
- next_month_date = date(last_processed.year + 1, 1, 1)
- else:
- next_month_date = date(last_processed.year, last_processed.month + 1, 1)
- next_month = next_month_date.strftime("%Y-%m")
+ if not candidates:
+ context.log.debug("Full events backfill: nothing left to enqueue")
+ return SensorResult(run_requests=[])
- if next_month <= end_month:
- # More months to process for this team
- cursor_data = {
- "team_id": team_id,
- "next_month": next_month,
- "earliest": earliest_month,
- }
- else:
- # Done with this team, move to next
- next_idx = bf_idx + 1
- if next_idx < len(backfills):
- cursor_data = {"team_id": backfills[next_idx].team_id}
- else:
- # All teams done - reset cursor to check again tomorrow
- cursor_data = {"completed": timezone.now().date().isoformat()}
-
- # Check if we're in "completed" state and should skip until new data
- if cursor_data.get("completed") == timezone.now().date().isoformat() and not new_partitions:
- context.log.debug("Full backfill complete for today")
- return SensorResult(run_requests=[], cursor=json.dumps(cursor_data))
+ # 4. Bounded top-up: emit only enough to refill the queue to the target depth. The
+ # `limit` bounds the status query — we only need in-flight count vs. the target.
+ inflight = context.instance.get_runs(
+ filters=RunsFilter(
+ job_name="duckling_events_backfill_job",
+ tags=_FULL_BACKFILL_RUN_TAG, # count only full-backfill runs, not the shared-job daily runs
+ statuses=[
+ DagsterRunStatus.QUEUED,
+ DagsterRunStatus.NOT_STARTED,
+ DagsterRunStatus.STARTING,
+ DagsterRunStatus.STARTED,
+ ],
+ ),
+ limit=EVENTS_BACKFILL_TARGET_QUEUE_DEPTH + 1,
+ )
+ slots = max(0, EVENTS_BACKFILL_TARGET_QUEUE_DEPTH - len(inflight))
+ to_emit = candidates[: min(slots, EVENTS_BACKFILL_MAX_PARTITIONS_PER_TICK)]
- if new_partitions:
- context.log.info(f"Creating {len(new_partitions)} monthly partitions")
- logger.info(
- "duckling_full_backfill_batch",
- partition_count=len(new_partitions),
- cursor=cursor_data,
+ if not to_emit:
+ context.log.debug(
+ f"Full events backfill: queue at capacity ({len(inflight)}/{EVENTS_BACKFILL_TARGET_QUEUE_DEPTH}), "
+ f"{len(candidates)} still pending"
)
+ return SensorResult(run_requests=[])
+ # run_key = partition_key so a re-tick or restart can't double-launch the same month.
+ # The tag lets the next tick's in-flight count see these as full-backfill runs.
+ run_requests = [RunRequest(partition_key=k, run_key=k, tags=_FULL_BACKFILL_RUN_TAG) for k in to_emit]
+ context.log.info(
+ f"Enqueuing {len(to_emit)} monthly partition(s) across {len(per_team_remaining)} team(s); "
+ f"{len(inflight)} in flight, {len(candidates) - len(to_emit)} still pending"
+ )
+ logger.info(
+ "duckling_full_backfill_enqueue",
+ emitted=len(to_emit),
+ inflight=len(inflight),
+ pending=len(candidates) - len(to_emit),
+ teams_with_work=len(per_team_remaining),
+ )
return SensorResult(
run_requests=run_requests,
- dynamic_partitions_requests=[duckling_events_partitions_def.build_add_request(new_partitions)]
- if new_partitions
- else [],
- cursor=json.dumps(cursor_data),
+ dynamic_partitions_requests=[duckling_events_partitions_def.build_add_request(to_emit)],
)
diff --git a/posthog/dags/test_events_backfill_to_duckling.py b/posthog/dags/test_events_backfill_to_duckling.py
index 3a5e3a7004d5..915f58cda9af 100644
--- a/posthog/dags/test_events_backfill_to_duckling.py
+++ b/posthog/dags/test_events_backfill_to_duckling.py
@@ -678,6 +678,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]
instance = DagsterInstance.ephemeral()
@@ -689,6 +690,10 @@ class TestFullBackfillSensorEarliestDate:
assert len(result.run_requests) > 0
first_key = result.run_requests[0].partition_key
assert first_key == f"1_{expected_first_month}"
+ # Round-robin order is oldest-month-first for a single team.
+ assert result.run_requests[0].run_key == first_key
+ # 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.dags.events_backfill_to_duckling.DuckLakeBackfill")
@@ -701,6 +706,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]
instance = DagsterInstance.ephemeral()
@@ -710,10 +716,132 @@ class TestFullBackfillSensorEarliestDate:
assert result.run_requests is not None
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
def test_earliest_backfill_date_is_2015(self):
assert EARLIEST_BACKFILL_DATE == datetime(2015, 1, 1)
+ @staticmethod
+ def _bf(team_id: int, earliest=None):
+ m = MagicMock()
+ m.team_id = team_id
+ m.earliest_event_date = earliest
+ return m
+
+ def _run_full_sensor(self, backfills, *, now, get_earliest, existing=None, get_runs=None):
+ """Drive duckling_events_full_backfill_sensor against mocked backfills + an ephemeral instance."""
+ 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.DuckLakeBackfill") as mock_cls,
+ patch("posthog.dags.events_backfill_to_duckling.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
+ if isinstance(get_earliest, list):
+ mock_ge.side_effect = get_earliest
+ else:
+ mock_ge.return_value = get_earliest
+
+ 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):
+ result = duckling_events_full_backfill_sensor(context)
+ else:
+ result = duckling_events_full_backfill_sensor(context)
+ return result, mock_ge
+
+ 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.
+ 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"]
+ # 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_skips_existing_partitions(self):
+ result, _ = self._run_full_sensor(
+ [self._bf(1, earliest=date(2020, 1, 1))],
+ now=datetime(2020, 3, 10, 12, 0, 0),
+ get_earliest=None, # earliest already cached → no lookup
+ existing=["1_2020-01"],
+ )
+ 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"]
+
+ def test_does_not_requery_cached_earliest(self):
+ result, mock_ge = self._run_full_sensor(
+ [self._bf(1, earliest=date(2020, 1, 1))],
+ now=datetime(2020, 2, 10, 12, 0, 0),
+ get_earliest=None,
+ )
+ mock_ge.assert_not_called()
+ assert [rr.partition_key for rr in result.run_requests] == ["1_2020-01", "1_2020-02"]
+
+ def test_caps_earliest_lookups_per_tick(self):
+ # 7 unresolved teams, cap is 5 → only 5 ClickHouse lookups this tick; the other two
+ # stay unresolved and contribute no partitions until a later tick.
+ backfills = [self._bf(t) for t in range(1, 8)]
+ result, mock_ge = self._run_full_sensor(
+ backfills, now=datetime(2020, 2, 10, 12, 0, 0), get_earliest=datetime(2020, 1, 1)
+ )
+ assert mock_ge.call_count == 5
+ teams_emitted = {rr.partition_key.split("_")[0] for rr in result.run_requests}
+ assert teams_emitted == {"1", "2", "3", "4", "5"}
+ assert backfills[5].earliest_event_date is None and backfills[6].earliest_event_date is None
+
+ def test_top_up_only_fills_to_target_depth(self):
+ # 98 runs already in flight against the depth-100 target → only 2 slots free this tick.
+ result, _ = self._run_full_sensor(
+ [self._bf(1, earliest=date(2015, 1, 1))],
+ now=datetime(2020, 3, 10, 12, 0, 0),
+ get_earliest=None,
+ get_runs=[MagicMock()] * 98,
+ )
+ assert len(result.run_requests) == 2
+
+ def test_top_up_emits_nothing_when_queue_full(self):
+ result, _ = self._run_full_sensor(
+ [self._bf(1, earliest=date(2015, 1, 1))],
+ now=datetime(2020, 3, 10, 12, 0, 0),
+ get_earliest=None,
+ get_runs=[MagicMock()] * 100,
+ )
+ assert len(result.run_requests) == 0
+
+ def test_inflight_count_filters_by_full_backfill_tag(self):
+ # The in-flight query must be scoped to full-backfill runs via the tag, so daily
+ # runs on the shared job can't starve the top-up.
+ 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.DuckLakeBackfill") as mock_cls,
+ patch("posthog.dags.events_backfill_to_duckling.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))]
+ instance = DagsterInstance.ephemeral()
+ context = build_sensor_context(instance=instance)
+ with patch.object(instance, "get_runs", return_value=[]) as mock_get_runs:
+ duckling_events_full_backfill_sensor(context)
+
+ runs_filter = mock_get_runs.call_args.kwargs["filters"]
+ assert runs_filter.tags == {"duckling_backfill_type": "full"}
+
class TestGetClusterRetry:
@patch("tenacity.nap.time.sleep")
diff --git a/posthog/ducklake/models.py b/posthog/ducklake/models.py
index deab3edbd6d5..a1bec1bb31c9 100644
--- a/posthog/ducklake/models.py
+++ b/posthog/ducklake/models.py
@@ -152,6 +152,13 @@ class DuckLakeBackfill(CreatedMetaFields, UpdatedMetaFields, UUIDModel):
help_text="Suffix for this team's warehouse tables in the duckling (events_<suffix>, persons_<suffix>). "
"User-supplied; falls back to the shared tables when unset.",
)
+ earliest_event_date = models.DateField(
+ null=True,
+ blank=True,
+ help_text="Cached earliest event date (clamped to the backfill floor) used to size the historical "
+ "backfill range. Populated lazily by the full-backfill sensor so it never re-queries ClickHouse; "
+ "leave unset to have the sensor resolve and store it on its next tick.",
+ )
class Meta:
db_table = "posthog_ducklakebackfill"
diff --git a/posthog/migrations/1238_ducklakebackfill_earliest_event_date.py b/posthog/migrations/1238_ducklakebackfill_earliest_event_date.py
new file mode 100644
index 000000000000..bb6e2966d4ce
--- /dev/null
+++ b/posthog/migrations/1238_ducklakebackfill_earliest_event_date.py
@@ -0,0 +1,19 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [("posthog", "1237_alter_integration_kind")]
+
+ operations = [
+ migrations.AddField(
+ model_name="ducklakebackfill",
+ name="earliest_event_date",
+ field=models.DateField(
+ blank=True,
+ help_text="Cached earliest event date (clamped to the backfill floor) used to size the historical "
+ "backfill range. Populated lazily by the full-backfill sensor so it never re-queries ClickHouse; "
+ "leave unset to have the sensor resolve and store it on its next tick.",
+ null=True,
+ ),
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 14c58165441a..664ecbdbfbed 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1237_alter_integration_kind
+1238_ducklakebackfill_earliest_event_date