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(phai): compact all checkpoint namespaces (safely across subgraphs) + fix admin button (#67300)

Paul D'Ambra62a5418bdb49
diff --git a/ee/hogai/django_checkpoint/compaction.py b/ee/hogai/django_checkpoint/compaction.py
index 1982b14f0fdf..604983ad2c67 100644
--- a/ee/hogai/django_checkpoint/compaction.py
+++ b/ee/hogai/django_checkpoint/compaction.py
@@ -18,6 +18,15 @@ class CompactionResult:
compacted: bool
checkpoints_deleted: int = 0
blobs_deleted: int = 0
+ namespaces: int = 0
+
+ def __add__(self, other: "CompactionResult") -> "CompactionResult":
+ return CompactionResult(
+ compacted=self.compacted or other.compacted,
+ checkpoints_deleted=self.checkpoints_deleted + other.checkpoints_deleted,
+ blobs_deleted=self.blobs_deleted + other.blobs_deleted,
+ namespaces=self.namespaces + other.namespaces,
+ )
def _is_safe_to_compact(conversation: Conversation) -> bool:
@@ -91,8 +100,14 @@ def compact_thread(thread_id: str, checkpoint_ns: str = "") -> CompactionResult:
referenced = Q()
for channel, version in channel_versions.items():
referenced |= Q(channel=channel, version=str(version))
+ # Scope by the *owning checkpoint's* namespace, not the blob's own checkpoint_ns:
+ # DjangoCheckpointer._put writes every blob with the default checkpoint_ns="" regardless
+ # of its checkpoint's namespace, so filtering on the blob's field would match nothing for
+ # a subgraph and let the cascade delete blobs the tip still references. Joining through the
+ # owning checkpoint keeps the reassignment inside this namespace — it never touches another
+ # namespace's blobs.
ConversationCheckpointBlob.objects.filter(
- Q(thread_id=thread_id, checkpoint_ns=checkpoint_ns) & referenced
+ Q(checkpoint__thread_id=thread_id, checkpoint__checkpoint_ns=checkpoint_ns) & referenced
).update(checkpoint=tip)
ConversationCheckpoint.objects.filter(pk=tip.pk).update(parent_checkpoint=None)
@@ -108,3 +123,20 @@ def compact_thread(thread_id: str, checkpoint_ns: str = "") -> CompactionResult:
checkpoints_deleted=checkpoints_deleted,
blobs_deleted=blobs_deleted,
)
+
+
+def compact_conversation(thread_id: str) -> CompactionResult:
+ """Compact every checkpoint namespace of a conversation, not just the root graph.
+
+ Max runs subgraphs (taxonomy, tools, deep-research, ...), each persisting checkpoints under its
+ own `checkpoint_ns`. `compact_thread` collapses a single namespace, so compacting only the root
+ ("") leaves every subgraph namespace untouched — most of a real conversation's checkpoints."""
+ # nosemgrep: idor-lookup-without-team (internal LangGraph checkpoint maintenance)
+ namespaces = list(
+ ConversationCheckpoint.objects.filter(thread_id=thread_id).values_list("checkpoint_ns", flat=True).distinct()
+ )
+ # Seed the namespace count here so callers (e.g. the admin audit log) don't re-query it.
+ result = CompactionResult(compacted=False, namespaces=len(namespaces))
+ for checkpoint_ns in namespaces:
+ result += compact_thread(thread_id, checkpoint_ns)
+ return result
diff --git a/ee/hogai/django_checkpoint/test/test_compaction.py b/ee/hogai/django_checkpoint/test/test_compaction.py
index d3cefb5f7d78..8de16cc2e552 100644
--- a/ee/hogai/django_checkpoint/test/test_compaction.py
+++ b/ee/hogai/django_checkpoint/test/test_compaction.py
@@ -22,7 +22,7 @@ from products.posthog_ai.backend.models.assistant import (
from ee.hogai.api.serializers import aget_conversation_state
from ee.hogai.django_checkpoint.checkpointer import DjangoCheckpointer
-from ee.hogai.django_checkpoint.compaction import compact_thread
+from ee.hogai.django_checkpoint.compaction import compact_conversation, compact_thread
from ee.hogai.utils.types import AssistantState
@@ -35,6 +35,14 @@ def _table_counts(thread_id: str) -> dict[str, int]:
}
+@sync_to_async
+def _namespace_counts(thread_id: str) -> dict[str, int]:
+ counts: dict[str, int] = {}
+ for ns in ConversationCheckpoint.objects.filter(thread_id=thread_id).values_list("checkpoint_ns", flat=True):
+ counts[ns] = counts.get(ns, 0) + 1
+ return counts
+
+
class TestCheckpointCompaction(NonAtomicBaseTest):
CLASS_DATA_LEVEL_SETUP = False
@@ -57,11 +65,63 @@ class TestCheckpointCompaction(NonAtomicBaseTest):
await graph.ainvoke({"messages": [HumanMessage(content=f"question {turn}")]}, config)
return conversation, graph, config
+ def _build_nested_graph(self, checkpointer: DjangoCheckpointer):
+ subgraph = StateGraph(AssistantState)
+
+ def sub_first(state: AssistantState) -> dict:
+ return {"messages": [AssistantMessage(content="sub first")]}
+
+ def sub_second(state: AssistantState) -> dict:
+ return {"messages": [AssistantMessage(content="sub second")]}
+
+ subgraph.add_node("sub_first", sub_first)
+ subgraph.add_node("sub_second", sub_second)
+ subgraph.add_edge(START, "sub_first")
+ subgraph.add_edge("sub_first", "sub_second")
+ subgraph.add_edge("sub_second", END)
+
+ parent = StateGraph(AssistantState)
+ parent.add_node("child", subgraph.compile())
+ parent.add_edge(START, "child")
+ parent.add_edge("child", END)
+ return parent.compile(checkpointer=checkpointer)
+
async def _message_contents(self, conversation: Conversation) -> list[str]:
state, _, _ = await aget_conversation_state(conversation, self.team, self.user)
assert state is not None, "UI load path returned no state"
return [m.content for m in state.messages]
+ async def test_compaction_handles_nested_subgraphs(self):
+ conversation = await Conversation.objects.acreate(user=self.user, team=self.team)
+ graph = self._build_nested_graph(DjangoCheckpointer())
+ config = {"configurable": {"thread_id": str(conversation.id), "checkpoint_ns": ""}}
+ for turn in range(2):
+ await graph.ainvoke({"messages": [HumanMessage(content=f"question {turn}")]}, config)
+
+ before = await _namespace_counts(str(conversation.id))
+ subgraph_namespaces = [ns for ns in before if ns != ""]
+ assert subgraph_namespaces, "expected subgraph checkpoints under a non-root namespace"
+ assert all(before[ns] > 1 for ns in subgraph_namespaces), "subgraph namespaces should accumulate checkpoints"
+ messages_before = await self._message_contents(conversation)
+
+ # Root-only compaction (the old admin behaviour) leaves every subgraph namespace untouched.
+ await sync_to_async(compact_thread)(str(conversation.id))
+ after_root_only = await _namespace_counts(str(conversation.id))
+ assert {ns: after_root_only[ns] for ns in subgraph_namespaces} == {ns: before[ns] for ns in subgraph_namespaces}
+
+ # compact_conversation collapses every namespace to its tip.
+ result = await sync_to_async(compact_conversation)(str(conversation.id))
+ assert result.compacted is True
+ after = await _namespace_counts(str(conversation.id))
+ assert all(count == 1 for count in after.values()), f"every namespace must collapse to its tip: {after}"
+
+ # The whole conversation — including subgraph state — still loads and resumes unchanged.
+ assert await self._message_contents(conversation) == messages_before
+ await graph.ainvoke({"messages": [HumanMessage(content="after compaction")]}, config)
+ resumed = await self._message_contents(conversation)
+ assert resumed[: len(messages_before)] == messages_before
+ assert "after compaction" in resumed
+
@parameterized.expand([("two_turns", 2), ("four_turns", 4)])
async def test_compaction_keeps_conversation_loadable_and_resumable(self, _name: str, n_turns: int):
conversation, graph, config = await self._seed_conversation(n_turns)
diff --git a/posthog/admin/admins/conversation_admin.py b/posthog/admin/admins/conversation_admin.py
index ce51fa03cb9c..3602569d9016 100644
--- a/posthog/admin/admins/conversation_admin.py
+++ b/posthog/admin/admins/conversation_admin.py
@@ -3,7 +3,6 @@ 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, reverse
@@ -13,7 +12,7 @@ from structlog import get_logger
from products.posthog_ai.backend.models.assistant import Conversation
-from ee.hogai.django_checkpoint.compaction import compact_thread
+from ee.hogai.django_checkpoint.compaction import compact_conversation
logger = get_logger()
@@ -42,11 +41,6 @@ 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/",
@@ -67,20 +61,21 @@ class ConversationAdmin(admin.ModelAdmin):
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.
+ checkpoints = conversation.checkpoints.aggregate(
+ total=Count("id"), namespaces=Count("checkpoint_ns", distinct=True)
+ )
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.
+ # A submit button in the admin's own <form> (not a nested one, which browsers won't submit):
+ # formaction posts with the form's CSRF token, so this destructive action never runs on a GET.
return format_html(
- "{} checkpoints, {} blobs ({}) &nbsp;"
- '<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(),
+ "{} checkpoints across {} namespace(s), {} blobs ({}) &nbsp;"
+ '<button type="submit" class="button" formmethod="post" formaction="{}" formnovalidate '
+ 'data-attr="conversation-admin-compact-now">Compact now</button>',
+ checkpoints["total"],
+ checkpoints["namespaces"],
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):
@@ -93,13 +88,14 @@ class ConversationAdmin(admin.ModelAdmin):
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))
+ result = compact_conversation(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,
+ namespaces=result.namespaces,
triggered_by=request.user.email,
)
if result.compacted:
@@ -117,7 +113,7 @@ class ConversationAdmin(admin.ModelAdmin):
# Bypasses the sweep's rollout allowlist — this is a deliberate staff override.
compacted = skipped = checkpoints = blobs = 0
for conversation in queryset:
- result = compact_thread(str(conversation.id))
+ result = compact_conversation(str(conversation.id))
if result.compacted:
compacted += 1
checkpoints += result.checkpoints_deleted
diff --git a/posthog/admin/test_conversation_admin.py b/posthog/admin/test_conversation_admin.py
index ba0244d0aaf8..d13e326ded1d 100644
--- a/posthog/admin/test_conversation_admin.py
+++ b/posthog/admin/test_conversation_admin.py
@@ -39,20 +39,20 @@ class TestConversationAdminCompactView(BaseTest):
_attach_messages(request)
return request
- @patch("posthog.admin.admins.conversation_admin.compact_thread")
+ @patch("posthog.admin.admins.conversation_admin.compact_conversation")
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")
+ @patch("posthog.admin.admins.conversation_admin.compact_conversation")
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")
+ @patch("posthog.admin.admins.conversation_admin.compact_conversation")
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
@@ -73,7 +73,7 @@ class TestConversationAdminCompactView(BaseTest):
),
]
)
- @patch("posthog.admin.admins.conversation_admin.compact_thread")
+ @patch("posthog.admin.admins.conversation_admin.compact_conversation")
def test_post_compacts_and_reports(self, result, expected_level, expected_substr, mock_compact) -> None:
mock_compact.return_value = result
request = self._request("post")