: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(flags): add dagster job to backfill flag_evaluations from events (#108484)
Phil Haack718a409eb1c2
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.mdindex a73820bab9d8..db3449411434 100644--- a/docs/internal/clickhouse-deletion-coverage.md+++ b/docs/internal/clickhouse-deletion-coverage.md@@ -254,6 +254,13 @@ A target that leaves the capability unset strands its rows permanently, becauseThat is the accepted cost for `sharded_events_json`, which is exempt on purpose.Rows a merge stranded before `sharded_flag_evaluations` joined the squash age out with their partition.+`flag_evaluations_backfill_job` (`posthog/dags/flag_evaluations_backfill.py`) is a second producer.+It copies `person_id` from `sharded_events`, so its rows meet the same parity.+It leaves `inserted_at` to the column default, which is the event `timestamp`, so every copied row sits inside the `inserted_at` bound of any request made after its event.+It does not copy a day while a `squash_person_overrides`, `deletes_job` or data deletion request run is queued or executing.+A day copied during one of them can read a row before the job rewrites it and insert it after the job sweeps `sharded_flag_evaluations`, which keeps what the job removed.+When one of those runs starts during a copy, the shard stops, and its error names the rows to delete before the backfill runs again.+## Related, and deliberately unchanged`_fetch_stats` counts only the events tables. It feeds `AUTO_APPROVE_MAX_EVENTS`, a cost heuristic rather than a completeness claim, so a request auto-approved as small may move somewhat more rows than measured.diff --git a/posthog/dags/common/__init__.py b/posthog/dags/common/__init__.pyindex 8583e24ee8a5..ae829467d402 100644--- a/posthog/dags/common/__init__.py+++ b/posthog/dags/common/__init__.py@@ -1,19 +1,23 @@from posthog.job_owners import JobOwnersfrom .common import (+ EXECUTING_RUN_STATUSES,check_for_concurrent_runs,chunk_ranges,dagster_tags,+ describe_runs,settings_with_log_comment,skip_if_already_running,skip_on_kill_switch,)__all__ = [+ "EXECUTING_RUN_STATUSES","JobOwners","check_for_concurrent_runs","chunk_ranges","dagster_tags",+ "describe_runs","settings_with_log_comment","skip_if_already_running","skip_on_kill_switch",diff --git a/posthog/dags/common/common.py b/posthog/dags/common/common.pyindex 4a88d79a8b9c..67143abd0002 100644--- a/posthog/dags/common/common.py+++ b/posthog/dags/common/common.py@@ -1,4 +1,4 @@-from collections.abc import Callable+from collections.abc import Callable, Iterable, Sequencefrom contextlib import suppressfrom datetime import datetime, timedeltafrom functools import wraps@@ -54,6 +54,43 @@ def settings_with_log_comment(return {"log_comment": qt.to_json()}+# Statuses under which a run's work may still land on the cluster. STARTING and STARTED runs+# execute. A CANCELING run's last ClickHouse mutation keeps applying on the server.+EXECUTING_RUN_STATUSES = (+ dagster.DagsterRunStatus.STARTING,+ dagster.DagsterRunStatus.STARTED,+ dagster.DagsterRunStatus.CANCELING,+)++ACTIVE_RUN_STATUSES = (+ dagster.DagsterRunStatus.QUEUED,+ dagster.DagsterRunStatus.NOT_STARTED,+ *EXECUTING_RUN_STATUSES,+)+++def describe_runs(+ instance: dagster.DagsterInstance,+ job_names: Iterable[str],+ *,+ exclude_run_id: str,+ statuses: Sequence[dagster.DagsterRunStatus] = ACTIVE_RUN_STATUSES,+ created_after: datetime | None = None,+) -> list[str]:+ """Describe each run of these jobs that matches the statuses and creation time, except the excluded run."""+ blockers: list[str] = []+ for job_name in job_names:+ records = instance.get_run_records(+ dagster.RunsFilter(job_name=job_name, statuses=list(statuses), created_after=created_after)+ )+ blockers.extend(+ f"{job_name} run {record.dagster_run.run_id}"+ for record in records+ if record.dagster_run.run_id != exclude_run_id+ )+ return blockers++def check_for_concurrent_runs(context: dagster.ScheduleEvaluationContext, tags: dict[str, str]) -> Optional[dagster.SkipReason]:diff --git a/posthog/dags/data_deletion_requests.py b/posthog/dags/data_deletion_requests.pyindex af90621d5f84..5dc8716c89dc 100644--- a/posthog/dags/data_deletion_requests.py+++ b/posthog/dags/data_deletion_requests.py@@ -1741,7 +1741,7 @@ def data_deletion_request_person_removal():# Pickup sensor: scans for APPROVED requests and launches jobs (max 1 at a time)# ----------------------------------------------------------------------------_DELETION_JOB_NAMES = [+DELETION_JOB_NAMES = [data_deletion_request_event_removal.name,data_deletion_request_hogql_event_removal.name,data_deletion_request_property_removal.name,@@ -1772,7 +1772,7 @@ def data_deletion_request_pickup_sensor(context: dagster.SensorEvaluationContextdagster.DagsterRunStatus.STARTED,]active_count = 0- for job_name in _DELETION_JOB_NAMES:+ for job_name in DELETION_JOB_NAMES:active_count += len(context.instance.get_run_records(dagster.RunsFilter(job_name=job_name, statuses=active_statuses),diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.pyindex 6b51ec25f231..5c71197b6e93 100644--- a/posthog/dags/deletes.py+++ b/posthog/dags/deletes.py@@ -26,7 +26,7 @@ from posthog.clickhouse.cluster import (wait_for_mutations_on_shards,)from posthog.clickhouse.plugin_log_entries import PLUGIN_LOG_ENTRIES_TABLE-from posthog.dags.common import JobOwners+from posthog.dags.common import EXECUTING_RUN_STATUSES, JobOwners, describe_runsfrom posthog.dags.common.dictionaries import Dictionaryfrom posthog.dags.common.staged_dictionary import (StagedDictionary,@@ -378,17 +378,6 @@ class AdhocEventDeletesDictionary(Dictionary):)-# Statuses under which a run's mutations may still land on the cluster: STARTING and STARTED are-# executing, and a CANCELING run's last mutation keeps applying server-side. QUEUED and-# NOT_STARTED are left out on purpose. A queued run has done nothing yet, and its own guard will-# see this run once it starts.-_EXECUTING_RUN_STATUSES = [- dagster.DagsterRunStatus.STARTING,- dagster.DagsterRunStatus.STARTED,- dagster.DagsterRunStatus.CANCELING,-]--@dagster.op(out=dagster.Out(dagster.Nothing))def ensure_no_concurrent_deletes_run(context: dagster.OpExecutionContext) -> None:"""Fail this run when another run of the same job, or any squash run, is executing.@@ -406,16 +395,13 @@ def ensure_no_concurrent_deletes_run(context: dagster.OpExecutionContext) -> Nonbetween its check and the sensor launching this run, so the launched run checks again here.This covers direct launchpad starts as well."""- blockers: list[str] = []- for job_name in (context.job_name, squash_person_overrides.name):- records = context.instance.get_run_records(- dagster.RunsFilter(job_name=job_name, statuses=_EXECUTING_RUN_STATUSES)- )- blockers.extend(- f"{job_name} run {record.dagster_run.run_id}"- for record in records- if record.dagster_run.run_id != context.run_id- )+ # A queued run has done nothing yet. Its own guard sees this run once it starts.+ blockers = describe_runs(+ context.instance,+ (context.job_name, squash_person_overrides.name),+ statuses=EXECUTING_RUN_STATUSES,+ exclude_run_id=context.run_id,+ )if blockers:raise dagster.Failure(description="This run yields to: " + "; ".join(blockers) + ". "@@ -1210,16 +1196,6 @@ def run_deletes_after_squash(context):)-# Everything that means a deletes_job or squash run is active or imminent. Unlike the in-job-# guard, QUEUED and NOT_STARTED count too: the question here is whether launching another run-# would collide, not which of two started runs came first.-_ACTIVE_RUN_STATUSES = [- dagster.DagsterRunStatus.QUEUED,- dagster.DagsterRunStatus.NOT_STARTED,- *_EXECUTING_RUN_STATUSES,-]--@dagster.opdef ensure_deletes_job_can_start(context: dagster.OpExecutionContext) -> None:"""Fail when launching deletes_job now would collide with an active or imminent run.@@ -1229,14 +1205,13 @@ def ensure_deletes_job_can_start(context: dagster.OpExecutionContext) -> None:motion and will launch deletes_job itself on success, so starting one by hand now would raceit. Another manual trigger means someone else already asked for a run."""- blockers: list[str] = []- for job_name in (deletes_job.name, squash_person_overrides.name, context.job_name):- records = context.instance.get_run_records(dagster.RunsFilter(job_name=job_name, statuses=_ACTIVE_RUN_STATUSES))- blockers.extend(- f"{job_name} run {record.dagster_run.run_id}"- for record in records- if record.dagster_run.run_id != context.run_id- )+ # Unlike the in-job guard, queued and not-started runs count here. This check asks whether+ # launching another run would collide, not which of two started runs came first.+ blockers = describe_runs(+ context.instance,+ (deletes_job.name, squash_person_overrides.name, context.job_name),+ exclude_run_id=context.run_id,+ )if blockers:raise dagster.Failure(description="deletes_job cannot start while these runs are active: "diff --git a/posthog/dags/flag_evaluations_backfill.py b/posthog/dags/flag_evaluations_backfill.pynew file mode 100644index 000000000000..ee9dc5e683d8--- /dev/null+++ b/posthog/dags/flag_evaluations_backfill.py@@ -0,0 +1,510 @@+import time+from collections.abc import Callable, Iterator, Sequence+from datetime import UTC, date, datetime, timedelta+from functools import partial+from typing import Any, TypeVar++import dagster+import pydantic+from clickhouse_driver import Client++from posthog.schema import ProductKey++from posthog.clickhouse.client import sync_execute+from posthog.clickhouse.client.connection import NodeRole, Workload+from posthog.clickhouse.cluster import ClickhouseCluster+from posthog.clickhouse.query_tagging import DagsterTags, Feature, tags_context+from posthog.cloud_utils import is_cloud+from posthog.dags.common import EXECUTING_RUN_STATUSES, JobOwners, dagster_tags, describe_runs+from posthog.dags.data_deletion_requests import DELETION_JOB_NAMES+from posthog.dags.deletes import deletes_job+from posthog.dags.person_overrides import squash_person_overrides+from posthog.dataclasses import frozen+from posthog.models.event.sql import EVENTS_DATA_TABLE+from posthog.models.flag_evaluations.sql import (+ FLAG_EVALUATIONS_DATA_TABLE,+ FLAG_EVALUATIONS_SOURCE_EVENT,+ FLAG_EVALUATIONS_TTL_DAYS,+)+from posthog.models.raw_sessions.sessions_v3 import GET_NUM_RAW_SESSIONS_ACTIVE_PARTS++T = TypeVar("T")++OWNER_TAG = {"owner": JobOwners.TEAM_FEATURE_FLAGS.value}++GIB = 1024**3+TIB = 1024 * GIB++# These jobs rewrite or delete rows in sharded_events and sharded_flag_evaluations, directly or+# through deletes_job. A day copied while one of them runs can read a row before the job changes+# it and insert it after the job swept sharded_flag_evaluations, so the copy keeps what the job+# removed: a stale person_id after a squash, or a row or property that a deletion erased.+BLOCKING_JOB_NAMES = (squash_person_overrides.name, deletes_job.name, *DELETION_JOB_NAMES)++_FINISHED_RUN_STATUSES = (+ dagster.DagsterRunStatus.SUCCESS,+ dagster.DagsterRunStatus.FAILURE,+ dagster.DagsterRunStatus.CANCELED,+)++# 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.+_COPIED_COLUMNS = "uuid, event, properties, timestamp, team_id, distinct_id, created_at, person_id, _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+# consumer's position. The lookback spans several days so that a partition that stops delivering+# stays in the query and reports its real lag. A partition that has delivered nothing for the whole+# lookback drops out of this query.+_KAFKA_LOOKBACK_DAYS = 7+_KAFKA_POSITION_QUERY = f"""+SELECT count(), max(lag_seconds)+FROM (+ SELECT _partition, dateDiff('second', max(inserted_at), now64(6)) AS lag_seconds+ FROM {FLAG_EVALUATIONS_DATA_TABLE}+ WHERE inserted_at >= now() - INTERVAL {_KAFKA_LOOKBACK_DAYS} DAY AND inserted_at != timestamp+ GROUP BY _partition+)+"""++_STORAGE_POLICY_DISKS_QUERY = f"""+SELECT policy.volume_priority, policy.move_factor, disk.free_space, disk.total_space+FROM system.storage_policies AS policy+ARRAY JOIN policy.disks AS disk_name+INNER JOIN system.disks AS disk ON disk.name = disk_name+WHERE policy.policy_name = (+ SELECT storage_policy FROM system.tables+ WHERE database = currentDatabase() AND name = '{FLAG_EVALUATIONS_DATA_TABLE}'+)+"""+++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.",+ )+ end_date: str | None = pydantic.Field(+ 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."+ ),+ )+ team_ids: list[int] | None = pydantic.Field(+ default=None, description="Copy only these teams. Leave empty to copy every team."+ )+ team_id_chunks: int = pydantic.Field(+ default=1, ge=1, description="Split each day into this many inserts by team_id % team_id_chunks."+ )+ dry_run: bool = pydantic.Field(+ default=False,+ description="Count the rows each day would copy instead of inserting them. The checks before each day still run.",+ )+ max_insert_threads: int = pydantic.Field(default=1, description="ClickHouse max_insert_threads for each insert.")+ max_execution_time_seconds: int = pydantic.Field(+ default=4 * 60 * 60, description="ClickHouse max_execution_time for each insert."+ )+ max_memory_usage_bytes: int = pydantic.Field(+ default=32 * GIB, description="ClickHouse max_memory_usage for each insert."+ )+ min_free_bytes: int = pydantic.Field(+ default=1 * TIB,+ description=(+ "Stop the shard when any of its replicas has less usable free space than this. Usable space leaves out "+ "the share of each disk that ClickHouse keeps free by moving parts to the next volume."+ ),+ )+ max_consumer_lag_seconds: int = pydantic.Field(+ default=60 * 60,+ description="Stop the shard when the Kafka path to flag_evaluations is further behind than this.",+ )+ blocking_run_poll_seconds: int = pydantic.Field(+ default=5 * 60,+ description="How often to check again while a squash, deletes or data deletion request run is active.",+ )+ max_unmerged_parts: int = pydantic.Field(+ default=100,+ description="Wait before each day until the day's partition has fewer active parts than this. 0 disables the wait.",+ )+ parts_check_poll_frequency_seconds: int = 30+ parts_check_max_wait_seconds: int = 60 * 60+++@frozen+class BackfillPlan:+ # Newest first, so a run that stops partway leaves contiguous recent history.+ days: tuple[date, ...]+ config: FlagEvaluationsBackfillConfig+++@frozen+class BlockingRunCheck:+ since: datetime+ finished_runs: frozenset[str]+++@frozen+class PolicyDisk:+ volume_priority: int+ move_factor: float+ free_bytes: int+ total_bytes: int+++@frozen+class DiskHeadroom:+ usable_bytes: int+ below_move_line: bool+++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)+ )+ 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."+ )+ if end > latest_end:+ raise dagster.Failure(description=f"end_date {end} is after yesterday ({latest_end}).")+ if start >= end:+ raise dagster.Failure(description=f"start_date {start} must be before end_date {end}.")+ return tuple(end - timedelta(days=offset) for offset in range(1, (end - start).days + 1))+++def disk_headroom(disks: Sequence[PolicyDisk]) -> DiskHeadroom:+ """Return the free space an insert can use on one host, under the table's storage policy.++ New parts land on the first volume. When a disk's free space drops below move_factor of its+ size, ClickHouse moves parts from it to the next volume, so that share of the disk is not+ usable. The last volume has no next volume, so all of its free space is usable.+ """+ last_volume = max(disk.volume_priority for disk in disks)+ usable = 0.0+ below_move_line = False+ for disk in disks:+ reserve = disk.move_factor * disk.total_bytes if disk.volume_priority < last_volume else 0.0+ usable += disk.free_bytes - reserve+ below_move_line = below_move_line or disk.free_bytes < reserve+ return DiskHeadroom(usable_bytes=int(usable), below_move_line=below_move_line)+++def build_copy_query(*, dry_run: bool, filter_team_ids: bool, chunked: bool) -> str:+ team_filter = ""+ if filter_team_ids:+ team_filter += " AND team_id IN %(team_ids)s"+ 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.+ select = f"""+SELECT {"count()" if dry_run else _COPIED_COLUMNS}+FROM {EVENTS_DATA_TABLE()}+PREWHERE event = %(event)s+ AND timestamp >= %(day_start)s AND timestamp < %(day_end)s{team_filter}+ AND (team_id, uuid) NOT IN (+ 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'+ AND JSONExtractString(properties, '$feature_flag') != ''+"""+ if dry_run:+ return select+ return f"INSERT INTO {FLAG_EVALUATIONS_DATA_TABLE} ({_COPIED_COLUMNS}){select}"++[email protected](tags=OWNER_TAG)+def plan_flag_evaluations_backfill(+ context: dagster.OpExecutionContext, config: FlagEvaluationsBackfillConfig+) -> BackfillPlan:+ """Resolve the window once, so a shard re-executed from the UI later copies the same days."""+ days = resolve_backfill_days(config, today=datetime.now(UTC).date())+ context.log.info(f"Backfilling {len(days)} day(s), newest first, from {days[0]} back to {days[-1]}")+ return BackfillPlan(days=days, config=config)++[email protected](out=dagster.DynamicOut(int), tags=OWNER_TAG)+def get_backfill_shards(+ context: dagster.OpExecutionContext,+ cluster: dagster.ResourceParam[ClickhouseCluster],+ plan: BackfillPlan,+) -> Iterator[dagster.DynamicOutput[int]]:+ """Fan out one backfill op per shard.++ Takes the plan as input so the fan-out runs after it. The mapping key makes each shard+ re-executable on its own from the Dagster UI.+ """+ shards = sorted(cluster.shards)+ context.log.info(f"Fanning out the backfill of {len(plan.days)} day(s) to {len(shards)} shard op(s)")+ for shard_num in shards:+ yield dagster.DynamicOutput(shard_num, mapping_key=f"shard_{shard_num}")+++@frozen+class ShardBackfill:+ """Copy planned days of $feature_flag_called events on one shard into flag_evaluations.++ 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.+ """++ cluster: ClickhouseCluster+ shard_num: int+ config: FlagEvaluationsBackfillConfig+ instance: dagster.DagsterInstance+ run_id: str+ log: dagster.DagsterLogManager+ query_tags: DagsterTags+ workload: Workload+ node_role: NodeRole++ def run(self, days: Sequence[date]) -> int:+ if not self.config.dry_run:+ self.check_no_other_backfill_run()+ copy_query = build_copy_query(+ dry_run=self.config.dry_run,+ filter_team_ids=bool(self.config.team_ids),+ chunked=self.config.team_id_chunks > 1,+ )+ settings: dict[str, Any] = {+ "max_execution_time": self.config.max_execution_time_seconds,+ "max_memory_usage": self.config.max_memory_usage_bytes,+ "max_insert_threads": self.config.max_insert_threads,+ }+ total_rows = 0+ for day in days:+ self.wait_for_parts_to_merge(day)+ blocking_run_check = self.wait_for_blocking_runs()+ self.check_disk_headroom()+ self.check_consumer_lag()+ 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+ 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++ def wait_for_parts_to_merge(self, day: date) -> None:+ if self.config.max_unmerged_parts <= 0:+ return+ query = GET_NUM_RAW_SESSIONS_ACTIVE_PARTS([f"{day:%Y%m}"], table=FLAG_EVALUATIONS_DATA_TABLE, use_cluster=False)+ deadline = time.monotonic() + self.config.parts_check_max_wait_seconds+ while True:+ active_parts = self._on_copy_host(partial(self._first_row, query))[0]+ if active_parts < self.config.max_unmerged_parts:+ return+ if time.monotonic() > deadline:+ raise dagster.Failure(+ description=f"Stopping shard {self.shard_num}: partition {day:%Y%m} still has {active_parts} "+ f"active parts after {self.config.parts_check_max_wait_seconds}s."+ )+ self.log.info(f"Waiting for partition {day:%Y%m} to merge: {active_parts} active parts")+ time.sleep(self.config.parts_check_poll_frequency_seconds)++ def check_no_other_backfill_run(self) -> None:+ # Each shard op checks, because a shard re-executed from the UI skips the plan op. The check+ # fails rather than waits, because two waiting runs would wait on each other.+ others = describe_runs(+ self.instance,+ (flag_evaluations_backfill_job.name,),+ statuses=EXECUTING_RUN_STATUSES,+ exclude_run_id=self.run_id,+ )+ if others:+ raise dagster.Failure(+ description=f"Stopping shard {self.shard_num}: {'; '.join(others)} is executing. "+ "Two backfills that copy the same day at once both insert its rows. "+ "Wait for that run to finish, then run the backfill again."+ )++ def wait_for_blocking_runs(self) -> BlockingRunCheck:+ while True:+ # The watermark comes before the scan. A run created during the scan then counts as created+ # after it. Run storage can record a creation time to the whole second. The watermark+ # therefore reaches one second back, and the post-copy check ignores runs that finished then.+ since = datetime.now(UTC) - timedelta(seconds=1)+ blockers = describe_runs(self.instance, BLOCKING_JOB_NAMES, exclude_run_id=self.run_id)+ if not blockers:+ break+ self.log.info(+ f"Waiting {self.config.blocking_run_poll_seconds}s for these runs to finish: {'; '.join(blockers)}"+ )+ time.sleep(self.config.blocking_run_poll_seconds)+ finished = describe_runs(+ self.instance,+ BLOCKING_JOB_NAMES,+ statuses=_FINISHED_RUN_STATUSES,+ created_after=since,+ exclude_run_id=self.run_id,+ )+ return BlockingRunCheck(since=since, finished_runs=frozenset(finished))++ def check_no_blocking_run_started(self, check: BlockingRunCheck, *, day: date) -> None:+ started = [+ run+ for run in describe_runs(+ self.instance,+ BLOCKING_JOB_NAMES,+ statuses=(*EXECUTING_RUN_STATUSES, *_FINISHED_RUN_STATUSES),+ created_after=check.since,+ exclude_run_id=self.run_id,+ )+ if run not in check.finished_runs+ ]+ if started:+ # A rerun for the same teams does not copy back the rows that earlier runs copied for other teams.+ team_filter = (+ f" AND team_id IN ({', '.join(map(str, self.config.team_ids))})" if self.config.team_ids else ""+ )+ raise dagster.Failure(+ description=f"Stopping shard {self.shard_num}: {'; '.join(started)} started while {day} copied. "+ "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."+ )++ def check_disk_headroom(self) -> None:+ # 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+ ).result()+ if not disks_by_host:+ raise dagster.Failure(description=f"No replica of shard {self.shard_num} reported its disks.")+ problems = []+ 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:+ problems.append(+ f"{host.connection_info.host} has {headroom.usable_bytes} usable bytes, "+ f"under the floor of {self.config.min_free_bytes}"+ )+ if problems:+ raise dagster.Failure(description=f"Stopping shard {self.shard_num}: " + "; ".join(problems))++ def check_consumer_lag(self) -> None:+ kafka_partitions, lag_seconds = self._on_copy_host(partial(self._first_row, _KAFKA_POSITION_QUERY))+ if kafka_partitions == 0:+ raise dagster.Failure(+ description=f"Stopping shard {self.shard_num}: no row reached {FLAG_EVALUATIONS_DATA_TABLE} "+ f"through Kafka in the last {_KAFKA_LOOKBACK_DAYS} days, so the consumer position is unknown."+ )+ if lag_seconds > self.config.max_consumer_lag_seconds:+ raise dagster.Failure(+ description=f"Stopping shard {self.shard_num}: the slowest Kafka partition is {lag_seconds}s behind, "+ f"over the limit of {self.config.max_consumer_lag_seconds}s. Copying now would insert rows "+ "that Kafka then delivers a second time."+ )++ def copy_day(self, day: date, copy_query: str, settings: dict[str, Any]) -> 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",+ "team_ids": tuple(self.config.team_ids or ()),+ "team_id_chunks": self.config.team_id_chunks,+ }++ def run_chunk(chunk: int, client: Client) -> int:+ result = sync_execute(+ copy_query,+ {**day_args, "chunk": chunk},+ settings=settings,+ workload=self.workload,+ sync_client=client,+ )+ if self.config.dry_run:+ return result[0][0]+ # sync_execute returns the written row count for an INSERT that wrote rows. It returns+ # an empty result for an INSERT that wrote none.+ return result if isinstance(result, int) else 0++ return sum(self._on_copy_host(partial(run_chunk, chunk)) for chunk in range(self.config.team_id_chunks))++ def _first_row(self, query: str, client: Client) -> tuple:+ return sync_execute(query, workload=self.workload, sync_client=client)[0]++ def _tagged(self, fn: Callable[[Client], T]) -> Callable[[Client], T]:+ # The cluster runs fn on a pool thread. The query tags do not cross into that thread.+ def tagged(client: Client) -> T:+ with tags_context(+ kind="dagster", dagster=self.query_tags, product=ProductKey.FEATURE_FLAGS, feature=Feature.BACKFILL+ ):+ return fn(client)++ return tagged++ def _on_copy_host(self, fn: Callable[[Client], T]) -> T:+ result = self.cluster.map_any_host_in_shards_by_role(+ {self.shard_num: self._tagged(fn)}, workload=self.workload, node_role=self.node_role+ ).result()+ return next(iter(result.values()))+++def _read_policy_disks(client: Client) -> list[PolicyDisk]:+ return [+ PolicyDisk(volume_priority=row[0], move_factor=row[1], free_bytes=row[2], total_bytes=row[3])+ for row in sync_execute(_STORAGE_POLICY_DISKS_QUERY, sync_client=client)+ ]++[email protected](tags=OWNER_TAG)+def backfill_flag_evaluations_shard(+ context: dagster.OpExecutionContext,+ cluster: dagster.ResourceParam[ClickhouseCluster],+ shard_num: int,+ plan: BackfillPlan,+) -> int:+ workload, node_role = (Workload.OFFLINE, NodeRole.DATA) if is_cloud() else (Workload.DEFAULT, NodeRole.ALL)+ total_rows = ShardBackfill(+ cluster=cluster,+ shard_num=shard_num,+ config=plan.config,+ instance=context.instance,+ run_id=context.run_id,+ log=context.log,+ query_tags=dagster_tags(context),+ workload=workload,+ node_role=node_role,+ ).run(plan.days)+ context.add_output_metadata(+ {+ "shard": dagster.MetadataValue.int(shard_num),+ "days": dagster.MetadataValue.int(len(plan.days)),+ "rows": dagster.MetadataValue.int(total_rows),+ "dry_run": dagster.MetadataValue.bool(plan.config.dry_run),+ }+ )+ return total_rows++[email protected](tags=OWNER_TAG)+def flag_evaluations_backfill_job() -> None:+ """Copy $feature_flag_called history from events into flag_evaluations, one op per shard.++ Safe to re-run over the same window: the anti-join inserts only rows that are missing.+ """+ plan = plan_flag_evaluations_backfill()+ shards = get_backfill_shards(plan=plan)+ shards.map(lambda shard_num: backfill_flag_evaluations_shard(shard_num, plan))diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.pyindex 850fa5d17d1f..34ed3ad5efd2 100644--- a/posthog/dags/locations/clickhouse.py+++ b/posthog/dags/locations/clickhouse.py@@ -13,6 +13,7 @@ from posthog.dags import (export_query_log_archive_to_s3,fix_missing_person_overrides,fix_person_id_overrides,+ flag_evaluations_backfill,orm_examples,part_breaker,person_overrides,@@ -44,6 +45,7 @@ defs = dagster.Definitions(backfill_materialized_column.backfill_materialized_column,fix_missing_person_overrides.fix_missing_person_overrides_job,fix_person_id_overrides.fix_person_id_overrides_job,+ flag_evaluations_backfill.flag_evaluations_backfill_job,person_overrides.cleanup_orphaned_person_overrides_snapshot,person_overrides.squash_person_overrides,person_pg_cleanup_drain.person_pg_cleanup_drain_job,diff --git a/posthog/dags/owners.yaml b/posthog/dags/owners.yamlindex af282d98edf0..2fcf36fc5623 100644--- a/posthog/dags/owners.yaml+++ b/posthog/dags/owners.yaml@@ -11,3 +11,7 @@ rules:owners: team-ingestion- match: '/sessions.py'owners: team-analytics-platform+ - match:+ - '/flag_evaluations_backfill.py'+ - '/tests/test_flag_evaluations_backfill.py'+ owners: team-feature-flagsdiff --git a/posthog/dags/slack_alerts.py b/posthog/dags/slack_alerts.pyindex 9c050114e462..0b23a7877134 100644--- a/posthog/dags/slack_alerts.py+++ b/posthog/dags/slack_alerts.py@@ -17,6 +17,7 @@ notification_channel_per_team = {JobOwners.TEAM_DATA_STACK.value: "#alerts-data-warehouse",JobOwners.TEAM_DATA_TOOLS.value: "#alerts-data-tools",JobOwners.TEAM_ERROR_TRACKING.value: "#alerts-error-tracking",+ JobOwners.TEAM_FEATURE_FLAGS.value: "#alerts-feature-flags",JobOwners.TEAM_GROWTH.value: "#alerts-growth",JobOwners.TEAM_AI_OBSERVABILITY.value: "#alerts-aio",JobOwners.TEAM_MANAGED_WAREHOUSE.value: "#alerts-managed-warehouse",diff --git a/posthog/dags/tests/test_flag_evaluations_backfill.py b/posthog/dags/tests/test_flag_evaluations_backfill.pynew file mode 100644index 000000000000..a79d3bdba720--- /dev/null+++ b/posthog/dags/tests/test_flag_evaluations_backfill.py@@ -0,0 +1,556 @@+import json+from collections import Counter+from collections.abc import Callable, Mapping+from dataclasses import replace+from datetime import UTC, date, datetime, time, timedelta+from functools import partial+from typing import Any+from uuid import NAMESPACE_URL, UUID, uuid5++import pytest+from unittest.mock import MagicMock, patch++import dagster+from clickhouse_driver import Client+from dagster._core.remote_origin import RegisteredCodeLocationOrigin, RemoteJobOrigin, RemoteRepositoryOrigin++from posthog.clickhouse.client.connection import Workload+from posthog.clickhouse.cluster import ClickhouseCluster, NodeRole+from posthog.clickhouse.query_tagging import DagsterTags+from posthog.dags.data_deletion_requests import data_deletion_request_property_removal+from posthog.dags.deletes import deletes_job+from posthog.dags.flag_evaluations_backfill import (+ FlagEvaluationsBackfillConfig,+ PolicyDisk,+ ShardBackfill,+ disk_headroom,+ flag_evaluations_backfill_job,+ resolve_backfill_days,+)+from posthog.dags.person_overrides import squash_person_overrides+from posthog.dags.tests.conftest import insert_flag_evaluations+from posthog.dataclasses import frozen+from posthog.models.event.sql import EVENTS_DATA_TABLE+from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_DATA_TABLE, FLAG_EVALUATIONS_SOURCE_EVENT++TEAM_ONE, TEAM_TWO, TEAM_THREE = 1, 2, 3+++@frozen+class SourceEvent:+ label: str+ team_id: int+ age: timedelta+ properties: Mapping[str, object]+ event: str = FLAG_EVALUATIONS_SOURCE_EVENT++ @property+ def uuid(self) -> UUID:+ return uuid5(NAMESPACE_URL, self.label)++ @property+ def distinct_id(self) -> str:+ return f"{self.label}-user"+++@frozen+class StoredRow:+ label: str+ flag_key: str+ response: str+ session_id: str+ person_id: UUID+ inserted_at_is_timestamp: bool+++def flag_called(label: str, team_id: int, age: timedelta) -> SourceEvent:+ return SourceEvent(+ label=label,+ team_id=team_id,+ age=age,+ properties={+ "$feature_flag": f"{label}-flag",+ "$feature_flag_response": "control",+ "$session_id": f"{label}-session",+ },+ )+++def copied(event: SourceEvent) -> StoredRow:+ return StoredRow(+ label=event.label,+ flag_key=str(event.properties["$feature_flag"]),+ response=str(event.properties["$feature_flag_response"]),+ session_id=str(event.properties["$session_id"]),+ person_id=uuid5(NAMESPACE_URL, event.distinct_id),+ inserted_at_is_timestamp=True,+ )+++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))+ALREADY_FORKED = flag_called("already_forked", TEAM_ONE, timedelta(days=5))++SOURCE_EVENTS = [+ INSIDE_RECENT,+ INSIDE_TEAM_THREE,+ INSIDE_OLD,+ ALREADY_FORKED,+ SourceEvent(+ label="numeric_flag_key",+ team_id=TEAM_ONE,+ age=timedelta(days=3),+ properties={"$feature_flag": 7, "$feature_flag_response": "control", "$session_id": "numeric-session"},+ ),+ SourceEvent(+ label="empty_flag_key",+ team_id=TEAM_ONE,+ age=timedelta(days=3),+ properties={"$feature_flag": "", "$feature_flag_response": "control", "$session_id": "empty-session"},+ ),+ SourceEvent(+ label="missing_flag_key",+ team_id=TEAM_ONE,+ age=timedelta(days=3),+ properties={"$feature_flag_response": "control", "$session_id": "missing-session"},+ ),+ replace(flag_called("other_event", TEAM_ONE, timedelta(days=3)), event="$pageview"),+ flag_called("today", TEAM_ONE, timedelta(0)),+ # Twelve hours before now is always after the start of yesterday, even when UTC midnight passes+ # between seeding and the run. A row from exactly one day ago would move into the window then.+ flag_called("half_a_day_ago", TEAM_ONE, timedelta(hours=12)),+ flag_called("past_retention", TEAM_ONE, timedelta(days=91)),+]++# The job stops unless each Kafka partition in flag_evaluations delivered a row within the+# consumer-lag limit, because only such rows show that the Kafka path has delivered everything up to+# the copy window. Rows with this identity stand in for that traffic. Their ages set the lag that+# the job reads.+KAFKA_PATH_ROW = SourceEvent(label="kafka_path_row", team_id=TEAM_ONE, age=timedelta(0), properties={})++SAME_UUID_OTHER_TEAM = replace(INSIDE_RECENT, team_id=TEAM_TWO)+++def forked(event: SourceEvent) -> StoredRow:+ # insert_flag_evaluations writes no properties, so the shard computes empty typed columns for the+ # row. A copied duplicate of the same uuid carries the source event's flag key instead.+ return StoredRow(+ label=event.label,+ flag_key="",+ response="",+ session_id="",+ person_id=uuid5(NAMESPACE_URL, event.distinct_id),+ inserted_at_is_timestamp=True,+ )+++DEFAULT_WINDOW_COPIES = (INSIDE_RECENT, INSIDE_TEAM_THREE, INSIDE_OLD)+++def seed_source_events(cluster: ClickhouseCluster, now: datetime, events: list[SourceEvent]) -> None:+ rows = [+ (+ event.uuid,+ event.event,+ json.dumps(event.properties),+ now - event.age,+ event.team_id,+ event.distinct_id,+ now - event.age,+ uuid5(NAMESPACE_URL, event.distinct_id),+ )+ for event in events+ ]++ 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)+ VALUES""",+ rows,+ )++ cluster.any_host_by_role(insert, NodeRole.DATA).result()+++def seed_flag_evaluation(cluster: ClickhouseCluster, now: datetime, event: SourceEvent) -> None:+ row = (event.team_id, event.distinct_id, uuid5(NAMESPACE_URL, event.distinct_id), event.uuid, now - event.age)+ cluster.any_host(partial(insert_flag_evaluations, [row])).result()+++def seed_kafka_path_row(+ cluster: ClickhouseCluster, now: datetime, age: timedelta = timedelta(0), partition: int = 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.+ inserted_at = now - age+ row = (+ KAFKA_PATH_ROW.team_id,+ KAFKA_PATH_ROW.distinct_id,+ uuid5(NAMESPACE_URL, KAFKA_PATH_ROW.distinct_id),+ KAFKA_PATH_ROW.uuid,+ inserted_at - timedelta(seconds=1),+ inserted_at,+ partition,+ )++ def insert(client: Client) -> None:+ client.execute(+ """INSERT INTO writable_flag_evaluations+ (team_id, distinct_id, person_id, uuid, timestamp, inserted_at, _partition)+ VALUES""",+ [row],+ )++ cluster.any_host(insert).result()+++def stored_rows(cluster: ClickhouseCluster) -> Counter[StoredRow]:+ labels = {event.uuid: event.label for event in SOURCE_EVENTS}++ def select(client: Client) -> list[tuple[UUID, str, str, str, UUID, int]]:+ return client.execute(+ """SELECT uuid, flag_key, response, session_id, person_id, inserted_at = timestamp+ FROM flag_evaluations+ WHERE uuid != %(kafka_path_row)s""",+ {"kafka_path_row": KAFKA_PATH_ROW.uuid},+ )++ return Counter(+ StoredRow(+ label=labels.get(uuid, str(uuid)),+ flag_key=flag_key,+ response=response,+ session_id=session_id,+ person_id=person_id,+ inserted_at_is_timestamp=bool(inserted_at_is_timestamp),+ )+ for uuid, flag_key, response, session_id, person_id, inserted_at_is_timestamp in cluster.any_host_by_role(+ select, NodeRole.DATA+ ).result()+ )+++def run_backfill(+ cluster: ClickhouseCluster, instance: dagster.DagsterInstance | None = None, **overrides: Any+) -> dagster.ExecuteInProcessResult:+ # The default disk floor exceeds the free space on a development machine, so every run starts+ # with the floor off. An explicit instance keeps the job from seeing squash or deletes runs that+ # other tests left in the shared PostgreSQL-backed instance.+ config = FlagEvaluationsBackfillConfig(**{"min_free_bytes": 0, **overrides})+ return flag_evaluations_backfill_job.execute_in_process(+ run_config=dagster.RunConfig(ops={"plan_flag_evaluations_backfill": config}),+ resources={"cluster": cluster},+ instance=instance or dagster.DagsterInstance.ephemeral(),+ raise_on_error=False,+ )+++def days_before(now: datetime, days: int) -> str:+ return (now - timedelta(days=days)).date().isoformat()+++ "config_for, reported_rows, expected_copies",+ [+ pytest.param(lambda now: {}, [3], DEFAULT_WINDOW_COPIES, id="default_window"),+ pytest.param(lambda now: {}, [3, 0], DEFAULT_WINDOW_COPIES, id="second_run_copies_nothing_new"),+ pytest.param(+ lambda now: {"start_date": days_before(now, 60), "end_date": days_before(now, 30)},+ [1],+ (INSIDE_OLD,),+ id="explicit_window_includes_start_day_and_excludes_end_day",+ ),+ pytest.param(lambda now: {"team_ids": [TEAM_TWO]}, [1], (INSIDE_OLD,), id="team_ids"),+ pytest.param(lambda now: {"team_id_chunks": 3}, [3], DEFAULT_WINDOW_COPIES, id="team_id_chunks"),+ pytest.param(lambda now: {"dry_run": True}, [3], (), id="dry_run"),+ ],+)+def test_backfill_copies_each_eligible_row_in_the_window_exactly_once(+ cluster: ClickhouseCluster,+ config_for: Callable[[datetime], dict[str, Any]],+ reported_rows: list[int],+ expected_copies: tuple[SourceEvent, ...],+) -> None:+ now = datetime.now(UTC)+ seed_source_events(cluster, now, SOURCE_EVENTS)+ seed_flag_evaluation(cluster, now, ALREADY_FORKED)+ seed_flag_evaluation(cluster, now, SAME_UUID_OTHER_TEAM)+ seed_kafka_path_row(cluster, now)++ results = [run_backfill(cluster, **config_for(now)) for _ in reported_rows]++ assert [result.success for result in results] == [True] * len(reported_rows)+ assert [sum(result.output_for_node("backfill_flag_evaluations_shard").values()) for result in results] == (+ reported_rows+ )+ assert stored_rows(cluster) == Counter(+ [forked(ALREADY_FORKED), forked(SAME_UUID_OTHER_TEAM), *(copied(event) for event in expected_copies)]+ )+++ "blocking_job, status, run_config",+ [+ pytest.param(squash_person_overrides, dagster.DagsterRunStatus.QUEUED, None, id="queued_squash"),+ pytest.param(deletes_job, dagster.DagsterRunStatus.STARTED, None, id="started_deletes"),+ pytest.param(+ data_deletion_request_property_removal,+ dagster.DagsterRunStatus.STARTED,+ {"ops": {"load_property_removal_request": {"config": {"request_id": "unused"}}}},+ id="started_property_removal",+ ),+ ],+)+def test_backfill_waits_for_an_active_blocking_run_before_copying(+ cluster: ClickhouseCluster,+ blocking_job: dagster.JobDefinition,+ status: dagster.DagsterRunStatus,+ 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)+ )+ seed_source_events(cluster, now, [on_first_copied_day])+ seed_kafka_path_row(cluster, now)+ instance = dagster.DagsterInstance.ephemeral()+ # Dagster refuses to store a QUEUED run that has no code location origin.+ origin = RemoteJobOrigin(+ RemoteRepositoryOrigin(RegisteredCodeLocationOrigin("clickhouse"), "__repository__"), blocking_job.name+ )+ blocking_run = instance.create_run_for_job(+ job_def=blocking_job, status=status, run_config=run_config, remote_job_origin=origin+ )+ copies_seen_while_blocked: list[int] = []++ def finish_blocking_run(_seconds: float) -> None:+ run = instance.get_run_by_id(blocking_run.run_id)+ if run is None or run.is_finished:+ return+ copies_seen_while_blocked.append(sum(stored_rows(cluster).values()))+ instance.report_run_canceled(run)++ # The patch replaces time.sleep for every caller in the process. max_unmerged_parts=0 turns off+ # the parts wait, so that the blocking-run poll is the only caller that reaches this fake.+ with patch("posthog.dags.flag_evaluations_backfill.time.sleep", side_effect=finish_blocking_run):+ result = run_backfill(cluster, instance=instance, max_unmerged_parts=0, start_date=days_before(now, 3))++ assert result.success+ assert copies_seen_while_blocked == [0]+ assert stored_rows(cluster) == Counter([copied(on_first_copied_day)])+++REPAIR_DELETE = (+ f"DELETE FROM {FLAG_EVALUATIONS_DATA_TABLE} WHERE toDate(timestamp) = '2026-03-10' AND inserted_at = timestamp"+)+++ "status, created_before_the_check, team_ids, repair",+ [+ pytest.param(dagster.DagsterRunStatus.STARTED, False, None, f"`{REPAIR_DELETE}`", id="started_during_the_copy"),+ pytest.param(+ dagster.DagsterRunStatus.SUCCESS, False, None, f"`{REPAIR_DELETE}`", id="finished_during_the_copy"+ ),+ pytest.param(+ dagster.DagsterRunStatus.STARTED,+ False,+ [TEAM_TWO, TEAM_THREE],+ f"`{REPAIR_DELETE} AND team_id IN ({TEAM_TWO}, {TEAM_THREE})`",+ id="started_during_a_team_scoped_copy",+ ),+ pytest.param(dagster.DagsterRunStatus.NOT_STARTED, False, None, None, id="not_started_yet"),+ pytest.param(dagster.DagsterRunStatus.CANCELED, True, None, None, id="finished_before_the_check"),+ ],+)+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,+ )+ if created_before_the_check:+ instance.create_run_for_job(job_def=deletes_job, status=status)+ check = backfill.wait_for_blocking_runs()+ if not created_before_the_check:+ instance.create_run_for_job(job_def=deletes_job, status=status)++ if repair is None:+ backfill.check_no_blocking_run_started(check, day=date(2026, 3, 10))+ else:+ with pytest.raises(dagster.Failure) as failure:+ backfill.check_no_blocking_run_started(check, day=date(2026, 3, 10))+ assert repair in str(failure.value.description)+++ "copy_fails", [pytest.param(False, id="copy_succeeds"), pytest.param(True, id="copy_fails_partway")]+)+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])+ seed_kafka_path_row(cluster, now)+ instance = dagster.DagsterInstance.ephemeral()+ copy_day = ShardBackfill.copy_day++ def copy_while_deletes_starts(backfill: ShardBackfill, *args: Any) -> int:+ instance.create_run_for_job(job_def=deletes_job, status=dagster.DagsterRunStatus.STARTED)+ rows = copy_day(backfill, *args)+ if copy_fails:+ raise RuntimeError("the insert stopped partway")+ 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))++ [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+++ "status, same_run, stops",+ [+ pytest.param(dagster.DagsterRunStatus.STARTED, False, True, id="another_run_executing"),+ pytest.param(dagster.DagsterRunStatus.NOT_STARTED, False, False, id="another_run_not_started"),+ pytest.param(dagster.DagsterRunStatus.STARTED, True, False, id="only_this_run_executing"),+ ],+)+def test_backfill_stops_before_copying_when_another_backfill_run_is_executing(+ status: dagster.DagsterRunStatus, same_run: bool, stops: bool+) -> 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,+ )++ with (+ patch.object(ShardBackfill, "check_disk_headroom"),+ patch.object(ShardBackfill, "check_consumer_lag"),+ patch.object(ShardBackfill, "copy_day", return_value=0) as copy_day,+ ):+ if stops:+ with pytest.raises(dagster.Failure, match=other_run.run_id):+ backfill.run([date(2026, 3, 10)])+ else:+ backfill.run([date(2026, 3, 10)])++ assert copy_day.called is not stops+++ "overrides, kafka_path_row_ages",+ [+ pytest.param({"min_free_bytes": 1 << 60}, [timedelta(0)], id="free_space_below_the_floor"),+ pytest.param(+ {"max_consumer_lag_seconds": 3600}, [timedelta(hours=2)], id="kafka_path_behind_by_more_than_the_limit"+ ),+ pytest.param({}, [timedelta(0), timedelta(days=2)], id="one_kafka_partition_silent_for_over_a_day"),+ pytest.param({}, [timedelta(days=8)], id="kafka_path_silent_for_the_whole_lookback"),+ ],+)+def test_backfill_fails_without_copying_when_a_safety_check_fails(+ cluster: ClickhouseCluster, overrides: dict[str, Any], kafka_path_row_ages: list[timedelta]+) -> None:+ 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)++ result = run_backfill(cluster, **overrides)++ assert not result.success+ assert stored_rows(cluster) == Counter()+++ "disks, usable_bytes, below_move_line",+ [+ pytest.param(+ [+ PolicyDisk(volume_priority=1, move_factor=0.1, free_bytes=300, total_bytes=1000),+ PolicyDisk(volume_priority=2, move_factor=0.1, free_bytes=500, total_bytes=2000),+ ],+ 700,+ 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(+ [PolicyDisk(volume_priority=1, move_factor=0.1, free_bytes=50, total_bytes=1000)],+ 50,+ False,+ id="single_volume_has_no_move_line",+ ),+ ],+)+def test_disk_headroom_leaves_out_the_share_the_mover_keeps_free(+ disks: list[PolicyDisk], usable_bytes: int, below_move_line: bool+) -> None:+ headroom = disk_headroom(disks)++ assert (headroom.usable_bytes, headroom.below_move_line) == (usable_bytes, below_move_line)+++ "overrides",+ [+ 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"),+ ],+)+def test_resolve_backfill_days_rejects_an_unsafe_window(overrides: dict[str, Any]) -> None:+ with pytest.raises(dagster.Failure):+ resolve_backfill_days(FlagEvaluationsBackfillConfig(**overrides), today=date(2026, 3, 10))+++ "overrides, newest, oldest, count",+ [+ 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"),+ ],+)+def test_resolve_backfill_days_lists_each_day_newest_first(+ overrides: dict[str, Any], newest: date, oldest: date, count: int+) -> None:+ days = resolve_backfill_days(FlagEvaluationsBackfillConfig(**overrides), today=date(2026, 3, 10))++ assert (days[0], days[-1], len(days)) == (newest, oldest, count)