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(dags): log squash and deletes_job runs with their watermark (#122034)

Paweł Szczur50365fb88e23
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index 980a3a5720a3..9cd6bfac65e5 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -138,6 +138,8 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
# --- Internal infra (audit, async, caching, scheduling) ---
"ActivityLog",
"AsyncDeletion",
+ # Instance-wide log of deletion Dagster runs, read by staff in Django admin only.
+ "DeletionRunLog",
"AsyncMigration",
"AsyncMigrationError",
# Outbound email delivery queue — looked up by PK / comment FK from internal
@@ -315,6 +317,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"Team",
"User",
# --- Instance-level config ---
+ "DeletionRunLog", # one row per deletion Dagster run, across all teams
"AsyncMigration",
"AsyncMigrationError",
"InstanceSetting",
diff --git a/posthog/admin/admins/async_deletion_admin.py b/posthog/admin/admins/async_deletion_admin.py
index 986984258eb0..07eac179b32e 100644
--- a/posthog/admin/admins/async_deletion_admin.py
+++ b/posthog/admin/admins/async_deletion_admin.py
@@ -1,6 +1,28 @@
+from datetime import datetime
+
from django.contrib import admin
+from django.db.models import QuerySet, Subquery
+from django.http import HttpRequest
+from django.utils.html import format_html
+from posthog.admin.admins.data_deletion_request_admin import dagster_run_url
from posthog.models import AsyncDeletion
+from posthog.models.async_deletion import DeletionRunJob, DeletionRunLog, DeletionRunStatus, DeletionType
+
+# deletes_job loads these types. The others are deleted by other jobs and never show up in its log.
+DELETES_JOB_TYPES = (DeletionType.Person, DeletionType.Team, DeletionType.Event)
+
+
+def deletion_status(deletion: AsyncDeletion, watermark: datetime | None) -> str:
+ """What support can tell a customer about one deletion request, based on the last deletes_job run."""
+ if deletion.delete_verified_at:
+ return f"Deleted on {deletion.delete_verified_at:%Y-%m-%d %H:%M} UTC"
+ if deletion.deletion_type not in DELETES_JOB_TYPES:
+ return "Pending. Not handled by deletes_job."
+ if deletion.deletion_type == DeletionType.Person and (watermark is None or deletion.created_at > watermark):
+ reached = f"The last run reached {watermark:%Y-%m-%d %H:%M} UTC." if watermark else "No run recorded yet."
+ return f"Waiting for the person overrides squash. {reached}"
+ return "Queued for the next deletes_job run"
@admin.register(AsyncDeletion)
@@ -14,12 +36,72 @@ class AsyncDeletionAdmin(admin.ModelAdmin):
"created_by",
"created_at",
"delete_verified_at",
+ "status",
)
list_filter = ("deletion_type", "delete_verified_at")
search_fields = ("key",)
+ def get_queryset(self, request: HttpRequest) -> QuerySet[AsyncDeletion]:
+ # A subquery keeps the watermark lookup to the one changelist query instead of one per row.
+ latest_watermark = (
+ DeletionRunLog.objects.filter(
+ job=DeletionRunJob.DELETES, status=DeletionRunStatus.SUCCEEDED, limited_to_team_id__isnull=True
+ )
+ .order_by("-started_at")
+ .values("watermark")[:1]
+ )
+ return super().get_queryset(request).annotate(latest_watermark=Subquery(latest_watermark))
+
+ @admin.display(description="Status")
+ def status(self, obj: AsyncDeletion) -> str:
+ return deletion_status(obj, getattr(obj, "latest_watermark", None))
+
+ def has_add_permission(self, request, obj=None):
+ return False
+
+ def has_change_permission(self, request, obj=None):
+ return False
+
+
+def _run_link(run_id: str) -> str:
+ url = dagster_run_url(run_id)
+ if url is None:
+ return run_id
+ return format_html('<a href="{}" target="_blank" rel="noopener">{}</a>', url, run_id)
+
+
[email protected](DeletionRunLog)
+class DeletionRunLogAdmin(admin.ModelAdmin):
+ list_display = (
+ "started_at",
+ "job",
+ "status",
+ "finished_at",
+ "squash_cutoff",
+ "watermark",
+ "skipped_person_deletions",
+ "oldest_skipped_created_at",
+ "dagster_run",
+ "reexecution_of",
+ )
+ list_filter = ("job", "status")
+ search_fields = ("dagster_run_id", "parent_run_id")
+ ordering = ("-started_at",)
+ readonly_fields = ("dagster_run", "reexecution_of")
+
+ @admin.display(description="Dagster run")
+ def dagster_run(self, obj: DeletionRunLog) -> str:
+ return _run_link(obj.dagster_run_id)
+
+ @admin.display(description="Re-execution of")
+ def reexecution_of(self, obj: DeletionRunLog) -> str:
+ return _run_link(obj.parent_run_id) if obj.parent_run_id else "-"
+
def has_add_permission(self, request, obj=None):
return False
def has_change_permission(self, request, obj=None):
return False
+
+ def has_delete_permission(self, request, obj=None):
+ return False
diff --git a/posthog/admin/test_async_deletion_admin.py b/posthog/admin/test_async_deletion_admin.py
new file mode 100644
index 000000000000..d00a6838ac3d
--- /dev/null
+++ b/posthog/admin/test_async_deletion_admin.py
@@ -0,0 +1,51 @@
+from datetime import UTC, datetime
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from posthog.admin.admins.async_deletion_admin import deletion_status
+from posthog.models.async_deletion import AsyncDeletion, DeletionType
+
+WATERMARK = datetime(2026, 10, 15, 22, 0, tzinfo=UTC)
+BEFORE = datetime(2026, 10, 14, 12, 0, tzinfo=UTC)
+AFTER = datetime(2026, 10, 17, 9, 0, tzinfo=UTC)
+
+
+class TestDeletionStatus(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("verified", DeletionType.Person, AFTER, AFTER, WATERMARK, "Deleted on 2026-10-17 09:00 UTC"),
+ (
+ "person_after_watermark",
+ DeletionType.Person,
+ AFTER,
+ None,
+ WATERMARK,
+ "Waiting for the person overrides squash. The last run reached 2026-10-15 22:00 UTC.",
+ ),
+ (
+ "person_without_a_run",
+ DeletionType.Person,
+ BEFORE,
+ None,
+ None,
+ "Waiting for the person overrides squash. No run recorded yet.",
+ ),
+ (
+ "person_before_watermark",
+ DeletionType.Person,
+ BEFORE,
+ None,
+ WATERMARK,
+ "Queued for the next deletes_job run",
+ ),
+ ("team_after_watermark", DeletionType.Team, AFTER, None, WATERMARK, "Queued for the next deletes_job run"),
+ ("group", DeletionType.Group, AFTER, None, WATERMARK, "Pending. Not handled by deletes_job."),
+ ]
+ )
+ def test_status(self, _name, deletion_type, created_at, verified_at, watermark, expected) -> None:
+ deletion = AsyncDeletion(
+ deletion_type=deletion_type, team_id=1, key="k", created_at=created_at, delete_verified_at=verified_at
+ )
+ assert deletion_status(deletion, watermark) == expected
diff --git a/posthog/dags/common/deletion_run_log.py b/posthog/dags/common/deletion_run_log.py
new file mode 100644
index 000000000000..5f2348cb8f48
--- /dev/null
+++ b/posthog/dags/common/deletion_run_log.py
@@ -0,0 +1,65 @@
+from typing import Any
+
+from django.utils import timezone
+
+import dagster
+
+from posthog.models.async_deletion import DeletionRunJob, DeletionRunLog, DeletionRunStatus
+
+# Run states after which a row still marked running will never be updated by the run itself.
+_FINAL_STATUSES = {
+ dagster.DagsterRunStatus.SUCCESS: DeletionRunStatus.SUCCEEDED,
+ dagster.DagsterRunStatus.FAILURE: DeletionRunStatus.FAILED,
+ dagster.DagsterRunStatus.CANCELED: DeletionRunStatus.CANCELED,
+}
+
+
+def _parent_run_id(instance: dagster.DagsterInstance, run_id: str) -> str | None:
+ run = instance.get_run_by_id(run_id)
+ return run.parent_run_id if run else None
+
+
+def record_run(context: dagster.OpExecutionContext, job: DeletionRunJob, **fields: Any) -> None:
+ DeletionRunLog.record(context.run_id, job, context.run.parent_run_id, **fields)
+
+
+def record_run_succeeded(context: dagster.OpExecutionContext, job: DeletionRunJob) -> None:
+ record_run(context, job, status=DeletionRunStatus.SUCCEEDED, finished_at=timezone.now())
+
+
+def record_run_failed(context: dagster.HookContext, job: DeletionRunJob) -> None:
+ DeletionRunLog.record(
+ context.run_id,
+ job,
+ _parent_run_id(context.instance, context.run_id),
+ status=DeletionRunStatus.FAILED,
+ finished_at=timezone.now(),
+ error=f"{context.op.name}: {context.op_exception}",
+ )
+
+
+def reconcile_running_logs(instance: dagster.DagsterInstance) -> int:
+ """Close rows whose run ended without a step reporting it: a cancel, a crashed worker, a partial op selection."""
+ closed = 0
+ for log in DeletionRunLog.objects.filter(status=DeletionRunStatus.RUNNING):
+ run = instance.get_run_by_id(log.dagster_run_id)
+ if run is None:
+ status, error = DeletionRunStatus.FAILED, "Dagster has no record of this run."
+ elif run.status in _FINAL_STATUSES:
+ status = _FINAL_STATUSES[run.status]
+ error = (
+ "" if status == DeletionRunStatus.SUCCEEDED else f"The run ended as {run.status.value} outside a step."
+ )
+ else:
+ continue
+ DeletionRunLog.objects.filter(pk=log.pk, status=DeletionRunStatus.RUNNING).update(
+ status=status, finished_at=timezone.now(), error=log.error or error
+ )
+ closed += 1
+ return closed
+
+
[email protected](default_status=dagster.DefaultSensorStatus.RUNNING, minimum_interval_seconds=3600)
+def reconcile_deletion_run_logs(context: dagster.SensorEvaluationContext) -> dagster.SkipReason:
+ closed = reconcile_running_logs(context.instance)
+ return dagster.SkipReason(f"Closed {closed} deletion run log rows whose run had ended.")
diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.py
index 9ee3291808de..d2da943804ce 100644
--- a/posthog/dags/deletes.py
+++ b/posthog/dags/deletes.py
@@ -3,11 +3,11 @@ import uuid
from collections import defaultdict
from collections.abc import Callable, Sequence
from dataclasses import dataclass
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from functools import partial
from django.conf import settings
-from django.db.models import Q
+from django.db.models import Count, Min, Q
from django.utils import timezone
import dagster
@@ -29,6 +29,7 @@ from posthog.clickhouse.cluster import (
)
from posthog.clickhouse.plugin_log_entries import PLUGIN_LOG_ENTRIES_TABLE
from posthog.dags.common import EXECUTING_RUN_STATUSES, JobOwners, describe_runs
+from posthog.dags.common.deletion_run_log import record_run, record_run_failed, record_run_succeeded
from posthog.dags.common.dictionaries import Dictionary
from posthog.dags.common.staged_dictionary import (
StagedDictionary,
@@ -37,7 +38,7 @@ from posthog.dags.common.staged_dictionary import (
)
from posthog.dags.person_overrides import squash_person_overrides
from posthog.dataclasses import frozen
-from posthog.models.async_deletion import AsyncDeletion, DeletionType
+from posthog.models.async_deletion import AsyncDeletion, DeletionRunJob, DeletionType
from posthog.models.deletion_targets import (
COVERAGE_DOC,
DEFAULT_DELETION_TARGETS,
@@ -469,8 +470,37 @@ def _targets_named(data_tables: Sequence[str]) -> tuple[DeletionTarget, ...]:
return tuple(target for target in PERSONAL_DATA_TARGETS if target.data_table in wanted)
+# How long a person deletion waits for squash when nothing is wrong: squash runs weekly with a
+# cutoff two days before it starts.
+EXPECTED_PERSON_DELETION_DELAY = timedelta(days=9)
+WATERMARK_HOLDERS_LIMIT = 20
+
+
+def _as_utc(moment: datetime) -> datetime:
+ return moment if moment.tzinfo else moment.replace(tzinfo=UTC)
+
+
+def _watermark_holders(cluster: ClickhouseCluster, older_than: datetime) -> list[dict[str, str | int]]:
+ query = Query(
+ f"""
+ SELECT team_id, count() AS rows, min(_timestamp) AS oldest
+ FROM {PERSON_DISTINCT_ID_OVERRIDES_TABLE}
+ WHERE _timestamp < %(older_than)s
+ GROUP BY team_id
+ ORDER BY oldest
+ LIMIT {WATERMARK_HOLDERS_LIMIT}
+ """,
+ {"older_than": older_than.astimezone(UTC).replace(tzinfo=None)},
+ )
+ return [
+ {"team_id": team_id, "rows": rows, "oldest": _as_utc(oldest).isoformat()}
+ for team_id, rows, oldest in cluster.any_host_by_role(query, NodeRole.DATA).result()
+ ]
+
+
@dagster.op(ins={"start_after": dagster.In(dagster.Nothing)})
def get_oldest_person_override_timestamp(
+ context: dagster.OpExecutionContext,
cluster: dagster.ResourceParam[ClickhouseCluster],
) -> datetime:
"""Get the oldest person override timestamp from the person_distinct_id_overrides table."""
@@ -479,6 +509,14 @@ def get_oldest_person_override_timestamp(
SELECT min(_timestamp) FROM {PERSON_DISTINCT_ID_OVERRIDES_TABLE}
"""
[[result]] = cluster.any_host_by_role(lambda client: client.execute(query), NodeRole.DATA).result()
+
+ # The holders only explain the watermark to staff, so a failed lookup must not stop the deletes.
+ try:
+ holders = _watermark_holders(cluster, timezone.now() - EXPECTED_PERSON_DELETION_DELAY)
+ except Exception as error:
+ context.log.warning(f"Could not list the teams that hold the watermark back: {error}")
+ holders = []
+ record_run(context, DeletionRunJob.DELETES, watermark=_as_utc(result), watermark_holders=holders)
return result
@@ -518,6 +556,7 @@ def load_pending_deletions(
)
if create_pending_deletions_table.team_id:
pending_deletions = pending_deletions.filter(team_id=create_pending_deletions_table.team_id)
+ _record_loaded_and_skipped(context, create_pending_deletions_table)
# Process and insert in chunks
total_rows = 0
@@ -552,6 +591,30 @@ def load_pending_deletions(
return create_pending_deletions_table
+def _record_loaded_and_skipped(context: dagster.OpExecutionContext, table: PendingDeletesTable) -> None:
+ unverified = AsyncDeletion.objects.filter(delete_verified_at__isnull=True)
+ if table.team_id:
+ unverified = unverified.filter(team_id=table.team_id)
+ loaded = unverified.filter(
+ Q(deletion_type=DeletionType.Person, created_at__lte=table.timestamp)
+ | Q(deletion_type__in=[DeletionType.Team, DeletionType.Event])
+ )
+ skipped = unverified.filter(deletion_type=DeletionType.Person, created_at__gt=table.timestamp).aggregate(
+ count=Count("id"), oldest=Min("created_at")
+ )
+ record_run(
+ context,
+ DeletionRunJob.DELETES,
+ limited_to_team_id=table.team_id,
+ loaded_counts={
+ DeletionType(row["deletion_type"]).label: row["count"]
+ for row in loaded.values("deletion_type").annotate(count=Count("id")).order_by()
+ },
+ skipped_person_deletions=skipped["count"],
+ oldest_skipped_created_at=skipped["oldest"],
+ )
+
+
@dagster.op
def create_deletes_dict(
context: dagster.OpExecutionContext,
@@ -1158,14 +1221,25 @@ def cleanup_delete_assets(
return True
+def record_deletes_run_succeeded(context: dagster.OpExecutionContext, cleaned_up: bool) -> None:
+ record_run_succeeded(context, DeletionRunJob.DELETES)
+
+
+def record_deletes_run_failure(context: dagster.HookContext) -> None:
+ record_run_failed(context, DeletionRunJob.DELETES)
+
+
@dagster.job(
+ hooks={record_deletes_run_failure},
tags={
"owner": JobOwners.TEAM_CLICKHOUSE.value,
# For a run-queue limit of 1 in Dagster deployment settings, so a second run queues
# instead of racing the guard; clickhouse_deletion_sweep_concurrency is the matched
# example. ensure_no_concurrent_deletes_run enforces mutual exclusion regardless.
"deletes_job_concurrency": "v1",
- }
+ },
)
def deletes_job():
"""Job that handles deletion of events."""
@@ -1207,7 +1281,7 @@ def deletes_job():
)
# Clean up
- cleanup_delete_assets(swept_targets, verified_deletion_resources)
+ record_deletes_run_succeeded(cleanup_delete_assets(swept_targets, verified_deletion_resources))
# What every sensor-launched deletes_job run carries. retry_max_attempts is raised because
diff --git a/posthog/dags/locations/clickhouse.py b/posthog/dags/locations/clickhouse.py
index d88c7c8871d1..0f1c9859a5c0 100644
--- a/posthog/dags/locations/clickhouse.py
+++ b/posthog/dags/locations/clickhouse.py
@@ -20,6 +20,7 @@ from posthog.dags import (
property_definitions,
warehouse_object_reads_daily,
)
+from posthog.dags.common import deletion_run_log
from . import loggers, resources
@@ -72,6 +73,7 @@ defs = dagster.Definitions(
clickhouse_cleanup.run_cleanup_sweep_after_deletes,
deletes.run_deletes_after_squash,
deletes.run_deletes_after_manual_trigger,
+ deletion_run_log.reconcile_deletion_run_logs,
data_deletion_requests.data_deletion_request_pickup_sensor,
data_deletion_requests.verify_queued_deletion_requests,
warehouse_object_reads_daily.warehouse_object_reads_daily_overdue_sensor,
diff --git a/posthog/dags/person_overrides.py b/posthog/dags/person_overrides.py
index 4ccbc6f8d8f3..c8bfc77e97a4 100644
--- a/posthog/dags/person_overrides.py
+++ b/posthog/dags/person_overrides.py
@@ -11,6 +11,7 @@ from posthog import settings
from posthog.clickhouse.client.connection import ClickHouseUser, get_clickhouse_creds
from posthog.clickhouse.cluster import ClickhouseCluster, MutationWaiter, wait_for_mutations_on_shards
from posthog.dags.common import JobOwners
+from posthog.dags.common.deletion_run_log import record_run, record_run_failed, record_run_succeeded
from posthog.dags.common.overrides_manager import OverridesSnapshotDictionary, OverridesSnapshotTable
from posthog.dags.common.staged_dictionary import (
StagedDictionary,
@@ -18,6 +19,7 @@ from posthog.dags.common.staged_dictionary import (
load_and_verify_on_every_cluster,
)
from posthog.dataclasses import frozen
+from posthog.models.async_deletion import DeletionRunJob
from posthog.models.deletion_targets import (
SQUASH_TARGETS,
TargetPlacement,
@@ -188,13 +190,29 @@ class PopulateSnapshotTableConfig(dagster.Config):
)
+def _parse_cutoff(timestamp: str) -> datetime.datetime | None:
+ # The config takes any format ClickHouse parses, so a value Python cannot read is logged as unknown.
+ try:
+ cutoff = datetime.datetime.fromisoformat(timestamp)
+ except ValueError:
+ return None
+ return cutoff if cutoff.tzinfo else cutoff.replace(tzinfo=datetime.UTC)
+
+
@dagster.op
def populate_snapshot_table(
+ context: dagster.OpExecutionContext,
cluster: dagster.ResourceParam[ClickhouseCluster],
table: PersonOverridesSnapshotTable,
config: PopulateSnapshotTableConfig,
) -> PersonOverridesSnapshotTable:
"""Fill the snapshot data with the selected overrides based on the configuration timestamp."""
+ record_run(
+ context,
+ DeletionRunJob.SQUASH_PERSON_OVERRIDES,
+ squash_cutoff=_parse_cutoff(config.timestamp),
+ squash_limit=config.limit,
+ )
cluster.any_host(partial(table.populate, timestamp=config.timestamp, limit=config.limit)).result()
return table
@@ -365,10 +383,20 @@ def cleanup_snapshot_resources(dictionary: PersonOverridesSnapshotDictionary) ->
return drop_snapshot_table(drop_snapshot_dictionary(dictionary))
[email protected](ins={"start_after": dagster.In(dagster.Nothing)})
+def record_squash_run_succeeded(context: dagster.OpExecutionContext) -> None:
+ record_run_succeeded(context, DeletionRunJob.SQUASH_PERSON_OVERRIDES)
+
+
+def record_squash_run_failure(context: dagster.HookContext) -> None:
+ record_run_failed(context, DeletionRunJob.SQUASH_PERSON_OVERRIDES)
+
+
# Job Definition
[email protected](tags={"owner": JobOwners.TEAM_CLICKHOUSE.value})
[email protected](tags={"owner": JobOwners.TEAM_CLICKHOUSE.value}, hooks={record_squash_run_failure})
def squash_person_overrides():
prepared_snapshot_table = wait_for_snapshot_table_replication(populate_snapshot_table(create_snapshot_table()))
prepared_dictionary = load_and_verify_snapshot_dictionary(create_snapshot_dictionary(prepared_snapshot_table))
@@ -376,7 +404,8 @@ def squash_person_overrides():
dictionary_after_override_delete_mutations = wait_for_overrides_delete_mutations(
start_overrides_delete_mutations(dictionary_after_person_id_update_mutations)
)
- cleanup_snapshot_resources(dictionary_after_override_delete_mutations)
+ snapshot_table = drop_snapshot_dictionary(dictionary_after_override_delete_mutations)
+ record_squash_run_succeeded(start_after=drop_snapshot_table(snapshot_table))
@dagster.job(tags={"owner": JobOwners.TEAM_CLICKHOUSE.value})
diff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.py
index 8614d03451a8..fd08ee043807 100644
--- a/posthog/dags/tests/test_deletes.py
+++ b/posthog/dags/tests/test_deletes.py
@@ -32,6 +32,7 @@ from posthog.dags.deletes import (
_count_through,
_count_unswept_rows,
_delete_predicate_params,
+ _watermark_holders,
cleanup_old_events_by_partition,
delete_events,
deletes_job,
@@ -47,7 +48,7 @@ from posthog.dags.deletes import (
)
from posthog.dags.person_overrides import squash_person_overrides
from posthog.dags.tests.conftest import insert_flag_evaluations
-from posthog.models.async_deletion import AsyncDeletion, DeletionType
+from posthog.models.async_deletion import AsyncDeletion, DeletionRunLog, DeletionRunStatus, DeletionType
from posthog.models.deletion_targets import DEFAULT_DELETION_TARGETS, EVENTS, PERSONAL_DATA_TARGETS, TargetPlacement
from posthog.models.event.sql import EVENTS_DATA_TABLE, EVENTS_JSON_DATA_TABLE
from posthog.models.events_retention_config import OrganizationEventsRetentionConfig, TeamEventsRetentionConfig
@@ -162,9 +163,16 @@ def test_full_job_person_deletes(cluster: ClickhouseCluster):
# Check overrides is correct
oldest_override_timestamp = cluster.any_host(get_oldest_override_timestamp).result()
assert oldest_override_timestamp == timestamp - timedelta(hours=hour_delay - 1)
+ assert _watermark_holders(cluster, timestamp - timedelta(hours=hour_delay - 3)) == [
+ {
+ "team_id": 0,
+ "rows": 2,
+ "oldest": (timestamp - timedelta(hours=hour_delay - 1)).replace(tzinfo=UTC).isoformat(),
+ }
+ ]
# Run the deletion job
- deletes_job.execute_in_process(
+ result = deletes_job.execute_in_process(
run_config={"ops": {"create_pending_deletions_table": {"config": {"timestamp": timestamp.isoformat()}}}},
resources={"cluster": cluster},
)
@@ -203,6 +211,13 @@ def test_full_job_person_deletes(cluster: ClickhouseCluster):
assert len(post_override_deletions) == hour_delay
assert not all(deletion.delete_verified_at is not None for deletion in post_override_deletions)
+ run_log = DeletionRunLog.objects.get(dagster_run_id=result.dagster_run.run_id)
+ assert run_log.status == DeletionRunStatus.SUCCEEDED
+ assert run_log.watermark == oldest_override_timestamp.replace(tzinfo=UTC)
+ assert run_log.loaded_counts == {"Person": delete_count - hour_delay}
+ assert run_log.skipped_person_deletions == hour_delay
+ assert run_log.oldest_skipped_created_at == min(d.created_at for d in post_override_deletions)
+
# Verify the temporary tables were cleaned up
table = PendingDeletesTable(timestamp=timestamp)
assert not any(cluster.map_all_hosts(table.exists).result().values())
diff --git a/posthog/dags/tests/test_deletion_run_log.py b/posthog/dags/tests/test_deletion_run_log.py
new file mode 100644
index 000000000000..a2e14f05e24c
--- /dev/null
+++ b/posthog/dags/tests/test_deletion_run_log.py
@@ -0,0 +1,56 @@
+from datetime import UTC, datetime
+
+import pytest
+from unittest.mock import Mock
+
+import dagster
+from parameterized import parameterized
+
+from posthog.dags.common.deletion_run_log import reconcile_running_logs
+from posthog.models.async_deletion import DeletionRunJob, DeletionRunLog, DeletionRunStatus
+
+WATERMARK = datetime(2026, 10, 15, 22, 0, tzinfo=UTC)
+
+
+def test_a_reexecution_keeps_what_the_parent_run_recorded_in_the_steps_it_skips() -> None:
+ DeletionRunLog.record(
+ "parent",
+ DeletionRunJob.DELETES,
+ None,
+ watermark=WATERMARK,
+ skipped_person_deletions=7,
+ loaded_counts={"Team": 1},
+ )
+ DeletionRunLog.record("parent", DeletionRunJob.DELETES, None, status=DeletionRunStatus.FAILED)
+
+ DeletionRunLog.record("child", DeletionRunJob.DELETES, "parent", status=DeletionRunStatus.SUCCEEDED)
+
+ child = DeletionRunLog.objects.get(dagster_run_id="child")
+ assert (child.parent_run_id, child.status) == ("parent", DeletionRunStatus.SUCCEEDED)
+ assert (child.watermark, child.skipped_person_deletions, child.loaded_counts) == (WATERMARK, 7, {"Team": 1})
+ assert DeletionRunLog.objects.get(dagster_run_id="parent").status == DeletionRunStatus.FAILED
+
+
+ [
+ ("succeeded", dagster.DagsterRunStatus.SUCCESS, DeletionRunStatus.SUCCEEDED),
+ ("failed", dagster.DagsterRunStatus.FAILURE, DeletionRunStatus.FAILED),
+ ("canceled", dagster.DagsterRunStatus.CANCELED, DeletionRunStatus.CANCELED),
+ ("missing", None, DeletionRunStatus.FAILED),
+ ("still_running", dagster.DagsterRunStatus.STARTED, DeletionRunStatus.RUNNING),
+ ]
+)
+def test_reconcile_closes_rows_whose_run_ended(
+ _name: str, run_status: dagster.DagsterRunStatus | None, expected: DeletionRunStatus
+) -> None:
+ DeletionRunLog.record("run", DeletionRunJob.SQUASH_PERSON_OVERRIDES, None)
+ instance = Mock()
+ instance.get_run_by_id.return_value = None if run_status is None else Mock(status=run_status)
+
+ reconcile_running_logs(instance)
+
+ log = DeletionRunLog.objects.get(dagster_run_id="run")
+ assert log.status == expected
+ assert (log.finished_at is None) == (expected == DeletionRunStatus.RUNNING)
diff --git a/posthog/dags/tests/test_person_overrides.py b/posthog/dags/tests/test_person_overrides.py
index bffea99449f7..fdc1629b7c20 100644
--- a/posthog/dags/tests/test_person_overrides.py
+++ b/posthog/dags/tests/test_person_overrides.py
@@ -1,5 +1,5 @@
import uuid as uuid_module
-from datetime import datetime, timedelta
+from datetime import UTC, datetime, timedelta
from functools import partial
from uuid import UUID
@@ -26,12 +26,13 @@ from posthog.dags.person_overrides import (
wait_for_overrides_delete_mutations,
)
from posthog.dags.tests.conftest import insert_flag_evaluations
-from posthog.models.async_deletion import AsyncDeletion, DeletionType
+from posthog.models.async_deletion import AsyncDeletion, DeletionRunJob, DeletionRunLog, DeletionRunStatus, DeletionType
from posthog.models.deletion_targets import EVENTS, EVENTS_JSON, FLAG_EVALUATIONS, TargetPlacement
from posthog.models.event.sql import EVENTS_DATA_TABLE, EVENTS_JSON_DATA_TABLE
from posthog.models.flag_evaluations.sql import FLAG_EVALUATIONS_DATA_TABLE
def test_full_job(cluster: ClickhouseCluster):
timestamp = datetime(2025, 1, 1)
@@ -105,6 +106,10 @@ def test_full_job(cluster: ClickhouseCluster):
assert len(remaining_overrides) == 2 # one candidate discarded due to limit, one out of timestamp range
assert "z" in remaining_overrides # outside of timestamp range
+ run_log = DeletionRunLog.objects.get(dagster_run_id=limited_run_result.dagster_run.run_id)
+ assert (run_log.job, run_log.status) == (DeletionRunJob.SQUASH_PERSON_OVERRIDES, DeletionRunStatus.SUCCEEDED)
+ assert (run_log.squash_cutoff, run_log.squash_limit) == (timestamp.replace(tzinfo=UTC), 2)
+
# run without limit to handle the remaining item(s)
full_run_result = squash_person_overrides.execute_in_process(
run_config=dagster.RunConfig(
@@ -199,6 +204,24 @@ def test_a_person_deletion_after_a_merge_reaches_flag_evaluations(cluster: Click
assert cluster.any_host(surviving_flag_evaluation_person_ids).result() == set()
+def test_a_failed_squash_run_is_logged_as_failed(cluster: ClickhouseCluster) -> None:
+ result = squash_person_overrides.execute_in_process(
+ run_config=dagster.RunConfig(
+ {populate_snapshot_table.name: PopulateSnapshotTableConfig(timestamp="not a date")}
+ ),
+ resources={"cluster": cluster},
+ raise_on_error=False,
+ )
+
+ assert not result.success
+ run_log = DeletionRunLog.objects.get(dagster_run_id=result.dagster_run.run_id)
+ assert run_log.status == DeletionRunStatus.FAILED
+ assert run_log.squash_cutoff is None
+ assert run_log.error.startswith(f"{populate_snapshot_table.name}: ")
+
+
def test_cleanup_job(cluster: ClickhouseCluster) -> None:
timestamp = datetime(2025, 1, 1)
diff --git a/posthog/migrations/1410_deletion_run_log.py b/posthog/migrations/1410_deletion_run_log.py
new file mode 100644
index 000000000000..7db2b4a67851
--- /dev/null
+++ b/posthog/migrations/1410_deletion_run_log.py
@@ -0,0 +1,106 @@
+# Generated by Django 5.2.18 on 2026-10-22 11:51
+
+import django.utils.timezone
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("posthog", "1409_activitylog_team_user_created_at_index"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="DeletionRunLog",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("dagster_run_id", models.CharField(max_length=64, unique=True)),
+ (
+ "parent_run_id",
+ models.CharField(
+ blank=True,
+ help_text="Set when this run is a re-execution of that run.",
+ max_length=64,
+ null=True,
+ ),
+ ),
+ (
+ "job",
+ models.CharField(
+ choices=[
+ ("squash_person_overrides", "Squash Person Overrides"),
+ ("deletes_job", "Deletes"),
+ ],
+ max_length=40,
+ ),
+ ),
+ (
+ "status",
+ models.CharField(
+ choices=[
+ ("running", "Running"),
+ ("succeeded", "Succeeded"),
+ ("failed", "Failed"),
+ ("canceled", "Canceled"),
+ ],
+ default="running",
+ max_length=20,
+ ),
+ ),
+ ("started_at", models.DateTimeField(default=django.utils.timezone.now)),
+ ("finished_at", models.DateTimeField(blank=True, null=True)),
+ ("error", models.TextField(blank=True, default="")),
+ ("squash_cutoff", models.DateTimeField(blank=True, null=True)),
+ ("squash_limit", models.BigIntegerField(blank=True, null=True)),
+ ("watermark", models.DateTimeField(blank=True, null=True)),
+ (
+ "limited_to_team_id",
+ models.IntegerField(
+ blank=True,
+ help_text="Set when the run was limited to one team.",
+ null=True,
+ ),
+ ),
+ (
+ "loaded_counts",
+ models.JSONField(
+ blank=True,
+ default=dict,
+ help_text="Loaded deletions per deletion type.",
+ ),
+ ),
+ (
+ "skipped_person_deletions",
+ models.IntegerField(blank=True, null=True),
+ ),
+ (
+ "oldest_skipped_created_at",
+ models.DateTimeField(blank=True, null=True),
+ ),
+ (
+ "watermark_holders",
+ models.JSONField(
+ blank=True,
+ default=list,
+ help_text="Teams with the oldest overrides, which keep the watermark back.",
+ ),
+ ),
+ ],
+ options={
+ "indexes": [
+ models.Index(
+ fields=["job", "status", "-started_at"],
+ name="deletion_run_log_latest",
+ )
+ ],
+ },
+ ),
+ ]
diff --git a/posthog/migrations/max_migration.txt b/posthog/migrations/max_migration.txt
index 7bfce60a81a4..b11bac36330d 100644
--- a/posthog/migrations/max_migration.txt
+++ b/posthog/migrations/max_migration.txt
@@ -1 +1 @@
-1409_activitylog_team_user_created_at_index
+1410_deletion_run_log
diff --git a/posthog/models/async_deletion/__init__.py b/posthog/models/async_deletion/__init__.py
index c9fd2fc6ef57..e3b857231682 100644
--- a/posthog/models/async_deletion/__init__.py
+++ b/posthog/models/async_deletion/__init__.py
@@ -1,3 +1,4 @@
from .async_deletion import AsyncDeletion, DeletionType
+from .deletion_run_log import DeletionRunJob, DeletionRunLog, DeletionRunStatus
-__all__ = ["AsyncDeletion", "DeletionType"]
+__all__ = ["AsyncDeletion", "DeletionRunJob", "DeletionRunLog", "DeletionRunStatus", "DeletionType"]
diff --git a/posthog/models/async_deletion/deletion_run_log.py b/posthog/models/async_deletion/deletion_run_log.py
new file mode 100644
index 000000000000..239735b32398
--- /dev/null
+++ b/posthog/models/async_deletion/deletion_run_log.py
@@ -0,0 +1,80 @@
+from typing import Any
+
+from django.db import models
+from django.utils import timezone
+
+
+class DeletionRunJob(models.TextChoices):
+ SQUASH_PERSON_OVERRIDES = "squash_person_overrides"
+ DELETES = "deletes_job"
+
+
+class DeletionRunStatus(models.TextChoices):
+ RUNNING = "running"
+ SUCCEEDED = "succeeded"
+ FAILED = "failed"
+ CANCELED = "canceled"
+
+
+class DeletionRunLog(models.Model):
+ """One row per squash_person_overrides or deletes_job Dagster run, for staff to read in Django admin.
+
+ deletes_job only loads person deletions requested at or before its watermark, the oldest
+ _timestamp left in person_distinct_id_overrides. The other deletions are left for a later run
+ and nothing else records that, so this log keeps the watermark and the skipped count per run.
+ """
+
+ dagster_run_id = models.CharField(max_length=64, unique=True)
+ parent_run_id = models.CharField(
+ max_length=64, null=True, blank=True, help_text="Set when this run is a re-execution of that run."
+ )
+ job = models.CharField(max_length=40, choices=DeletionRunJob.choices)
+ status = models.CharField(max_length=20, choices=DeletionRunStatus.choices, default=DeletionRunStatus.RUNNING)
+ started_at = models.DateTimeField(default=timezone.now)
+ finished_at = models.DateTimeField(null=True, blank=True)
+ error = models.TextField(blank=True, default="")
+
+ # squash_person_overrides: the overrides with _timestamp before this cutoff are folded into the events.
+ squash_cutoff = models.DateTimeField(null=True, blank=True)
+ squash_limit = models.BigIntegerField(null=True, blank=True)
+
+ # deletes_job: person deletions with created_at after the watermark are not loaded in this run.
+ watermark = models.DateTimeField(null=True, blank=True)
+ limited_to_team_id = models.IntegerField(
+ null=True, blank=True, help_text="Set when the run was limited to one team."
+ )
+ loaded_counts = models.JSONField(default=dict, blank=True, help_text="Loaded deletions per deletion type.")
+ skipped_person_deletions = models.IntegerField(null=True, blank=True)
+ oldest_skipped_created_at = models.DateTimeField(null=True, blank=True)
+ watermark_holders = models.JSONField(
+ default=list, blank=True, help_text="Teams with the oldest overrides, which keep the watermark back."
+ )
+
+ # A re-execution reuses the outputs of the steps it skips, so it inherits what those steps recorded.
+ INHERITED_FIELDS = (
+ "squash_cutoff",
+ "squash_limit",
+ "watermark",
+ "limited_to_team_id",
+ "loaded_counts",
+ "skipped_person_deletions",
+ "oldest_skipped_created_at",
+ "watermark_holders",
+ )
+
+ class Meta:
+ indexes = [models.Index(fields=["job", "status", "-started_at"], name="deletion_run_log_latest")]
+
+ @classmethod
+ def record(cls, dagster_run_id: str, job: DeletionRunJob, parent_run_id: str | None, **fields: Any) -> None:
+ """Create the run's row on its first write and update it on every later one."""
+ inherited = (
+ cls.objects.filter(dagster_run_id=parent_run_id).values(*cls.INHERITED_FIELDS).first()
+ if parent_run_id
+ else None
+ )
+ cls.objects.update_or_create(
+ dagster_run_id=dagster_run_id,
+ defaults={"job": job, **fields},
+ create_defaults={**(inherited or {}), "job": job, "parent_run_id": parent_run_id, **fields},
+ )