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(ai-research): run the person replay lookup in a background task (#115711)

Eli Reismanefa74001adae
diff --git a/posthog/models/person/bulk_delete.py b/posthog/models/person/bulk_delete.py
index 0589892560e9..833046b22320 100644
--- a/posthog/models/person/bulk_delete.py
+++ b/posthog/models/person/bulk_delete.py
@@ -411,9 +411,8 @@ def _queue_training_deletion_isolating_failures(
) -> builtins.list[Person]:
"""Queue training deletion for ``persons`` and return the ones it succeeded for.
- Each call scans replay events for the distinct IDs it is given, so the batch goes out as one
- flattened call. Only when that raises are the persons retried one at a time, which pins the
- failure on the person that causes it instead of blocking the whole batch.
+ The batch goes out as one flattened call, which only queues the replay lookup. Only when that
+ raises are the persons retried one at a time, so a failure is pinned on the persons it affects.
"""
try:
queue_person_training_deletion(
diff --git a/products/ai_training/backend/facade/api.py b/products/ai_training/backend/facade/api.py
index d26265125d23..5b7067db5549 100644
--- a/products/ai_training/backend/facade/api.py
+++ b/products/ai_training/backend/facade/api.py
@@ -1,7 +1,7 @@
from collections.abc import Sequence
from products.ai_training.backend import config
-from products.ai_training.backend.logic import deletion
+from products.ai_training.backend.logic import deletion, person_deletion
def privacy_enabled() -> bool:
@@ -13,4 +13,4 @@ def queue_training_deletion(team_id: int, kind: str, identifiers: Sequence[str]
def queue_person_training_deletion(team_id: int, distinct_ids: Sequence[str]) -> None:
- deletion.queue_person_training_deletion(team_id, distinct_ids)
+ person_deletion.queue_person_training_deletion(team_id, distinct_ids)
diff --git a/products/ai_training/backend/facade/tasks.py b/products/ai_training/backend/facade/tasks.py
index 82ca7cbbd174..a41190c82942 100644
--- a/products/ai_training/backend/facade/tasks.py
+++ b/products/ai_training/backend/facade/tasks.py
@@ -1,3 +1,4 @@
from products.ai_training.backend.tasks.tasks import (
process_ai_training_privacy_requests as process_ai_training_privacy_requests,
+ resolve_person_training_sessions_task as resolve_person_training_sessions_task,
)
diff --git a/products/ai_training/backend/logic/deletion.py b/products/ai_training/backend/logic/deletion.py
index 4851198cc4d9..6cf955687405 100644
--- a/products/ai_training/backend/logic/deletion.py
+++ b/products/ai_training/backend/logic/deletion.py
@@ -1,5 +1,6 @@
import uuid
from collections.abc import Sequence
+from datetime import datetime
from posthog.hogql import ast
@@ -34,12 +35,20 @@ def queue_training_deletion(team_id: int, kind: str, identifiers: Sequence[str]
AITrainingDeletionRequest.objects.for_team(team_id).bulk_create(requests)
-def queue_person_training_deletion(team_id: int, distinct_ids: Sequence[str]) -> None:
+def resolve_person_training_sessions(team_id: int, distinct_ids: Sequence[str], started_before: datetime) -> None:
+ """Queue training deletion for the replay sessions of ``distinct_ids`` that started before ``started_before``.
+
+ The cutoff is the time of the person deletion. A session that starts later belongs to a person
+ created after the deletion, and that session stays eligible for collection.
+ """
if not privacy_enabled() or not distinct_ids:
return
from posthog.hogql.query import execute_hogql_query # noqa: PLC0415 - Keep HogQL off startup.
- team = Team.objects.get(id=team_id)
+ team = Team.objects.filter(id=team_id).first()
+ if team is None:
+ # Team deletion queues its own request, which removes every key of the team.
+ return
unique = sorted(set(distinct_ids))
for offset in range(0, len(unique), 1000):
cursor = ""
@@ -49,6 +58,7 @@ def queue_person_training_deletion(team_id: int, distinct_ids: Sequence[str]) ->
SELECT session_id
FROM raw_session_replay_events
WHERE distinct_id IN {distinct_ids} AND session_id > {cursor}
+ AND min_first_timestamp <= {started_before}
GROUP BY session_id
ORDER BY session_id
LIMIT 1000
@@ -60,6 +70,7 @@ def queue_person_training_deletion(team_id: int, distinct_ids: Sequence[str]) ->
exprs=[ast.Constant(value=value) for value in unique[offset : offset + 1000]]
),
"cursor": ast.Constant(value=cursor),
+ "started_before": ast.Constant(value=started_before),
},
)
sessions = [str(row[0]) for row in response.results or []]
diff --git a/products/ai_training/backend/logic/person_deletion.py b/products/ai_training/backend/logic/person_deletion.py
new file mode 100644
index 000000000000..4308a505fd45
--- /dev/null
+++ b/products/ai_training/backend/logic/person_deletion.py
@@ -0,0 +1,27 @@
+from collections.abc import Sequence
+
+from django.utils import timezone
+
+from products.ai_training.backend.config import privacy_enabled
+from products.ai_training.backend.tasks.tasks import resolve_person_training_sessions_task
+
+# Matches the lookup's own batch, so one task runs one replay scan per page of sessions.
+PERSON_LOOKUP_DISTINCT_IDS_PER_TASK = 1000
+
+
+def queue_person_training_deletion(team_id: int, distinct_ids: Sequence[str]) -> None:
+ """Hand the replay session lookup for ``distinct_ids`` to a background task.
+
+ The lookup scans ClickHouse, which can be at capacity for minutes at a time. The caller only
+ waits for the task to be queued, so a busy cluster delays the training deletion and does not
+ fail the person deletion. The task carries the distinct IDs, because the caller deletes the
+ person that owns them.
+ """
+ if not privacy_enabled() or not distinct_ids:
+ return
+ started_before = timezone.now().isoformat()
+ unique = sorted(set(distinct_ids))
+ for offset in range(0, len(unique), PERSON_LOOKUP_DISTINCT_IDS_PER_TASK):
+ resolve_person_training_sessions_task.delay(
+ team_id, unique[offset : offset + PERSON_LOOKUP_DISTINCT_IDS_PER_TASK], started_before
+ )
diff --git a/products/ai_training/backend/tasks/tasks.py b/products/ai_training/backend/tasks/tasks.py
index 5c9a2025f6bb..32becb22ab7c 100644
--- a/products/ai_training/backend/tasks/tasks.py
+++ b/products/ai_training/backend/tasks/tasks.py
@@ -1,10 +1,16 @@
-from celery import shared_task
+from datetime import datetime
+
+import structlog
+from celery import Task, shared_task
from posthog.tasks.utils import CeleryQueue
-from products.ai_training.backend.facade.api import privacy_enabled
+from products.ai_training.backend.config import privacy_enabled
+from products.ai_training.backend.logic.deletion import resolve_person_training_sessions
from products.ai_training.backend.privacy.store import AITrainingPrivacyStore
+logger = structlog.get_logger(__name__)
+
@shared_task(
name="posthog.tasks.ai_training_privacy.process_ai_training_privacy_requests",
@@ -16,3 +22,44 @@ from products.ai_training.backend.privacy.store import AITrainingPrivacyStore
def process_ai_training_privacy_requests() -> None:
if privacy_enabled():
AITrainingPrivacyStore.from_settings().drain()
+
+
+# The retries span about 24 hours, well inside the 10 days that deleted recordings keep their
+# replay index rows. Each wait stays under the Redis broker's one-hour visibility timeout,
+# because a longer wait makes the broker deliver the waiting retry a second time.
+PERSON_LOOKUP_MAX_RETRIES = 52
+PERSON_LOOKUP_RETRY_BASE_SECONDS = 60
+PERSON_LOOKUP_RETRY_MAX_SECONDS = 1800
+
+
+def person_lookup_retry_countdown(retries: int) -> int:
+ return min(PERSON_LOOKUP_RETRY_BASE_SECONDS * 2**retries, PERSON_LOOKUP_RETRY_MAX_SECONDS)
+
+
+# Late ack plus reject-on-worker-lost redeliver the lookup when a worker restarts mid-run. The
+# caller has deleted the person by then, so this task holds the only copy of its distinct IDs.
+@shared_task(
+ bind=True,
+ ignore_result=True,
+ queue=CeleryQueue.LONG_RUNNING.value,
+ acks_late=True,
+ reject_on_worker_lost=True,
+ max_retries=PERSON_LOOKUP_MAX_RETRIES,
+)
+def resolve_person_training_sessions_task(
+ self: Task, team_id: int, distinct_ids: list[str], started_before: str
+) -> None:
+ try:
+ resolve_person_training_sessions(team_id, distinct_ids, datetime.fromisoformat(started_before))
+ except Exception as exc:
+ retries = self.request.retries
+ if retries >= PERSON_LOOKUP_MAX_RETRIES:
+ logger.exception(
+ "ai_training.person_lookup_gave_up",
+ team_id=team_id,
+ distinct_id_count=len(distinct_ids),
+ retries=retries,
+ error_type=type(exc).__name__,
+ )
+ # Past max_retries this raises ``exc`` instead of scheduling another run.
+ raise self.retry(exc=exc, countdown=person_lookup_retry_countdown(retries))
diff --git a/products/ai_training/backend/tests/test_deletion.py b/products/ai_training/backend/tests/test_deletion.py
index a59165230874..668be7d65ba3 100644
--- a/products/ai_training/backend/tests/test_deletion.py
+++ b/products/ai_training/backend/tests/test_deletion.py
@@ -1,18 +1,43 @@
+from datetime import UTC, datetime, timedelta
from uuid import UUID
+from posthog.test.base import BaseTest, ClickhouseTestMixin
from unittest.mock import AsyncMock, MagicMock, patch
from django.db import DatabaseError
from django.test import TestCase, override_settings
+from celery.exceptions import Retry
from parameterized import parameterized
from posthog.api.person import PersonViewSet
+from posthog.exceptions import ClickHouseAtCapacity
from posthog.models import Person, Team
from posthog.models.team.util import delete_team_records
+from posthog.session_recordings.queries.test.session_replay_sql import produce_replay_summary
+from posthog.uuidt import uuid7
from products.ai_training.backend.facade.api import queue_person_training_deletion, queue_training_deletion
+from products.ai_training.backend.logic.deletion import resolve_person_training_sessions
from products.ai_training.backend.models import AITrainingDeletionRequest
+from products.ai_training.backend.tasks.tasks import (
+ PERSON_LOOKUP_MAX_RETRIES,
+ person_lookup_retry_countdown,
+ resolve_person_training_sessions_task,
+)
+
+# The Redis broker redelivers a message that a worker holds longer than this.
+BROKER_VISIBILITY_TIMEOUT_SECONDS = 3600
+
+
+def _teams(team: Team) -> MagicMock:
+ return MagicMock(first=MagicMock(return_value=team))
+
+
+def _apply_lookup_task(retries: int) -> None:
+ resolve_person_training_sessions_task.apply(
+ args=(7, ["known"], datetime.now(UTC).isoformat()), retries=retries, throw=True
+ )
@override_settings(AI_RESEARCH_REPLAY_KEY_TABLE="test-table")
@@ -37,7 +62,7 @@ class TestAITrainingDeletionOutbox(TestCase):
temporal.start_workflow = AsyncMock()
session_id = "01a09f92-e780-7000-8000-000000000001"
with (
- patch("products.ai_training.backend.logic.deletion.Team.objects.get", return_value=Team(id=7)),
+ patch("products.ai_training.backend.logic.deletion.Team.objects.filter", return_value=_teams(Team(id=7))),
patch(
"posthog.hogql.query.execute_hogql_query",
return_value=MagicMock(results=[[session_id]]),
@@ -66,7 +91,7 @@ class TestAITrainingDeletionOutbox(TestCase):
def test_person_lookup_paginates_without_storing_user_ids(self) -> None:
sessions = [f"01a09f92-e780-7000-8000-{index:012x}" for index in range(1001)]
with (
- patch("products.ai_training.backend.logic.deletion.Team.objects.get", return_value=Team(id=7)),
+ patch("products.ai_training.backend.logic.deletion.Team.objects.filter", return_value=_teams(Team(id=7))),
patch(
"posthog.hogql.query.execute_hogql_query",
side_effect=[
@@ -83,6 +108,66 @@ class TestAITrainingDeletionOutbox(TestCase):
self.assertEqual(lookup.call_args.kwargs["placeholders"]["cursor"].value, sessions[999])
self.assertEqual(AITrainingDeletionRequest.objects.for_team(7).count(), 2)
+ def test_person_deletion_queues_the_lookup_instead_of_waiting_on_clickhouse(self) -> None:
+ person = Person(id=1, uuid=UUID("00000000-0000-0000-0000-000000000007"))
+ person._distinct_ids = ["known", "alias"]
+ view = MagicMock(team_id=7, organization=MagicMock(id=UUID("00000000-0000-0000-0000-00000000000a")))
+ with (
+ patch("posthog.hogql.query.execute_hogql_query", side_effect=ClickHouseAtCapacity()) as lookup,
+ patch.object(resolve_person_training_sessions_task, "delay") as enqueue,
+ patch("posthog.api.person.resolve_persons_for_deletion", return_value=[person]),
+ patch("posthog.models.person.util.publish_person_tombstone", return_value=[]),
+ ):
+ summary = PersonViewSet._bulk_delete_persons(view, MagicMock(user=None), distinct_ids=["known", "missing"])
+ self.assertEqual(summary["deletion_errors"], [])
+ lookup.assert_not_called()
+ enqueue.assert_called_once()
+ team_id, distinct_ids, started_before = enqueue.call_args.args
+ self.assertEqual((team_id, distinct_ids), (7, ["alias", "known", "missing"]))
+ self.assertLess(datetime.now(UTC) - datetime.fromisoformat(started_before), timedelta(minutes=1))
+
+ @parameterized.expand(
+ [
+ ("first_failure_retries", 0, ClickHouseAtCapacity(), Retry),
+ ("last_failure_gives_up", PERSON_LOOKUP_MAX_RETRIES, ClickHouseAtCapacity(), ClickHouseAtCapacity),
+ ("retry_succeeds", 3, MagicMock(results=[["01a09f92-e780-7000-8000-000000000001"]]), None),
+ ]
+ )
+ def test_person_lookup_retries_a_busy_cluster_until_its_budget_runs_out(
+ self, _name: str, retries: int, response: object, raised: type[BaseException] | None
+ ) -> None:
+ with (
+ patch("products.ai_training.backend.logic.deletion.Team.objects.filter", return_value=_teams(Team(id=7))),
+ patch("posthog.hogql.query.execute_hogql_query", side_effect=[response]),
+ ):
+ if raised is None:
+ _apply_lookup_task(retries)
+ elif raised is Retry:
+ with self.assertRaises(Retry) as retry:
+ _apply_lookup_task(retries)
+ scheduled: Retry = retry.exception
+ self.assertEqual(scheduled.when, person_lookup_retry_countdown(retries))
+ else:
+ with self.assertRaises(raised):
+ _apply_lookup_task(retries)
+ queued = list(AITrainingDeletionRequest.objects.for_team(7).values_list("identifiers", flat=True))
+ self.assertEqual(queued, [] if raised else [["01a09f92-e780-7000-8000-000000000001"]])
+
+ def test_person_lookup_retries_for_a_day_without_outliving_the_broker_visibility_timeout(self) -> None:
+ countdowns = [person_lookup_retry_countdown(retries) for retries in range(PERSON_LOOKUP_MAX_RETRIES)]
+ self.assertLess(max(countdowns), BROKER_VISIBILITY_TIMEOUT_SECONDS)
+ self.assertGreaterEqual(sum(countdowns), 24 * 3600)
+
+ def test_person_lookup_runs_on_a_queue_with_clickhouse_access(self) -> None:
+ # The ai_research_privacy worker has restricted grants and no ClickHouse access.
+ self.assertEqual(resolve_person_training_sessions_task.signature().type.queue, "long_running")
+
+ def test_person_lookup_for_a_deleted_team_finishes_without_a_lookup(self) -> None:
+ with patch("posthog.hogql.query.execute_hogql_query") as lookup:
+ resolve_person_training_sessions(987654, ["known"], datetime.now(UTC))
+ lookup.assert_not_called()
+ self.assertFalse(AITrainingDeletionRequest.objects.for_team(987654).exists())
+
def test_team_deletion_and_deletion_request_commit_together(self) -> None:
with patch.object(Team, "objects") as teams:
teams.select_for_update.return_value.filter.return_value = [Team(id=7)]
@@ -104,3 +189,30 @@ class TestAITrainingDeletionOutbox(TestCase):
with self.assertRaisesRegex(DatabaseError, "outbox unavailable"):
delete_team_records([7])
teams.filter.return_value.delete.assert_not_called()
+
+
+@override_settings(AI_RESEARCH_REPLAY_KEY_TABLE="test-table")
+class TestPersonTrainingSessionLookup(ClickhouseTestMixin, BaseTest):
+ def test_resolves_sessions_that_started_before_the_deletion_including_deleted_recordings(self) -> None:
+ deleted_at = datetime.now(UTC).replace(microsecond=0) - timedelta(hours=2)
+ before, deleted_recording, after, other_person = (str(uuid7()) for _ in range(4))
+ for session_id, distinct_id, started_at, is_deleted in [
+ (before, "known", deleted_at - timedelta(hours=1), False),
+ (deleted_recording, "known", deleted_at - timedelta(days=1), True),
+ (after, "known", deleted_at + timedelta(minutes=5), False),
+ (other_person, "someone-else", deleted_at - timedelta(hours=1), False),
+ ]:
+ produce_replay_summary(
+ team_id=self.team.pk,
+ session_id=session_id,
+ distinct_id=distinct_id,
+ first_timestamp=started_at,
+ last_timestamp=started_at + timedelta(minutes=1),
+ is_deleted=is_deleted,
+ ensure_analytics_event_in_session=False,
+ )
+
+ resolve_person_training_sessions(self.team.pk, ["known"], deleted_at)
+
+ queued = AITrainingDeletionRequest.objects.for_team(self.team.pk).get()
+ self.assertEqual(queued.identifiers, sorted([before, deleted_recording]))
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
index 84b9e5e481c3..05b6a080a2c3 100644
--- a/products/ai_training/docs/replay-data.md
+++ b/products/ai_training/docs/replay-data.md
@@ -123,7 +123,9 @@ Existing recording, person, team, and organization deletion flows enqueue ML del
Person deletion resolves the combined supplied and profile distinct IDs through the replay ClickHouse index.
This lookup also runs when the user does not select replay deletion and includes IDs with no remaining person profile.
Only the resulting session IDs enter the ML deletion outbox.
-A lookup failure stops the request before profile deletion so it can retry.
+The lookup runs in a background task, so person deletion waits only until the task is queued.
+The task carries the distinct IDs, because the profile they belong to is deleted by then.
+A failed lookup retries with backoff for about 24 hours, then fails the task, which the task failure metric reports.
Team deletion and its deletion outbox request commit in the same database transaction.
If the outbox write fails, team deletion fails and can retry.
Consent changes do not enqueue deletion requests.
@@ -136,7 +138,7 @@ Its team IDs refer to the original environment, without resolving a child enviro
| Person | Resolve its session IDs through replay, then apply session deletion to each result. |
| Team | Remove its session keys and its image keys, and close the current month and the next one. |
-The person lookup matches any available replay row for the requested IDs, then deduplicates and paginates sessions.
+The person lookup matches any available replay row for the requested IDs that began before the deletion, then deduplicates and paginates sessions.
It does not filter out recordings marked deleted or past their replay retention date while their index rows remain.
Replay index retention limits this lookup: after those rows expire, person deletion cannot discover the corresponding ML sessions.
New sessions from the same person can be collected if consent permits them.