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): skip backfill rows whose fork row can still be in kafka (#111129)

Phil Haackbae5b055f1d0
diff --git a/posthog/dags/flag_evaluations_backfill.py b/posthog/dags/flag_evaluations_backfill.py
index 2b8fbcb93bdf..dbcfc4971f49 100644
--- a/posthog/dags/flag_evaluations_backfill.py
+++ b/posthog/dags/flag_evaluations_backfill.py
@@ -79,6 +79,12 @@ FROM (
)
"""
+# Ingestion's producer sets each message's Kafka create time when it calls produce.
+# librdkafka retries a failed produce until message.timeout.ms, which defaults to five minutes.
+# A retried row keeps the create time of its first attempt, so it can reach flag_evaluations after rows
+# with a later create time.
+_KAFKA_DELIVERY_TIMEOUT = timedelta(minutes=5)
+
_STORAGE_POLICY_DISKS_QUERY = f"""
SELECT policy.volume_priority, policy.move_factor, disk.free_space, disk.total_space
FROM system.storage_policies AS policy
@@ -110,7 +116,8 @@ class FlagEvaluationsBackfillConfig(dagster.Config):
default=None,
description=(
"Day after the last day to copy (YYYY-MM-DD, UTC, exclusive). Defaults to yesterday, which is also "
- "the latest allowed value: the Kafka path must have delivered every row before it."
+ "the latest allowed value. Every copied day therefore ended at least a day before the run. That gives "
+ "late Kafka rows a day to reach flag_evaluations, so the job does not copy their calls a second time."
),
)
team_ids: list[int] | None = pydantic.Field(
@@ -244,6 +251,10 @@ def build_copy_query(*, dry_run: bool, filter_team_ids: bool, chunked: bool) ->
if chunked:
team_filter += " AND modulo(team_id, %(team_id_chunks)s) = %(chunk)s"
# The eligibility filter is the ingestion fork's rule, in the form PARITY_CHECK.md uses.
+ # Ingestion queues a call's fork row before its events row, so the fork row's Kafka create time is never
+ # later than the events row's _timestamp. A source row whose _timestamp is at or after created_before can
+ # still have its fork row in Kafka. Copying it would store the call twice, so the job skips it. Kafka then
+ # delivers its fork row, or a later run copies it.
select = f"""
SELECT {"count()" if dry_run else _COPIED_COLUMNS}
FROM {EVENTS_DATA_TABLE()}
@@ -253,7 +264,8 @@ PREWHERE event = %(event)s
SELECT team_id, uuid FROM {FLAG_EVALUATIONS_DATA_TABLE}
WHERE timestamp >= %(day_start)s AND timestamp < %(day_end)s{team_filter}
)
-WHERE JSONType(properties, '$feature_flag') = 'String'
+WHERE _timestamp < %(created_before)s
+ AND JSONType(properties, '$feature_flag') = 'String'
AND JSONExtractString(properties, '$feature_flag') != ''
"""
if dry_run:
@@ -330,12 +342,12 @@ class ShardBackfill:
break
self.wait_for_parts_to_merge(day)
blocking_run_check = self._wait_for_disk_and_blocking_runs()
- self.check_consumer_lag()
+ created_before = self.consumer_cutoff()
# 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)
+ rows = self.copy_day(day, copy_query, settings, created_before)
finally:
if not self.config.dry_run:
self.check_no_blocking_run_started(blocking_run_check, day=day)
@@ -487,7 +499,13 @@ class ShardBackfill:
raise dagster.Failure(description=f"Stopping shard {self.shard_num}: " + "; ".join(problems))
return hosts_moving_parts
- def check_consumer_lag(self) -> None:
+ def consumer_cutoff(self) -> datetime:
+ """Stop the shard when the Kafka path to flag_evaluations is too far behind.
+
+ Otherwise return a cutoff such that flag_evaluations holds every fork row whose Kafka create time is
+ before it.
+ """
+ checked_at = datetime.now(UTC)
kafka_partitions, lag_seconds = self._on_copy_host(partial(self._first_row, _KAFKA_POSITION_QUERY))
if kafka_partitions == 0:
raise dagster.Failure(
@@ -500,12 +518,17 @@ class ShardBackfill:
f"over the limit of {self.config.max_consumer_lag_seconds}s. Copying now would insert rows "
"that Kafka then delivers a second time."
)
+ # A part can reach the copy host after newer parts, through a postponed replication fetch or a queued
+ # Distributed send. The anti-join reads only local parts. The cutoff therefore subtracts the whole lag
+ # limit rather than the measured lag, which leaves that much slack for a late part.
+ return checked_at - timedelta(seconds=self.config.max_consumer_lag_seconds) - _KAFKA_DELIVERY_TIMEOUT
- def copy_day(self, day: date, copy_query: str, settings: dict[str, Any]) -> int:
+ def copy_day(self, day: date, copy_query: str, settings: dict[str, Any], created_before: datetime) -> int:
day_args = {
"event": FLAG_EVALUATIONS_SOURCE_EVENT,
"day_start": f"{day:%Y-%m-%d} 00:00:00",
"day_end": f"{day + timedelta(days=1):%Y-%m-%d} 00:00:00",
+ "created_before": f"{created_before:%Y-%m-%d %H:%M:%S}",
"team_ids": tuple(self.config.team_ids or ()),
"team_id_chunks": self.config.team_id_chunks,
}
diff --git a/posthog/dags/tests/test_flag_evaluations_backfill.py b/posthog/dags/tests/test_flag_evaluations_backfill.py
index a1b00b31e22f..ae06269e0010 100644
--- a/posthog/dags/tests/test_flag_evaluations_backfill.py
+++ b/posthog/dags/tests/test_flag_evaluations_backfill.py
@@ -46,6 +46,8 @@ class SourceEvent:
age: timedelta
properties: Mapping[str, object]
event: str = FLAG_EVALUATIONS_SOURCE_EVENT
+ # The age of the row's Kafka create time (_timestamp), when that differs from the event's age.
+ kafka_time_age: timedelta | None = None
@property
def uuid(self) -> UUID:
@@ -92,14 +94,20 @@ def copied(event: SourceEvent) -> StoredRow:
INSIDE_RECENT = flag_called("inside_recent", TEAM_ONE, timedelta(days=2, hours=12))
INSIDE_TEAM_THREE = flag_called("inside_team_three", TEAM_THREE, timedelta(days=30))
-INSIDE_OLD = flag_called("inside_old", TEAM_TWO, timedelta(days=60))
+# The default one-hour lag limit and the five-minute delivery timeout put the cutoff 65 minutes before the check.
+# A row that ingestion produced two hours ago is older than the cutoff, so the job copies it.
+INSIDE_OLD = replace(flag_called("inside_old", TEAM_TWO, timedelta(days=60)), kafka_time_age=timedelta(hours=2))
ALREADY_FORKED = flag_called("already_forked", TEAM_ONE, timedelta(days=5))
+# An import dated inside the window that ingestion produced just before the consumer-lag check. Its fork row
+# can still be in Kafka, so the job does not copy it.
+IMPORTED_JUST_NOW = replace(flag_called("imported_just_now", TEAM_ONE, timedelta(days=4)), kafka_time_age=timedelta(0))
SOURCE_EVENTS = [
INSIDE_RECENT,
INSIDE_TEAM_THREE,
INSIDE_OLD,
ALREADY_FORKED,
+ IMPORTED_JUST_NOW,
SourceEvent(
label="numeric_flag_key",
team_id=TEAM_ONE,
@@ -168,6 +176,7 @@ def seed_source_events(cluster: ClickhouseCluster, now: datetime, events: list[S
event.distinct_id,
now - event.age,
uuid5(NAMESPACE_URL, event.distinct_id),
+ now - (event.age if event.kafka_time_age is None else event.kafka_time_age),
)
for event in events
]
@@ -175,7 +184,7 @@ def seed_source_events(cluster: ClickhouseCluster, now: datetime, events: list[S
def insert(client: Client) -> None:
client.execute(
f"""INSERT INTO {EVENTS_DATA_TABLE()}
- (uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id)
+ (uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id, _timestamp)
VALUES""",
rows,
)
@@ -486,7 +495,7 @@ def test_backfill_stops_before_copying_when_another_backfill_run_is_executing(
with (
patch.object(ShardBackfill, "_hosts_moving_parts", return_value=[]),
- patch.object(ShardBackfill, "check_consumer_lag"),
+ patch.object(ShardBackfill, "consumer_cutoff"),
patch.object(ShardBackfill, "copy_day", return_value=0) as copy_day,
):
if stops:
@@ -520,7 +529,7 @@ def test_backfill_ignores_a_blocking_run_that_finished_while_it_waited_for_disk(
with (
patch.object(ShardBackfill, "wait_for_disk_headroom", side_effect=finish_a_deletes_run),
patch.object(ShardBackfill, "_hosts_moving_parts", side_effect=rereads),
- patch.object(ShardBackfill, "check_consumer_lag"),
+ patch.object(ShardBackfill, "consumer_cutoff"),
patch.object(ShardBackfill, "copy_day", return_value=5),
):
totals = shard_backfill(instance=instance).run([datetime.now(UTC).date() - timedelta(days=1)])
@@ -573,7 +582,7 @@ def test_backfill_stops_at_the_first_expired_day(start: datetime, step: str, ste
with (
patch.object(ShardBackfill, "wait_for_parts_to_merge", side_effect=patched("wait_for_parts_to_merge")),
patch.object(ShardBackfill, "_hosts_moving_parts", return_value=[]),
- patch.object(ShardBackfill, "check_consumer_lag"),
+ patch.object(ShardBackfill, "consumer_cutoff"),
patch.object(ShardBackfill, "copy_day", side_effect=patched("copy_day")) as copy_day,
):
totals = shard_backfill().run(days)
@@ -624,6 +633,17 @@ def test_backfill_fails_without_copying_when_a_safety_check_fails(
assert stored_rows(cluster) == Counter()
+def test_consumer_cutoff_sits_the_lag_limit_and_the_delivery_timeout_before_the_check() -> None:
+ cluster = MagicMock()
+ cluster.map_any_host_in_shards_by_role.return_value.result.return_value = {1: (2, 30)}
+ backfill = shard_backfill(FlagEvaluationsBackfillConfig(max_consumer_lag_seconds=600), cluster=cluster)
+
+ with time_machine.travel(datetime(2026, 3, 10, 12, tzinfo=UTC), tick=False):
+ created_before = backfill.consumer_cutoff()
+
+ assert created_before == datetime(2026, 3, 10, 11, 45, tzinfo=UTC)
+
+
BELOW_MOVE_LINE = [
PolicyDisk(volume_priority=1, move_factor=0.1, free_bytes=50, total_bytes=1000),
PolicyDisk(volume_priority=2, move_factor=0.1, free_bytes=5000, total_bytes=8000),
@@ -722,7 +742,7 @@ def test_backfill_waits_while_clickhouse_moves_parts_off_a_full_disk(
with (
patch("posthog.dags.flag_evaluations_backfill.time.monotonic", side_effect=lambda: clock[0]),
patch("posthog.dags.flag_evaluations_backfill.time.sleep", side_effect=advance_clock) as sleep,
- patch.object(ShardBackfill, "check_consumer_lag"),
+ patch.object(ShardBackfill, "consumer_cutoff"),
patch.object(ShardBackfill, "copy_day", return_value=5) as copy_day,
):
if failure is None: