: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(phai): show checkpoint size and per-conversation compact button in admin (#67064)
Paul D'Ambra5a0def50abfc
diff --git a/posthog/admin/admins/conversation_admin.py b/posthog/admin/admins/conversation_admin.pyindex e717294cc45a..ce51fa03cb9c 100644--- a/posthog/admin/admins/conversation_admin.py+++ b/posthog/admin/admins/conversation_admin.py@@ -1,11 +1,24 @@from django.contrib import admin, messages-from django.urls import reverse+from django.core.exceptions import PermissionDenied+from django.db.models import Count, Sum+from django.db.models.functions import Length+from django.http import HttpResponseNotAllowed+from django.middleware.csrf import get_token+from django.shortcuts import redirect+from django.template.defaultfilters import filesizeformat+from django.urls import path, reversefrom django.utils.html import format_html+from structlog import get_logger+from products.posthog_ai.backend.models.assistant import Conversationfrom ee.hogai.django_checkpoint.compaction import compact_thread+logger = get_logger()++_COMPACT_SKIP_REASON = "not idle, awaiting approval, or nothing to compact"+@admin.register(Conversation)class ConversationAdmin(admin.ModelAdmin):@@ -18,6 +31,7 @@ class ConversationAdmin(admin.ModelAdmin):# isn't guaranteed registered when ConversationAdmin's system checks run (admin.E039).# raw_id_fields needs no registered target admin and still avoids the full-table <select>.raw_id_fields = ("task",)+ readonly_fields = ("checkpoint_storage",)ordering = ("-updated_at",)actions = ["compact_checkpoints"]@@ -28,6 +42,19 @@ class ConversationAdmin(admin.ModelAdmin):# Conversation is soft-deleted by the app; don't expose a cascading hard-delete here.return False+ def changeform_view(self, request, object_id=None, form_url="", extra_context=None):+ # Stash the request so checkpoint_storage can mint a CSRF token for its POST form.+ self._current_request = request+ return super().changeform_view(request, object_id, form_url, extra_context)++ def get_urls(self):+ compact_url = path(+ "<path:object_id>/compact/",+ self.admin_site.admin_view(self.compact_view),+ name="posthog_ai_conversation_compact",+ )+ return [compact_url, *super().get_urls()]+@admin.display(description="Team")def team_link(self, conversation: Conversation):return format_html(@@ -36,6 +63,55 @@ class ConversationAdmin(admin.ModelAdmin):conversation.team.name,)+ @admin.display(description="Checkpoint storage")+ def checkpoint_storage(self, conversation: Conversation):+ # Change-page only — do not add to list_display: the bytea Length() sum would run per row.+ # Blobs hold the bulk of a thread's bytes; query them via `thread`, not the `checkpoint` FK.+ blobs = conversation.blobs.aggregate(count=Count("id"), total_bytes=Sum(Length("blob")))+ request = getattr(self, "_current_request", None)+ # POST form rather than a link: compaction deletes rows, so it must not run on a GET.+ return format_html(+ "{} checkpoints, {} blobs ({}) "+ '<form method="post" action="{}" style="display: inline">'+ '<input type="hidden" name="csrfmiddlewaretoken" value="{}">'+ '<button type="submit" class="button" data-attr="conversation-admin-compact-now">Compact now</button>'+ "</form>",+ conversation.checkpoints.count(),+ blobs["count"] or 0,+ filesizeformat(blobs["total_bytes"] or 0),+ reverse("admin:posthog_ai_conversation_compact", args=[conversation.pk]),+ get_token(request) if request is not None else "",+ )++ def compact_view(self, request, object_id: str):+ conversation = self.get_object(request, object_id)+ if conversation is None:+ self.message_user(request, "Conversation not found.", messages.ERROR)+ return redirect("admin:posthog_ai_conversation_changelist")+ if not self.has_change_permission(request, conversation):+ raise PermissionDenied+ if request.method != "POST":+ return HttpResponseNotAllowed(["POST"])+ # Bypasses the sweep's rollout allowlist — this is a deliberate staff override.+ result = compact_thread(str(conversation.id))+ logger.info(+ "admin_compact_conversation",+ conversation_id=str(conversation.id),+ compacted=result.compacted,+ checkpoints_deleted=result.checkpoints_deleted,+ blobs_deleted=result.blobs_deleted,+ triggered_by=request.user.email,+ )+ if result.compacted:+ self.message_user(+ request,+ f"Compacted — reclaimed {result.checkpoints_deleted} checkpoints and {result.blobs_deleted} blobs.",+ messages.SUCCESS,+ )+ else:+ self.message_user(request, f"Nothing compacted ({_COMPACT_SKIP_REASON}).", messages.WARNING)+ return redirect("admin:posthog_ai_conversation_change", conversation.id)+@admin.action(description="Compact checkpoints (keep latest, reclaim storage)")def compact_checkpoints(self, request, queryset) -> None:# Bypasses the sweep's rollout allowlist — this is a deliberate staff override.@@ -51,6 +127,6 @@ class ConversationAdmin(admin.ModelAdmin):self.message_user(request,f"Compacted {compacted} conversation(s) — reclaimed {checkpoints} checkpoints "- f"and {blobs} blobs. Skipped {skipped} (not idle, awaiting approval, or nothing to compact).",+ f"and {blobs} blobs. Skipped {skipped} ({_COMPACT_SKIP_REASON}).",messages.SUCCESS if compacted else messages.WARNING,)diff --git a/posthog/admin/test_conversation_admin.py b/posthog/admin/test_conversation_admin.pynew file mode 100644index 000000000000..ba0244d0aaf8--- /dev/null+++ b/posthog/admin/test_conversation_admin.py@@ -0,0 +1,89 @@+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.contrib.admin.sites import AdminSite+from django.contrib.messages import constants as message_constants+from django.contrib.messages.storage.fallback import FallbackStorage+from django.core.exceptions import PermissionDenied+from django.http import HttpResponseNotAllowed+from django.test import RequestFactory++from parameterized import parameterized++from posthog.admin.admins.conversation_admin import ConversationAdmin++from products.posthog_ai.backend.models.assistant import Conversation++from ee.hogai.django_checkpoint.compaction import CompactionResult+++def _attach_messages(request) -> None:+ request.session = {}+ request._messages = FallbackStorage(request)+++class TestConversationAdminCompactView(BaseTest):+ def setUp(self) -> None:+ super().setUp()+ # is_superuser is a read-only property returning is_staff, so staff => has change permission.+ self.user.is_staff = True+ self.user.save()+ self.factory = RequestFactory()+ self.admin = ConversationAdmin(Conversation, AdminSite())+ self.conversation = Conversation.objects.create(team=self.team, user=self.user)+ self.compact_url = f"/admin/posthog_ai/conversation/{self.conversation.id}/compact/"++ def _request(self, method: str):+ request = getattr(self.factory, method)(self.compact_url)+ request.user = self.user+ _attach_messages(request)+ return request++ @patch("posthog.admin.admins.conversation_admin.compact_thread")+ def test_get_is_rejected_and_does_not_compact(self, mock_compact) -> None:+ response = self.admin.compact_view(self._request("get"), str(self.conversation.id))+ assert isinstance(response, HttpResponseNotAllowed)+ mock_compact.assert_not_called()++ @patch("posthog.admin.admins.conversation_admin.compact_thread")+ def test_post_without_change_permission_is_denied_and_does_not_compact(self, mock_compact) -> None:+ with patch.object(self.admin, "has_change_permission", return_value=False):+ with self.assertRaises(PermissionDenied):+ self.admin.compact_view(self._request("post"), str(self.conversation.id))+ mock_compact.assert_not_called()++ @patch("posthog.admin.admins.conversation_admin.compact_thread")+ def test_missing_conversation_redirects_to_changelist_without_compacting(self, mock_compact) -> None:+ response = self.admin.compact_view(self._request("post"), "01920000-0000-0000-0000-000000000000")+ assert response.status_code == 302+ assert response.url.endswith("/conversation/")+ mock_compact.assert_not_called()++ @parameterized.expand(+ [+ (+ CompactionResult(compacted=True, checkpoints_deleted=3, blobs_deleted=5),+ message_constants.SUCCESS,+ "reclaimed 3 checkpoints and 5 blobs",+ ),+ (+ CompactionResult(compacted=False),+ message_constants.WARNING,+ "Nothing compacted",+ ),+ ]+ )+ @patch("posthog.admin.admins.conversation_admin.compact_thread")+ def test_post_compacts_and_reports(self, result, expected_level, expected_substr, mock_compact) -> None:+ mock_compact.return_value = result+ request = self._request("post")++ response = self.admin.compact_view(request, str(self.conversation.id))++ mock_compact.assert_called_once_with(str(self.conversation.id))+ assert response.status_code == 302+ assert str(self.conversation.id) in response.url+ messages = list(request._messages)+ assert len(messages) == 1+ assert messages[0].level == expected_level+ assert expected_substr in messages[0].message