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): sweep embedding documents of deleted events and teams (#101775)

Tue Haulund52d0448d36c7
diff --git a/docs/internal/clickhouse-deletion-coverage.md b/docs/internal/clickhouse-deletion-coverage.md
index 7ef2946b9549..fcfda2c960a2 100644
--- a/docs/internal/clickhouse-deletion-coverage.md
+++ b/docs/internal/clickhouse-deletion-coverage.md
@@ -93,6 +93,7 @@ Skipping one of those tables is worse than under-deleting: the overrides that re
- `sharded_events` — all sweeps.
- `sharded_events_json` — all sweeps. Optional: only present after the native-JSON migration.
- `sharded_flag_evaluations` — person, team, queued-uuid and event removal. Not property removal (below). Optional.
+- `sharded_posthog_document_embeddings_<model>` — event and team deletion, through `delete_event_documents`. An embedded document is keyed by the id of the thing it describes (`document_id`), and an Event deletion's key is that same id, so the pending dictionary is joined on `(team_id, Event, document_id)`. Every per-model table listed by the error tracking facade's `document_embedding_tables` is swept and counted.
## Tables on TTL alone
diff --git a/posthog/dags/deletes.py b/posthog/dags/deletes.py
index ae32c0e4239b..9b85c689ab3b 100644
--- a/posthog/dags/deletes.py
+++ b/posthog/dags/deletes.py
@@ -35,7 +35,13 @@ 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.deletion_targets import COVERAGE_DOC, resolve_placements, surviving_rows_sql, sweep_clusters
+from posthog.models.deletion_targets import (
+ COVERAGE_DOC,
+ _any_node_has,
+ resolve_placements,
+ surviving_rows_sql,
+ sweep_clusters,
+)
from posthog.models.event.deletion import events_data_tables
from posthog.models.event.sql import EVENTS_DATA_TABLE
from posthog.models.group.sql import GROUPS_TABLE
@@ -46,6 +52,8 @@ from posthog.models.person.sql import (
PERSONS_TABLE,
)
+from products.error_tracking.backend.facade.api import DocumentEmbeddingTable, document_embedding_tables
+
class DeleteConfig(dagster.Config):
team_id: int | None = pydantic.Field(
@@ -150,6 +158,13 @@ _DELETE_PREDICATE = """or(
)"""
+# Embedding documents are keyed by the id of the thing they describe, and an Event deletion's key is
+# that same id, so the pending dictionary answers for both. Team deletions clear the team's documents.
+_DOCUMENT_DELETE_PREDICATE = """or(
+ dictHas(%(pending_deletes_dictionary)s, (team_id, %(event_deletion_type)s, document_id)),
+ dictHas(%(pending_deletes_dictionary)s, (team_id, %(team_deletion_type)s, team_id))
+)"""
+
ShardMutations = dict[int, MutationWaiters]
# Shard numbers are per cluster, so a sweep spanning two of them cannot key its waiters by shard
# alone. Keyed by cluster name and the role that owns its shards rather than by handle: the handle
@@ -651,6 +666,57 @@ def delete_events(
return (load_and_verify_deletes_dictionary, cluster_mutations)
+def delete_event_documents(
+ context: dagster.OpExecutionContext,
+ cluster: dagster.ResourceParam[ClickhouseCluster],
+ load_and_verify_deletes_dictionary: PendingDeletesDictionary,
+) -> tuple[PendingDeletesDictionary, ClusterShardMutations]:
+ """Delete the embedding documents of the events and teams queued for deletion.
+
+ An event queued by an `AsyncDeletion` of type `Event` may have had its text embedded into the
+ per-model `document_embeddings` tables under `document_id` equal to the event uuid, and those
+ rows carry the text itself, so they go with the event. A deleted team's documents go with the team.
+ """
+
+ def count_pending_deletes(client: Client) -> int:
+ result = client.execute(
+ f"""
+ SELECT count()
+ FROM {load_and_verify_deletes_dictionary.qualified_name}
+ WHERE deletion_type IN ({DeletionType.Event}, {DeletionType.Team})
+ """
+ )
+ return result[0][0] if result else 0
+
+ pending = cluster.any_host_by_role(count_pending_deletes, NodeRole.DATA).result()
+ if pending == 0:
+ context.add_output_metadata({"pending_deletes": dagster.MetadataValue.int(0)})
+ return (load_and_verify_deletes_dictionary, {})
+
+ context.add_output_metadata({"pending_deletes": dagster.MetadataValue.int(pending)})
+
+ reuse_floor = _mutation_reuse_floor(cluster)
+ by_shard: dict[int, list[MutationWaiter]] = {}
+ for table in _present_document_embedding_tables(cluster):
+ runner = LightweightDeleteMutationRunner(
+ table=table.sharded_table,
+ predicate=_DOCUMENT_DELETE_PREDICATE,
+ parameters=_document_delete_predicate_params(load_and_verify_deletes_dictionary),
+ reuse_since=reuse_floor,
+ )
+ for host, mutation in cluster.map_one_host_per_shard(runner).result().items():
+ if host.shard_num is not None:
+ by_shard.setdefault(host.shard_num, []).append(mutation)
+
+ cluster_mutations: ClusterShardMutations = {
+ (cluster.data_cluster_name, cluster.shard_role): {
+ shard_num: MutationWaiters(waiters=shard_waiters) for shard_num, shard_waiters in by_shard.items()
+ }
+ }
+ return (load_and_verify_deletes_dictionary, cluster_mutations)
+
+
def delete_team_data(
context: dagster.OpExecutionContext,
cluster: dagster.ResourceParam[ClickhouseCluster],
@@ -760,6 +826,23 @@ class VerifiedDeletionResources:
adhoc_event_deletes_dictionary: AdhocEventDeletesDictionary
+def _present_document_embedding_tables(cluster: ClickhouseCluster) -> list[DocumentEmbeddingTable]:
+ """The embeddings tables that exist here: the Python registry can name a model whose migration has not landed.
+
+ Present on any shard host counts, as for the registered targets: a table missing from some hosts
+ makes the mutation fail loudly there, which beats skipping the deletion.
+ """
+ return [table for table in document_embedding_tables() if _any_node_has(cluster, table.sharded_table)]
+
+
+def _document_delete_predicate_params(pending_deletes_dictionary: "PendingDeletesDictionary") -> dict[str, str | int]:
+ return {
+ "pending_deletes_dictionary": pending_deletes_dictionary.qualified_name,
+ "event_deletion_type": DeletionType.Event,
+ "team_deletion_type": DeletionType.Team,
+ }
+
+
def _delete_predicate_params(
pending_deletes_dictionary: "PendingDeletesDictionary",
adhoc_event_deletes_dictionary: "AdhocEventDeletesDictionary",
@@ -802,6 +885,7 @@ def _count_through(
table: str,
params: dict[str, str | int],
max_execution_time: int,
+ predicate: str = _DELETE_PREDICATE,
) -> int | None:
"""Survivors on ``table``, or None when no attempt could complete.
@@ -811,7 +895,7 @@ def _count_through(
slow or sick host.
"""
query = Query(
- surviving_rows_sql(table, _DELETE_PREDICATE),
+ surviving_rows_sql(table, predicate),
params,
settings={"max_execution_time": str(max_execution_time)},
)
@@ -868,6 +952,16 @@ def _count_unswept_rows(
params,
max_execution_time,
)
+ document_params = _document_delete_predicate_params(pending_deletes_dictionary)
+ for table in _present_document_embedding_tables(cluster):
+ counts[table.distributed_table] = _count_through(
+ context,
+ partial(_rows_from_any_host, cluster),
+ table.distributed_table,
+ document_params,
+ max_execution_time,
+ predicate=_DOCUMENT_DELETE_PREDICATE,
+ )
return counts
@@ -979,6 +1073,10 @@ def deletes_job():
# Delete all data requested
delete_mutations = delete_events(pending_deletes_dictionary, adhoc_event_deletes_dictionary)
pending_deletes_dictionary = wait_for_delete_mutations_in_shards(delete_mutations)
+ document_mutations = delete_event_documents(pending_deletes_dictionary)
+ pending_deletes_dictionary = wait_for_delete_mutations_in_shards.alias("wait_for_document_delete_mutations")(
+ document_mutations
+ )
for table in [
PERSON_DISTINCT_ID2_TABLE,
diff --git a/posthog/dags/tests/test_deletes.py b/posthog/dags/tests/test_deletes.py
index 3bfaabdaca84..362c582efc10 100644
--- a/posthog/dags/tests/test_deletes.py
+++ b/posthog/dags/tests/test_deletes.py
@@ -288,6 +288,19 @@ def test_full_job_team_deletes(cluster: ClickhouseCluster):
cluster.any_host(insert_plugin_log_entries).result()
cluster.any_host(insert_person_distinct_id2).result()
+ # One embedded document for a deleted team and one for a kept team; the team's documents go with the team.
+ def insert_documents(client: Client) -> None:
+ client.execute(
+ """INSERT INTO writable_posthog_document_embeddings_text_embedding_3_large_3072
+ (team_id, product, document_type, rendering, document_id, timestamp, inserted_at, content, embedding) VALUES""",
+ [
+ (team_id, "test", "doc", "text", str(UUID(int=team_id)), timestamp, timestamp, "text", [0.0] * 3072)
+ for team_id in (0, delete_count)
+ ],
+ )
+
+ cluster.any_host(insert_documents).result()
+
def get_by_team(table: str, client: Client) -> dict[int, int]:
result = client.execute(f"SELECT team_id, count(1) FROM {table} GROUP BY team_id")
if not isinstance(result, list):
@@ -350,6 +363,14 @@ def test_full_job_team_deletes(cluster: ClickhouseCluster):
final_events = cluster.any_host(partial(get_by_team, "writable_events")).result()
assert len(final_events) == event_count - delete_count, f"expected events data was not deleted"
+ final_documents = cluster.any_host(
+ partial(get_by_team, "distributed_posthog_document_embeddings_text_embedding_3_large_3072")
+ ).result()
+ # Other tests leave documents for their own teams in this table, so only the two inserted above are judged.
+ assert {team for team in final_documents if team in (0, delete_count)} == {delete_count}, (
+ "the deleted team's embedded documents survived"
+ )
+
final_persons = cluster.any_host(partial(get_by_team, "person")).result()
assert len(final_persons) == event_count - delete_count, f"expected person data was not deleted"
@@ -513,7 +534,27 @@ def test_full_job_deletes_events_queued_in_postgres(cluster: ClickhouseCluster):
result = client.execute("SELECT uuid FROM writable_events WHERE team_id >= 9000 AND team_id < 9020")
return {row[0] for row in result} if isinstance(result, list) else set()
+ # The embedded text of an event lives under its uuid as document_id, and goes with the event. Each team
+ # also holds a document for an event nobody queued, which an arm that matched on team alone would take.
+ def insert_documents(client: Client) -> None:
+ client.execute(
+ """INSERT INTO writable_posthog_document_embeddings_text_embedding_3_large_3072
+ (team_id, product, document_type, rendering, document_id, timestamp, inserted_at, content, embedding) VALUES""",
+ [
+ (team_id, "test", "doc", "text", document_id, timestamp, timestamp, "text", [0.0] * 3072)
+ for team_id, _, uuid, _ in events
+ for document_id in (str(uuid), f"unqueued-{uuid}")
+ ],
+ )
+
+ def surviving_document_ids(client: Client) -> set[str]:
+ result = client.execute(
+ "SELECT document_id FROM distributed_posthog_document_embeddings_text_embedding_3_large_3072 WHERE team_id >= 9000 AND team_id < 9020"
+ )
+ return {row[0] for row in result} if isinstance(result, list) else set()
+
cluster.any_host(insert_events).result()
+ cluster.any_host(insert_documents).result()
for team_id, _, uuid, _ in queued:
deletion = AsyncDeletion.objects.create(team_id=team_id, deletion_type=DeletionType.Event, key=str(uuid))
# The sweep only covers rows ingested before the request, so the request has to postdate the insert.
@@ -527,6 +568,9 @@ def test_full_job_deletes_events_queued_in_postgres(cluster: ClickhouseCluster):
surviving = cluster.any_host(surviving_uuids).result()
assert surviving == {event[2] for event in kept}
+ assert cluster.any_host(surviving_document_ids).result() == {str(event[2]) for event in kept} | {
+ f"unqueued-{event[2]}" for event in events
+ }
assert not AsyncDeletion.objects.filter(deletion_type=DeletionType.Event, delete_verified_at__isnull=True).exists()
diff --git a/products/error_tracking/backend/facade/api.py b/products/error_tracking/backend/facade/api.py
index ed58e0529ad3..6e917da72c89 100644
--- a/products/error_tracking/backend/facade/api.py
+++ b/products/error_tracking/backend/facade/api.py
@@ -16,6 +16,7 @@ from posthog.event_usage import groups
from products.access_control.backend.models.role import RoleMembership
from .. import logic, weekly_digest, weekly_digest_delivery
+from ..indexed_embedding import EMBEDDING_TABLES
from ..logic import external_references, rules
from ..models import (
ErrorTrackingIssue,
@@ -27,6 +28,7 @@ from ..remote_config import build_error_tracking_config as build_error_tracking_
from . import contracts
from .contracts import (
CrashFreeSummary as CrashFreeSummary,
+ DocumentEmbeddingTable as DocumentEmbeddingTable,
ExceptionSummary as ExceptionSummary,
)
@@ -779,3 +781,17 @@ def build_team_section_payload(data: dict[str, Any]) -> dict[str, Any]:
def send_digest_to_workflow(digest: dict[str, Any], distinct_id: str) -> None:
weekly_digest_delivery.send_digest_to_workflow(digest, distinct_id)
+
+
+def document_embedding_tables() -> list[DocumentEmbeddingTable]:
+ """Every per-model embeddings table.
+
+ Other products embed their documents into these tables too, so a sweep that removes a
+ product's rows needs the full list rather than the one model it writes with.
+ """
+ return [
+ DocumentEmbeddingTable(
+ sharded_table=table.sharded_table_name(), distributed_table=table.distributed_table_name()
+ )
+ for table in EMBEDDING_TABLES
+ ]
diff --git a/products/error_tracking/backend/facade/contracts.py b/products/error_tracking/backend/facade/contracts.py
index f59560544e87..393dd46f31ca 100644
--- a/products/error_tracking/backend/facade/contracts.py
+++ b/products/error_tracking/backend/facade/contracts.py
@@ -22,6 +22,14 @@ ERROR_TRACKING_ISSUE_SEVERITIES = ("low", "medium", "high", "critical")
SOURCE_MAPS_DOCS_URL = "https://posthog.com/docs/error-tracking/upload-source-maps"
+@dataclass(frozen=True)
+class DocumentEmbeddingTable:
+ """One per-model embeddings table: the sharded storage table and the Distributed table that reads it."""
+
+ sharded_table: str
+ distributed_table: str
+
+
@dataclass(frozen=True)
class ExceptionSummary:
exception_count: int