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): match only copied rows in the backfill cleanup delete (#111169)

Phil Haack249f31f8b888
diff --git a/posthog/dags/flag_evaluations_backfill.py b/posthog/dags/flag_evaluations_backfill.py
index 722cf5bdbb94..2b8fbcb93bdf 100644
--- a/posthog/dags/flag_evaluations_backfill.py
+++ b/posthog/dags/flag_evaluations_backfill.py
@@ -50,9 +50,15 @@ _FINISHED_RUN_STATUSES = (
# The nine DEFAULT columns are left out so the shard computes them from properties, the same way
# it does for rows from Kafka. inserted_at is left out so its DEFAULT stamps the event timestamp:
# that keeps every copied row inside the deletion sweep's `inserted_at <= request.created_at` bound,
-# and it keeps copied rows out of the consumer-lag query below.
+# and it keeps copied rows out of the consumer-lag query below. _partition and _offset are left out
+# so that both are 0 on a copied row. _COPIED_ROW_FILTER relies on that.
_COPIED_COLUMNS = "uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id, _timestamp"
+# A row from Kafka also has inserted_at = timestamp when its timestamp has no sub-second part and
+# falls in the second that Kafka received it. Kafka gives offset 0 only to the first message in a
+# partition, so the only Kafka row this filter can match is the first message in partition 0.
+_COPIED_ROW_FILTER = "_partition = 0 AND _offset = 0 AND inserted_at = timestamp"
+
# A copied row's inserted_at is its timestamp, so the inserted_at != timestamp filter limits this
# query to rows that arrived through the Kafka path.
# Rows from every Kafka partition reach every shard. The slowest partition therefore sets the
@@ -434,7 +440,7 @@ class ShardBackfill:
"The copy can hold rows or person_ids that the run removed from sharded_flag_evaluations. "
f"After that run finishes, delete the rows this job copied for {day} on shard {self.shard_num} "
f"(`DELETE FROM {FLAG_EVALUATIONS_DATA_TABLE} WHERE toDate(timestamp) = '{day}' "
- f"AND inserted_at = timestamp{team_filter}`), then run the backfill again for the same teams."
+ f"AND {_COPIED_ROW_FILTER}{team_filter}`), then run the backfill again for the same teams."
)
def wait_for_disk_headroom(self) -> None:
diff --git a/posthog/dags/tests/test_flag_evaluations_backfill.py b/posthog/dags/tests/test_flag_evaluations_backfill.py
index 269e3e70eb2f..a1b00b31e22f 100644
--- a/posthog/dags/tests/test_flag_evaluations_backfill.py
+++ b/posthog/dags/tests/test_flag_evaluations_backfill.py
@@ -1,3 +1,4 @@
+import re
import json
from collections import Counter
from collections.abc import Callable, Mapping
@@ -131,6 +132,12 @@ SOURCE_EVENTS = [
# the job reads.
KAFKA_PATH_ROW = SourceEvent(label="kafka_path_row", team_id=TEAM_ONE, age=timedelta(0), properties={})
+# A Kafka row whose inserted_at equals its timestamp, as on a copied row. This happens when the event
+# timestamp has no sub-second part and falls in the second that Kafka received the event.
+KAFKA_ROW_IN_ITS_EVENT_SECOND = SourceEvent(
+ label="kafka_row_in_its_event_second", team_id=TEAM_ONE, age=timedelta(0), properties={}
+)
+
SAME_UUID_OTHER_TEAM = replace(INSIDE_RECENT, team_id=TEAM_TWO)
@@ -184,28 +191,32 @@ def seed_flag_evaluation(cluster: ClickhouseCluster, now: datetime, event: Sourc
def seed_kafka_path_row(
cluster: ClickhouseCluster,
now: datetime,
- age: timedelta = timedelta(0),
+ event: SourceEvent = KAFKA_PATH_ROW,
partition: int = 0,
+ offset: int = 1,
+ delivery_delay: timedelta = timedelta(seconds=1),
consumer_delay: timedelta = timedelta(0),
) -> None:
# The lag check skips rows whose inserted_at equals their timestamp, because the backfill copies
- # rows that way. A Kafka row arrives after its event, so its inserted_at is later.
- kafka_time = now - age
+ # rows that way. A Kafka row usually arrives after its event, so its inserted_at is later.
+ # The cleanup filter treats offset 0 in partition 0 as a copy, so the default offset is 1.
+ kafka_time = now - event.age
row = (
- KAFKA_PATH_ROW.team_id,
- KAFKA_PATH_ROW.distinct_id,
- uuid5(NAMESPACE_URL, KAFKA_PATH_ROW.distinct_id),
- KAFKA_PATH_ROW.uuid,
- kafka_time - timedelta(seconds=1),
+ event.team_id,
+ event.distinct_id,
+ uuid5(NAMESPACE_URL, event.distinct_id),
+ event.uuid,
+ kafka_time - delivery_delay,
kafka_time + consumer_delay,
kafka_time,
partition,
+ offset,
)
def insert(client: Client) -> None:
client.execute(
"""INSERT INTO writable_flag_evaluations
- (team_id, distinct_id, person_id, uuid, timestamp, inserted_at, _timestamp, _partition)
+ (team_id, distinct_id, person_id, uuid, timestamp, inserted_at, _timestamp, _partition, _offset)
VALUES""",
[row],
)
@@ -214,7 +225,7 @@ def seed_kafka_path_row(
def stored_rows(cluster: ClickhouseCluster) -> Counter[StoredRow]:
- labels = {event.uuid: event.label for event in SOURCE_EVENTS}
+ labels = {event.uuid: event.label for event in [*SOURCE_EVENTS, KAFKA_ROW_IN_ITS_EVENT_SECOND]}
def select(client: Client) -> list[tuple[UUID, str, str, str, UUID, int]]:
return client.execute(
@@ -258,6 +269,10 @@ def days_before(now: datetime, days: int) -> str:
return (now - timedelta(days=days)).date().isoformat()
+def age_at_noon(now: datetime, days_ago: int) -> timedelta:
+ return now - datetime.combine(now.date() - timedelta(days=days_ago), time(12), tzinfo=UTC)
+
+
def shard_backfill(
config: FlagEvaluationsBackfillConfig | None = None,
*,
@@ -340,9 +355,7 @@ def test_backfill_waits_for_an_active_blocking_run_before_copying(
run_config: dict[str, Any] | None,
) -> None:
now = datetime.now(UTC)
- on_first_copied_day = replace(
- INSIDE_RECENT, age=now - datetime.combine(now.date() - timedelta(days=2), time(12), tzinfo=UTC)
- )
+ on_first_copied_day = replace(INSIDE_RECENT, age=age_at_noon(now, days_ago=2))
seed_source_events(cluster, now, [on_first_copied_day])
seed_kafka_path_row(cluster, now)
instance = dagster.DagsterInstance.ephemeral()
@@ -373,7 +386,8 @@ def test_backfill_waits_for_an_active_blocking_run_before_copying(
REPAIR_DELETE = (
- f"DELETE FROM {FLAG_EVALUATIONS_DATA_TABLE} WHERE toDate(timestamp) = '2026-03-10' AND inserted_at = timestamp"
+ f"DELETE FROM {FLAG_EVALUATIONS_DATA_TABLE} WHERE toDate(timestamp) = '2026-03-10' "
+ "AND _partition = 0 AND _offset = 0 AND inserted_at = timestamp"
)
@@ -422,8 +436,12 @@ def test_backfill_names_the_day_when_a_blocking_run_starts_during_its_copy(
cluster: ClickhouseCluster, copy_fails: bool
) -> None:
now = datetime.now(UTC)
- seed_source_events(cluster, now, [INSIDE_RECENT])
+ on_first_copied_day = replace(INSIDE_RECENT, age=age_at_noon(now, days_ago=2))
+ kafka_row_on_first_copied_day = replace(KAFKA_ROW_IN_ITS_EVENT_SECOND, age=on_first_copied_day.age)
+ seed_source_events(cluster, now, [on_first_copied_day])
seed_kafka_path_row(cluster, now)
+ for partition, offset in [(0, 1), (1, 0)]:
+ seed_kafka_path_row(cluster, now, kafka_row_on_first_copied_day, partition, offset, delivery_delay=timedelta(0))
instance = dagster.DagsterInstance.ephemeral()
copy_day = ShardBackfill.copy_day
@@ -435,11 +453,19 @@ def test_backfill_names_the_day_when_a_blocking_run_starts_during_its_copy(
return rows
with patch.object(ShardBackfill, "copy_day", autospec=True, side_effect=copy_while_deletes_starts):
- result = run_backfill(cluster, instance=instance, start_date=days_before(now, 3))
+ # An explicit end_date keeps on_first_copied_day the first day copied if UTC midnight passes.
+ result = run_backfill(cluster, instance=instance, start_date=days_before(now, 3), end_date=days_before(now, 1))
[failure] = result.get_step_failure_events()
assert failure.step_failure_data.error is not None
- assert "started while" in failure.step_failure_data.error.message
+ message = failure.step_failure_data.error.message
+ assert "started while" in message
+ assert stored_rows(cluster) == Counter({copied(on_first_copied_day): 1, forked(KAFKA_ROW_IN_ITS_EVENT_SECOND): 2})
+
+ [repair_delete] = re.findall(r"`(DELETE FROM [^`]+)`", message)
+ cluster.map_one_host_per_shard(lambda client: client.execute(repair_delete)).result()
+
+ assert stored_rows(cluster) == Counter({forked(KAFKA_ROW_IN_ITS_EVENT_SECOND): 2})
@pytest.mark.parametrize(
@@ -588,7 +614,9 @@ def test_backfill_fails_without_copying_when_a_safety_check_fails(
now = datetime.now(UTC)
seed_source_events(cluster, now, [INSIDE_RECENT])
for partition, age in enumerate(kafka_path_row_ages):
- seed_kafka_path_row(cluster, now, age=age, partition=partition, consumer_delay=consumer_delay)
+ seed_kafka_path_row(
+ cluster, now, replace(KAFKA_PATH_ROW, age=age), partition=partition, consumer_delay=consumer_delay
+ )
result = run_backfill(cluster, **overrides)