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): wait for the clickhouse mover instead of stopping the backfill (#110338)

Phil Haack8f95348d5220
diff --git a/posthog/dags/flag_evaluations_backfill.py b/posthog/dags/flag_evaluations_backfill.py
index 282a3a306a0c..9424bba65851 100644
--- a/posthog/dags/flag_evaluations_backfill.py
+++ b/posthog/dags/flag_evaluations_backfill.py
@@ -142,6 +142,19 @@ class FlagEvaluationsBackfillConfig(dagster.Config):
)
parts_check_poll_frequency_seconds: int = 30
parts_check_max_wait_seconds: int = 60 * 60
+ disk_check_max_wait_seconds: int = pydantic.Field(
+ default=2 * 60 * 60,
+ description=(
+ "Wait before each day while a replica has less free space than its move_factor reserve, which ClickHouse "
+ "restores by moving parts to the next volume. Stop the shard when one such wait lasts this long. The "
+ "limit starts again after each wait for a squash, deletes or data deletion run."
+ ),
+ )
+ disk_check_poll_frequency_seconds: int = pydantic.Field(
+ default=60,
+ ge=1,
+ description="How often to read the disks again while a replica is below its move_factor reserve.",
+ )
@frozen
@@ -307,8 +320,7 @@ class ShardBackfill:
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()
+ blocking_run_check = self._wait_for_disk_and_blocking_runs()
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):
@@ -324,6 +336,15 @@ class ShardBackfill:
self.log.info(f"Shard {self.shard_num}, {day}: {action} {rows} row(s)")
return ShardBackfillTotals(days=copied_days, rows=total_rows)
+ def _wait_for_disk_and_blocking_runs(self) -> BlockingRunCheck:
+ # The post-copy check counts every blocking run that starts after wait_for_blocking_runs returns.
+ # That wait therefore comes last. A squash can keep it waiting for hours. The disk can fill in that time.
+ while True:
+ self.wait_for_disk_headroom()
+ blocking_run_check = self.wait_for_blocking_runs()
+ if not self._hosts_moving_parts():
+ return blocking_run_check
+
def _reached_expired_day(self, day: date, *, uncopied_days: int) -> bool:
if day >= earliest_backfill_day(datetime.now(UTC).date()):
return False
@@ -413,7 +434,26 @@ class ShardBackfill:
f"AND inserted_at = timestamp{team_filter}`), then run the backfill again for the same teams."
)
- def check_disk_headroom(self) -> None:
+ def wait_for_disk_headroom(self) -> None:
+ deadline = time.monotonic() + self.config.disk_check_max_wait_seconds
+ while True:
+ hosts_moving_parts = self._hosts_moving_parts()
+ if not hosts_moving_parts:
+ return
+ hosts = ", ".join(hosts_moving_parts)
+ if time.monotonic() >= deadline:
+ raise dagster.Failure(
+ description=f"Stopping shard {self.shard_num}: ClickHouse is still moving parts off a disk "
+ f"below its move_factor reserve on {hosts} after {self.config.disk_check_max_wait_seconds}s."
+ )
+ self.log.info(f"Waiting for ClickHouse to move parts off a disk below its move_factor reserve on {hosts}")
+ time.sleep(self.config.disk_check_poll_frequency_seconds)
+
+ def _hosts_moving_parts(self) -> list[str]:
+ """Return the replicas below their move_factor reserve.
+
+ Raise when a replica is under the min_free_bytes floor or reports no disks.
+ """
# Every replica of the shard, including offline ones, stores a copy of each inserted part.
disks_by_host = self.cluster.map_hosts_in_shard_by_role(
self.shard_num, self._tagged(_read_policy_disks), node_role=self.node_role
@@ -421,23 +461,22 @@ class ShardBackfill:
if not disks_by_host:
raise dagster.Failure(description=f"No replica of shard {self.shard_num} reported its disks.")
problems = []
+ hosts_moving_parts = []
for host, disks in disks_by_host.items():
if not disks:
problems.append(f"{host.connection_info.host} has no disks for {FLAG_EVALUATIONS_DATA_TABLE}")
continue
headroom = disk_headroom(disks)
- if headroom.below_move_line:
- problems.append(
- f"{host.connection_info.host} has a disk with less free space than its move_factor reserve, "
- "so ClickHouse is moving parts off it"
- )
- elif headroom.usable_bytes < self.config.min_free_bytes:
+ if headroom.usable_bytes < self.config.min_free_bytes:
problems.append(
f"{host.connection_info.host} has {headroom.usable_bytes} usable bytes, "
f"under the floor of {self.config.min_free_bytes}"
)
+ elif headroom.below_move_line:
+ hosts_moving_parts.append(host.connection_info.host)
if problems:
raise dagster.Failure(description=f"Stopping shard {self.shard_num}: " + "; ".join(problems))
+ return hosts_moving_parts
def check_consumer_lag(self) -> None:
kafka_partitions, lag_seconds = self._on_copy_host(partial(self._first_row, _KAFKA_POSITION_QUERY))
diff --git a/posthog/dags/tests/test_flag_evaluations_backfill.py b/posthog/dags/tests/test_flag_evaluations_backfill.py
index d7494677c154..511c5bea12af 100644
--- a/posthog/dags/tests/test_flag_evaluations_backfill.py
+++ b/posthog/dags/tests/test_flag_evaluations_backfill.py
@@ -258,10 +258,11 @@ def shard_backfill(
*,
instance: dagster.DagsterInstance | None = None,
run_id: str = "backfill-run",
+ cluster: MagicMock | None = None,
) -> ShardBackfill:
# The cluster is a mock, so the default config turns off the parts wait, which queries it.
return ShardBackfill(
- cluster=MagicMock(),
+ cluster=cluster or MagicMock(),
shard_num=1,
config=config or FlagEvaluationsBackfillConfig(max_unmerged_parts=0),
instance=instance or dagster.DagsterInstance.ephemeral(),
@@ -453,7 +454,7 @@ def test_backfill_stops_before_copying_when_another_backfill_run_is_executing(
yesterday = datetime.now(UTC).date() - timedelta(days=1)
with (
- patch.object(ShardBackfill, "check_disk_headroom"),
+ patch.object(ShardBackfill, "_hosts_moving_parts", return_value=[]),
patch.object(ShardBackfill, "check_consumer_lag"),
patch.object(ShardBackfill, "copy_day", return_value=0) as copy_day,
):
@@ -466,6 +467,36 @@ def test_backfill_stops_before_copying_when_another_backfill_run_is_executing(
assert copy_day.called is not stops
+ "rereads, finished_during_disk_wait",
+ [
+ pytest.param([[]], 1, id="first_disk_wait"),
+ pytest.param([["replica-1"], []], 2, id="disk_wait_after_the_reread"),
+ ],
+)
+def test_backfill_ignores_a_blocking_run_that_finished_while_it_waited_for_disk(
+ rereads: list[list[str]], finished_during_disk_wait: int
+) -> None:
+ instance = dagster.DagsterInstance.ephemeral()
+ disk_waits = 0
+
+ def finish_a_deletes_run() -> None:
+ nonlocal disk_waits
+ disk_waits += 1
+ if disk_waits == finished_during_disk_wait:
+ instance.create_run_for_job(job_def=deletes_job, status=dagster.DagsterRunStatus.SUCCESS)
+
+ 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, "copy_day", return_value=5),
+ ):
+ totals = shard_backfill(instance=instance).run([datetime.now(UTC).date() - timedelta(days=1)])
+
+ assert totals == ShardBackfillTotals(days=1, rows=5)
+
+
# The earliest day the TTL keeps is 2025-12-11 on 2026-03-10, and 2025-12-12 on 2026-03-11.
@pytest.mark.parametrize(
"start, step, step_day, effect",
@@ -510,7 +541,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, "check_disk_headroom"),
+ patch.object(ShardBackfill, "_hosts_moving_parts", return_value=[]),
patch.object(ShardBackfill, "check_consumer_lag"),
patch.object(ShardBackfill, "copy_day", side_effect=patched("copy_day")) as copy_day,
):
@@ -546,6 +577,20 @@ def test_backfill_fails_without_copying_when_a_safety_check_fails(
assert stored_rows(cluster) == Counter()
+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),
+]
+ABOVE_MOVE_LINE = [
+ PolicyDisk(volume_priority=1, move_factor=0.1, free_bytes=300, total_bytes=1000),
+ PolicyDisk(volume_priority=2, move_factor=0.1, free_bytes=4750, total_bytes=8000),
+]
+UNDER_THE_FLOOR = [
+ PolicyDisk(volume_priority=1, move_factor=0.1, free_bytes=300, total_bytes=1000),
+ PolicyDisk(volume_priority=2, move_factor=0.1, free_bytes=100, total_bytes=8000),
+]
+
+
@pytest.mark.parametrize(
"disks, usable_bytes, below_move_line",
[
@@ -558,15 +603,7 @@ def test_backfill_fails_without_copying_when_a_safety_check_fails(
False,
id="hot_volume_keeps_its_move_reserve",
),
- pytest.param(
- [
- 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),
- ],
- 4950,
- True,
- id="hot_volume_below_its_move_line",
- ),
+ pytest.param(BELOW_MOVE_LINE, 4950, True, id="hot_volume_below_its_move_line"),
pytest.param(
[PolicyDisk(volume_priority=1, move_factor=0.1, free_bytes=50, total_bytes=1000)],
50,
@@ -583,6 +620,73 @@ def test_disk_headroom_leaves_out_the_share_the_mover_keeps_free(
assert (headroom.usable_bytes, headroom.below_move_line) == (usable_bytes, below_move_line)
+# The job reads the disks on each poll of the disk wait, and once more after the wait for squash and deletes runs.
+ "readings, overrides, sleeps, failure",
+ [
+ pytest.param([BELOW_MOVE_LINE, ABOVE_MOVE_LINE, ABOVE_MOVE_LINE], {}, 1, None, id="mover_frees_the_disk"),
+ pytest.param([BELOW_MOVE_LINE], {"min_free_bytes": 10_000}, 0, "under the floor", id="under_the_floor"),
+ pytest.param(
+ [ABOVE_MOVE_LINE, BELOW_MOVE_LINE, ABOVE_MOVE_LINE, ABOVE_MOVE_LINE],
+ {},
+ 0,
+ None,
+ id="mover_frees_the_disk_after_the_blocking_wait",
+ ),
+ pytest.param(
+ [ABOVE_MOVE_LINE, BELOW_MOVE_LINE, BELOW_MOVE_LINE],
+ {"disk_check_max_wait_seconds": 0},
+ 0,
+ "still moving parts",
+ id="disk_still_full_after_the_blocking_wait",
+ ),
+ pytest.param(
+ [ABOVE_MOVE_LINE, BELOW_MOVE_LINE, BELOW_MOVE_LINE, BELOW_MOVE_LINE, BELOW_MOVE_LINE],
+ {"disk_check_max_wait_seconds": 120},
+ 2,
+ "still moving parts",
+ id="disk_wait_runs_out_after_polling",
+ ),
+ pytest.param(
+ [ABOVE_MOVE_LINE, UNDER_THE_FLOOR],
+ {},
+ 0,
+ "under the floor",
+ id="disk_under_the_floor_after_the_blocking_wait",
+ ),
+ ],
+)
+def test_backfill_waits_while_clickhouse_moves_parts_off_a_full_disk(
+ readings: list[list[PolicyDisk]], overrides: dict[str, Any], sleeps: int, failure: str | None
+) -> None:
+ host = MagicMock()
+ host.connection_info.host = "replica-1"
+ cluster = MagicMock()
+ cluster.map_hosts_in_shard_by_role.return_value.result.side_effect = [{host: disks} for disks in readings]
+ backfill = shard_backfill(
+ FlagEvaluationsBackfillConfig(**{"min_free_bytes": 1000, "max_unmerged_parts": 0, **overrides}), cluster=cluster
+ )
+ yesterday = datetime.now(UTC).date() - timedelta(days=1)
+ clock = [0.0]
+
+ def advance_clock(seconds: float) -> None:
+ clock[0] += seconds
+
+ 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, "copy_day", return_value=5) as copy_day,
+ ):
+ if failure is None:
+ backfill.run([yesterday])
+ else:
+ with pytest.raises(dagster.Failure, match=failure):
+ backfill.run([yesterday])
+
+ assert (sleep.call_count, copy_day.called) == (sleeps, failure is None)
+
+
@pytest.mark.parametrize(
"overrides",
[