: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(admin): show AI training opt-in history on the organization page (#80611)
Robbie5468427af1a5
diff --git a/posthog/admin/admins/organization_admin.py b/posthog/admin/admins/organization_admin.pyindex b9e0b48b7c7d..22cc55db18ec 100644--- a/posthog/admin/admins/organization_admin.py+++ b/posthog/admin/admins/organization_admin.py@@ -12,6 +12,7 @@ from django.utils import timezonefrom django.utils.html import format_htmlfrom django.utils.safestring import mark_safe+from posthog.admin.ai_training_opt_in_history import get_ai_training_opt_in_historyfrom posthog.admin.authorization import can_trigger_admin_deletionfrom posthog.admin.inline_registry import extra_inlines_forfrom posthog.admin.inlines.organization_domain_inline import OrganizationDomainInline@@ -149,6 +150,7 @@ class OrganizationAdmin(admin.ModelAdmin):"is_ai_training_opted_in","is_ai_training_locked","is_ai_training_cta_shown",+ "ai_training_opt_in_history_display","trigger_deletion_display",]inlines = [@@ -169,6 +171,7 @@ class OrganizationAdmin(admin.ModelAdmin):"customer_trust_scores","bulk_delete_data_display","sync_to_billing_display",+ "ai_training_opt_in_history_display","trigger_deletion_display",]search_fields = ("name", "members__email", "team__api_token")@@ -311,6 +314,17 @@ class OrganizationAdmin(admin.ModelAdmin):url = reverse("admin:organization_model_counts", args=[organization.pk])return format_html('<a class="button" href="{}">View counts</a>', url)+ @admin.display(description="AI training opt-in history")+ def ai_training_opt_in_history_display(self, organization: Organization):+ # UUIDT sets the id before the save, so the add form's unsaved instance also has a pk.+ if organization._state.adding:+ return "-"+ # render_to_string returns a SafeString, so this method does not need mark_safe.+ return render_to_string(+ "admin/organization/ai_training_opt_in_history.html",+ {"history": get_ai_training_opt_in_history(organization)},+ )+@admin.display(description="Sync to billing")def sync_to_billing_display(self, organization: Organization):if not organization.pk:diff --git a/posthog/admin/ai_training_opt_in_history.py b/posthog/admin/ai_training_opt_in_history.pynew file mode 100644index 000000000000..9cf8c58d1d93--- /dev/null+++ b/posthog/admin/ai_training_opt_in_history.py@@ -0,0 +1,199 @@+"""Reconstructs an organization's AI training opt-in history for the Django admin.++This module reads two sources: the organization's current value, and the `ActivityLog` rows that+changed `is_ai_training_opted_in`. It reports only what those sources recorded. It does not repeat+the rules that set the starting value. Those rules cover region, license, and HIPAA.+"""++from dataclasses import dataclass+from datetime import UTC, datetime+from typing import Optional++from django.db import transaction+from django.db.models import Q++from posthog.exceptions_capture import capture_exception+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.organization import Organization++# This value matches `detail.changes[].field`. That key holds the display name from+# `field_name_overrides`. It equals the model field name because Organization sets no override for+# this field. An override would empty this panel. `test_manual_opt_in_then_opt_out...` catches that.+AI_TRAINING_OPT_IN_FIELD = "is_ai_training_opted_in"++# Each organization save writes one ActivityLog row. That row holds every field the save changed, so+# it holds at most one opt-in change. 50 rows mean 50 toggles. The panel reports any row above 50.+MAX_ENTRIES_SHOWN = 50+++@dataclass(frozen=True)+class OptInChange:+ changed_at: datetime+ before: Optional[bool]+ after: Optional[bool]+ actor: str+ origin: str+ client: Optional[str]+ ip_address: Optional[str]++ @property+ def changed_at_display(self) -> str:+ return _timestamp(self.changed_at)++ @property+ def transition_display(self) -> str:+ return f"{_describe_value(self.before)} → {_describe_value(self.after)}"+++@dataclass(frozen=True)+class OptInHistory:+ headline: str+ changes: list[OptInChange]+ warning: Optional[str] = None+ truncated: bool = False+ error: Optional[str] = None+++def _describe_value(value: Optional[bool]) -> str:+ if value is None:+ return "not set"+ return "opted in" if value else "opted out"+++def _was_system(entry: ActivityLog) -> bool:+ # log_activity sets is_system from `user is None` and never updates it. Deleting a user sets the+ # user column to null. A null user therefore means automation or a deleted person.+ if entry.is_system is None:+ return entry.user_id is None+ return entry.is_system+++def _describe_actor(entry: ActivityLog) -> str:+ if entry.user is not None:+ if entry.was_impersonated:+ return f"{entry.user.email} (acting-as, PostHog staff member not recorded)"+ return entry.user.email+ return "system" if _was_system(entry) else "user since deleted"+++def _describe_origin(entry: ActivityLog) -> str:+ if _was_system(entry):+ return "automatic"+ return "manual (staff impersonation)" if entry.was_impersonated else "manual"+++def _opt_in_change_in(entry: ActivityLog) -> Optional[dict]:+ for change in (entry.detail or {}).get("changes") or []:+ if isinstance(change, dict) and change.get("field") == AI_TRAINING_OPT_IN_FIELD:+ return change+ # This return is defensive. _opt_in_activity only admits rows that hold an opt-in change, so this line does not run.+ return None+++def _to_change(entry: ActivityLog, change: dict) -> OptInChange:+ return OptInChange(+ changed_at=entry.created_at,+ before=change.get("before"),+ after=change.get("after"),+ actor=_describe_actor(entry),+ origin=_describe_origin(entry),+ client=entry.client,+ ip_address=entry.ip_address,+ )+++def _opt_in_activity(organization: Organization):+ return ActivityLog.objects.filter(+ organization_id=organization.id,+ scope="Organization",+ item_id=str(organization.id),+ # This filter uses whole-column containment, not `detail__changes__contains`. Both match the+ # same rows, because jsonb containment is recursive. Only this form uses the GIN index on+ # detail. A filter on `detail -> 'changes'` scans the organization's whole activity history.+ detail__contains={"changes": [{"field": AI_TRAINING_OPT_IN_FIELD}]},+ )+++def _was_opted_in(organization: Organization, changes: list[OptInChange], truncated: bool) -> bool:+ if any(c.after is True or c.before is True for c in changes):+ return True+ # A window that holds every row is the whole history, so the scan above already answered this.+ # Only a truncated window can hide an older opt-in, so only it needs the uncapped query.+ return truncated and _has_recorded_opt_in(organization)+++def _has_recorded_opt_in(organization: Organization) -> bool:+ return (+ _opt_in_activity(organization)+ .filter(+ Q(detail__contains={"changes": [{"field": AI_TRAINING_OPT_IN_FIELD, "after": True}]})+ | Q(detail__contains={"changes": [{"field": AI_TRAINING_OPT_IN_FIELD, "before": True}]})+ )+ .exists()+ )+++def _fetch_changes(organization: Organization) -> tuple[list[OptInChange], bool]:+ # This query sorts newest first, so an organization above the cap keeps its most recent changes.+ # Support asks about those. The loop below reverses them, so the panel reads oldest to newest.+ entries = list(+ _opt_in_activity(organization).select_related("user").order_by("-created_at", "-id")[: MAX_ENTRIES_SHOWN + 1]+ )++ truncated = len(entries) > MAX_ENTRIES_SHOWN+ changes = []+ for entry in reversed(entries[:MAX_ENTRIES_SHOWN]):+ change = _opt_in_change_in(entry)+ if change is not None:+ changes.append(_to_change(entry, change))+ return changes, truncated+++def _timestamp(value: datetime) -> str:+ return value.astimezone(UTC).strftime("%Y-%m-%d %H:%M UTC")+++def _build_headline(current: Optional[bool], was_opted_in: bool) -> str:+ if current is True:+ return "Currently opted in"++ # This says "No recorded opt-in", not "Never opted in". Two paths leave no row to find: an+ # opt-out written outside the ORM, and an activity-log write that failed.+ headline = "Currently opted out, was opted in previously" if was_opted_in else "No recorded opt-in"+ # The column accepts null, and every other surface reads null as opted out. Name the null value+ # here, so support does not assume that a person set the column to false.+ return f"{headline} (value is null)" if current is None else headline+++def _hipaa_conflict_warning(organization: Organization) -> Optional[str]:+ # The replay ML mirror reads is_ai_training_opted_in alone. That gate is in+ # nodejs/src/ingestion/pipelines/sessionreplay/ai-training-optin-filter-step.ts. No code in that+ # pipeline reads is_hipaa. Change this warning if that gate starts to read is_hipaa.+ if not organization.is_hipaa or organization.is_ai_training_opted_in is not True:+ return None+ return (+ "HIPAA is set, but the AI training opt-in is on. The training pipeline reads the opt-in and "+ "does not check HIPAA, so this organization's session recordings are eligible for training. "+ "Their settings page shows them as opted out, and the API blocks them from changing it "+ "themselves. Turn the opt-in off here if that is wrong."+ )+++def get_ai_training_opt_in_history(organization: Organization) -> OptInHistory:+ try:+ # This savepoint rolls a failed query back cleanly. The admin runs each change-form POST in+ # a transaction. Without the savepoint, a caught error leaves that transaction aborted, and+ # the next query turns a form validation error into a 500.+ with transaction.atomic():+ changes, truncated = _fetch_changes(organization)+ was_opted_in = _was_opted_in(organization, changes, truncated)+ except Exception as e:+ capture_exception(e)+ return OptInHistory(headline="Could not load opt-in history", changes=[], error=str(e))++ return OptInHistory(+ headline=_build_headline(organization.is_ai_training_opted_in, was_opted_in),+ changes=changes,+ warning=_hipaa_conflict_warning(organization),+ truncated=truncated,+ )diff --git a/posthog/admin/test_ai_training_opt_in_history.py b/posthog/admin/test_ai_training_opt_in_history.pynew file mode 100644index 000000000000..ce5bb6e68816--- /dev/null+++ b/posthog/admin/test_ai_training_opt_in_history.py@@ -0,0 +1,208 @@+from posthog.test.base import APIBaseTest++from django.contrib.admin.sites import AdminSite++from parameterized import parameterized++from posthog.admin.admins.organization_admin import OrganizationAdmin+from posthog.admin.ai_training_opt_in_history import MAX_ENTRIES_SHOWN, get_ai_training_opt_in_history+from posthog.models.activity_logging.activity_log import ActivityLog+from posthog.models.organization import Organization, OrganizationMembership+from posthog.models.user import User+++class TestAITrainingOptInHistory(APIBaseTest):+ def setUp(self) -> None:+ super().setUp()+ self.organization_membership.level = OrganizationMembership.Level.ADMIN+ self.organization_membership.save()++ def _set_opt_in_without_logging(self, value: bool | None) -> None:+ # This mirrors how an organization gets its starting value. The creation default and the+ # column's migration default both write to Postgres without an activity log row.+ Organization.objects.filter(pk=self.organization.pk).update(is_ai_training_opted_in=value)+ self.organization.refresh_from_db()++ def _log_opt_in_change(+ self, *, user: User | None, before: bool | None, after: bool | None, is_system: bool+ ) -> ActivityLog:+ return ActivityLog.objects.create(+ organization_id=self.organization.id,+ item_id=str(self.organization.id),+ scope="Organization",+ activity="updated",+ user=user,+ is_system=is_system,+ was_impersonated=False,+ detail={+ "name": self.organization.name,+ "changes": [+ {+ "type": "Organization",+ "action": "changed",+ "field": "is_ai_training_opted_in",+ "before": before,+ "after": after,+ }+ ],+ },+ )++ def _patch_organization(self, updates: dict) -> None:+ response = self.client.patch(f"/api/organizations/{self.organization.id}/", updates, format="json")+ self.assertEqual(response.status_code, 200, response.json())+ self.organization.refresh_from_db()++ @parameterized.expand(+ [+ (False, "No recorded opt-in"),+ (None, "No recorded opt-in (value is null)"),+ (True, "Currently opted in"),+ ]+ )+ def test_headline_without_any_recorded_change(self, current: bool | None, expected_headline: str) -> None:+ self._set_opt_in_without_logging(current)++ history = get_ai_training_opt_in_history(self.organization)++ self.assertEqual(history.headline, expected_headline)+ self.assertEqual(history.changes, [])++ def test_manual_opt_in_then_opt_out_is_attributed_to_the_user_who_made_it(self) -> None:+ self._set_opt_in_without_logging(False)++ self._patch_organization({"is_ai_training_opted_in": True})+ self._patch_organization({"is_ai_training_opted_in": False})++ history = get_ai_training_opt_in_history(self.organization)++ self.assertEqual(history.headline, "Currently opted out, was opted in previously")+ self.assertEqual(+ [(c.before, c.after, c.origin, c.actor) for c in history.changes],+ [+ (False, True, "manual", self.user.email),+ (True, False, "manual", self.user.email),+ ],+ )++ def test_change_without_a_user_is_labelled_automatic(self) -> None:+ self._set_opt_in_without_logging(True)++ self.organization.is_ai_training_opted_in = False+ self.organization.save()++ history = get_ai_training_opt_in_history(self.organization)++ self.assertEqual(len(history.changes), 1)+ self.assertEqual(history.changes[0].origin, "automatic")+ self.assertEqual(history.changes[0].actor, "system")++ def test_reads_the_opt_in_change_out_of_a_multi_field_update(self) -> None:+ self._set_opt_in_without_logging(False)++ self._patch_organization({"name": "Renamed org", "is_ai_training_opted_in": True})++ history = get_ai_training_opt_in_history(self.organization)++ self.assertEqual(len(history.changes), 1)+ self.assertEqual((history.changes[0].before, history.changes[0].after), (False, True))++ @parameterized.expand(+ [+ (True, True, True),+ (True, False, False),+ (False, True, False),+ (True, None, False),+ ]+ )+ def test_warns_only_when_a_hipaa_organization_is_opted_in(+ self, is_hipaa: bool, opted_in: bool | None, expect_warning: bool+ ) -> None:+ self.organization.is_hipaa = is_hipaa+ self.organization.save()+ self._set_opt_in_without_logging(opted_in)++ history = get_ai_training_opt_in_history(self.organization)++ self.assertEqual(history.warning is not None, expect_warning)++ def test_change_by_a_since_deleted_user_is_not_reported_as_automatic(self) -> None:+ self._set_opt_in_without_logging(False)+ departed = User.objects.create_and_join(self.organization, "[email protected]", None)+ self._log_opt_in_change(user=departed, before=True, after=False, is_system=False)+ departed.delete()++ history = get_ai_training_opt_in_history(self.organization)++ self.assertEqual(len(history.changes), 1)+ self.assertEqual(history.changes[0].origin, "manual")+ self.assertEqual(history.changes[0].actor, "user since deleted")++ def test_opt_in_older_than_the_cap_still_counts_towards_the_headline(self) -> None:+ self._set_opt_in_without_logging(False)+ self._log_opt_in_change(user=None, before=False, after=True, is_system=True)+ # The column accepts null, so the newest changes can alternate without ever holding True.+ # These changes push the only opt-in out of the displayed window.+ for index in range(MAX_ENTRIES_SHOWN + 1):+ before, after = (None, False) if index % 2 == 0 else (False, None)+ self._log_opt_in_change(user=None, before=before, after=after, is_system=True)++ history = get_ai_training_opt_in_history(self.organization)++ self.assertTrue(history.truncated)+ self.assertNotIn(True, [c.after for c in history.changes] + [c.before for c in history.changes])+ self.assertEqual(history.headline, "Currently opted out, was opted in previously")++ def test_history_over_the_cap_is_flagged_as_truncated(self) -> None:+ self._set_opt_in_without_logging(False)+ for index in range(MAX_ENTRIES_SHOWN + 1):+ self._log_opt_in_change(user=None, before=index % 2 == 1, after=index % 2 == 0, is_system=True)++ history = get_ai_training_opt_in_history(self.organization)++ self.assertTrue(history.truncated)+ self.assertEqual(len(history.changes), MAX_ENTRIES_SHOWN)++ def test_impersonated_change_names_the_customer_and_says_the_staff_member_is_unrecorded(self) -> None:+ self._set_opt_in_without_logging(False)+ entry = self._log_opt_in_change(user=self.user, before=True, after=False, is_system=False)+ ActivityLog.objects.filter(pk=entry.pk).update(was_impersonated=True)++ history = get_ai_training_opt_in_history(self.organization)++ self.assertEqual(history.changes[0].origin, "manual (staff impersonation)")+ self.assertIn(self.user.email, history.changes[0].actor)+ self.assertIn("not recorded", history.changes[0].actor)++ def test_row_predating_the_is_system_column_falls_back_to_the_user_column(self) -> None:+ self._set_opt_in_without_logging(False)+ entry = self._log_opt_in_change(user=None, before=True, after=False, is_system=False)+ ActivityLog.objects.filter(pk=entry.pk).update(is_system=None)++ history = get_ai_training_opt_in_history(self.organization)++ self.assertEqual(history.changes[0].origin, "automatic")+ self.assertEqual(history.changes[0].actor, "system")++ def test_admin_panel_renders_the_headline_and_the_change_rows(self) -> None:+ self._set_opt_in_without_logging(False)+ self._patch_organization({"is_ai_training_opted_in": True})++ html = OrganizationAdmin(Organization, AdminSite()).ai_training_opt_in_history_display(self.organization)++ self.assertIn("Currently opted in", html)+ self.assertIn("opted out → opted in", html)+ self.assertIn(self.user.email, html)++ def test_admin_panel_is_blank_on_the_add_form(self) -> None:+ html = OrganizationAdmin(Organization, AdminSite()).ai_training_opt_in_history_display(Organization())++ self.assertEqual(html, "-")++ def test_changes_to_other_organization_fields_are_excluded(self) -> None:+ self._patch_organization({"name": "Renamed org"})+ self._patch_organization({"is_ai_data_processing_approved": False})++ history = get_ai_training_opt_in_history(self.organization)++ self.assertEqual(history.changes, [])diff --git a/posthog/templates/admin/organization/ai_training_opt_in_history.html b/posthog/templates/admin/organization/ai_training_opt_in_history.htmlnew file mode 100644index 000000000000..b014b1b0d17d--- /dev/null+++ b/posthog/templates/admin/organization/ai_training_opt_in_history.html@@ -0,0 +1,44 @@+{% if history.error %}+<div style="padding: 8px; border-left: 3px solid #dc3545;">+ <strong>{{ history.headline }}</strong>+ <p style="margin: 4px 0 0;">Reload the page. If it keeps failing, read the organization's activity log directly.</p>+ <p style="margin: 4px 0 0;">Error: {{ history.error }}</p>+</div>+{% else %}+{% if history.warning %}+<div style="margin-bottom: 12px; padding: 8px; border-left: 3px solid #dc3545;">+ {{ history.warning }}+</div>+{% endif %}+<strong>{{ history.headline }}</strong>++{% if history.changes %}+{% if history.truncated %}+<p>Showing the most recent {{ history.changes|length }} changes only. There are more in the activity log.</p>+{% endif %}+<table style="border-collapse: collapse; width: 100%; margin-top: 12px;">+ <thead>+ <tr>+ <th style="padding: 6px; text-align: left;">When</th>+ <th style="padding: 6px; text-align: left;">Change</th>+ <th style="padding: 6px; text-align: left;">Origin</th>+ <th style="padding: 6px; text-align: left;">Actor</th>+ <th style="padding: 6px; text-align: left;">Client</th>+ <th style="padding: 6px; text-align: left;">IP</th>+ </tr>+ </thead>+ <tbody>+ {% for change in history.changes %}+ <tr style="border-top: 1px solid;">+ <td style="padding: 6px; white-space: nowrap;">{{ change.changed_at_display }}</td>+ <td style="padding: 6px;">{{ change.transition_display }}</td>+ <td style="padding: 6px;">{{ change.origin }}</td>+ <td style="padding: 6px;">{{ change.actor }}</td>+ <td style="padding: 6px;">{{ change.client|default_if_none:"-" }}</td>+ <td style="padding: 6px;">{{ change.ip_address|default_if_none:"-" }}</td>+ </tr>+ {% endfor %}+ </tbody>+</table>+{% endif %}+{% endif %}