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(persons): queue after the sweep's delete, keep sweep and drain apart (#111239)

Eli Reismanc27e4d68f839
diff --git a/posthog/dags/clickhouse_cleanup.py b/posthog/dags/clickhouse_cleanup.py
index 2c8c7f9a7529..606fc1ad7df0 100644
--- a/posthog/dags/clickhouse_cleanup.py
+++ b/posthog/dags/clickhouse_cleanup.py
@@ -8,6 +8,9 @@ the ops below are chained on each other's output to force them into sequence.
The person sweep destroys the tombstones its own worklist is derived from, so the run freezes that
worklist into a persisted snapshot table first, scoped by run id. Everything downstream, including
the Postgres handoff, reads the snapshot rather than recomputing it.
+
+The Postgres handoff follows the ClickHouse person delete, so the drain (person_pg_cleanup_drain.py)
+never removes a person that ClickHouse still holds, and the sweep and the drain never run together.
"""
import re
@@ -38,7 +41,7 @@ from posthog.clickhouse.cleanup_snapshots import (
from posthog.clickhouse.cluster import ClickhouseCluster, LightweightDeleteMutationRunner, MutationWaiter, NodeRole
from posthog.clickhouse.custom_metrics import MetricsClient
from posthog.clickhouse.workload import Workload
-from posthog.dags.common import JobOwners
+from posthog.dags.common import EXECUTING_RUN_STATUSES, JobOwners, describe_runs
from posthog.dags.common.common import settings_with_log_comment
from posthog.dags.common.dictionaries import Dictionary
from posthog.dags.common.staged_dictionary import (
@@ -76,6 +79,17 @@ DEFAULT_TEAM_BATCHES = 1
# run leaves the rest queued.
DEFAULT_MAX_COHORTS = 2_000
+# A row produced before a tombstone can still be in flight; landing after the delete, it revives the key.
+# A day bounds that delay with margin.
+DEFAULT_MIN_TOMBSTONE_AGE_SECONDS = 24 * 3600
+
+# Named here rather than imported, because the drain module imports this one.
+PERSON_PG_CLEANUP_DRAIN_JOB = "person_pg_cleanup_drain_job"
+# The drain stops before its next request once it sees an executing sweep, so a wait this long means
+# the drain is stuck.
+DRAIN_STOP_TIMEOUT_SECONDS = 2 * 3600
+DRAIN_STOP_POLL_SECONDS = 30.0
+
class CleanupConfig(dagster.Config):
"""Read once, by the first op, and carried to every later op on CleanupRun.
@@ -132,6 +146,12 @@ class CleanupConfig(dagster.Config):
description="Snapshot at most this many deleted persons, 0 for all of them. A capped run deletes a slice "
"and the next run picks up the rest, because the worklist derives from the tombstones that remain.",
)
+ min_tombstone_age_seconds: int = pydantic.Field(
+ default=DEFAULT_MIN_TOMBSTONE_AGE_SECONDS,
+ ge=0,
+ description="Snapshot a tombstoned key only when its tombstone was produced to Kafka at least this many "
+ "seconds ago, so every row produced before it has landed. 0 turns the check off.",
+ )
min_team_id: int = pydantic.Field(default=0, description="Only sweep persons with team_id >= this, 0 to disable.")
max_team_id: int = pydantic.Field(default=0, description="Only sweep persons with team_id <= this, 0 to disable.")
@@ -228,6 +248,7 @@ class DeletedPersonsTable(SnapshotTable):
self,
client: Client,
settings: Mapping[str, int] | None = None,
+ min_tombstone_age_seconds: int = DEFAULT_MIN_TOMBSTONE_AGE_SECONDS,
min_team_id: int = 0,
max_team_id: int = 0,
max_persons: int = 0,
@@ -238,6 +259,8 @@ class DeletedPersonsTable(SnapshotTable):
# The team filter and the LIMIT bound what one run takes on; whatever they exclude keeps
# its tombstones, so the next run picks it up. team_id leads the sort key, which is what
# lets the range prune the scan rather than only filter it.
+ # _timestamp is the Kafka message time of the tombstone, and now() is the ClickHouse
+ # clock, so the minimum age does not depend on the clock of the host that runs this op.
team_filter = ""
if min_team_id:
team_filter += f" AND team_id >= {int(min_team_id)}"
@@ -251,19 +274,21 @@ class DeletedPersonsTable(SnapshotTable):
FROM {PERSONS_TABLE}
WHERE (team_id, id) IN (SELECT team_id, id FROM {PERSONS_TABLE} WHERE is_deleted > 0{team_filter}){team_filter}
GROUP BY team_id, id
- HAVING argMax(is_deleted, version) > 0{cap}
+ HAVING argMax(is_deleted, version) > 0
+ AND argMax(_timestamp, version) <= now() - toIntervalSecond(%(min_tombstone_age_seconds)s){cap}
""",
- {"run_id": self.run_id},
+ {"run_id": self.run_id, "min_tombstone_age_seconds": min_tombstone_age_seconds},
settings=settings,
)
@dataclass(frozen=True)
class RevivedPersonsTable(SnapshotTable):
- """Snapshotted persons that came back to life while the run was in flight.
+ """Snapshotted persons this run must not delete: revived while the run was in flight, or held
+ back because a distinct id they own waits for the minimum tombstone age.
Every dictionary below reads its source through an anti-join against this table, so recording
- a revival here is what excludes it. That keeps the checkpoints free of mutations on the
+ a person here is what excludes it. That keeps the checkpoints free of mutations on the
snapshot tables, which would be far slower than an insert.
"""
@@ -289,6 +314,43 @@ class RevivedPersonsTable(SnapshotTable):
)
return self.count(client)
+ def populate_deferred_owners(
+ self,
+ client: Client,
+ persons: DeletedPersonsTable,
+ settings: Mapping[str, int] | None = None,
+ min_tombstone_age_seconds: int = DEFAULT_MIN_TOMBSTONE_AGE_SECONDS,
+ ) -> int:
+ # A key that OrphanedDistinctIdsTable defers for the minimum tombstone age holds back its owner,
+ # or the drain would hard-delete the key's Postgres row with the person. The inner filter only
+ # narrows the scan: a deferred key's newest version is a recent tombstone that names the owner.
+ client.execute(
+ f"""
+ INSERT INTO {self.qualified_name} (run_id, team_id, person_id)
+ SELECT %(run_id)s, team_id, owner
+ FROM (
+ SELECT team_id, argMax(person_id, version) AS owner
+ FROM {PERSON_DISTINCT_ID2_TABLE}
+ WHERE (team_id, distinct_id) IN (
+ SELECT team_id, distinct_id
+ FROM {PERSON_DISTINCT_ID2_TABLE}
+ WHERE is_deleted > 0
+ AND _timestamp > now() - toIntervalSecond(%(min_tombstone_age_seconds)s)
+ AND (team_id, person_id) IN ({persons.run_keys_query})
+ )
+ GROUP BY team_id, distinct_id
+ HAVING argMax(is_deleted, version) > 0
+ AND argMax(_timestamp, version) > now() - toIntervalSecond(%(min_tombstone_age_seconds)s)
+ )
+ WHERE (team_id, owner) IN ({persons.run_keys_query})
+ AND (team_id, owner) NOT IN ({self.run_keys_query})
+ GROUP BY team_id, owner
+ """,
+ {"run_id": self.run_id, "min_tombstone_age_seconds": min_tombstone_age_seconds},
+ settings=settings,
+ )
+ return self.count(client)
+
@dataclass(frozen=True)
class OrphanedDistinctIdsTable(SnapshotTable):
@@ -297,6 +359,10 @@ class OrphanedDistinctIdsTable(SnapshotTable):
own_tombstone records why a key is here. The exclusion at each checkpoint is re-derived from
live data in RevivedDistinctIdsTable rather than from this column, because both the tombstone
and the owner can change while the run is in flight.
+
+ A key with its own tombstone waits for the minimum tombstone age, and holds its owner back with
+ it (RevivedPersonsTable.populate_deferred_owners). A live key owned by a snapshotted person
+ does not wait, because that person already met the minimum age.
"""
table_name = CLEANUP_ORPHANED_DISTINCT_IDS_TABLE
@@ -304,7 +370,11 @@ class OrphanedDistinctIdsTable(SnapshotTable):
dictionary_types = "team_id Int64, distinct_id String, max_version Int64"
def populate(
- self, client: Client, persons_dictionary: "SnapshotDictionary", settings: Mapping[str, int] | None = None
+ self,
+ client: Client,
+ persons_dictionary: "SnapshotDictionary",
+ settings: Mapping[str, int] | None = None,
+ min_tombstone_age_seconds: int = DEFAULT_MIN_TOMBSTONE_AGE_SECONDS,
) -> None:
# person_distinct_id2 is keyed on (team_id, distinct_id) with person_id as a value, so a
# distinct id can be repointed over time. Deleting rows that merely match a deleted
@@ -327,9 +397,13 @@ class OrphanedDistinctIdsTable(SnapshotTable):
WHERE is_deleted > 0 OR dictHas('{persons_dictionary.qualified_name}', (team_id, person_id))
)
GROUP BY team_id, distinct_id
- HAVING own_tombstone OR dictHas('{persons_dictionary.qualified_name}', (team_id, person_id))
+ HAVING if(
+ own_tombstone,
+ argMax(_timestamp, version) <= now() - toIntervalSecond(%(min_tombstone_age_seconds)s),
+ dictHas('{persons_dictionary.qualified_name}', (team_id, person_id))
+ )
""",
- {"run_id": self.run_id},
+ {"run_id": self.run_id, "min_tombstone_age_seconds": min_tombstone_age_seconds},
settings=settings,
)
@@ -452,6 +526,8 @@ class CleanupRun:
dry_run: bool
cleanup: bool
team_batches: int
+ # Keep the default: a run pickled without this field reads the class default when it unpickles.
+ min_tombstone_age_seconds: int = DEFAULT_MIN_TOMBSTONE_AGE_SECONDS
cohort_sweep: bool
max_cohorts: int
shards: int
@@ -471,6 +547,7 @@ class CleanupRun:
orphaned_count: int = 0
# They ride on the run because the publishing op is the only place that sees a whole sweep.
stranded_runs_reaped: int = 0 # clear_removed_cohort_data
+ deferred_person_count: int = 0 # snapshot_orphaned_distinct_ids
revived_person_count: int = 0 # both recheck_revived_persons checkpoints, summed
revived_distinct_id_count: int = 0 # both recheck_revived_persons checkpoints, summed
queued_for_postgres: int = 0 # persist_deleted_persons
@@ -489,6 +566,7 @@ class CleanupRun:
dry_run=config.dry_run,
cleanup=config.cleanup,
team_batches=config.team_batches,
+ min_tombstone_age_seconds=config.min_tombstone_age_seconds,
cohort_sweep=config.cohort_sweep,
max_cohorts=config.max_cohorts,
shards=config.shards,
@@ -547,6 +625,29 @@ def _create_dictionary(
return dictionary
+def wait_for_drain_to_stop(context: dagster.OpExecutionContext) -> None:
+ """Block until no Postgres drain run executes, so the drain never runs while the sweep does.
+
+ Each side checks after its own run starts, so the side that checks second always sees the other.
+ A drain run in a terminal status has no request in flight.
+ """
+ deadline = time.monotonic() + DRAIN_STOP_TIMEOUT_SECONDS
+ while blockers := describe_runs(
+ context.instance,
+ (PERSON_PG_CLEANUP_DRAIN_JOB,),
+ statuses=EXECUTING_RUN_STATUSES,
+ exclude_run_id=context.run_id,
+ ):
+ if time.monotonic() >= deadline:
+ raise dagster.Failure(
+ f"The Postgres drain did not stop within {DRAIN_STOP_TIMEOUT_SECONDS}s: {'; '.join(blockers)}. "
+ "Cancel it, then launch a new sweep run, or re-execute this run from "
+ "persist_deleted_persons if that op failed."
+ )
+ context.log.info(f"Waiting {DRAIN_STOP_POLL_SECONDS}s for the Postgres drain to stop: {'; '.join(blockers)}")
+ time.sleep(DRAIN_STOP_POLL_SECONDS)
+
+
class TombstoneQueueConfig(dagster.Config):
visibility_timeout_seconds: int = 600
poll_interval_seconds: int = 15
@@ -606,6 +707,7 @@ def clear_removed_cohort_data(
long or failed. Going first also keeps the person snapshot as close to its own delete as
possible, which is what bounds how many persons can revive mid-run.
"""
+ wait_for_drain_to_stop(context)
run = CleanupRun.for_run(context.run_id, config)
reaped = reap_stranded_run_assets(context, cluster)
run = replace(run, stranded_runs_reaped=reaped)
@@ -665,6 +767,7 @@ def snapshot_deleted_persons(
partial(
run.persons.populate,
settings=run.query_settings,
+ min_tombstone_age_seconds=run.min_tombstone_age_seconds,
min_team_id=run.min_team_id,
max_team_id=run.max_team_id,
max_persons=run.max_persons,
@@ -693,11 +796,32 @@ def snapshot_orphaned_distinct_ids(
run: CleanupRun,
) -> CleanupRun:
"""Resolve which distinct ids belong to the snapshotted persons, or tombstoned themselves."""
+ # Runs before the persons dictionary, so a held-back person reaches neither delete nor the queue.
+ # Runs before the distinct id snapshot, so a key that reaches the minimum age in between only delays its owner.
+ deferred_before = cluster.any_host_by_role(
+ partial(run.revived.count, settings=run.query_settings), NodeRole.DATA
+ ).result()
+ deferred_total = cluster.any_host_by_role(
+ partial(
+ run.revived.populate_deferred_owners,
+ persons=run.persons,
+ settings=run.query_settings,
+ min_tombstone_age_seconds=run.min_tombstone_age_seconds,
+ ),
+ NodeRole.DATA,
+ ).result()
+ cluster.map_all_hosts(run.revived.sync_replica).result()
+ deferred = deferred_total - deferred_before
_create_dictionary(context, cluster, run.persons_dictionary, run)
started = time.monotonic()
cluster.any_host_by_role(
- partial(run.orphaned.populate, persons_dictionary=run.persons_dictionary, settings=run.query_settings),
+ partial(
+ run.orphaned.populate,
+ persons_dictionary=run.persons_dictionary,
+ settings=run.query_settings,
+ min_tombstone_age_seconds=run.min_tombstone_age_seconds,
+ ),
NodeRole.DATA,
).result()
cluster.map_all_hosts(run.orphaned.sync_replica).result()
@@ -710,10 +834,11 @@ def snapshot_orphaned_distinct_ids(
context.add_output_metadata(
{
"orphaned_distinct_ids": dagster.MetadataValue.int(count),
+ "deferred_persons": dagster.MetadataValue.int(deferred),
"snapshot_seconds": dagster.MetadataValue.float(snapshot_seconds),
}
)
- return replace(run, orphaned_count=count)
+ return replace(run, orphaned_count=count, deferred_person_count=deferred)
def recheck_revived_persons(name: str) -> dagster.OpDefinition:
@@ -1110,6 +1235,8 @@ def delete_orphaned_distinct_ids(
context.log.info("dry run: skipping the delete from %s", PERSON_DISTINCT_ID2_TABLE)
return run
+ # A run re-executed from this op skips the first op's wait.
+ wait_for_drain_to_stop(context)
_require_snapshot_intact(cluster, run.orphaned, run.orphaned_count, run.query_settings)
team_ids = cluster.any_host_by_role(partial(run.orphaned.team_ids, settings=run.query_settings), NodeRole.DATA)
ranges = _team_ranges(team_ids.result(), run.team_batches)
@@ -1135,12 +1262,16 @@ def delete_orphaned_distinct_ids(
)
-# The drain deletes from this table while we write it, and a lock conflict would otherwise fail
-# the whole weekly sweep.
+# The drain does not run beside this op, but any other session that locks these rows can still
+# conflict, and a lock conflict would otherwise fail the whole weekly sweep.
PG_QUEUE_CONFLICT_CODES = frozenset({"55P03", "40P01"})
PG_QUEUE_RETRY_WINDOW_SECONDS = 300.0
PG_QUEUE_RETRY_BACKOFF_SECONDS = 1.0
+# Covers what the in-op conflict retry does not, such as a dropped connection; the persist is idempotent.
+# The failure hook fires only after the last attempt, so the dictionaries survive a pending retry.
+PERSIST_RETRY_POLICY = dagster.RetryPolicy(max_retries=3, delay=60, backoff=dagster.Backoff.EXPONENTIAL)
+
def _write_queue_page(
connection: psycopg2.extensions.connection,
@@ -1179,14 +1310,18 @@ def _write_queue_page(
time.sleep(pause)
[email protected](retry_policy=PERSIST_RETRY_POLICY)
def persist_deleted_persons(
context: dagster.OpExecutionContext,
cluster: dagster.ResourceParam[ClickhouseCluster],
persons_database_url: dagster.ResourceParam[str],
run: CleanupRun,
) -> CleanupRun:
- """Hand the swept persons to Postgres, before the step that makes them unrecoverable.
+ """Hand the persons that delete_persons removed from ClickHouse to Postgres.
+
+ If this op fails after its retries, those persons stay in Postgres as tombstones, which costs
+ only storage. The failure hook counts it, and a re-execution from this op queues them while the
+ snapshot is inside its TTL.
The queue is advisory, never authoritative. Rows sit here until the drain runs, so a person
can be revived after being queued no matter how carefully this op checks. ClickHouse also
@@ -1198,6 +1333,8 @@ def persist_deleted_persons(
context.log.info("dry run: skipping the write to %s", PG_CLEANUP_QUEUE_TABLE)
return run
+ # A run re-executed from this op skips the first op's wait.
+ wait_for_drain_to_stop(context)
# Connected here rather than at resource init: a connect failure at init happens before the
# step exists, so no failure hook runs and the run's dictionaries are stranded. Failing
# inside the op is a step failure, which is what lets drop_assets_on_failure fire. It also
@@ -1291,6 +1428,8 @@ def delete_persons(
context.log.info("dry run: skipping the delete from %s", PERSONS_TABLE)
return run
+ # A run re-executed from this op skips the first op's wait.
+ wait_for_drain_to_stop(context)
_require_snapshot_intact(cluster, run.persons, run.persons_count, run.query_settings)
team_ids = cluster.any_host_by_role(partial(run.persons.team_ids, settings=run.query_settings), NodeRole.DATA)
ranges = _team_ranges(team_ids.result(), run.team_batches)
@@ -1346,6 +1485,11 @@ def _sweep_gauges(run: CleanupRun, completed_at: float) -> list[PublishedGauge]:
help_text="Orphaned distinct id mappings this run snapshotted, under the same cap",
value=run.orphaned_count,
),
+ PublishedGauge(
+ name="posthog_clickhouse_deletion_sweep_deferred_persons",
+ help_text="Snapshotted persons held back until a distinct id they own reaches the minimum tombstone age",
+ value=run.deferred_person_count,
+ ),
PublishedGauge(
name="posthog_clickhouse_deletion_sweep_revived_persons",
help_text="Persons that came back between the snapshot and the delete, and were excluded",
@@ -1524,12 +1668,18 @@ def drop_assets_on_failure(context: dagster.HookContext) -> None:
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.
+
+ A failed persist_deleted_persons is counted: the persons its run deleted from ClickHouse stay in
+ Postgres as tombstones until a re-execution from that op, because no later snapshot finds them.
"""
+ if context.step_key == persist_deleted_persons.name:
+ _emit(MetricsClient(context.resources.cluster), "clickhouse_cleanup_persist_failed", {})
_kill_and_drop_run_assets(context.resources.cluster, context.run_id.replace("-", "_"))
# The rows this job writes to person_pg_cleanup_queue are drained by person_pg_cleanup_drain_job,
-# which runs on its own daily schedule rather than in this chain.
+# which runs on its own daily schedule rather than in this chain. The two never run together:
+# the drain stops when it sees this job executing, and this job waits for the drain to stop.
@dagster.job(
hooks={drop_assets_on_failure},
tags={
@@ -1549,14 +1699,13 @@ def clickhouse_deletion_sweep_job():
run = recheck_revived_persons("recheck_before_distinct_id_delete")(run)
run = delete_orphaned_distinct_ids(run)
- # One checkpoint covers both the handoff and the person delete, so they agree on who is
- # deleted. Checking again between them would let a revival spare a person in ClickHouse
- # while its row stayed queued, and the Postgres drain would then clear a live person.
+ # One checkpoint covers both the person delete and the handoff, so they agree on who is deleted.
run = recheck_revived_persons("recheck_before_person_delete")(run)
- run = persist_deleted_persons(run)
+ run = delete_persons(run)
- # Each op takes the previous op's output, which is what keeps the sweeps in sequence.
- drop_snapshot_assets(publish_sweep_metrics(delete_persons(run)))
+ # Each op takes the previous op's output, which is what keeps the sweeps in sequence. The
+ # handoff follows the delete, so the drain never removes a person that ClickHouse still holds.
+ drop_snapshot_assets(publish_sweep_metrics(persist_deleted_persons(run)))
# What the sensor launches with. Every field is pinned so a changed default cannot move production,
@@ -1575,6 +1724,7 @@ SCHEDULED_RUN_CONFIG = {
# Never 0: unbounded takes the whole backlog in one run. 30M outpaces both
# regions' weekly arrivals, so the backlog converges.
"max_persons": 30_000_000,
+ "min_tombstone_age_seconds": 24 * 3600,
"shards": 16,
"max_execution_time": 1800,
# The orphaned distinct id populate, not the persons one, sets this. 64 GiB failed it.
diff --git a/posthog/dags/person_pg_cleanup_drain.py b/posthog/dags/person_pg_cleanup_drain.py
index 3e4e8f330e68..2065956d916f 100644
--- a/posthog/dags/person_pg_cleanup_drain.py
+++ b/posthog/dags/person_pg_cleanup_drain.py
@@ -1,6 +1,6 @@
"""Drain person_pg_cleanup_queue into Postgres hard deletes.
-The ClickHouse sweep (clickhouse_cleanup.py) removes a deleted person's rows from ClickHouse and
+The ClickHouse sweep (clickhouse_cleanup.py) removes a deleted person's rows from ClickHouse, then
queues the person here. Postgres still holds the tombstoned posthog_person row and its dependent
rows (distinct ids, hash key overrides, cohort memberships) until this job asks personhog to
delete them.
@@ -20,6 +20,9 @@ reopened and the statement run again), a fatal gRPC code, or more blocked person
max_blocked. The one state the job parks is a tombstoned person that still owns a live distinct
id: personhog reports it as blocked, and its row is stamped blocked_at and skipped for a retry
interval, because ingestion can still reach that person and no delete may resolve it.
+
+The drain stops before each page, request and retry when a sweep executes, and the sweep waits for
+it to stop, so the two never run together.
"""
import math
@@ -42,8 +45,14 @@ from prometheus_client import Gauge
from posthog.clickhouse.cluster import ClickhouseCluster
from posthog.clickhouse.custom_metrics import MetricsClient
-from posthog.dags.clickhouse_cleanup import PG_CLEANUP_QUEUE_TABLE, PublishedGauge
-from posthog.dags.common import JobOwners
+from posthog.dags.clickhouse_cleanup import (
+ DRAIN_STOP_POLL_SECONDS,
+ PERSON_PG_CLEANUP_DRAIN_JOB,
+ PG_CLEANUP_QUEUE_TABLE,
+ PublishedGauge,
+ clickhouse_deletion_sweep_job,
+)
+from posthog.dags.common import EXECUTING_RUN_STATUSES, JobOwners, describe_runs
from posthog.dataclasses import frozen
from posthog.metrics import pushed_metrics_registry
from posthog.personhog_client.client import PersonHogClient, personhog_call, require_personhog_client
@@ -59,6 +68,11 @@ DRAIN_METRICS_JOB = "person_pg_cleanup_drain"
# Server-side cap on DeleteTombstonedPersonsRequest.person_uuids.
RPC_MAX_UUIDS = 1000
+# The sweep polls for the drain this often, so checking for the sweep more often only loads
+# Dagster's run storage.
+SWEEP_CHECK_INTERVAL_SECONDS = DRAIN_STOP_POLL_SECONDS
+STOPPED_EARLY = frozenset({"max_runtime", "sweep_running"})
+
# tonic takes min(client deadline, personhog-router's BACKEND_TIMEOUT_MS), which is 15 s, so this
# deadline is what bounds a request.
ROUTER_BACKEND_TIMEOUT_SECONDS = 5.0
@@ -283,8 +297,8 @@ class DrainTotals:
}
-class _OutOfTime(Exception):
- """The run's deadline passed while a request or statement was being retried."""
+class _Stopped(Exception):
+ """The run's deadline passed, or a sweep started, while a request or statement was being retried."""
def chunks_for_page(rows: Sequence[QueueRow], rpc_batch_size: int) -> list[Chunk]:
@@ -488,6 +502,7 @@ class _Drain:
self.totals.step_rows_min = self.totals.step_rows_max = self.step_rows
self.successes_at_step = 0
self.deadline = math.inf if config.max_runtime_seconds == 0 else _now_monotonic() + config.max_runtime_seconds
+ self.next_sweep_check = 0.0
self.blocked_before = datetime.now(UTC) - timedelta(hours=config.blocked_retry_hours)
def out_of_time(self) -> bool:
@@ -546,8 +561,8 @@ class _Drain:
self.close()
elif pg_is_queue_conflict(exc):
self.totals.pg_queue_conflict_retries += 1
- if self.out_of_time():
- raise _OutOfTime from exc
+ if self.should_stop():
+ raise _Stopped from exc
pause = backoff_seconds(PG_RETRY_BACKOFF_SECONDS, failures)
self.context.log.warning(
"persons Postgres %s (%s); attempt %d in %.1fs",
@@ -562,9 +577,36 @@ class _Drain:
self.totals.pg_seconds_total += time.perf_counter() - started
return result
+ def yield_to_sweep(self) -> bool:
+ """Stop when a sweep run executes, so the drain never runs while the sweep does.
+
+ Unresolved rows stay queued, and checking before every page, request and retry keeps the sweep's
+ wait to one attempt.
+ """
+ if self.totals.stopped_reason == "sweep_running":
+ return True
+ now = time.monotonic()
+ if now < self.next_sweep_check:
+ return False
+ self.next_sweep_check = now + SWEEP_CHECK_INTERVAL_SECONDS
+ sweeps = describe_runs(
+ self.context.instance,
+ (clickhouse_deletion_sweep_job.name,),
+ statuses=EXECUTING_RUN_STATUSES,
+ exclude_run_id=self.context.run_id,
+ )
+ if not sweeps:
+ return False
+ self.context.log.warning("stopping for the ClickHouse sweep: %s", "; ".join(sweeps))
+ self.totals.stopped_reason = "sweep_running"
+ return True
+
+ def should_stop(self) -> bool:
+ return self.out_of_time() or self.yield_to_sweep()
+
def pages(self) -> Iterator[list[QueueRow]]:
after: QueueCursor | None = None
- while not self.out_of_time():
+ while not self.should_stop():
limit = self.page_limit()
if limit <= 0:
self.totals.stopped_reason = "max_persons"
@@ -632,8 +674,8 @@ class _Drain:
"grpc_code": dagster.MetadataValue.text(_code_name(code)),
},
) from exc
- if self.out_of_time():
- raise _OutOfTime from exc
+ if self.should_stop():
+ raise _Stopped from exc
pause = backoff_seconds(self.config.retry_backoff_seconds, failures)
self.context.log.warning(
"personhog delete of %d persons failed (%s); attempt %d in %.1fs with a %d-row budget",
@@ -672,7 +714,7 @@ class _Drain:
self.totals.chunks += 1
pending: Sequence[str] = chunk.person_uuids
while pending:
- if self.out_of_time():
+ if self.should_stop():
# Rows of the persons still pending stay queued; the next run continues them.
return
response = self.send(chunk, pending)
@@ -765,16 +807,16 @@ class _Drain:
continue
for chunk in chunks_for_page(page, self.config.rpc_batch_size):
self.resolve(chunk)
- if self.totals.stopped_reason == "max_runtime":
+ if self.totals.stopped_reason in STOPPED_EARLY:
break
if self.totals.pages % LOG_EVERY_PAGES == 0:
self.emit_counters_since(emitted)
emitted = self.snapshot()
self.log_progress()
- if self.totals.stopped_reason == "max_runtime":
+ if self.totals.stopped_reason in STOPPED_EARLY:
# Requests left in this page were never sent, so their rows stay queued.
break
- except _OutOfTime:
+ except _Stopped:
# Raised inside a retry, so the rows of that request stay queued for the next run.
pass
except Exception:
@@ -898,7 +940,7 @@ def _drain_gauges(totals: DrainTotals, completed_at: float) -> list[PublishedGau
),
PublishedGauge(
name=f"{prefix}pg_queue_conflict_retries",
- help_text="Queue statements retried after a lock or serialization conflict, mostly with the sweep",
+ help_text="Queue statements retried after a lock or serialization conflict",
value=totals.pg_queue_conflict_retries,
),
PublishedGauge(
@@ -914,11 +956,15 @@ def publish_drain_metrics(context: dagster.OpExecutionContext, totals: DrainTota
"""Publish what the run measured, so alerting and dashboards can read it.
A dry run publishes nothing. It deletes nothing, so moving the last-success gauge would let an
- ad-hoc run from the Dagster UI mask a drain that has stopped working.
+ ad-hoc run from the Dagster UI mask a drain that has stopped working. A run that stopped for
+ the sweep publishes nothing for the same reason: a sweep that never finishes stops every drain.
"""
if totals.dry_run:
context.log.info("dry run: publishing no metrics")
return totals
+ if totals.stopped_reason == "sweep_running":
+ context.log.info("stopped for the sweep: publishing no metrics")
+ return totals
gauges = _drain_gauges(totals, time.time())
with pushed_metrics_registry(DRAIN_METRICS_JOB) as registry:
@@ -930,6 +976,7 @@ def publish_drain_metrics(context: dagster.OpExecutionContext, totals: DrainTota
@dagster.job(
+ name=PERSON_PG_CLEANUP_DRAIN_JOB,
tags={
"owner": JobOwners.TEAM_INGESTION.value,
# Limit 1 in charts (argocd/dagster/deployment_settings), so a second drain queues rather
diff --git a/posthog/dags/tests/test_clickhouse_cleanup.py b/posthog/dags/tests/test_clickhouse_cleanup.py
index 6f0ef17346c4..e1e960d66a7c 100644
--- a/posthog/dags/tests/test_clickhouse_cleanup.py
+++ b/posthog/dags/tests/test_clickhouse_cleanup.py
@@ -2,6 +2,7 @@ import time
import itertools
from collections.abc import Iterator
from contextlib import AbstractContextManager, contextmanager
+from copy import deepcopy
from dataclasses import replace
from datetime import UTC, datetime, timedelta
from functools import partial
@@ -14,7 +15,6 @@ import dagster
import psycopg2
from clickhouse_driver import Client
from prometheus_client import CollectorRegistry
-from psycopg2 import OperationalError
from posthog.clickhouse.cleanup_snapshots import (
CLEANUP_DELETED_PERSONS_TABLE,
@@ -34,6 +34,7 @@ from posthog.dags.clickhouse_cleanup import (
OrphanedDistinctIdsTable,
clickhouse_deletion_sweep_job,
)
+from posthog.dags.person_pg_cleanup_drain import person_pg_cleanup_drain_job
from posthog.models.async_deletion import AsyncDeletion, DeletionType
from posthog.models.person.util import create_person, create_person_distinct_id
from posthog.persons_db import persons_db_url
@@ -46,9 +47,17 @@ COHORT_ID = 77
RUN_FOR_REAL = {"ops": {"clear_removed_cohort_data": {"config": {"dry_run": False}}}}
+def without_age_floor(run_config: dict | None) -> dict:
+ # Tests write their rows moments before the run, so the default minimum tombstone age would skip them all.
+ run_config = deepcopy(run_config or {})
+ op_config = run_config.setdefault("ops", {}).setdefault("clear_removed_cohort_data", {}).setdefault("config", {})
+ op_config.setdefault("min_tombstone_age_seconds", 0)
+ return run_config
+
+
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,
+ run_config=without_age_floor(run_config),
resources={"cluster": cluster, "persons_database_url": persons_db_url(writer=True)},
raise_on_error=raise_on_error,
instance=instance,
@@ -277,6 +286,72 @@ def test_removes_every_version_of_a_distinct_id_repointed_to_a_deleted_person(
assert cluster.any_host(current_owner("moved")).result() is None
+def insert_distinct_id(
+ cluster: ClickhouseCluster, distinct_id: str, person_id: str, version: int, produced_at: datetime, is_deleted=False
+) -> None:
+ # create_person_distinct_id stamps _timestamp with now(), so an older _timestamp needs a direct insert.
+ row = (TEAM_ID, distinct_id, UUID(person_id), int(is_deleted), version, produced_at, 0, 0)
+ cluster.any_host(
+ lambda client: client.execute(
+ "INSERT INTO person_distinct_id2"
+ " (team_id, distinct_id, person_id, is_deleted, version, _timestamp, _offset, _partition) VALUES",
+ [row],
+ )
+ ).result()
+
+
+def test_the_age_floor_defers_tombstones_produced_too_recently(cluster: ClickhouseCluster, persons_database):
+ # The minimum age applies to the newest version's production time. Reading the oldest version or
+ # the first tombstone instead deletes a key whose newest tombstone is still recent.
+ old = datetime.now(UTC) - timedelta(days=2)
+ young = datetime.now(UTC) - timedelta(hours=1)
+ swept = create_person(team_id=TEAM_ID, version=0, is_deleted=True, timestamp=old)
+ held = create_person(team_id=TEAM_ID, version=0, is_deleted=True, timestamp=old)
+ young_tombstone = create_person(team_id=TEAM_ID, version=0, is_deleted=True, timestamp=young)
+ deleted_recently = create_person(team_id=TEAM_ID, version=0, timestamp=old)
+ create_person(uuid=deleted_recently, team_id=TEAM_ID, version=1, is_deleted=True, timestamp=young)
+ deleted_again = create_person(team_id=TEAM_ID, version=1, is_deleted=True, timestamp=old)
+ create_person(uuid=deleted_again, team_id=TEAM_ID, version=2, is_deleted=True, timestamp=young)
+
+ live = create_person(team_id=TEAM_ID, version=0)
+ for distinct_id, owner, tombstoned_at in [
+ ("young_tombstone", live, young),
+ ("old_tombstone", live, old),
+ # Its own tombstone is recent, so it waits and holds back its owner.
+ ("young_tombstone_of_held_person", held, young),
+ ]:
+ insert_distinct_id(cluster, distinct_id, owner, version=0, produced_at=old)
+ insert_distinct_id(cluster, distinct_id, owner, version=1, produced_at=tombstoned_at, is_deleted=True)
+ # A live mapping of a person old enough to delete goes with that person.
+ insert_distinct_id(cluster, "live_of_swept_person", swept, version=0, produced_at=young)
+
+ floor = clickhouse_cleanup.DEFAULT_MIN_TOMBSTONE_AGE_SECONDS
+ result = run_job(
+ cluster,
+ persons_database,
+ run_config={
+ "ops": {"clear_removed_cohort_data": {"config": {"dry_run": False, "min_tombstone_age_seconds": floor}}}
+ },
+ )
+
+ assert cluster.any_host(rows_for(swept)).result() == 0
+ assert cluster.any_host(rows_for(held)).result() == 1
+ assert cluster.any_host(rows_for(young_tombstone)).result() == 1
+ # A background merge may collapse two versions at any point, so only survival is stable.
+ assert cluster.any_host(rows_for(deleted_recently)).result() > 0
+ assert cluster.any_host(rows_for(deleted_again)).result() > 0
+ assert [str(row[1]) for row in queued_rows(persons_database)] == [swept]
+ assert result.output_for_node("publish_sweep_metrics").deferred_person_count == 1
+ assert cluster.any_host(surviving_distinct_ids).result() == {"young_tombstone", "young_tombstone_of_held_person"}
+
+
+def test_the_age_floor_rejects_a_negative_age():
+ # A negative minimum age puts the cutoff in the future, which deletes every tombstone however recent.
+ with pytest.raises(ValueError, match="greater than or equal to 0"):
+ clickhouse_cleanup.CleanupConfig(min_tombstone_age_seconds=-1)
+
+
@pytest.mark.django_db
def test_queues_the_deleted_persons_for_postgres(cluster: ClickhouseCluster, persons_database):
deleted = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
@@ -298,6 +373,40 @@ def test_queues_the_deleted_persons_for_postgres(cluster: ClickhouseCluster, per
assert len(queued_rows(persons_database)) == 1
[email protected]("failing_op", ["delete_persons", "persist_deleted_persons"])
+def test_a_failed_person_delete_queues_nothing_for_postgres(
+ cluster: ClickhouseCluster, persons_database, failing_op: str
+):
+ # A person queued before a ClickHouse delete that then fails is drained from Postgres while
+ # ClickHouse still holds it.
+ doomed = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ real_runner = clickhouse_cleanup.LightweightDeleteMutationRunner
+
+ def fail_on_the_person_table(*args, **kwargs):
+ if kwargs["table"] == clickhouse_cleanup.PERSONS_TABLE:
+ raise RuntimeError("person delete failed")
+ return real_runner(*args, **kwargs)
+
+ def fail_the_queue_write(*args, **kwargs):
+ # allow_retries=False skips the op's retry policy, whose delays run on the wall clock.
+ raise dagster.Failure("queue write failed", allow_retries=False)
+
+ failure = (
+ patch.object(clickhouse_cleanup, "LightweightDeleteMutationRunner", fail_on_the_person_table)
+ if failing_op == "delete_persons"
+ else patch.object(clickhouse_cleanup, "_write_queue_page", fail_the_queue_write)
+ )
+ with failure, patch.object(clickhouse_cleanup, "_emit", wraps=clickhouse_cleanup._emit) as emit:
+ result = run_job(cluster, persons_database, raise_on_error=False)
+
+ assert not result.success
+ assert cluster.any_host(rows_for(doomed)).result() == (1 if failing_op == "delete_persons" else 0)
+ assert queued_rows(persons_database) == []
+ persist_failures = [call for call in emit.call_args_list if call.args[1] == "clickhouse_cleanup_persist_failed"]
+ assert len(persist_failures) == (1 if failing_op == "persist_deleted_persons" else 0)
+
+
@pytest.mark.django_db
def test_queues_every_person_across_page_boundaries(cluster: ClickhouseCluster, persons_database, monkeypatch):
# The handoff pages its ClickHouse read by keyset and commits per page; an off-by-one at a
@@ -477,7 +586,8 @@ def test_a_postgres_connect_failure_drops_the_dictionaries(cluster: ClickhouseCl
# keep working, or the cohort op fails first and the wrong step trips the hook.
if args and isinstance(args[0], str):
- raise OperationalError("connection timed out")
+ # allow_retries=False skips the op's retry policy, whose delays run on the wall clock.
+ raise dagster.Failure("connection timed out", allow_retries=False)
return real_connect(*args, **kwargs)
@@ -539,7 +649,7 @@ def test_a_same_run_retry_rewrites_no_rows(cluster: ClickhouseCluster, persons_d
# upserts the same person twice. The op is invoked directly instead, as a retry would.
create_person(team_id=TEAM_ID, version=0, is_deleted=True)
run = clickhouse_cleanup.CleanupRun.for_run("persist_retry_run", clickhouse_cleanup.CleanupConfig(dry_run=False))
- cluster.any_host(run.persons.populate).result()
+ cluster.any_host(partial(run.persons.populate, min_tombstone_age_seconds=0)).result()
cluster.map_all_hosts(run.persons.sync_replica).result()
run = replace(run, distinct_ids_deleted_at=datetime(2026, 1, 1, tzinfo=UTC), persons_count=1)
@@ -576,11 +686,11 @@ def test_excludes_a_person_revived_while_the_run_is_in_flight(cluster: Clickhous
original = OrphanedDistinctIdsTable.populate
- def revive_then_populate(self, client, persons_dictionary, settings=None):
+ def revive_then_populate(self, client, persons_dictionary, **kwargs):
# Fires after the snapshot is taken and the dictionary is loaded, so the checkpoint is
# the only thing standing between the revived person and the delete.
create_person(uuid=revived, team_id=TEAM_ID, version=10, is_deleted=False)
- return original(self, client, persons_dictionary, settings=settings)
+ return original(self, client, persons_dictionary, **kwargs)
with patch.object(OrphanedDistinctIdsTable, "populate", revive_then_populate):
result = run_job(cluster, persons_database)
@@ -774,8 +884,8 @@ def test_keeps_a_distinct_id_recaptured_while_the_run_is_in_flight(cluster: Clic
original = OrphanedDistinctIdsTable.populate
- def recapture_then_populate(self, client, persons_dictionary, settings=None):
- result = original(self, client, persons_dictionary, settings=settings)
+ def recapture_then_populate(self, client, persons_dictionary, **kwargs):
+ result = original(self, client, persons_dictionary, **kwargs)
# A client captures the id again after the snapshot froze the reason it qualified. Trusting
# that snapshot would delete every version of the mapping, including this live one.
create_person_distinct_id(team_id=TEAM_ID, distinct_id="recaptured", person_id=live, version=200)
@@ -866,8 +976,8 @@ def test_rows_written_after_the_snapshot_survive(cluster: ClickhouseCluster, per
original = OrphanedDistinctIdsTable.populate
- def write_after_snapshot(self, client, persons_dictionary, settings=None):
- result = original(self, client, persons_dictionary, settings=settings)
+ def write_after_snapshot(self, client, persons_dictionary, **kwargs):
+ result = original(self, client, persons_dictionary, **kwargs)
create_person_distinct_id(team_id=TEAM_ID, distinct_id="racing", person_id=deleted, version=500)
return result
@@ -903,10 +1013,11 @@ def test_a_retried_snapshot_populate_cannot_skew_the_dictionary(cluster: Clickho
# dictionary must read the newest max_version bound, not whichever duplicate it happens upon.
person = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
table = clickhouse_cleanup.DeletedPersonsTable(run_id="retry_run")
- cluster.any_host(table.populate).result()
+ populate = partial(table.populate, min_tombstone_age_seconds=0)
+ cluster.any_host(populate).result()
# The person gains a higher deleted version between the attempt and its retry.
create_person(uuid=person, team_id=TEAM_ID, version=3, is_deleted=True)
- cluster.any_host(table.populate).result()
+ cluster.any_host(populate).result()
cluster.map_all_hosts(table.sync_replica).result()
dictionary = clickhouse_cleanup.SnapshotDictionary(
@@ -1087,12 +1198,16 @@ def test_the_sweep_sensor_launches_a_real_run_after_deletes():
assert request.run_key == "11111111-1111-1111-1111-111111111111"
-def test_the_job_carries_the_operational_tags():
+def test_the_job_carries_its_operational_settings():
# The charts run-queue limit matches the concurrency tag, and the janitor's unconditional reap
# depends on it. max_runtime is the only bound on total runtime.
tags = clickhouse_deletion_sweep_job.tags
assert tags["clickhouse_deletion_sweep_concurrency"] == "v1"
assert int(tags["dagster/max_runtime"]) == 43200
+ # The persist follows the person delete, so a dropped connection without a retry leaves every
+ # person the run deleted in Postgres, where no later snapshot finds them.
+ persist_retries = clickhouse_cleanup.persist_deleted_persons.retry_policy
+ assert persist_retries is not None and persist_retries.max_retries >= 1
@pytest.mark.parametrize(
@@ -1130,6 +1245,51 @@ def test_the_sweep_sensor_skips_while_a_sweep_is_already_active(status: dagster.
assert isinstance(result, dagster.SkipReason)
+def test_the_sweep_waits_for_an_executing_drain_before_it_touches_anything(
+ cluster: ClickhouseCluster, persons_database
+):
+ # The drain stops only before its next request, so a sweep that does not wait races a request in flight.
+ doomed = create_person(team_id=TEAM_ID, version=0, is_deleted=True)
+ instance = dagster.DagsterInstance.ephemeral()
+ drain_run = instance.create_run_for_job(
+ job_def=person_pg_cleanup_drain_job, status=dagster.DagsterRunStatus.STARTED
+ )
+ real_sleep = time.sleep
+ seen_while_draining: list[tuple[int, list[tuple]]] = []
+
+ def stop_the_drain(seconds: float) -> None:
+ run = instance.get_run_by_id(drain_run.run_id)
+ if run is None or run.is_finished:
+ real_sleep(seconds)
+ return
+ seen_while_draining.append((cluster.any_host(rows_for(doomed)).result(), queued_rows(persons_database)))
+ instance.report_run_canceled(run)
+
+ # The patch replaces time.sleep for every caller in the process, so other callers keep the real one.
+ with patch("posthog.dags.clickhouse_cleanup.time.sleep", side_effect=stop_the_drain):
+ result = run_job(cluster, persons_database, instance=instance)
+
+ assert result.success
+ assert seen_while_draining == [(1, [])]
+ assert cluster.any_host(rows_for(doomed)).result() == 0
+
+
+def test_the_sweep_fails_when_the_drain_does_not_stop():
+ # An unbounded wait would hold the weekly sweep until its max_runtime kills it.
+ instance = dagster.DagsterInstance.ephemeral()
+ instance.create_run_for_job(job_def=person_pg_cleanup_drain_job, status=dagster.DagsterRunStatus.STARTED)
+ context = dagster.build_op_context(instance=instance)
+ clock = itertools.chain([0.0], itertools.repeat(float(clickhouse_cleanup.DRAIN_STOP_TIMEOUT_SECONDS)))
+
+ with (
+ patch("posthog.dags.clickhouse_cleanup.time.monotonic", side_effect=lambda: next(clock)),
+ patch("posthog.dags.clickhouse_cleanup.time.sleep"),
+ pytest.raises(dagster.Failure, match="did not stop"),
+ ):
+ clickhouse_cleanup.wait_for_drain_to_stop(context)
+
+
def _sweep_run(dry_run: bool) -> clickhouse_cleanup.CleanupRun:
config = clickhouse_cleanup.CleanupConfig(dry_run=dry_run)
return clickhouse_cleanup.CleanupRun.for_run("11111111-1111-1111-1111-111111111111", config)
@@ -1167,6 +1327,7 @@ def test_publishes_every_measurement_the_run_took() -> None:
_sweep_run(dry_run=False),
persons_count=11,
orphaned_count=22,
+ deferred_person_count=5,
revived_person_count=3,
revived_distinct_id_count=4,
queued_for_postgres=7,
@@ -1180,6 +1341,7 @@ def test_publishes_every_measurement_the_run_took() -> None:
prefix = "posthog_clickhouse_deletion_sweep_"
assert registry.get_sample_value(f"{prefix}snapshot_deleted_persons") == 11
assert registry.get_sample_value(f"{prefix}snapshot_orphaned_distinct_ids") == 22
+ assert registry.get_sample_value(f"{prefix}deferred_persons") == 5
assert registry.get_sample_value(f"{prefix}revived_persons") == 3
assert registry.get_sample_value(f"{prefix}revived_distinct_ids") == 4
assert registry.get_sample_value(f"{prefix}queued_for_postgres") == 7
diff --git a/posthog/dags/tests/test_person_pg_cleanup_drain.py b/posthog/dags/tests/test_person_pg_cleanup_drain.py
index 3106182572a6..144e2869c042 100644
--- a/posthog/dags/tests/test_person_pg_cleanup_drain.py
+++ b/posthog/dags/tests/test_person_pg_cleanup_drain.py
@@ -17,7 +17,7 @@ from prometheus_client import CollectorRegistry
from posthog.clickhouse.cluster import ClickhouseCluster
from posthog.clickhouse.custom_metrics import MetricsClient
from posthog.dags import person_pg_cleanup_drain as drain
-from posthog.dags.clickhouse_cleanup import PG_CLEANUP_QUEUE_TABLE
+from posthog.dags.clickhouse_cleanup import PG_CLEANUP_QUEUE_TABLE, clickhouse_deletion_sweep_job
from posthog.dags.person_pg_cleanup_drain import (
Chunk,
DrainTotals,
@@ -58,12 +58,20 @@ def queued(conn) -> list[tuple[int, str, datetime, datetime | None]]:
return cursor.fetchall()
-def run_job(cluster: ClickhouseCluster, *, dry_run: bool = False, raise_on_error: bool = True, **overrides):
+def run_job(
+ cluster: ClickhouseCluster,
+ *,
+ dry_run: bool = False,
+ raise_on_error: bool = True,
+ instance: dagster.DagsterInstance | None = None,
+ **overrides,
+):
config = {"dry_run": dry_run, **FAST, **overrides}
return person_pg_cleanup_drain_job.execute_in_process(
run_config={"ops": {OP: {"config": config}}},
resources={"cluster": cluster, "persons_database_url": persons_db_url(writer=True)},
raise_on_error=raise_on_error,
+ instance=instance,
)
@@ -562,6 +570,61 @@ def test_max_runtime_stops_between_pages_unless_disabled(
assert len(queued(persons_database)) == 3 - expected_deleted
+ "status,starts,expected_deleted,stopped_reason",
+ [
+ pytest.param(dagster.DagsterRunStatus.STARTED, "before", 0, "sweep_running", id="executing_sweep"),
+ # A canceling sweep's last mutation keeps applying server-side, so it still executes.
+ pytest.param(dagster.DagsterRunStatus.CANCELING, "before", 0, "sweep_running", id="canceling_sweep"),
+ pytest.param(dagster.DagsterRunStatus.STARTED, "mid_run", 1, "sweep_running", id="sweep_starts_mid_run"),
+ # A page can outlast the sweep's wait, so the drain also checks before each request.
+ pytest.param(dagster.DagsterRunStatus.STARTED, "mid_page", 1, "sweep_running", id="sweep_starts_mid_page"),
+ # A failing request can retry for the whole retry window, so the drain also checks before each retry.
+ pytest.param(
+ dagster.DagsterRunStatus.STARTED, "during_retry", 0, "sweep_running", id="sweep_starts_during_a_retry"
+ ),
+ pytest.param(dagster.DagsterRunStatus.SUCCESS, "before", 3, "drained", id="finished_sweep"),
+ ],
+)
+def test_the_drain_stops_while_a_sweep_executes(
+ cluster: ClickhouseCluster, persons_database, monkeypatch, status, starts, expected_deleted, stopped_reason
+):
+ # The sweep waits for the drain to stop, so a drain that kept going would hold the weekly sweep.
+ fake = get_active_fake()
+ uuids = [seed_tombstoned(fake, TEAM_A, person_id) for person_id in range(1, 4)]
+ queue(persons_database, [(TEAM_A, uuid, SWEEP_1) for uuid in uuids])
+ monkeypatch.setattr(drain, "SWEEP_CHECK_INTERVAL_SECONDS", 0.0)
+ instance = dagster.DagsterInstance.ephemeral()
+ start_sweep = partial(instance.create_run_for_job, job_def=clickhouse_deletion_sweep_job, status=status)
+ if starts == "before":
+ start_sweep()
+ else:
+ original = fake.delete_tombstoned_persons
+ calls = 0
+
+ def start_sweep_on_the_first_request(
+ request: DeleteTombstonedPersonsRequest, timeout: float | None = None
+ ) -> DeleteTombstonedPersonsResponse:
+ nonlocal calls
+ calls += 1
+ if calls == 1:
+ start_sweep()
+ if starts == "during_retry":
+ raise _RpcError(grpc.StatusCode.UNAVAILABLE)
+ return original(request, timeout=timeout)
+
+ monkeypatch.setattr(fake, "delete_tombstoned_persons", start_sweep_on_the_first_request)
+
+ # One row per request either way: one page per row, or one page of three rows.
+ result = run_job(cluster, instance=instance, page_size=3 if starts == "mid_page" else 1, rpc_batch_size=1)
+
+ assert result.success
+ totals = totals_of(result)
+ assert (totals.stopped_reason, totals.persons_deleted) == (stopped_reason, expected_deleted)
+ assert len(queued(persons_database)) == 3 - expected_deleted
+
+
@pytest.mark.django_db
@pytest.mark.parametrize("failing", ["rpc", "pg"])
def test_max_runtime_ends_a_retry_loop_cleanly(cluster: ClickhouseCluster, persons_database, monkeypatch, failing):
@@ -758,8 +821,15 @@ def publish(totals: DrainTotals) -> tuple[CollectorRegistry, list[str]]:
return registry, pushed_jobs
-def test_a_dry_run_publishes_no_metrics():
- registry, pushed_jobs = publish(DrainTotals(dry_run=True, rows_read=5))
+ "totals",
+ [
+ pytest.param(DrainTotals(dry_run=True, rows_read=5), id="dry_run"),
+ pytest.param(DrainTotals(stopped_reason="sweep_running", rows_read=5), id="stopped_for_the_sweep"),
+ ],
+)
+def test_a_run_that_cannot_prove_the_drain_works_publishes_no_metrics(totals: DrainTotals):
+ registry, pushed_jobs = publish(totals)
# The helper pushes with PUT, which replaces the whole job. Entering it with an empty
# registry would delete the last-success gauge, so not entering it at all is the assertion.