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.

feat(clickhouse): reap stranded sweep assets at run start (#92929)

Eli Reismand1caeb634986
diff --git a/posthog/dags/clickhouse_cleanup.py b/posthog/dags/clickhouse_cleanup.py
index cbd9697fb1f3..33ef7cf9edde 100644
--- a/posthog/dags/clickhouse_cleanup.py
+++ b/posthog/dags/clickhouse_cleanup.py
@@ -10,6 +10,7 @@ worklist into a persisted snapshot table first, scoped by run id. Everything dow
the Postgres handoff, reads the snapshot rather than recomputing it.
"""
+import re
import time
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, replace
@@ -88,7 +89,8 @@ class CleanupConfig(dagster.Config):
)
cleanup: bool = pydantic.Field(
default=True,
- description="Drop the dictionaries and clear this run's snapshot rows when the run finishes.",
+ description="Drop the dictionaries and clear this run's snapshot rows when the run finishes. "
+ "False keeps them only until the next run's janitor reaps them.",
)
team_batches: int = pydantic.Field(
default=DEFAULT_TEAM_BATCHES,
@@ -533,7 +535,13 @@ def clear_removed_cohort_data(
possible, which is what bounds how many persons can revive mid-run.
"""
run = CleanupRun.for_run(context.run_id, config)
- context.add_output_metadata({"dry_run": dagster.MetadataValue.bool(run.dry_run)})
+ reaped = reap_stranded_run_assets(context, cluster)
+ context.add_output_metadata(
+ {
+ "dry_run": dagster.MetadataValue.bool(run.dry_run),
+ "stranded_runs_reaped": dagster.MetadataValue.int(reaped),
+ }
+ )
if run.dry_run:
context.log.info("dry run: skipping the cohort sweep")
@@ -1138,27 +1146,17 @@ def drop_snapshot_assets(
cluster.any_host_by_role(table.drop_run_partition, NodeRole.DATA).result()
[email protected]_hook(required_resource_keys={"cluster"})
-def drop_assets_on_failure(context: dagster.HookContext) -> None:
- """Drop this run's dictionaries when an op fails.
+def _drop_dictionary(client: Client, qualified_name: str) -> None:
+ client.execute(f"DROP DICTIONARY IF EXISTS {qualified_name} SYNC")
- Dagster skips downstream ops after a failure, so drop_snapshot_assets never runs and the
- dictionaries would survive on the cluster and accumulate across failures. Their names come
- from the run id alone, so this needs nothing from the failed op.
- This ignores the cleanup flag on purpose. A stranded dictionary holds its whole key set in
- memory on every host, which costs more than the ability to inspect it after a failure.
+def _kill_and_drop_run_assets(cluster: ClickhouseCluster, run_id: str) -> None:
+ """Kill the mutations that still read a run's dictionaries, then drop the dictionaries.
- The failed run's rows are left behind deliberately. They cost far less than a dictionary and
- the tables' TTL reaps them, so a failed sweep stays inspectable in the meantime.
+ Kill first: a dropped dictionary fails its readers. Killing a half-applied ordered delete
+ is safe because each key's tombstone stays the surviving max version.
"""
- run_id = context.run_id.replace("-", "_")
- cluster = context.resources.cluster
- # A mutation still reading one of these dictionaries would fail the moment it is dropped, so
- # kill this run's mutations first. Killing a half-applied ordered delete is safe: every
- # intermediate state leaves each key's tombstone as the surviving max version, so nothing
- # resurrects. Only mutations naming this run's dictionaries are touched.
def kill_run_mutations(client: Client) -> None:
for table in (PERSON_DISTINCT_ID2_TABLE, PERSONS_TABLE):
client.execute(
@@ -1175,7 +1173,89 @@ def drop_assets_on_failure(context: dagster.HookContext) -> None:
for table_name in CLEANUP_SNAPSHOT_TABLES:
name = f"{settings.CLICKHOUSE_DATABASE}.{table_name}_{run_id}_dictionary"
- cluster.map_all_hosts(lambda client, n=name: client.execute(f"DROP DICTIONARY IF EXISTS {n} SYNC")).result()
+ cluster.map_all_hosts(partial(_drop_dictionary, qualified_name=name)).result()
+
+
+# Exactly the per-run dictionary names this job generates; the janitor touches nothing else.
+_RUN_SCOPED_DICTIONARY = re.compile(
+ r"^(?:" + "|".join(re.escape(t) for t in CLEANUP_SNAPSHOT_TABLES) + r")"
+ r"_([0-9a-f]{8}_[0-9a-f]{4}_[0-9a-f]{4}_[0-9a-f]{4}_[0-9a-f]{12})_dictionary$"
+)
+
+# Statuses in which a run can no longer be using its dictionaries. Sourced from the public enum
+# rather than dagster's private FINISHED_STATUSES so an upstream rename cannot break the import.
+_TERMINAL_RUN_STATUSES = frozenset(
+ {dagster.DagsterRunStatus.SUCCESS, dagster.DagsterRunStatus.FAILURE, dagster.DagsterRunStatus.CANCELED}
+)
+
+
+def reap_stranded_run_assets(context: dagster.OpExecutionContext, cluster: ClickhouseCluster) -> int:
+ """Drop dictionaries left by finished sweep runs, and return how many runs were reaped.
+
+ Cancellation, run-worker crashes, and pre-step failures skip the failure hook, and
+ dictionaries have no TTL. Only runs this instance knows to be finished are reaped:
+ an active run's assets are in use, and an unknown run id cannot be proven dead.
+ """
+ try:
+ current = context.run_id.replace("-", "_")
+
+ def dictionary_names(client: Client) -> list[str]:
+ rows = client.execute(
+ "SELECT name FROM system.dictionaries WHERE database = %(database)s",
+ {"database": settings.CLICKHOUSE_DATABASE},
+ )
+ return [row[0] for row in rows]
+
+ names: set[str] = set()
+ for host_names in cluster.map_all_hosts(dictionary_names).result().values():
+ names.update(host_names)
+
+ reaped: list[str] = []
+ for name in sorted(names):
+ match = _RUN_SCOPED_DICTIONARY.match(name)
+ if not match or match.group(1) == current or match.group(1) in reaped:
+ continue
+ run_id = match.group(1)
+ stranded_run = context.instance.get_run_by_id(run_id.replace("_", "-"))
+ if stranded_run is None:
+ context.log.warning("not reaping %s: this instance does not know run %s", name, run_id)
+ continue
+ if stranded_run.status not in _TERMINAL_RUN_STATUSES:
+ continue
+ context.log.warning("reaping stranded assets of finished run %s", run_id)
+ try:
+ _kill_and_drop_run_assets(cluster, run_id)
+ except Exception:
+ # One unreapable run must not shadow the later ones, or block them forever.
+ context.log.exception("failed to reap run %s", run_id)
+ _emit(MetricsClient(cluster), "clickhouse_cleanup_stranded_runs_unreapable", {})
+ continue
+ reaped.append(run_id)
+
+ if reaped:
+ _emit(MetricsClient(cluster), "clickhouse_cleanup_stranded_runs_reaped", {}, value=len(reaped))
+ return len(reaped)
+ except Exception:
+ # Leftovers cost memory, not correctness, so a broken janitor must not block the sweep.
+ context.log.exception("failed to reap stranded run assets")
+ return 0
+
+
[email protected]_hook(required_resource_keys={"cluster"})
+def drop_assets_on_failure(context: dagster.HookContext) -> None:
+ """Drop this run's dictionaries when an op fails.
+
+ Dagster skips downstream ops after a failure, so drop_snapshot_assets never runs and the
+ dictionaries would survive on the cluster and accumulate across failures. Their names come
+ from the run id alone, so this needs nothing from the failed op.
+
+ This ignores the cleanup flag on purpose. A stranded dictionary holds its whole key set in
+ memory on every host, which costs more than the ability to inspect it after a failure.
+
+ The failed run's rows are left behind deliberately. They cost far less than a dictionary and
+ the tables' TTL reaps them, so a failed sweep stays inspectable in the meantime.
+ """
+ _kill_and_drop_run_assets(context.resources.cluster, context.run_id.replace("-", "_"))
@dagster.job(hooks={drop_assets_on_failure}, tags={"owner": JobOwners.TEAM_CLICKHOUSE.value})
diff --git a/posthog/dags/tests/test_clickhouse_cleanup.py b/posthog/dags/tests/test_clickhouse_cleanup.py
index f5121126a6df..a0b390154403 100644
--- a/posthog/dags/tests/test_clickhouse_cleanup.py
+++ b/posthog/dags/tests/test_clickhouse_cleanup.py
@@ -54,11 +54,12 @@ def persons_database() -> Iterator[psycopg2.extensions.connection]:
conn.close()
-def run_job(cluster: ClickhouseCluster, persons_database, run_config=RUN_FOR_REAL, raise_on_error=True):
+def run_job(cluster: ClickhouseCluster, persons_database, run_config=RUN_FOR_REAL, raise_on_error=True, instance=None):
return clickhouse_deletion_sweep_job.execute_in_process(
run_config=run_config,
resources={"cluster": cluster, "persons_database_url": persons_db_url(writer=True)},
raise_on_error=raise_on_error,
+ instance=instance,
)
@@ -340,6 +341,124 @@ def test_requeues_a_person_the_drain_already_cleaned(cluster: ClickhouseCluster,
assert rows[0][3] is None, "cleaned_at must be cleared so the drain picks the person up again"
+def _foreign_run_dictionary(cluster: ClickhouseCluster, run_id: str) -> clickhouse_cleanup.SnapshotDictionary:
+ # A stranded dictionary the way a dead run leaves one: created on every host, source table
+ # rows irrelevant (the janitor drops by name, never by content).
+ scoped = run_id.replace("-", "_")
+ dictionary = clickhouse_cleanup.SnapshotDictionary(
+ source=clickhouse_cleanup.DeletedPersonsTable(run_id=scoped),
+ excluded=clickhouse_cleanup.RevivedPersonsTable(run_id=scoped),
+ )
+ cluster.map_all_hosts(partial(dictionary.create, shards=1, max_execution_time=0, max_memory_usage=0)).result()
+ return dictionary
+
+
+def test_the_janitor_reaps_a_terminal_runs_dictionaries(cluster: ClickhouseCluster, persons_database):
+ # Cancellation and pre-step failures fire no hook, so their dictionaries survive until the
+ # next run reaps them. Dropping the janitor call, or breaking its name parse, leaks tens of
+ # GiB per host per dead run with no path back but manual DDL.
+ instance = dagster.DagsterInstance.ephemeral()
+ dead = instance.create_run_for_job(job_def=clickhouse_deletion_sweep_job, status=dagster.DagsterRunStatus.FAILURE)
+ _foreign_run_dictionary(cluster, dead.run_id)
+ assert cluster.any_host(dictionaries_for_run(dead.run_id)).result() == 1
+
+ result = run_job(cluster, persons_database, instance=instance)
+
+ assert result.success
+ assert cluster.any_host(dictionaries_for_run(dead.run_id)).result() == 0
+
+
+def test_the_janitor_leaves_an_active_runs_dictionaries_alone(cluster: ClickhouseCluster, persons_database):
+ # An active run's dictionaries are in use; reaping them would let two runs eat each other's
+ # worklists, which is the isolation the whole run-id scoping exists to protect.
+ instance = dagster.DagsterInstance.ephemeral()
+ active = instance.create_run_for_job(job_def=clickhouse_deletion_sweep_job, status=dagster.DagsterRunStatus.STARTED)
+ dictionary = _foreign_run_dictionary(cluster, active.run_id)
+ try:
+ result = run_job(cluster, persons_database, instance=instance)
+ assert result.success
+ assert cluster.any_host(dictionaries_for_run(active.run_id)).result() == 1
+ finally:
+ cluster.map_all_hosts(dictionary.drop).result()
+
+
+def test_the_janitor_leaves_unknown_dictionaries_alone(cluster: ClickhouseCluster, persons_database):
+ # A run id this instance does not know cannot be proven dead, so it must survive with a
+ # warning rather than be guessed at.
+ stranger = "99999999-9999-4999-8999-999999999999"
+ dictionary = _foreign_run_dictionary(cluster, stranger)
+ try:
+ result = run_job(cluster, persons_database, instance=dagster.DagsterInstance.ephemeral())
+ assert result.success
+ assert cluster.any_host(dictionaries_for_run(stranger)).result() == 1
+ finally:
+ cluster.map_all_hosts(dictionary.drop).result()
+
+
+def test_the_janitor_reaps_past_a_run_it_cannot_reap(cluster: ClickhouseCluster, persons_database):
+ # One unreapable run must not shadow the later ones, or they stay stranded on every sweep.
+ instance = dagster.DagsterInstance.ephemeral()
+ dead_a = instance.create_run_for_job(job_def=clickhouse_deletion_sweep_job, status=dagster.DagsterRunStatus.FAILURE)
+ dead_b = instance.create_run_for_job(job_def=clickhouse_deletion_sweep_job, status=dagster.DagsterRunStatus.FAILURE)
+ first, second = sorted([dead_a.run_id, dead_b.run_id])
+ dict_first = _foreign_run_dictionary(cluster, first)
+ _foreign_run_dictionary(cluster, second)
+
+ real = clickhouse_cleanup._kill_and_drop_run_assets
+
+ def fail_on_first(cluster_arg, run_id):
+ if run_id == first.replace("-", "_"):
+ raise RuntimeError("unreapable")
+ return real(cluster_arg, run_id)
+
+ try:
+ with patch.object(clickhouse_cleanup, "_kill_and_drop_run_assets", side_effect=fail_on_first):
+ result = run_job(cluster, persons_database, instance=instance)
+ assert result.success
+ assert cluster.any_host(dictionaries_for_run(second)).result() == 0
+ assert cluster.any_host(dictionaries_for_run(first)).result() == 1
+ finally:
+ cluster.map_all_hosts(dict_first.drop).result()
+
+
+def test_the_janitor_kills_a_stranded_runs_mutations_before_dropping(
+ cluster: ClickhouseCluster, persons_database, monkeypatch
+):
+ # A canceled run's last mutation keeps retrying server-side. Dropping its dictionary without
+ # the kill leaves that mutation failing forever and blocking every later mutation on the
+ # table, so the janitor must kill first, exactly like the failure hook.
+ instance = dagster.DagsterInstance.ephemeral()
+ dead = instance.create_run_for_job(job_def=clickhouse_deletion_sweep_job, status=dagster.DagsterRunStatus.CANCELED)
+ dictionary = _foreign_run_dictionary(cluster, dead.run_id)
+ runner = clickhouse_cleanup.LightweightDeleteMutationRunner(
+ table="person_distinct_id2",
+ predicate=(
+ f"throwIf(version >= 0, 'stranded sweep') OR isNotNull("
+ f"dictGetOrNull({dictionary.qualified_name!r}, 'max_version', (team_id, distinct_id)))"
+ ),
+ )
+ cluster.any_host(runner).result()
+
+ result = run_job(cluster, persons_database, instance=instance)
+
+ assert result.success
+ assert cluster.any_host(dictionaries_for_run(dead.run_id)).result() == 0
+
+ def unfinished_mutations(client) -> int:
+ [[count]] = client.execute(
+ "SELECT count() FROM system.mutations WHERE NOT is_done AND NOT is_killed AND table = %(table)s",
+ {"table": "person_distinct_id2"},
+ )
+ return count
+
+ assert cluster.any_host(unfinished_mutations).result() == 0
+
+
@pytest.mark.django_db
def test_a_dry_run_never_dials_postgres(cluster: ClickhouseCluster, persons_database):
# The EU dry run failed at Postgres resource init on a network path a dry run never needed.