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(ai-research): add explicit deletion for ML training data (#99635)

Robbiee16981793ba9
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index 9a11440075f9..e1e9c75f8685 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -387,9 +387,9 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
user_scoped: set[str] = set()
no_scope: set[str] = set()
- # Billing alerts are organization-scoped through BillingAlertConfiguration. Team is only an
- # execution context; claim and event records inherit scope through their canonical parent.
organization_scoped_overrides = {
+ "AITrainingConsent", # Plain organization_id survives organization deletion.
+ # Billing alerts inherit scope through BillingAlertConfiguration; team is an execution context.
"BillingAlertConfiguration",
"BillingAlertEvaluationClaim",
"BillingAlertEvent",
diff --git a/.semgrep/rules/security/idor-team-scoped-models.yaml b/.semgrep/rules/security/idor-team-scoped-models.yaml
index 66c2e1939acb..d6bff1e5eef9 100644
--- a/.semgrep/rules/security/idor-team-scoped-models.yaml
+++ b/.semgrep/rules/security/idor-team-scoped-models.yaml
@@ -74,6 +74,7 @@ rules:
|AgentTransportBinding
|AgentUser
|AIObservabilityChecklistItemState
+ |AITrainingDeletionRequest
|Alert
|AlertConfiguration
|Annotation
@@ -486,6 +487,7 @@ rules:
|AgentTransportBinding
|AgentUser
|AIObservabilityChecklistItemState
+ |AITrainingDeletionRequest
|Alert
|AlertConfiguration
|Annotation
diff --git a/bin/celery-queues.env b/bin/celery-queues.env
index 7aa3ceb87104..5cd934b61789 100644
--- a/bin/celery-queues.env
+++ b/bin/celery-queues.env
@@ -2,4 +2,4 @@
# Important: Add new queues to make Celery consume tasks from them.
# NOTE: Keep in sync with posthog/tasks/utils.py
-CELERY_WORKER_QUEUES=celery,stats,email,analytics_queries,analytics_limited,long_running,exports,subscription_delivery,usage_reports,integrations,feature_flags,feature_flags_long_running
+CELERY_WORKER_QUEUES=ai_research_privacy,celery,stats,email,analytics_queries,analytics_limited,long_running,exports,subscription_delivery,usage_reports,integrations,feature_flags,feature_flags_long_running
diff --git a/bin/docker-worker-ai-training-privacy b/bin/docker-worker-ai-training-privacy
new file mode 100755
index 000000000000..e5fcd64029a0
--- /dev/null
+++ b/bin/docker-worker-ai-training-privacy
@@ -0,0 +1,12 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+export SECRET_KEY="$(python -c 'import secrets; print(secrets.token_urlsafe(64))')"
+export SKIP_ASYNC_MIGRATIONS_SETUP=1
+export PROMETHEUS_MULTIPROC_DIR=/tmp/posthog_celery_prometheus
+
+exec celery -A posthog worker -Ofair \
+ --queues=ai_research_privacy \
+ --concurrency=1 \
+ --prefetch-multiplier=1 \
+ --without-gossip --without-mingle --without-heartbeat
diff --git a/frontend/package.json b/frontend/package.json
index 1f65a6c841f5..298243ab5216 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -85,6 +85,7 @@
"@posthog/products-actions": "workspace:*",
"@posthog/products-ai-gateway": "workspace:*",
"@posthog/products-ai-observability": "workspace:*",
+ "@posthog/products-ai-training": "workspace:*",
"@posthog/products-alerts": "workspace:*",
"@posthog/products-annotations": "workspace:*",
"@posthog/products-apm": "workspace:*",
diff --git a/hogli.yaml b/hogli.yaml
index 93943e8928db..9165a1fdb75c 100644
--- a/hogli.yaml
+++ b/hogli.yaml
@@ -1254,3 +1254,7 @@ environment:
bin_script: profile_migrations
description: 'Profile Django migrations on fresh DBs and render a per-op timing report'
hidden: true
+ docker:worker:ai:training:privacy:
+ bin_script: docker-worker-ai-training-privacy
+ description: 'Start the dedicated AI training privacy worker'
+ hidden: true
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e3fdf991a038..946a4a3eefc5 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -650,6 +650,9 @@ importers:
'@posthog/products-ai-observability':
specifier: workspace:*
version: link:../products/ai_observability
+ '@posthog/products-ai-training':
+ specifier: workspace:*
+ version: link:../products/ai_training
'@posthog/products-alerts':
specifier: workspace:*
version: link:../products/alerts
@@ -2456,6 +2459,8 @@ importers:
specifier: 'catalog:'
version: 0.2.4([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
+ products/ai_training: {}
+
products/alerts:
dependencies:
'@posthog/brand':
diff --git a/posthog/api/person.py b/posthog/api/person.py
index 7ff27956b625..f6aa9a1d3b71 100644
--- a/posthog/api/person.py
+++ b/posthog/api/person.py
@@ -82,6 +82,7 @@ from posthog.utils import (
relative_date_parse_with_delta_mapping,
)
+from products.ai_training.backend.facade.api import queue_person_training_deletion
from products.cohorts.backend.models.cohort import Cohort
from products.cohorts.backend.models.util import get_all_cohort_ids_by_person_uuid
from products.workflows.backend.api.message_assets import (
@@ -890,6 +891,11 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
raise ValidationError("You need to specify either distinct_ids or ids")
persons = resolve_persons_for_deletion(self.team_id, ids, distinct_ids)
+ if not keep_person or delete_recordings:
+ queue_person_training_deletion(
+ self.team_id,
+ [*(distinct_ids or []), *(value for person in persons for value in person.distinct_ids)],
+ )
persons_deleted = 0
errors: builtins.list[dict[str, str]] = []
@@ -900,6 +906,7 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
actor=cast(User, request.user),
request=request,
organization_id=self.organization.id,
+ queue_ai_training_deletion=False,
)
persons_deleted = result.deleted_count
errors = [{"person_uuid": str(u)} for u in result.errors]
@@ -907,7 +914,9 @@ class PersonViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if delete_events:
queue_person_event_deletion(self.team_id, persons, actor=cast(User, request.user))
if delete_recordings:
- queue_person_recording_deletion(self.team_id, persons, actor=cast(User, request.user))
+ queue_person_recording_deletion(
+ self.team_id, persons, actor=cast(User, request.user), queue_ai_training_deletion=False
+ )
return {
"persons_found": len(persons),
diff --git a/posthog/celery_queues.py b/posthog/celery_queues.py
index d7bf7d7ccdea..a961189c9b94 100644
--- a/posthog/celery_queues.py
+++ b/posthog/celery_queues.py
@@ -29,6 +29,7 @@ from enum import Enum
class CeleryQueue(Enum):
+ AI_RESEARCH_PRIVACY = "ai_research_privacy"
DEFAULT = "celery"
STATS = "stats"
EMAIL = "email"
diff --git a/posthog/models/person/bulk_delete.py b/posthog/models/person/bulk_delete.py
index 7f190e62c2c5..5223ca2762af 100644
--- a/posthog/models/person/bulk_delete.py
+++ b/posthog/models/person/bulk_delete.py
@@ -27,6 +27,8 @@ from posthog.models.user import User
from posthog.temporal.common.client import sync_connect
from posthog.temporal.session_replay.delete_recordings.types import DeletionConfig, RecordingsWithPersonInput
+from products.ai_training.backend.facade.api import queue_person_training_deletion
+
logger = structlog.get_logger(__name__)
@@ -63,6 +65,7 @@ def delete_persons_profile(
actor: User | None,
request=None,
organization_id=None,
+ queue_ai_training_deletion: bool = True,
) -> PersonProfileDeletionResult:
"""Run ClickHouse Kafka tombstones, then a single Postgres batch delete.
@@ -71,6 +74,10 @@ def delete_persons_profile(
"""
from posthog.personhog_client.client import personhog_call
+ if queue_ai_training_deletion:
+ queue_person_training_deletion(
+ team_id, [distinct_id for person in persons for distinct_id in person.distinct_ids]
+ )
deleted: builtins.list[Person] = []
errors: builtins.list[uuid_lib.UUID] = []
# A missing map entry (or a failed batch fetch) passes None below, making delete_person
@@ -143,9 +150,14 @@ def queue_person_recording_deletion(
*,
actor: User | None,
reason: str = "person deletion",
+ queue_ai_training_deletion: bool = True,
) -> None:
if not persons:
return
+ if queue_ai_training_deletion:
+ queue_person_training_deletion(
+ team_id, [distinct_id for person in persons for distinct_id in person.distinct_ids]
+ )
_start_recording_workflows(team_id, persons, actor, reason)
diff --git a/posthog/models/team/util.py b/posthog/models/team/util.py
index 6eb80ca26713..75ecb3485357 100644
--- a/posthog/models/team/util.py
+++ b/posthog/models/team/util.py
@@ -11,6 +11,7 @@ from posthog.cache_utils import cache_for
from posthog.models.async_migration import is_async_migration_complete
from posthog.temporal.common.client import sync_connect
+from products.ai_training.backend.facade.api import queue_training_deletion
from products.batch_exports.backend.service import BatchExportServiceScheduleNotFound, batch_export_delete_schedule
from products.dashboards.backend.models.dashboard_tile import DashboardTile
@@ -351,7 +352,10 @@ def delete_team_records(team_ids: list[int]) -> None:
from posthog.models.team import Team
with transaction.atomic():
- list(Team.objects.select_for_update().filter(id__in=team_ids))
+ # nosemgrep: hot-parent-row-select-for-update -- Team deletion must block concurrent child inserts.
+ teams = list(Team.objects.select_for_update().filter(id__in=team_ids))
+ for team in teams:
+ queue_training_deletion(team.pk, "team")
Team.objects.filter(id__in=team_ids).delete()
diff --git a/posthog/session_recordings/session_recording_api.py b/posthog/session_recordings/session_recording_api.py
index 151e259555e7..fd5f87d581c3 100644
--- a/posthog/session_recordings/session_recording_api.py
+++ b/posthog/session_recordings/session_recording_api.py
@@ -115,6 +115,7 @@ from products.access_control.backend.presentation.access_control import (
AccessControlViewSetMixin,
UserAccessControlSerializerMixin,
)
+from products.ai_training.backend.facade.api import queue_training_deletion
from ..models.product_intent.product_intent import ProductIntent
from .queries.combine_session_ids_for_filtering import combine_session_id_filters
@@ -1623,6 +1624,8 @@ class SessionRecordingViewSet(
Returns list of session IDs that failed to delete.
"""
+ queue_training_deletion(self.team.id, "session", session_ids)
+
async def _delete_all() -> list[str]:
async with recording_api_client() as storage:
return await storage.delete_recordings(session_ids, self.team.id, deleted_by=deleted_by)
diff --git a/posthog/settings/ingestion.py b/posthog/settings/ingestion.py
index 14168963f796..2d88039789cd 100644
--- a/posthog/settings/ingestion.py
+++ b/posthog/settings/ingestion.py
@@ -151,3 +151,8 @@ BILLING_USAGE_RECORDS_HOGQL_ORGANIZATION_IDS: set[UUID | Literal["*"]] = {
)
if organization_id
}
+
+AI_RESEARCH_REPLAY_PRIVACY_TABLE = os.getenv("AI_RESEARCH_REPLAY_PRIVACY_TABLE", "")
+AI_RESEARCH_REPLAY_AWS_REGION = os.getenv("AI_RESEARCH_REPLAY_AWS_REGION", "us-east-1")
+AI_RESEARCH_REPLAY_DYNAMODB_ENDPOINT = os.getenv("AI_RESEARCH_REPLAY_DYNAMODB_ENDPOINT", "")
+AI_RESEARCH_REPLAY_KMS_KEY_ARN = os.getenv("AI_RESEARCH_REPLAY_KMS_KEY_ARN", "")
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index b4129f924ca5..84403c2588df 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -41,6 +41,7 @@ AXES_HTTP_RESPONSE_CODE = 403
# TODO: Automatically generate these like we do for the frontend
# NOTE: Add these definitions here and on `tach.toml`
PRODUCTS_APPS = [
+ "products.ai_training.backend.apps.AiTrainingConfig",
"products.analytics_platform.backend.apps.AnalyticsPlatformConfig",
"products.early_access_features.backend.apps.EarlyAccessFeaturesConfig",
"products.tasks.backend.apps.TasksConfig",
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index 46832fed46e5..0793a72c11d3 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -75,6 +75,8 @@ from posthog.tasks.uploaded_media import sweep_abandoned_media_uploads_task
from posthog.tasks.wizard_blocklist import revoke_blocklisted_gateway_credentials
from posthog.utils import get_crontab, get_instance_region
+from products.ai_training.backend.facade.api import privacy_enabled
+from products.ai_training.backend.facade.tasks import process_ai_training_privacy_requests
from products.approvals.backend.tasks import expire_old_change_requests, validate_pending_change_requests
from products.canvas.backend.tasks import cleanup_canvas_builds, sweep_canvas_builds
from products.conversations.backend.tasks.email import flush_pending_email_replies
@@ -247,6 +249,8 @@ def add_periodic_task_with_expiry(
def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
+ if privacy_enabled():
+ sender.add_periodic_task(30.0, process_ai_training_privacy_requests.s(), name="process-ai-training-privacy")
# Short-interval heartbeat tasks (<60s) use intervals since cron minimum is 1 minute.
# These are fine because they run more frequently than beat restarts.
if not settings.DEBUG:
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 3b605d0f9924..fd90d6fc46eb 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -10,6 +10,7 @@
'posthog.models.product_intent.product_intent.calculate_product_activation',
'posthog.query_cache.tasks.delete_query_cache_blob',
'posthog.tasks.activity_log.broadcast_activity_log_to_organization',
+ 'posthog.tasks.ai_training_privacy.process_ai_training_privacy_requests',
'posthog.tasks.async_migrations.run_async_migration',
'posthog.tasks.auth_token_cache_verification.verify_and_fix_auth_token_cache_task',
'posthog.tasks.calculate_cohort.calculate_cohort_ch',
diff --git a/posthog/tasks/test/test_scheduled.py b/posthog/tasks/test/test_scheduled.py
index 93c5c86190e3..d61c72afdba4 100644
--- a/posthog/tasks/test/test_scheduled.py
+++ b/posthog/tasks/test/test_scheduled.py
@@ -1,5 +1,9 @@
+from unittest.mock import MagicMock
+
from django.test import SimpleTestCase, TestCase
+from parameterized import parameterized
+
from posthog.celery import app
from posthog.tasks.scheduled import instance_spread_minute, setup_periodic_tasks
@@ -15,6 +19,22 @@ class TestScheduledTasks(TestCase):
assert exc is None, exc
+class TestPrivacyTaskScheduling(SimpleTestCase):
+ @parameterized.expand([("disabled", "", 0), ("enabled", "test-table", 1)])
+ def test_privacy_schedule_requires_configured_worker(self, _name: str, table: str, expected_count: int) -> None:
+ sender = MagicMock()
+ with self.settings(AI_RESEARCH_REPLAY_PRIVACY_TABLE=table):
+ setup_periodic_tasks(sender)
+ calls = [
+ call
+ for call in sender.add_periodic_task.call_args_list
+ if call.kwargs.get("name") == "process-ai-training-privacy"
+ ]
+ self.assertEqual(len(calls), expected_count)
+ if calls:
+ self.assertEqual(calls[0].args[1].type.queue, "ai_research_privacy")
+
+
class TestInstanceSpreadMinute(SimpleTestCase):
def test_one_installation_keeps_its_minute_in_every_process(self) -> None:
# A literal, because the minute has to survive a beat restart. A hash that
diff --git a/products/ai_training/README.md b/products/ai_training/README.md
new file mode 100644
index 000000000000..20bbd97a01a9
--- /dev/null
+++ b/products/ai_training/README.md
@@ -0,0 +1,21 @@
+# AI training
+
+AI Research owns the deletion controls for ML training data.
+
+The backend contains the privacy key store, encrypted-data reader, deletion requests, worker task, and management commands.
+Feature tests and encryption fixtures live in `backend/tests/`.
+Application lifecycle hooks call `backend/facade/api.py`.
+
+The `AITrainingDeletionRequest` model uses the main PostgreSQL database so team deletion and its request commit together.
+The worker keeps its existing Celery task name so queued tasks survive deployment.
+
+Ingestion uses the organization's existing AI training opt-in flag.
+Consent controls ingestion only; withdrawing consent preserves stored data and keys.
+Re-enabling consent resumes existing sessions.
+No consent backfill or deployment command is required.
+Person deletion resolves sessions through the replay index and queues only session IDs.
+ML data and key indexes do not store distinct IDs.
+Replay index retention limits which sessions a person lookup can find.
+The `delete_ai_training_month` command removes keys for a session month.
+
+See [ML replay data contracts](docs/replay-data.md) for consent, encryption, deletion, and reader behavior.
diff --git a/products/ai_training/__init__.py b/products/ai_training/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/ai_training/backend/__init__.py b/products/ai_training/backend/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/ai_training/backend/apps.py b/products/ai_training/backend/apps.py
new file mode 100644
index 000000000000..e69e6a7ed50e
--- /dev/null
+++ b/products/ai_training/backend/apps.py
@@ -0,0 +1,6 @@
+from django.apps import AppConfig
+
+
+class AiTrainingConfig(AppConfig):
+ name = "products.ai_training.backend"
+ label = "ai_training"
diff --git a/products/ai_training/backend/config.py b/products/ai_training/backend/config.py
new file mode 100644
index 000000000000..848ca41dba40
--- /dev/null
+++ b/products/ai_training/backend/config.py
@@ -0,0 +1,5 @@
+from django.conf import settings
+
+
+def privacy_enabled() -> bool:
+ return bool(getattr(settings, "AI_RESEARCH_REPLAY_PRIVACY_TABLE", ""))
diff --git a/products/ai_training/backend/facade/__init__.py b/products/ai_training/backend/facade/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/ai_training/backend/facade/api.py b/products/ai_training/backend/facade/api.py
new file mode 100644
index 000000000000..d26265125d23
--- /dev/null
+++ b/products/ai_training/backend/facade/api.py
@@ -0,0 +1,16 @@
+from collections.abc import Sequence
+
+from products.ai_training.backend import config
+from products.ai_training.backend.logic import deletion
+
+
+def privacy_enabled() -> bool:
+ return config.privacy_enabled()
+
+
+def queue_training_deletion(team_id: int, kind: str, identifiers: Sequence[str] = ()) -> None:
+ deletion.queue_training_deletion(team_id, kind, identifiers)
+
+
+def queue_person_training_deletion(team_id: int, distinct_ids: Sequence[str]) -> None:
+ deletion.queue_person_training_deletion(team_id, distinct_ids)
diff --git a/products/ai_training/backend/facade/contracts.py b/products/ai_training/backend/facade/contracts.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/ai_training/backend/facade/enums.py b/products/ai_training/backend/facade/enums.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/ai_training/backend/facade/tasks.py b/products/ai_training/backend/facade/tasks.py
new file mode 100644
index 000000000000..82ca7cbbd174
--- /dev/null
+++ b/products/ai_training/backend/facade/tasks.py
@@ -0,0 +1,3 @@
+from products.ai_training.backend.tasks.tasks import (
+ process_ai_training_privacy_requests as process_ai_training_privacy_requests,
+)
diff --git a/products/ai_training/backend/logic/__init__.py b/products/ai_training/backend/logic/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/ai_training/backend/logic/deletion.py b/products/ai_training/backend/logic/deletion.py
new file mode 100644
index 000000000000..4851198cc4d9
--- /dev/null
+++ b/products/ai_training/backend/logic/deletion.py
@@ -0,0 +1,69 @@
+import uuid
+from collections.abc import Sequence
+
+from posthog.hogql import ast
+
+from posthog.models.team.team import Team
+
+from products.ai_training.backend.config import privacy_enabled
+from products.ai_training.backend.models import AITrainingDeletionRequest
+
+
+def queue_training_deletion(team_id: int, kind: str, identifiers: Sequence[str] = ()) -> None:
+ if not privacy_enabled():
+ return
+ if kind not in {"team", "session"}:
+ raise ValueError("Unsupported AI training deletion scope")
+ if kind == "session":
+ normalized = []
+ for value in identifiers:
+ try:
+ session_id = uuid.UUID(value)
+ except (ValueError, AttributeError):
+ continue
+ if session_id.version == 7:
+ normalized.append(str(session_id))
+ identifiers = normalized
+ unique = sorted(set(identifiers))
+ if kind != "team" and not unique:
+ return
+ requests = [
+ AITrainingDeletionRequest(team_id=team_id, kind=kind, identifiers=unique[offset : offset + 1000])
+ for offset in range(0, max(1, len(unique)), 1000)
+ ]
+ AITrainingDeletionRequest.objects.for_team(team_id).bulk_create(requests)
+
+
+def queue_person_training_deletion(team_id: int, distinct_ids: Sequence[str]) -> None:
+ 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)
+ unique = sorted(set(distinct_ids))
+ for offset in range(0, len(unique), 1000):
+ cursor = ""
+ while True:
+ response = execute_hogql_query(
+ query="""
+ SELECT session_id
+ FROM raw_session_replay_events
+ WHERE distinct_id IN {distinct_ids} AND session_id > {cursor}
+ GROUP BY session_id
+ ORDER BY session_id
+ LIMIT 1000
+ """,
+ team=team,
+ query_type="AITrainingPersonDeletion",
+ placeholders={
+ "distinct_ids": ast.Tuple(
+ exprs=[ast.Constant(value=value) for value in unique[offset : offset + 1000]]
+ ),
+ "cursor": ast.Constant(value=cursor),
+ },
+ )
+ sessions = [str(row[0]) for row in response.results or []]
+ queue_training_deletion(team_id, "session", sessions)
+ if len(sessions) < 1000:
+ break
+ cursor = sessions[-1]
diff --git a/products/ai_training/backend/management/commands/delete_ai_training_month.py b/products/ai_training/backend/management/commands/delete_ai_training_month.py
new file mode 100644
index 000000000000..b7617fea1d46
--- /dev/null
+++ b/products/ai_training/backend/management/commands/delete_ai_training_month.py
@@ -0,0 +1,26 @@
+from argparse import ArgumentParser
+from typing import Any
+
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError
+
+from products.ai_training.backend.privacy.reader import KEY_READ_LEASE_SECONDS
+from products.ai_training.backend.privacy.store import AITrainingPrivacyStore
+
+
+class Command(BaseCommand):
+ help = "Permanently block an ML session month and remove its session and image keys."
+
+ def add_arguments(self, parser: ArgumentParser) -> None:
+ parser.add_argument("session_month", help="UTC session start month, in YYYY-MM format")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ if not settings.AI_RESEARCH_REPLAY_PRIVACY_TABLE:
+ raise CommandError("AI_RESEARCH_REPLAY_PRIVACY_TABLE is not configured")
+ try:
+ count = AITrainingPrivacyStore.from_settings().delete_month(options["session_month"])
+ except ValueError as error:
+ raise CommandError(str(error)) from error
+ self.stdout.write(
+ f"Removed {count} indexed keys. Existing read leases expire within {KEY_READ_LEASE_SECONDS} seconds."
+ )
diff --git a/products/ai_training/backend/migrations/0001_initial.py b/products/ai_training/backend/migrations/0001_initial.py
new file mode 100644
index 000000000000..e74ad4a9036c
--- /dev/null
+++ b/products/ai_training/backend/migrations/0001_initial.py
@@ -0,0 +1,54 @@
+# Generated by Django 5.2.17 on 2026-09-14 11:09
+
+import django.utils.timezone
+import django.db.models.manager
+from django.db import migrations, models
+
+import posthog.uuidt
+
+
+class Migration(migrations.Migration):
+ initial = True
+
+ dependencies = []
+
+ operations = [
+ migrations.CreateModel(
+ name="AITrainingDeletionRequest",
+ fields=[
+ (
+ "id",
+ models.UUIDField(
+ default=posthog.uuidt.uuid7,
+ editable=False,
+ primary_key=True,
+ serialize=False,
+ ),
+ ),
+ ("team_id", models.BigIntegerField()),
+ ("kind", models.CharField(max_length=32)),
+ ("identifiers", models.JSONField(default=list)),
+ ("created_at", models.DateTimeField(default=django.utils.timezone.now)),
+ (
+ "leased_until",
+ models.DateTimeField(default=django.utils.timezone.now),
+ ),
+ ("completed_at", models.DateTimeField(null=True)),
+ ("cursor", models.JSONField(default=dict)),
+ ],
+ options={
+ "db_table": "posthog_aitrainingdeletionrequest",
+ "default_manager_name": "all_teams",
+ "indexes": [
+ models.Index(
+ condition=models.Q(("completed_at__isnull", True)),
+ fields=["created_at"],
+ name="ai_training_pending_requests",
+ )
+ ],
+ },
+ managers=[
+ ("all_teams", django.db.models.manager.Manager()),
+ ],
+ ),
+ ]
diff --git a/products/ai_training/backend/migrations/__init__.py b/products/ai_training/backend/migrations/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/ai_training/backend/migrations/max_migration.txt b/products/ai_training/backend/migrations/max_migration.txt
new file mode 100644
index 000000000000..cbab66dde92a
--- /dev/null
+++ b/products/ai_training/backend/migrations/max_migration.txt
@@ -0,0 +1 @@
+0001_initial
diff --git a/products/ai_training/backend/models.py b/products/ai_training/backend/models.py
new file mode 100644
index 000000000000..58df6dbb98f0
--- /dev/null
+++ b/products/ai_training/backend/models.py
@@ -0,0 +1,30 @@
+from django.db import models
+from django.utils import timezone
+
+from posthog.models.scoping.manager import EnvironmentScopedManager
+from posthog.models.utils import uuid7
+
+
+class AITrainingDeletionRequest(models.Model):
+ id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
+ team_id = models.BigIntegerField()
+ kind = models.CharField(max_length=32)
+ identifiers = models.JSONField(default=list)
+ created_at = models.DateTimeField(default=timezone.now)
+ leased_until = models.DateTimeField(default=timezone.now)
+ completed_at = models.DateTimeField(null=True)
+ cursor = models.JSONField(default=dict)
+
+ all_teams = models.Manager()
+ objects = EnvironmentScopedManager()
+
+ class Meta:
+ db_table = "posthog_aitrainingdeletionrequest"
+ default_manager_name = "all_teams"
+ indexes = [
+ models.Index(
+ fields=["created_at"],
+ condition=models.Q(completed_at__isnull=True),
+ name="ai_training_pending_requests",
+ )
+ ]
diff --git a/products/ai_training/backend/presentation/__init__.py b/products/ai_training/backend/presentation/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/ai_training/backend/privacy/reader.py b/products/ai_training/backend/privacy/reader.py
new file mode 100644
index 000000000000..58abf68f12ae
--- /dev/null
+++ b/products/ai_training/backend/privacy/reader.py
@@ -0,0 +1,247 @@
+from __future__ import annotations
+
+import re
+import json
+import time
+import base64
+import random
+import hashlib
+from collections import OrderedDict
+from collections.abc import Sequence
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import field
+from datetime import UTC, datetime
+from threading import Lock
+from typing import Protocol, TypedDict, cast
+
+from nacl.secret import SecretBox
+
+from posthog.dataclasses import frozen
+
+KEY_READ_LEASE_SECONDS = 300
+
+DynamoItem = dict[str, dict[str, str | bool | bytes]]
+
+
+class BatchReadResponse(TypedDict, total=False):
+ Responses: dict[str, list[DynamoItem]]
+ UnprocessedKeys: dict[str, object]
+
+
+class DynamoReader(Protocol):
+ def batch_get_item(self, **kwargs: object) -> BatchReadResponse: ...
+
+
+class KmsReader(Protocol):
+ def decrypt(self, **kwargs: object) -> dict[str, bytes]: ...
+
+
+@frozen
+class TrainingKeyIdentity:
+ team_id: int
+ organization_id: str
+ session_id: str | None = None
+ session_month: str | None = None
+
+ def context(self, kind: str, ref: str | None = None) -> dict[str, str | int]:
+ context: dict[str, str | int] = {
+ "teamId": self.team_id,
+ "organizationId": self.organization_id,
+ "kind": kind,
+ }
+ if self.session_id is not None:
+ context["sessionId"] = self.session_id
+ if self.session_month is not None:
+ context["sessionMonth"] = self.session_month
+ if ref is not None:
+ context["ref"] = ref
+ return context
+
+ def month_block_location(self) -> TrainingKeyLocation:
+ month = self.session_month
+ if self.session_id:
+ timestamp_ms = int(self.session_id[:8] + self.session_id[9:13], 16)
+ month = datetime.fromtimestamp(timestamp_ms / 1000, UTC).strftime("%Y-%m")
+ if month is None or re.fullmatch(r"[0-9]{4}-(0[1-9]|1[0-2])", month) is None:
+ raise ValueError("ML key requires a session month")
+ return TrainingKeyLocation(pk=f"month:{month}", sk="deleted")
+
+ def wrapping_context(self) -> dict[str, str]:
+ context = {
+ "purpose": "ai-research-session" if self.session_id else "ai-research-image",
+ "team_id": str(self.team_id),
+ "organization_id": self.organization_id,
+ }
+ if self.session_id:
+ context["session_id"] = self.session_id
+ if self.session_month is not None:
+ context["session_month"] = self.session_month
+ return context
+
+
+@frozen
+class TrainingDataKey:
+ identity: TrainingKeyIdentity
+ plaintext: bytes = field(repr=False)
+ decrypt_until: float = field(default_factory=lambda: time.monotonic() + KEY_READ_LEASE_SECONDS)
+
+ def encrypt(self, kind: str, data: bytes, ref: str | None = None) -> bytes:
+ context = self.identity.context(kind, ref)
+ authenticated = json.dumps({"context": context, "data": base64.b64encode(data).decode()}).encode()
+ encrypted = SecretBox(self.plaintext).encrypt(authenticated)
+ return json.dumps(
+ {
+ "v": 2,
+ "context": context,
+ "nonce": base64.b64encode(encrypted.nonce).decode(),
+ "ciphertext": base64.b64encode(encrypted.ciphertext).decode(),
+ }
+ ).encode()
+
+ def decrypt(self, envelope_bytes: bytes, kind: str, ref: str | None = None) -> bytes:
+ if time.monotonic() >= self.decrypt_until:
+ raise TimeoutError("ML key read lease expired; read the key again")
+ envelope = json.loads(envelope_bytes)
+ context = self.identity.context(kind, ref)
+ if envelope.get("v") != 2 or envelope.get("context") != context:
+ raise ValueError("ML envelope context mismatch")
+ decoded = json.loads(
+ SecretBox(self.plaintext).decrypt(
+ base64.b64decode(envelope["ciphertext"], validate=True),
+ base64.b64decode(envelope["nonce"], validate=True),
+ )
+ )
+ if decoded.get("context") != context:
+ raise ValueError("ML authenticated context mismatch")
+ return base64.b64decode(decoded["data"], validate=True)
+
+
+@frozen
+class TrainingKeyLocation:
+ pk: str
+ sk: str
+
+ @classmethod
+ def session(cls, team_id: int, session_id: str) -> TrainingKeyLocation:
+ shard = int(hashlib.sha256(session_id.encode()).hexdigest()[:8], 16) % 32
+ return cls(pk=f"team:{team_id}:shard:{shard}", sk=f"session:{session_id}")
+
+ @classmethod
+ def image(cls, team_id: int, session_month: str) -> TrainingKeyLocation:
+ return cls(pk=f"team:{team_id}", sk=f"image:{session_month}")
+
+ def encoded(self) -> DynamoItem:
+ return {"pk": {"S": self.pk}, "sk": {"S": self.sk}}
+
+
+class TrainingDataKeyReader:
+ def __init__(
+ self,
+ dynamo: DynamoReader,
+ kms: KmsReader,
+ table_name: str,
+ master_key_arn: str,
+ cache_max: int = 10000,
+ cache_seconds: int = 60,
+ kms_requests_per_second: int = 20,
+ ) -> None:
+ if cache_max < 1 or cache_seconds < 1 or kms_requests_per_second < 1:
+ raise ValueError("ML key cache and request limits must be positive")
+ self.kms_requests_per_second = kms_requests_per_second
+ self.next_request_at = 0.0
+ self.lock = Lock()
+ self.dynamo = dynamo
+ self.kms = kms
+ self.table_name = table_name
+ self.master_key_arn = master_key_arn
+ self.cache_max = cache_max
+ self.cache_seconds = cache_seconds
+ self.cache: OrderedDict[bytes, tuple[float, bytes]] = OrderedDict()
+
+ def bulk_read(self, locations: Sequence[TrainingKeyLocation]) -> dict[TrainingKeyLocation, DynamoItem]:
+ unique = list(dict.fromkeys(locations))
+ result: dict[TrainingKeyLocation, DynamoItem] = {}
+ for start in range(0, len(unique), 100):
+ pending: dict[str, object] = {
+ self.table_name: {
+ "Keys": [location.encoded() for location in unique[start : start + 100]],
+ "ConsistentRead": True,
+ }
+ }
+ for attempt in range(5):
+ response = self.dynamo.batch_get_item(RequestItems=pending)
+ for row in response.get("Responses", {}).get(self.table_name, []):
+ result[TrainingKeyLocation(pk=str(row["pk"]["S"]), sk=str(row["sk"]["S"]))] = row
+ pending = response.get("UnprocessedKeys", {})
+ if not pending:
+ break
+ time.sleep(random.uniform(0, min(1, 0.05 * 2**attempt)))
+ if pending:
+ raise TimeoutError("ML key batch read did not complete")
+ return result
+
+ def read(self, locations: Sequence[TrainingKeyLocation]) -> dict[TrainingKeyLocation, TrainingDataKey]:
+ decrypt_until = time.monotonic() + KEY_READ_LEASE_SECONDS
+ stored = self.bulk_read(locations)
+ identities: dict[TrainingKeyLocation, TrainingKeyIdentity] = {}
+ for location, row in stored.items():
+ if row.get("deleted", {}).get("BOOL") is True or not row.get("wrapped_key", {}).get("B"):
+ continue
+ identities[location] = TrainingKeyIdentity(
+ team_id=int(str(row["team_id"]["N"])),
+ organization_id=str(row["organization_id"]["S"]),
+ session_id=location.sk.removeprefix("session:") if location.sk.startswith("session:") else None,
+ session_month=str(row["session_month"]["S"]) if location.sk.startswith("image:") else None,
+ )
+ state = self.bulk_read(
+ [
+ location
+ for identity in identities.values()
+ for location in (
+ identity.month_block_location(),
+ TrainingKeyLocation(pk=f"team:{identity.team_id}", sk="deleted"),
+ )
+ ]
+ )
+ eligible: dict[TrainingKeyLocation, TrainingKeyIdentity] = {}
+ for location, identity in identities.items():
+ if (
+ identity.month_block_location() in state
+ or TrainingKeyLocation(pk=f"team:{identity.team_id}", sk="deleted") in state
+ ):
+ continue
+ eligible[location] = identity
+ with ThreadPoolExecutor(max_workers=8) as executor:
+ plaintexts = executor.map(
+ lambda location: self.decrypt_key(
+ eligible[location], cast(bytes, stored[location]["wrapped_key"]["B"])
+ ),
+ eligible,
+ )
+ return {
+ location: TrainingDataKey(identity=eligible[location], plaintext=plaintext, decrypt_until=decrypt_until)
+ for location, plaintext in zip(eligible, plaintexts, strict=True)
+ }
+
+ def decrypt_key(self, identity: TrainingKeyIdentity, wrapped: bytes) -> bytes:
+ cache_id = hashlib.sha256(wrapped + json.dumps(identity.wrapping_context(), sort_keys=True).encode()).digest()
+ with self.lock:
+ cached = self.cache.get(cache_id)
+ if cached and cached[0] > time.monotonic():
+ self.cache.move_to_end(cache_id)
+ return cached[1]
+ scheduled_at = max(time.monotonic(), self.next_request_at)
+ self.next_request_at = scheduled_at + 1 / self.kms_requests_per_second
+ wait = scheduled_at - time.monotonic()
+ if wait > 0:
+ time.sleep(wait)
+ plaintext = self.kms.decrypt(
+ KeyId=self.master_key_arn, CiphertextBlob=wrapped, EncryptionContext=identity.wrapping_context()
+ )["Plaintext"]
+ if len(plaintext) != SecretBox.KEY_SIZE:
+ raise ValueError("Invalid ML data key")
+ with self.lock:
+ self.cache[cache_id] = (time.monotonic() + self.cache_seconds, plaintext)
+ while len(self.cache) > self.cache_max:
+ self.cache.popitem(last=False)
+ return plaintext
diff --git a/products/ai_training/backend/privacy/store.py b/products/ai_training/backend/privacy/store.py
new file mode 100644
index 000000000000..d7c067be1ff1
--- /dev/null
+++ b/products/ai_training/backend/privacy/store.py
@@ -0,0 +1,209 @@
+import re
+import time
+import hashlib
+from collections.abc import Sequence
+from datetime import datetime, timedelta
+from typing import Protocol, TypedDict, cast
+
+from django.conf import settings
+from django.db import transaction
+from django.utils import timezone
+
+import boto3
+import structlog
+from botocore.config import Config
+
+from products.ai_training.backend.models import AITrainingDeletionRequest
+from products.ai_training.backend.privacy.reader import KEY_READ_LEASE_SECONDS
+
+logger = structlog.get_logger(__name__)
+
+KEY_SHARDS = 32
+DynamoItem = dict[str, dict[str, str | bool | bytes]]
+
+
+class DynamoResponse(TypedDict, total=False):
+ Item: DynamoItem
+ Items: list[DynamoItem]
+ LastEvaluatedKey: DynamoItem
+
+
+class DeletionWork(TypedDict, total=False):
+ op: str
+ team_id: int
+ shard: int
+ after: DynamoItem
+
+
+class PrivacyDynamoClient(Protocol):
+ def put_item(self, **kwargs: object) -> DynamoResponse: ...
+ def get_item(self, **kwargs: object) -> DynamoResponse: ...
+ def query(self, **kwargs: object) -> DynamoResponse: ...
+ def transact_write_items(self, **kwargs: object) -> DynamoResponse: ...
+
+
+def item_key(pk: str, sk: str) -> DynamoItem:
+ return {"pk": {"S": pk}, "sk": {"S": sk}}
+
+
+def identity_digest(value: str) -> str:
+ return hashlib.sha256(value.encode()).hexdigest()
+
+
+def session_key(team_id: int, session_id: str) -> DynamoItem:
+ shard = int(identity_digest(session_id)[:8], 16) % KEY_SHARDS
+ return item_key(f"team:{team_id}:shard:{shard}", f"session:{session_id}")
+
+
+class AITrainingPrivacyStore:
+ def __init__(self, client: PrivacyDynamoClient, table_name: str) -> None:
+ self.client = client
+ self.table_name = table_name
+
+ @classmethod
+ def from_settings(cls) -> "AITrainingPrivacyStore":
+ client = boto3.client(
+ "dynamodb",
+ region_name=settings.AI_RESEARCH_REPLAY_AWS_REGION,
+ endpoint_url=settings.AI_RESEARCH_REPLAY_DYNAMODB_ENDPOINT or None,
+ config=Config(connect_timeout=5, read_timeout=5, retries={"max_attempts": 4, "mode": "standard"}),
+ )
+ return cls(cast(PrivacyDynamoClient, client), settings.AI_RESEARCH_REPLAY_PRIVACY_TABLE)
+
+ def block(self, team_id: int) -> None:
+ self.client.put_item(
+ TableName=self.table_name, Item={**item_key(f"team:{team_id}", "deleted"), "deleted": {"BOOL": True}}
+ )
+
+ def delete_month(self, session_month: str) -> int:
+ if re.fullmatch(r"[0-9]{4}-(0[1-9]|1[0-2])", session_month) is None:
+ raise ValueError("Session month must use YYYY-MM")
+ self.client.put_item(
+ TableName=self.table_name,
+ Item={**item_key(f"month:{session_month}", "deleted"), "deleted": {"BOOL": True}},
+ )
+ count = 0
+ for shard in range(KEY_SHARDS):
+ cursor = None
+ while True:
+ response = self.page(f"month:{session_month}:shard:{shard}", "key:", cursor)
+ rows = response.get("Items", [])
+ self.shred([item_key(str(row["key_pk"]["S"]), str(row["key_sk"]["S"])) for row in rows])
+ count += len(rows)
+ cursor = response.get("LastEvaluatedKey")
+ if not cursor:
+ break
+ return count
+
+ def page(self, pk: str, prefix: str, cursor: DynamoItem | None = None) -> DynamoResponse:
+ return self.client.query(
+ TableName=self.table_name,
+ KeyConditionExpression="pk = :pk AND begins_with(sk, :prefix)",
+ ExpressionAttributeValues={":pk": {"S": pk}, ":prefix": {"S": prefix}},
+ ConsistentRead=True,
+ Limit=50,
+ **({"ExclusiveStartKey": cursor} if cursor else {}),
+ )
+
+ def shred(self, keys: Sequence[DynamoItem]) -> None:
+ unique = {str(key["pk"]["S"]) + "\0" + str(key["sk"]["S"]): key for key in keys}
+ values = list(unique.values())
+ for offset in range(0, len(values), 100):
+ self.client.transact_write_items(
+ TransactItems=[
+ {
+ "Update": {
+ "TableName": self.table_name,
+ "Key": {"pk": key["pk"], "sk": key["sk"]},
+ "UpdateExpression": "SET deleted = :deleted REMOVE wrapped_key",
+ "ExpressionAttributeValues": {":deleted": {"BOOL": True}},
+ },
+ }
+ for key in values[offset : offset + 100]
+ ]
+ )
+
+ def initialize(self, request: AITrainingDeletionRequest) -> list[DeletionWork]:
+ if request.team_id is None:
+ raise ValueError("AI training deletion request has no team")
+ team_id = request.team_id
+ if request.kind == "team":
+ self.block(team_id)
+ return [{"op": "team", "team_id": team_id, "shard": -1}]
+ if request.kind == "session":
+ self.shred([session_key(team_id, value) for value in request.identifiers])
+ return []
+ raise ValueError("Unknown AI training deletion request")
+
+ def advance(self, work: DeletionWork) -> list[DeletionWork]:
+ if work["op"] != "team":
+ raise ValueError("Unknown AI training deletion operation")
+ team_id = int(work["team_id"])
+ shard = int(work["shard"])
+ pk = f"team:{team_id}" if shard == -1 else f"team:{team_id}:shard:{shard}"
+ prefix = "image:" if shard == -1 else "session:"
+ response = self.page(pk, prefix, work.get("after"))
+ self.shred(response.get("Items", []))
+ if response.get("LastEvaluatedKey"):
+ return [{**work, "after": response["LastEvaluatedKey"]}]
+ if shard + 1 < KEY_SHARDS:
+ next_work: DeletionWork = {**work, "shard": shard + 1}
+ next_work.pop("after", None)
+ return [next_work]
+ return []
+
+ def apply(self, request: AITrainingDeletionRequest, deadline: float) -> bool:
+ work = request.cursor.get("work")
+ if work is None:
+ work = self.initialize(request)
+ request.cursor = {"work": work}
+ request.save(update_fields=["cursor"])
+ while work:
+ if time.monotonic() >= deadline:
+ return False
+ work = self.advance(work[0]) + work[1:]
+ request.cursor = {"work": work}
+ request.save(update_fields=["cursor"])
+ now = timezone.now()
+ complete_after = request.cursor.get("complete_after")
+ if complete_after is None:
+ request.cursor = {"work": [], "complete_after": now.timestamp() + KEY_READ_LEASE_SECONDS}
+ request.save(update_fields=["cursor"])
+ return False
+ if now.timestamp() < complete_after:
+ return False
+ request.completed_at = now
+ request.identifiers = []
+ request.save(update_fields=["completed_at", "identifiers"])
+ return True
+
+ def drain(self, limit: int = 100, budget_seconds: int = 240) -> int:
+ deadline = time.monotonic() + budget_seconds
+ completed = 0
+ for _ in range(limit):
+ if time.monotonic() >= deadline:
+ break
+ with transaction.atomic():
+ request = (
+ AITrainingDeletionRequest.objects.unscoped()
+ .select_for_update(skip_locked=True)
+ .filter(completed_at__isnull=True, leased_until__lte=timezone.now())
+ .order_by("created_at")
+ .first()
+ )
+ if request is None:
+ break
+ request.leased_until = timezone.now() + timedelta(seconds=300)
+ request.save(update_fields=["leased_until"])
+ try:
+ completed += int(self.apply(request, deadline))
+ except Exception:
+ logger.exception("ai_training_deletion_request_failed", request_id=str(request.pk), kind=request.kind)
+ request.leased_until = timezone.now() + timedelta(minutes=5)
+ else:
+ request.leased_until = max(
+ timezone.now(),
+ datetime.fromtimestamp(request.cursor.get("complete_after", 0), tz=timezone.get_current_timezone()),
+ )
+ request.save(update_fields=["leased_until"])
+ return completed
diff --git a/products/ai_training/backend/tasks/tasks.py b/products/ai_training/backend/tasks/tasks.py
new file mode 100644
index 000000000000..5c9a2025f6bb
--- /dev/null
+++ b/products/ai_training/backend/tasks/tasks.py
@@ -0,0 +1,18 @@
+from celery import shared_task
+
+from posthog.tasks.utils import CeleryQueue
+
+from products.ai_training.backend.facade.api import privacy_enabled
+from products.ai_training.backend.privacy.store import AITrainingPrivacyStore
+
+
+@shared_task(
+ name="posthog.tasks.ai_training_privacy.process_ai_training_privacy_requests",
+ ignore_result=True,
+ queue=CeleryQueue.AI_RESEARCH_PRIVACY.value,
+ soft_time_limit=270,
+ time_limit=300,
+)
+def process_ai_training_privacy_requests() -> None:
+ if privacy_enabled():
+ AITrainingPrivacyStore.from_settings().drain()
diff --git a/products/ai_training/backend/tests/__init__.py b/products/ai_training/backend/tests/__init__.py
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/products/ai_training/backend/tests/fixtures/encryption_vector.json b/products/ai_training/backend/tests/fixtures/encryption_vector.json
new file mode 100644
index 000000000000..0695dc8aa88e
--- /dev/null
+++ b/products/ai_training/backend/tests/fixtures/encryption_vector.json
@@ -0,0 +1,20 @@
+{
+ "context": {
+ "teamId": 7,
+ "organizationId": "00000000-0000-4000-8000-000000000007",
+ "sessionId": "01994569-4380-7000-8000-000000000007"
+ },
+ "key": "BwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwc=",
+ "data": "c3ludGhldGljIGludGVyb3BlcmFiaWxpdHkgcGF5bG9hZA==",
+ "envelope": {
+ "v": 2,
+ "context": {
+ "teamId": 7,
+ "organizationId": "00000000-0000-4000-8000-000000000007",
+ "sessionId": "01994569-4380-7000-8000-000000000007",
+ "kind": "rrweb"
+ },
+ "nonce": "AwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMD",
+ "ciphertext": "J7ZDxBv0xIHU+NbDMakk4Zfw4/QVzp9N/3Nou2Fw5EHMoFUnJlmLR1uMpdNQ9RzghmLG2IQZxuytZzl6nXIwDjThieTFFxsTD88iry/Q3f/IUXtrfO8AwN71Edwmw5cQe4BWZiI1F3lmYLi3SqiwWWOgDAQcaFAy95e9dIaB2uMh74M1617MqtZLMQnnvLwoDUSk60ovZhTwL5spBFy02JOaAOxpazluT8+qeuQEzfgI+/54rUzdJPg6gScSOBIAQWp3Jbk9xVOrxtdqLB4BtPKAPYwqFwIJtuS/UQ=="
+ }
+}
diff --git a/products/ai_training/backend/tests/test_deletion.py b/products/ai_training/backend/tests/test_deletion.py
new file mode 100644
index 000000000000..750dbd9b1c29
--- /dev/null
+++ b/products/ai_training/backend/tests/test_deletion.py
@@ -0,0 +1,108 @@
+from uuid import UUID
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.db import DatabaseError
+from django.test import TestCase, override_settings
+
+from parameterized import parameterized
+
+from posthog.api.person import PersonViewSet
+from posthog.models import Person, Team
+from posthog.models.team.util import delete_team_records
+
+from products.ai_training.backend.facade.api import queue_person_training_deletion, queue_training_deletion
+from products.ai_training.backend.models import AITrainingDeletionRequest
+
+
+@override_settings(AI_RESEARCH_REPLAY_PRIVACY_TABLE="test-table")
+class TestAITrainingDeletionOutbox(TestCase):
+ def test_queue_filters_invalid_session_ids_and_batches_valid_sessions(self) -> None:
+ session_id = "01a09f92-e780-7000-8000-000000000001"
+ queue_training_deletion(7, "session", ["invalid", session_id.upper(), session_id])
+ request = AITrainingDeletionRequest.objects.for_team(7).get()
+ self.assertEqual(request.identifiers, [session_id])
+ queue_training_deletion(7, "session", [f"01a09f92-e780-7000-8000-{index:012x}" for index in range(1001)])
+ self.assertEqual(AITrainingDeletionRequest.objects.for_team(7).count(), 3)
+
+ @parameterized.expand([(False, False), (False, True), (True, True)])
+ def test_bulk_person_deletion_resolves_all_ids_and_queues_only_sessions(
+ self, keep_person: bool, delete_recordings: bool
+ ) -> None:
+ person = Person(id=1, uuid=UUID("00000000-0000-0000-0000-000000000007"))
+ person._distinct_ids = ["known", "alias"]
+ view = MagicMock(team_id=7)
+ request = MagicMock(user=None)
+ temporal = MagicMock()
+ 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(
+ "posthog.hogql.query.execute_hogql_query",
+ return_value=MagicMock(results=[[session_id]]),
+ ) as lookup,
+ patch("posthog.api.person.resolve_persons_for_deletion", return_value=[person]),
+ patch("posthog.models.person.bulk_delete._batched_get_distinct_ids_for_persons", return_value={}),
+ patch("posthog.models.person.bulk_delete.delete_person"),
+ patch("posthog.models.person.bulk_delete.delete_persons_from_postgres"),
+ patch("posthog.models.person.bulk_delete.sync_connect", return_value=temporal),
+ ):
+ PersonViewSet._bulk_delete_persons(
+ view,
+ request,
+ distinct_ids=["known", "missing"],
+ delete_recordings=delete_recordings,
+ keep_person=keep_person,
+ )
+ queued = AITrainingDeletionRequest.objects.for_team(7).get()
+ self.assertEqual(queued.kind, "session")
+ self.assertEqual(queued.identifiers, [session_id])
+ self.assertEqual(lookup.call_count, 1)
+ self.assertEqual(lookup.call_args.kwargs["team"].id, 7)
+ self.assertEqual(
+ [value.value for value in lookup.call_args.kwargs["placeholders"]["distinct_ids"].exprs],
+ ["alias", "known", "missing"],
+ )
+
+ 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(
+ "posthog.hogql.query.execute_hogql_query",
+ side_effect=[
+ MagicMock(results=[[value] for value in sessions[:1000]]),
+ MagicMock(results=[[sessions[-1]]]),
+ ],
+ ) as lookup,
+ ):
+ queue_person_training_deletion(7, ["[email protected]"])
+ identifiers = [
+ value for request in AITrainingDeletionRequest.objects.for_team(7).all() for value in request.identifiers
+ ]
+ self.assertEqual(sorted(identifiers), sessions)
+ self.assertEqual(lookup.call_args.kwargs["placeholders"]["cursor"].value, sessions[999])
+ self.assertEqual(AITrainingDeletionRequest.objects.for_team(7).count(), 2)
+
+ 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)]
+ teams.filter.return_value.delete.side_effect = RuntimeError("team delete failed")
+ with self.assertRaisesRegex(RuntimeError, "team delete failed"):
+ delete_team_records([7])
+ self.assertFalse(AITrainingDeletionRequest.objects.for_team(7).exists())
+
+ teams.filter.return_value.delete.side_effect = None
+ delete_team_records([7])
+ self.assertEqual(AITrainingDeletionRequest.objects.for_team(7).get().kind, "team")
+
+ def test_team_deletion_does_not_run_if_deletion_request_write_fails(self) -> None:
+ with (
+ patch.object(Team, "objects") as teams,
+ patch("django.db.models.query.QuerySet.bulk_create", side_effect=DatabaseError("outbox unavailable")),
+ ):
+ teams.select_for_update.return_value.filter.return_value = [Team(id=7)]
+ with self.assertRaisesRegex(DatabaseError, "outbox unavailable"):
+ delete_team_records([7])
+ teams.filter.return_value.delete.assert_not_called()
diff --git a/products/ai_training/backend/tests/test_privacy_reader.py b/products/ai_training/backend/tests/test_privacy_reader.py
new file mode 100644
index 000000000000..754a39aedb2a
--- /dev/null
+++ b/products/ai_training/backend/tests/test_privacy_reader.py
@@ -0,0 +1,74 @@
+import json
+import base64
+from dataclasses import replace
+from pathlib import Path
+
+from unittest import TestCase
+from unittest.mock import MagicMock
+
+from products.ai_training.backend.privacy.reader import (
+ TrainingDataKey,
+ TrainingDataKeyReader,
+ TrainingKeyIdentity,
+ TrainingKeyLocation,
+)
+
+
+class TestTrainingDataKeyReader(TestCase):
+ def test_shared_node_envelope_and_owner_binding(self) -> None:
+ path = Path(__file__).parent / "fixtures/encryption_vector.json"
+ vector = json.loads(path.read_text())
+ identity = TrainingKeyIdentity(
+ team_id=vector["context"]["teamId"],
+ organization_id=vector["context"]["organizationId"],
+ session_id=vector["context"]["sessionId"],
+ )
+ key = TrainingDataKey(identity=identity, plaintext=base64.b64decode(vector["key"]))
+ envelope = json.dumps(vector["envelope"]).encode()
+ self.assertEqual(key.decrypt(envelope, "rrweb"), base64.b64decode(vector["data"]))
+ for wrong_key in [
+ replace(key, identity=replace(identity, team_id=8)),
+ replace(key, identity=replace(identity, organization_id="another-organization")),
+ ]:
+ with self.assertRaises(ValueError):
+ wrong_key.decrypt(envelope, "rrweb")
+ with self.assertRaises(ValueError):
+ key.decrypt(envelope, "score")
+ with self.assertRaises(TimeoutError):
+ replace(key, decrypt_until=0).decrypt(envelope, "rrweb")
+
+ def test_deleted_keys_cannot_be_restored_from_cache(self) -> None:
+ location = TrainingKeyLocation.session(7, "01994569-4380-7000-8000-000000000007")
+ rows = {
+ location: {
+ **location.encoded(),
+ "team_id": {"N": "7"},
+ "organization_id": {"S": "test"},
+ "wrapped_key": {"B": b"wrapped"},
+ },
+ }
+ dynamo = MagicMock()
+ dynamo.batch_get_item.side_effect = lambda **kwargs: {
+ "Responses": {
+ "table": [
+ rows[loc]
+ for item in kwargs["RequestItems"]["table"]["Keys"]
+ if (loc := TrainingKeyLocation(pk=item["pk"]["S"], sk=item["sk"]["S"])) in rows
+ ]
+ }
+ }
+ kms = MagicMock()
+ kms.decrypt.return_value = {"Plaintext": bytes([7]) * 32}
+ reader = TrainingDataKeyReader(dynamo, kms, "table", "kms-key")
+ self.assertIn(location, reader.read([location]))
+ self.assertIn(location, reader.read([location]))
+ self.assertEqual(kms.decrypt.call_count, 1)
+ month = TrainingKeyLocation(pk="month:2025-09", sk="deleted")
+ rows[month] = {**month.encoded(), "deleted": {"BOOL": True}}
+ self.assertEqual(reader.read([location]), {})
+ del rows[month]
+ self.assertIn(location, reader.read([location]))
+ rows[location].pop("wrapped_key")
+ rows[location]["deleted"] = {"BOOL": True}
+ self.assertEqual(reader.read([location]), {})
+ self.assertEqual(kms.decrypt.call_count, 1)
diff --git a/products/ai_training/backend/tests/test_privacy_store.py b/products/ai_training/backend/tests/test_privacy_store.py
new file mode 100644
index 000000000000..fe6e895c8222
--- /dev/null
+++ b/products/ai_training/backend/tests/test_privacy_store.py
@@ -0,0 +1,88 @@
+import time
+from datetime import timedelta
+
+from unittest.mock import MagicMock, patch
+
+from django.test import SimpleTestCase
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from products.ai_training.backend.privacy.store import AITrainingPrivacyStore, DynamoResponse, item_key, session_key
+from products.ai_training.backend.tasks.tasks import process_ai_training_privacy_requests
+
+
+class TestAITrainingPrivacyStore(SimpleTestCase):
+ @parameterized.expand([("disabled", "", False), ("enabled", "test-table", True)])
+ def test_privacy_task_uses_dedicated_queue_and_only_drains_when_enabled(
+ self, _name: str, table: str, enabled: bool
+ ) -> None:
+ with (
+ self.settings(AI_RESEARCH_REPLAY_PRIVACY_TABLE=table),
+ patch("products.ai_training.backend.tasks.tasks.AITrainingPrivacyStore.from_settings") as store,
+ ):
+ signature = process_ai_training_privacy_requests.signature()
+ self.assertEqual(signature.type.queue, "ai_research_privacy")
+ self.assertEqual(
+ signature.type.name, "posthog.tasks.ai_training_privacy.process_ai_training_privacy_requests"
+ )
+ signature.apply().get()
+ self.assertEqual(store.called, enabled)
+ self.assertEqual(store.return_value.drain.called, enabled)
+
+ def test_month_deletion_blocks_before_querying_and_shreds_all_index_pages(self) -> None:
+ client = MagicMock()
+ cursor = item_key("month:2026-09:shard:0", "key:cursor")
+ targets = [session_key(7, "01a09f92-e780-7000-8000-000000000001"), item_key("team:7", "image:1:2026-09")]
+ pages: list[DynamoResponse] = []
+ for index, target in enumerate(targets):
+ page: DynamoResponse = {"Items": [{"key_pk": target["pk"], "key_sk": target["sk"]}]}
+ if index == 0:
+ page["LastEvaluatedKey"] = cursor
+ pages.append(page)
+ pages.extend({"Items": []} for _ in range(31))
+
+ def query(**kwargs: object) -> DynamoResponse:
+ self.assertEqual(client.put_item.call_args.kwargs["Item"]["pk"]["S"], "month:2026-09")
+ self.assertTrue(kwargs["ConsistentRead"])
+ return pages.pop(0)
+
+ client.query.side_effect = query
+ store = AITrainingPrivacyStore(client, "table")
+ self.assertEqual(store.delete_month("2026-09"), 2)
+ self.assertEqual(
+ [call.kwargs["TransactItems"][0]["Update"]["Key"] for call in client.transact_write_items.call_args_list],
+ targets,
+ )
+ self.assertEqual(client.query.call_args_list[1].kwargs["ExclusiveStartKey"], cursor)
+ self.assertEqual(client.query.call_count, 33)
+ with self.assertRaises(ValueError):
+ store.delete_month("2026-13")
+
+ def test_session_deletion_shreds_keys_without_querying_user_indexes(self) -> None:
+ client = MagicMock()
+ sessions = ["01a09f92-e780-7000-8000-000000000001", "01a09f92-e780-7000-8000-000000000002"]
+ store = AITrainingPrivacyStore(client, "table")
+ self.assertEqual(store.initialize(MagicMock(kind="session", team_id=7, identifiers=sessions)), [])
+ updates = client.transact_write_items.call_args.kwargs["TransactItems"]
+ self.assertEqual([update["Update"]["Key"] for update in updates], [session_key(7, value) for value in sessions])
+ self.assertTrue(
+ all(
+ update["Update"]["UpdateExpression"] == "SET deleted = :deleted REMOVE wrapped_key"
+ for update in updates
+ )
+ )
+ client.query.assert_not_called()
+
+ def test_completion_waits_for_reader_leases_without_sleeping_in_the_worker(self) -> None:
+ request = MagicMock(kind="team", cursor={"work": []}, completed_at=None)
+ store = AITrainingPrivacyStore(MagicMock(), "table")
+ now = timezone.now()
+ with patch("products.ai_training.backend.privacy.store.timezone.now", return_value=now):
+ self.assertFalse(store.apply(request, time.monotonic() + 1))
+ self.assertIsNone(request.completed_at)
+ with patch(
+ "products.ai_training.backend.privacy.store.timezone.now", return_value=now + timedelta(seconds=301)
+ ):
+ self.assertTrue(store.apply(request, time.monotonic() + 1))
+ self.assertEqual(request.identifiers, [])
diff --git a/products/ai_training/docs/replay-data.md b/products/ai_training/docs/replay-data.md
new file mode 100644
index 000000000000..65b81d293d3d
--- /dev/null
+++ b/products/ai_training/docs/replay-data.md
@@ -0,0 +1,188 @@
+# ML replay data
+
+The Django controls and their tests live in `products/ai_training/backend/`, owned by AI Research.
+Application lifecycle hooks use the product facade; the models share the main database to preserve atomic transactions.
+
+AI Research owns the ML mirror, its encryption keys, and its training readers.
+The mirror collects scrubbed recordings from organizations that consent to AI training.
+Its storage and deletion implementation is separate from production session replay.
+
+## Session versions
+
+The cutoff is **Monday, 2026-09-14 at 11:00 UTC**, which is noon in Europe/London.
+The session UUIDv7 timestamp selects the version:
+
+- Before the cutoff: v1 uses HMAC team and session IDs.
+- At or after the cutoff: v2 uses raw team and session IDs and encrypted payloads.
+- An invalid UUIDv7 timestamp selects v1.
+
+Event timestamps, arrival times, retries, and flushes do not change the version.
+Both versions can occur in one ingestion batch.
+Their replay blocks, images, and metadata use separate storage paths.
+The version applies to the whole session, including a session that crosses the cutoff.
+
+## Consent
+
+Ingestion uses the organization's existing `is_ai_training_opted_in` flag for both versions.
+The team lookup caches this flag for up to five minutes.
+Withdrawing consent stops collection after that refresh and preserves previously collected data and keys.
+Re-enabling consent resumes existing sessions as well as new sessions, using their existing keys.
+Messages already admitted to the mirror can finish processing.
+Session start time selects the dataset version and monthly partition only.
+There is no separate consent model, DynamoDB consent entry, consent timestamp, or initialization command.
+
+## Keys and batch processing
+
+The independent DynamoDB table stores session keys, team image keys, deletion markers, and monthly key indexes.
+ML outputs omit distinct IDs, including their hashes and pseudonyms.
+The metadata consumer projects supported fields before storage, including for messages already in Kafka.
+A session has one data key.
+New sessions share one image key per team and session start month.
+KMS wraps each data key with an encryption context that binds its owner and purpose.
+Payload encryption uses XSalsa20-Poly1305.
+The authenticated payload also binds the dataset kind and, for images, the object or reference being encrypted.
+
+Ingestion processes privacy state in batches:
+
+1. Bulk-read session keys, team blocks, month blocks, and image keys.
+2. Resolve keys in memory while processing the batch.
+3. Commit bounded DynamoDB transactions before publishing replay blocks or image messages.
+4. On a competing write, bulk-read the winning state and retry with its keys.
+
+Conditional writes prevent a deletion from being undone by an in-flight batch.
+Kafka offsets advance only after the required writes and publication succeed.
+DynamoDB transactions have at most 100 actions and stay below the request size limit.
+Reads use strongly consistent `BatchGetItem` requests with bounded retries for unprocessed keys.
+
+KMS plaintext caches reduce repeated decrypt calls.
+A cache hit does not bypass live key and deletion checks.
+Ingestion also checks current consent.
+Each process limits KMS concurrency and request rate; deployment capacity must account for the sum across replicas.
+Readers check live state before each batch and permit key use for at most five minutes from the start of that read.
+An expired read must obtain permission again.
+
+The privacy table has no TTL or point-in-time recovery.
+Its resource policy denies backups, exports, and enabling continuous backups or Kinesis copies.
+Do not copy wrapped keys into object storage, logs, workflow payloads, or another persistent cache.
+Restoring a deleted wrapped key would defeat deletion.
+
+## Deletion
+
+Existing recording, person, team, and organization deletion flows enqueue ML privacy work.
+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 privacy outbox.
+A lookup failure stops the request before profile deletion so it can retry.
+Team deletion and its privacy outbox request commit in the same database transaction.
+If the outbox write fails, team deletion fails and can retry.
+Consent changes do not enqueue privacy requests.
+The outbox survives removal of the source team or organization.
+Its team IDs refer to the original environment, without resolving a child environment to its parent.
+
+| Scope | Effect |
+| ------- | ----------------------------------------------------------------------------------- |
+| Session | Remove its wrapped key and permanently block that session ID. |
+| Person | Resolve its session IDs through replay, then apply session deletion to each result. |
+| Team | Permanently block the team and remove its session and image keys. |
+
+The person lookup matches any available replay row for the requested IDs, 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.
+Team lookups use 32 session shards with strongly consistent DynamoDB queries.
+Deleting a resolved session removes all of its events, including events from other identities.
+
+Deletion uses resumable query pages and stores progress in the outbox.
+A failed request backs off without blocking unrelated requests.
+Completion follows key removal and the five-minute reader lifetime.
+Scrubbed images remain available after session or person deletion, but become unreadable after team or month deletion.
+
+This mechanism covers encrypted v2 objects.
+It does not erase legacy plaintext objects, previously downloaded data, derived training artifacts, or a trained model.
+Legacy dataset retirement needs a separate storage operation before claiming deletion across the entire bucket.
+
+## Monthly key deletion
+
+Key creation writes a month index entry in the same DynamoDB transaction as the wrapped key.
+The index uses 32 partitions named `month:<YYYY-MM>:shard:<0..31>` and stores key locations, without copying wrapped keys.
+Session keys and image keys appear in this index.
+
+Run `python manage.py delete_ai_training_month YYYY-MM` to permanently block that UTC session month and remove its keys.
+The command uses strongly consistent queries and bounded writes.
+Rerun the command after an interrupted run; it preserves the month block and safely repeats completed pages.
+Readers reject blocked months even when a wrapped key remains during deletion.
+Existing read leases expire within five minutes.
+The matching monthly S3 folders can then be removed from each dataset.
+Deleting a month does not affect another month's image keys.
+
+## Data layout and readers
+
+| Dataset | Default path | Encryption key |
+| -------------------- | ------------------------------------------------ | --------------------------------------- |
+| Replay blocks | `rrweb_2/` | Session |
+| Metadata catalog | `block-metadata/v2/dt=<arrival-date>/` | Each row's payload uses its session key |
+| Inline image shards | `scrubbed-images/v2/<YYYY-MM>/<team>/shards/` | Team and session month |
+| Inline image indexes | `scrubbed-images/v2/<YYYY-MM>/<team>/index/` | Team and session month |
+| URL images | `scrubbed-images/v2/<YYYY-MM>/<team>/url/<hash>` | Team and session month |
+
+Metadata catalogs expose raw `team_id`, `session_id`, `format_version`, and an encrypted `payload`.
+URLs, block locations, and replay indexes are inside that payload.
+Neither the catalog nor its encrypted payload includes a distinct-ID field.
+V2 does not write a separate plaintext replay index.
+
+Athena can select catalog rows but cannot decrypt replay fields.
+Training readers must bulk-read live keys and deletion markers before decrypting.
+Cross-account readers use the full DynamoDB table ARN and the prod-us KMS key ARN.
+Both accounts must authorize the reader role.
+Readers have key-read and decrypt permissions; they cannot create keys or change deletion state.
+
+Use metadata block locations and byte ranges to fetch recordings, then decrypt before decompressing.
+Include all relevant metadata arrival dates when collecting a session with late blocks.
+
+Join analytics on both raw team and session IDs.
+Remove identifiers from model inputs.
+Resolve image references before training because they contain team IDs.
+
+## Images and Kafka
+
+V2 references are `image:v2:<team>:<YYYY-MM>:<hash>` and `imageurl:v2:<team>:<YYYY-MM>:<hash>`.
+Images do not deduplicate across teams or session start months.
+Source messages use session keys; stored scrubbed images use team image keys.
+Source deduplication includes the session, so deleting one source session cannot suppress another session's copy.
+The v2 image-fetch frontier uses a separate, initially empty DynamoDB history table.
+It does not inherit v1 seen flags or successful fetch results.
+
+ML Kafka producers write `ai_research_ingestion_version: 1` or `2`.
+Retries and dead-letter replay preserve this header and the encrypted bytes.
+Headerless queued messages mean v1.
+Unknown versions and conflicting v2 ownership are rejected; a failed v2 decode never falls back to v1.
+
+Legacy image references and paths remain available for v1 sessions.
+Their HMAC key must remain stable while that data is in use.
+
+## Configuration
+
+New privacy settings use `AI_RESEARCH_REPLAY_*`:
+
+- `PRIVACY_TABLE`, `KMS_KEY_ARN`, and `AWS_REGION` select the key store and wrapping key.
+- `KEY_CACHE_MAX`, `KEY_CACHE_LIFETIME_MS`, and `KMS_REQUESTS_PER_SECOND` bound ingestion key caching and KMS traffic.
+- `IMAGE_FETCH_V2_DYNAMODB_TABLE` selects the fresh v2 frontier.
+- `S3_PREFIX` selects v2 replay storage and defaults to `rrweb_2`.
+
+Established HMAC settings retain their transition aliases.
+When both aliases are set, the `AI_RESEARCH_REPLAY_*` value takes precedence, including an explicit empty value.
+The wrapped HMAC secret keeps the single name `SESSION_RECORDING_ML_PSEUDONYM_WRAPPED_KEY` in both the environment and secret store.
+It has no new alias.
+Renaming configuration must not rotate that key.
+
+### Privacy worker isolation
+
+The privacy task uses the `ai_research_privacy` Celery queue.
+In prod-us, only the dedicated `ai-research-privacy-worker` deployment consumes this queue.
+Its service account has a dedicated IAM role and cloud-database user.
+The database user needs SELECT and UPDATE only on `posthog_aitrainingdeletionrequest`.
+The worker starts with `bin/docker-worker-ai-training-privacy` and does not use shared Django signing secrets.
+Its process-local signing key is not used for application requests.
+The worker skips general migration checks; the outbox table must exist before deployment.
+All processes that enqueue privacy work, including the general-purpose Temporal worker, need the privacy table setting.
+Shared Django and Temporal workers cannot delete keys from the privacy table.
diff --git a/products/ai_training/manifest.tsx b/products/ai_training/manifest.tsx
new file mode 100644
index 000000000000..976f8bcb28ea
--- /dev/null
+++ b/products/ai_training/manifest.tsx
@@ -0,0 +1,12 @@
+import { ProductManifest } from '../../frontend/src/types'
+
+export const manifest: ProductManifest = {
+ name: 'AiTraining',
+ scenes: {},
+ routes: {},
+ redirects: {},
+ urls: {},
+ fileSystemTypes: {},
+ treeItemsNew: [],
+ treeItemsProducts: [],
+}
diff --git a/products/ai_training/package.json b/products/ai_training/package.json
new file mode 100644
index 000000000000..0b59fe6700b5
--- /dev/null
+++ b/products/ai_training/package.json
@@ -0,0 +1,7 @@
+{
+ "name": "@posthog/products-ai-training",
+ "scripts": {
+ "backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/tests -v --tb=short",
+ "backend:contract-check": "echo 'Contract files unchanged'"
+ }
+}
diff --git a/products/ai_training/product.yaml b/products/ai_training/product.yaml
new file mode 100644
index 000000000000..765cbc5f8d7f
--- /dev/null
+++ b/products/ai_training/product.yaml
@@ -0,0 +1,3 @@
+name: AI training
+owners:
+ - ai-research
diff --git a/products/ai_training/tsconfig.json b/products/ai_training/tsconfig.json
new file mode 100644
index 000000000000..fe425d6fcba8
--- /dev/null
+++ b/products/ai_training/tsconfig.json
@@ -0,0 +1,6 @@
+{
+ "extends": "../../tsconfig.json",
+ "compilerOptions": {
+ "composite": true
+ }
+}
diff --git a/products/ai_training/turbo.json b/products/ai_training/turbo.json
new file mode 100644
index 000000000000..2cb8f5ab8b94
--- /dev/null
+++ b/products/ai_training/turbo.json
@@ -0,0 +1,16 @@
+{
+ "extends": ["//"],
+ "tasks": {
+ "backend:contract-check": {
+ "inputs": [
+ "backend/facade/**",
+ "backend/presentation/**",
+ "backend/tasks/**",
+ "backend/models.py",
+ "backend/migrations/**"
+ ],
+ "outputs": [],
+ "cache": true
+ }
+ }
+}
diff --git a/pyproject.toml b/pyproject.toml
index 2f72dab3b0ca..7f8a9f3517b2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -26,6 +26,7 @@ dependencies = [
"clickhouse-pool==0.5.3",
"circular-dict==1.9",
"cryptography==46.0.7",
+ "PyNaCl==1.5.0",
"dagster==1.10.18",
"dagster-cloud==1.10.18",
"dagster-aws==0.26.18",
diff --git a/tach.toml b/tach.toml
index c6d31badaa49..6617eb6ae37a 100644
--- a/tach.toml
+++ b/tach.toml
@@ -79,6 +79,7 @@ layer = "modules"
[[modules]]
path = "posthog"
depends_on = [
+ "products.ai_training",
"products.autoresearch",
"products.cohorts",
"ee",
@@ -1511,3 +1512,17 @@ expose = [
from = [
"products.data_quality",
]
+
+[[modules]]
+path = "products.ai_training"
+depends_on = ["posthog"]
+layer = "modules"
+
+[[interfaces]]
+expose = [
+ "backend\\.facade.*",
+ "backend\\.presentation\\.views.*",
+]
+from = [
+ "products.ai_training",
+]
diff --git a/uv.lock b/uv.lock
index e269570e94d2..9eb71f21e4b3 100644
--- a/uv.lock
+++ b/uv.lock
@@ -5667,6 +5667,7 @@ dependencies = [
{ name = "pymongo" },
{ name = "pymssql" },
{ name = "pymysql" },
+ { name = "pynacl" },
{ name = "pyod" },
{ name = "pypdf" },
{ name = "pyroscope-io" },
@@ -5948,6 +5949,7 @@ requires-dist = [
{ name = "pymongo", specifier = "==4.13.2" },
{ name = "pymssql", specifier = "==2.3.5" },
{ name = "pymysql", specifier = "==1.1.1" },
+ { name = "pynacl", specifier = "==1.5.0" },
{ name = "pyod", specifier = "==2.0.7" },
{ name = "pypdf", specifier = "==6.10.2" },
{ name = "pyroscope-io", specifier = "~=0.8.8" },