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(flags): stop the backfill from copying days the ttl has expired (#109599)

Phil Haack38d91de07486
diff --git a/posthog/dags/flag_evaluations_backfill.py b/posthog/dags/flag_evaluations_backfill.py
index ee9dc5e683d8..282a3a306a0c 100644
--- a/posthog/dags/flag_evaluations_backfill.py
+++ b/posthog/dags/flag_evaluations_backfill.py
@@ -82,10 +82,20 @@ WHERE policy.policy_name = (
"""
+# The TTL expires each row at the start of toDate(timestamp) + FLAG_EVALUATIONS_TTL_DAYS.
+# The day FLAG_EVALUATIONS_TTL_DAYS back has already expired when today starts.
+# A TTL merge can drop the rows copied for that day soon after the insert.
+_EARLIEST_START_DAYS_AGO = FLAG_EVALUATIONS_TTL_DAYS - 1
+
+
class FlagEvaluationsBackfillConfig(dagster.Config):
start_date: str | None = pydantic.Field(
default=None,
- description="First day to copy (YYYY-MM-DD, UTC, inclusive). Defaults to 90 days before today.",
+ description=(
+ f"First day to copy (YYYY-MM-DD, UTC, inclusive). Defaults to {_EARLIEST_START_DAYS_AGO} days "
+ "before today, which is also the earliest allowed value. A run copies the oldest days last. It "
+ "stops at the first day that the TTL has expired by the time the run reaches it."
+ ),
)
end_date: str | None = pydantic.Field(
default=None,
@@ -161,18 +171,25 @@ class DiskHeadroom:
below_move_line: bool
+@frozen
+class ShardBackfillTotals:
+ days: int
+ rows: int
+
+
+def earliest_backfill_day(today: date) -> date:
+ return today - timedelta(days=_EARLIEST_START_DAYS_AGO)
+
+
def resolve_backfill_days(config: FlagEvaluationsBackfillConfig, *, today: date) -> tuple[date, ...]:
latest_end = today - timedelta(days=1)
- start = (
- date.fromisoformat(config.start_date)
- if config.start_date
- else today - timedelta(days=FLAG_EVALUATIONS_TTL_DAYS)
- )
+ earliest_start = earliest_backfill_day(today)
+ start = date.fromisoformat(config.start_date) if config.start_date else earliest_start
end = date.fromisoformat(config.end_date) if config.end_date else latest_end
- earliest_start = today - timedelta(days=FLAG_EVALUATIONS_TTL_DAYS)
if start < earliest_start:
raise dagster.Failure(
- description=f"start_date {start} is before {earliest_start}. The TTL drops those rows as soon as they land."
+ description=f"start_date {start} is before {earliest_start}. "
+ f"The {FLAG_EVALUATIONS_TTL_DAYS}-day TTL has already expired those rows."
)
if end > latest_end:
raise dagster.Failure(description=f"end_date {end} is after yesterday ({latest_end}).")
@@ -255,7 +272,9 @@ class ShardBackfill:
sharded_events and sharded_flag_evaluations share a shard key, so the copy reads and writes
only this shard's local tables. The checks run before every day, not once at the start,
- because a run spans days and the weekly squash can start partway through.
+ because a run spans days. The weekly squash can start partway through, and the TTL can
+ expire a planned day before the run reaches it. Days run newest first, so the run stops at
+ the first expired day.
"""
cluster: ClickhouseCluster
@@ -268,7 +287,7 @@ class ShardBackfill:
workload: Workload
node_role: NodeRole
- def run(self, days: Sequence[date]) -> int:
+ def run(self, days: Sequence[date]) -> ShardBackfillTotals:
if not self.config.dry_run:
self.check_no_other_backfill_run()
copy_query = build_copy_query(
@@ -282,20 +301,37 @@ class ShardBackfill:
"max_insert_threads": self.config.max_insert_threads,
}
total_rows = 0
+ copied_days = 0
for day in days:
+ uncopied_days = len(days) - copied_days
+ if self._reached_expired_day(day, uncopied_days=uncopied_days):
+ break
self.wait_for_parts_to_merge(day)
blocking_run_check = self.wait_for_blocking_runs()
self.check_disk_headroom()
self.check_consumer_lag()
+ # The waits above have no shared deadline. The TTL boundary moves at UTC midnight.
+ if self._reached_expired_day(day, uncopied_days=uncopied_days):
+ break
try:
rows = self.copy_day(day, copy_query, settings)
finally:
if not self.config.dry_run:
self.check_no_blocking_run_started(blocking_run_check, day=day)
total_rows += rows
+ copied_days += 1
action = "would copy" if self.config.dry_run else "copied"
self.log.info(f"Shard {self.shard_num}, {day}: {action} {rows} row(s)")
- return total_rows
+ return ShardBackfillTotals(days=copied_days, rows=total_rows)
+
+ def _reached_expired_day(self, day: date, *, uncopied_days: int) -> bool:
+ if day >= earliest_backfill_day(datetime.now(UTC).date()):
+ return False
+ self.log.warning(
+ f"Shard {self.shard_num}: stopping at {day}, because the TTL has already expired it. "
+ f"{uncopied_days} planned day(s) are not copied."
+ )
+ return True
def wait_for_parts_to_merge(self, day: date) -> None:
if self.config.max_unmerged_parts <= 0:
@@ -477,7 +513,7 @@ def backfill_flag_evaluations_shard(
plan: BackfillPlan,
) -> int:
workload, node_role = (Workload.OFFLINE, NodeRole.DATA) if is_cloud() else (Workload.DEFAULT, NodeRole.ALL)
- total_rows = ShardBackfill(
+ totals = ShardBackfill(
cluster=cluster,
shard_num=shard_num,
config=plan.config,
@@ -491,12 +527,12 @@ def backfill_flag_evaluations_shard(
context.add_output_metadata(
{
"shard": dagster.MetadataValue.int(shard_num),
- "days": dagster.MetadataValue.int(len(plan.days)),
- "rows": dagster.MetadataValue.int(total_rows),
+ "days": dagster.MetadataValue.int(totals.days),
+ "rows": dagster.MetadataValue.int(totals.rows),
"dry_run": dagster.MetadataValue.bool(plan.config.dry_run),
}
)
- return total_rows
+ return totals.rows
@dagster.job(tags=OWNER_TAG)
diff --git a/posthog/dags/tests/test_flag_evaluations_backfill.py b/posthog/dags/tests/test_flag_evaluations_backfill.py
index a79d3bdba720..d7494677c154 100644
--- a/posthog/dags/tests/test_flag_evaluations_backfill.py
+++ b/posthog/dags/tests/test_flag_evaluations_backfill.py
@@ -8,6 +8,7 @@ from typing import Any
from uuid import NAMESPACE_URL, UUID, uuid5
import pytest
+import time_machine
from unittest.mock import MagicMock, patch
import dagster
@@ -23,6 +24,7 @@ from posthog.dags.flag_evaluations_backfill import (
FlagEvaluationsBackfillConfig,
PolicyDisk,
ShardBackfill,
+ ShardBackfillTotals,
disk_headroom,
flag_evaluations_backfill_job,
resolve_backfill_days,
@@ -251,6 +253,26 @@ def days_before(now: datetime, days: int) -> str:
return (now - timedelta(days=days)).date().isoformat()
+def shard_backfill(
+ config: FlagEvaluationsBackfillConfig | None = None,
+ *,
+ instance: dagster.DagsterInstance | None = None,
+ run_id: str = "backfill-run",
+) -> ShardBackfill:
+ # The cluster is a mock, so the default config turns off the parts wait, which queries it.
+ return ShardBackfill(
+ cluster=MagicMock(),
+ shard_num=1,
+ config=config or FlagEvaluationsBackfillConfig(max_unmerged_parts=0),
+ instance=instance or dagster.DagsterInstance.ephemeral(),
+ run_id=run_id,
+ log=MagicMock(),
+ query_tags=DagsterTags(),
+ workload=Workload.DEFAULT,
+ node_role=NodeRole.ALL,
+ )
+
+
@pytest.mark.django_db
@pytest.mark.parametrize(
"config_for, reported_rows, expected_copies",
@@ -371,17 +393,7 @@ def test_backfill_stops_when_a_blocking_run_starts_during_a_copy(
status: dagster.DagsterRunStatus, created_before_the_check: bool, team_ids: list[int] | None, repair: str | None
) -> None:
instance = dagster.DagsterInstance.ephemeral()
- backfill = ShardBackfill(
- cluster=MagicMock(),
- shard_num=1,
- config=FlagEvaluationsBackfillConfig(team_ids=team_ids),
- instance=instance,
- run_id="backfill-run",
- log=MagicMock(),
- query_tags=DagsterTags(),
- workload=Workload.DEFAULT,
- node_role=NodeRole.ALL,
- )
+ backfill = shard_backfill(FlagEvaluationsBackfillConfig(team_ids=team_ids), instance=instance)
if created_before_the_check:
instance.create_run_for_job(job_def=deletes_job, status=status)
check = backfill.wait_for_blocking_runs()
@@ -437,17 +449,8 @@ def test_backfill_stops_before_copying_when_another_backfill_run_is_executing(
) -> None:
instance = dagster.DagsterInstance.ephemeral()
other_run = instance.create_run_for_job(job_def=flag_evaluations_backfill_job, status=status)
- backfill = ShardBackfill(
- cluster=MagicMock(),
- shard_num=1,
- config=FlagEvaluationsBackfillConfig(max_unmerged_parts=0),
- instance=instance,
- run_id=other_run.run_id if same_run else "backfill-run",
- log=MagicMock(),
- query_tags=DagsterTags(),
- workload=Workload.DEFAULT,
- node_role=NodeRole.ALL,
- )
+ backfill = shard_backfill(instance=instance, run_id=other_run.run_id if same_run else "backfill-run")
+ yesterday = datetime.now(UTC).date() - timedelta(days=1)
with (
patch.object(ShardBackfill, "check_disk_headroom"),
@@ -456,13 +459,67 @@ def test_backfill_stops_before_copying_when_another_backfill_run_is_executing(
):
if stops:
with pytest.raises(dagster.Failure, match=other_run.run_id):
- backfill.run([date(2026, 3, 10)])
+ backfill.run([yesterday])
else:
- backfill.run([date(2026, 3, 10)])
+ backfill.run([yesterday])
assert copy_day.called is not stops
+# The earliest day the TTL keeps is 2025-12-11 on 2026-03-10, and 2025-12-12 on 2026-03-11.
+ "start, step, step_day, effect",
+ [
+ pytest.param(
+ datetime(2026, 3, 10, 23, tzinfo=UTC),
+ "copy_day",
+ date(2026, 3, 9),
+ "pass_midnight",
+ id="midnight_passes_during_the_previous_copy",
+ ),
+ pytest.param(
+ datetime(2026, 3, 10, 23, tzinfo=UTC),
+ "wait_for_parts_to_merge",
+ date(2025, 12, 11),
+ "pass_midnight",
+ id="midnight_passes_during_the_waits_before_the_copy",
+ ),
+ pytest.param(
+ datetime(2026, 3, 11, 1, tzinfo=UTC),
+ "wait_for_parts_to_merge",
+ date(2025, 12, 11),
+ "fail",
+ id="day_expired_before_its_waits",
+ ),
+ ],
+)
+def test_backfill_stops_at_the_first_expired_day(start: datetime, step: str, step_day: date, effect: str) -> None:
+ days = [date(2026, 3, 9), date(2025, 12, 12), date(2025, 12, 11)]
+
+ with time_machine.travel(start, tick=False) as traveller:
+
+ def patched(name: str) -> Callable[..., int]:
+ def run_step(day: date, *args: Any) -> int:
+ if (name, day) == (step, step_day):
+ if effect == "fail":
+ raise dagster.Failure(description=f"{name} failed for {day}")
+ traveller.shift(timedelta(hours=2))
+ return 5
+
+ return run_step
+
+ with (
+ patch.object(ShardBackfill, "wait_for_parts_to_merge", side_effect=patched("wait_for_parts_to_merge")),
+ patch.object(ShardBackfill, "check_disk_headroom"),
+ patch.object(ShardBackfill, "check_consumer_lag"),
+ patch.object(ShardBackfill, "copy_day", side_effect=patched("copy_day")) as copy_day,
+ ):
+ totals = shard_backfill().run(days)
+
+ assert [call.args[0] for call in copy_day.call_args_list] == days[:2]
+ assert totals == ShardBackfillTotals(days=2, rows=10)
+
+
@pytest.mark.django_db
@pytest.mark.parametrize(
"overrides, kafka_path_row_ages",
@@ -531,7 +588,7 @@ def test_disk_headroom_leaves_out_the_share_the_mover_keeps_free(
[
pytest.param({"end_date": "2026-03-10"}, id="end_date_after_yesterday"),
pytest.param({"start_date": "2026-03-01", "end_date": "2026-03-01"}, id="empty_window"),
- pytest.param({"start_date": "2025-12-09"}, id="start_date_past_the_ttl"),
+ pytest.param({"start_date": "2025-12-10"}, id="start_date_already_expired"),
],
)
def test_resolve_backfill_days_rejects_an_unsafe_window(overrides: dict[str, Any]) -> None:
@@ -545,7 +602,7 @@ def test_resolve_backfill_days_rejects_an_unsafe_window(overrides: dict[str, Any
pytest.param(
{"start_date": "2026-03-06", "end_date": "2026-03-09"}, date(2026, 3, 8), date(2026, 3, 6), 3, id="explicit"
),
- pytest.param({}, date(2026, 3, 8), date(2025, 12, 10), 89, id="default"),
+ pytest.param({}, date(2026, 3, 8), date(2025, 12, 11), 88, id="default"),
],
)
def test_resolve_backfill_days_lists_each_day_newest_first(