: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(llma): add checkpoint compaction primitive with on-demand admin trigger (#66320)
Paul D'Ambra89dc3fb94526
diff --git a/ee/hogai/django_checkpoint/compaction.py b/ee/hogai/django_checkpoint/compaction.pynew file mode 100644index 000000000000..1982b14f0fdf--- /dev/null+++ b/ee/hogai/django_checkpoint/compaction.py@@ -0,0 +1,110 @@+from dataclasses import dataclass++from django.db import transaction+from django.db.models import Q++from langgraph.checkpoint.serde.types import TASKS++from products.posthog_ai.backend.models.assistant import (+ Conversation,+ ConversationCheckpoint,+ ConversationCheckpointBlob,+ ConversationCheckpointWrite,+)+++@dataclass(frozen=True)+class CompactionResult:+ compacted: bool+ checkpoints_deleted: int = 0+ blobs_deleted: int = 0+++def _is_safe_to_compact(conversation: Conversation) -> bool:+ """A thread is only safe to collapse when it has finished a turn and has no pending approval.++ Compaction nulls the tip's parent, which drops the parent's pending Sends — so any thread+ that is mid-run, being cancelled, or paused at an approval interrupt must be left untouched."""+ if conversation.status != Conversation.Status.IDLE:+ return False+ return not any(+ isinstance(decision, dict) and decision.get("decision_status") == "pending"+ for decision in (conversation.approval_decisions or {}).values()+ )+++def compact_thread(thread_id: str, checkpoint_ns: str = "") -> CompactionResult:+ """Collapse a conversation thread to its latest checkpoint, keeping it fully resumable.++ The latest checkpoint plus the blobs its `channel_versions` reference is a complete,+ resumable snapshot (the accumulating `messages` channel stores the whole history at its+ latest version). This relies on every channel persisting a *complete* value per version, which+ `DjangoCheckpointer._put` does today. A langgraph `DeltaChannel` would break it — the tip is+ rarely a delta snapshot point, so keeping only the tip would silently reconstruct that channel+ as empty. Max uses no delta channels; do not adopt one without revisiting this. Every older+ checkpoint, superseded blob version, and stale write is dead weight. Two storage traps make+ this more than a delete:++ - The `parent_checkpoint` self-FK cascades, so deleting an ancestor would take the tip with+ it. We null the tip's parent first to detach it from the chain.+ - A blob is owned (FK, cascade) by the checkpoint that created its version, which may be an+ ancestor. We reassign the blobs the tip still references to the tip before deleting, so+ the cascade can't remove a blob the tip needs.++ Only checkpoints strictly older than the chosen tip are deleted, so a thread that resumes+ between selecting the tip and deleting is never corrupted (the newer checkpoint is left in+ place and its parent chain stays valid)."""+ with transaction.atomic():+ # nosemgrep: idor-lookup-without-team (internal LangGraph checkpoint maintenance)+ conversation = Conversation.objects.select_for_update().filter(pk=thread_id).first()+ if conversation is None or not _is_safe_to_compact(conversation):+ return CompactionResult(compacted=False)++ # `checkpoint__isnull=False` mirrors the read path (`DjangoCheckpointer._get_checkpoint_qs`):+ # `put_writes` can create a checkpoint row before `put` fills in its JSON, so a higher-id+ # placeholder with a null checkpoint must never be chosen as the tip — doing so would+ # reassign no blobs and delete the real latest state beneath it.+ tip = (+ ConversationCheckpoint.objects.filter(+ thread_id=thread_id, checkpoint_ns=checkpoint_ns, checkpoint__isnull=False+ )+ .order_by("-id")+ .first()+ )+ if tip is None:+ return CompactionResult(compacted=False)++ # A tip whose parent still holds pending Sends (the TASKS channel) would lose that+ # routing when we detach the parent. Leave such a thread intact rather than risk an+ # unresumable tip; an idle, fully-completed turn has no such writes.+ if (+ tip.parent_checkpoint_id is not None+ and ConversationCheckpointWrite.objects.filter(+ checkpoint_id=tip.parent_checkpoint_id, channel=TASKS+ ).exists()+ ):+ return CompactionResult(compacted=False)++ # `or {}` is for the type checker only — the tip is guaranteed non-null by the filter above.+ channel_versions: dict[str, object] = (tip.checkpoint or {}).get("channel_versions", {})+ if channel_versions:+ referenced = Q()+ for channel, version in channel_versions.items():+ referenced |= Q(channel=channel, version=str(version))+ ConversationCheckpointBlob.objects.filter(+ Q(thread_id=thread_id, checkpoint_ns=checkpoint_ns) & referenced+ ).update(checkpoint=tip)++ ConversationCheckpoint.objects.filter(pk=tip.pk).update(parent_checkpoint=None)++ _, deleted_by_model = ConversationCheckpoint.objects.filter(+ thread_id=thread_id, checkpoint_ns=checkpoint_ns, id__lt=tip.id+ ).delete()++ checkpoints_deleted = deleted_by_model.get(ConversationCheckpoint._meta.label, 0)+ blobs_deleted = deleted_by_model.get(ConversationCheckpointBlob._meta.label, 0)+ return CompactionResult(+ compacted=checkpoints_deleted > 0,+ checkpoints_deleted=checkpoints_deleted,+ blobs_deleted=blobs_deleted,+ )diff --git a/ee/hogai/django_checkpoint/test/test_compaction.py b/ee/hogai/django_checkpoint/test/test_compaction.pynew file mode 100644index 000000000000..d3cefb5f7d78--- /dev/null+++ b/ee/hogai/django_checkpoint/test/test_compaction.py@@ -0,0 +1,186 @@+# type: ignore++import uuid++from posthog.test.base import NonAtomicBaseTest++from asgiref.sync import sync_to_async+from langgraph.checkpoint.base.id import uuid6+from langgraph.checkpoint.serde.types import TASKS+from langgraph.graph import END, START+from langgraph.graph.state import StateGraph+from parameterized import parameterized++from posthog.schema import AssistantMessage, HumanMessage++from products.posthog_ai.backend.models.assistant import (+ Conversation,+ ConversationCheckpoint,+ ConversationCheckpointBlob,+ ConversationCheckpointWrite,+)++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.utils.types import AssistantState+++@sync_to_async+def _table_counts(thread_id: str) -> dict[str, int]:+ return {+ "checkpoints": ConversationCheckpoint.objects.filter(thread_id=thread_id).count(),+ "blobs": ConversationCheckpointBlob.objects.filter(thread_id=thread_id).count(),+ "writes": ConversationCheckpointWrite.objects.filter(checkpoint__thread_id=thread_id).count(),+ }+++class TestCheckpointCompaction(NonAtomicBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def _build_graph(self, checkpointer: DjangoCheckpointer):+ graph = StateGraph(AssistantState)++ def respond(state: AssistantState) -> dict:+ return {"messages": [AssistantMessage(content=f"reply to message {len(state.messages)}")]}++ graph.add_node("respond", respond)+ graph.add_edge(START, "respond")+ graph.add_edge("respond", END)+ return graph.compile(checkpointer=checkpointer)++ async def _seed_conversation(self, n_turns: int) -> tuple[Conversation, object, dict]:+ conversation = await Conversation.objects.acreate(user=self.user, team=self.team)+ graph = self._build_graph(DjangoCheckpointer())+ config = {"configurable": {"thread_id": str(conversation.id), "checkpoint_ns": ""}}+ for turn in range(n_turns):+ await graph.ainvoke({"messages": [HumanMessage(content=f"question {turn}")]}, config)+ return conversation, graph, config++ 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]++ @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)++ before = await _table_counts(str(conversation.id))+ assert before["checkpoints"] > 1, "expected multiple checkpoints before compaction"++ messages_before = await self._message_contents(conversation)+ assert len(messages_before) == 2 * n_turns++ result = await sync_to_async(compact_thread)(str(conversation.id))+ assert result.compacted is True+ assert result.checkpoints_deleted > 0+ assert result.blobs_deleted > 0++ after = await _table_counts(str(conversation.id))+ assert after["checkpoints"] == 1, "compaction must leave exactly one checkpoint"+ assert after["blobs"] < before["blobs"], "compaction must reclaim superseded blobs"+ assert after["writes"] < before["writes"], "compaction must reclaim superseded writes"++ # The UI load path still returns the full transcript, unchanged.+ messages_after = await self._message_contents(conversation)+ assert messages_after == messages_before++ # And the thread is still resumable: a further turn sees the prior context.+ await graph.ainvoke({"messages": [HumanMessage(content="after compaction")]}, config)+ messages_resumed = await self._message_contents(conversation)+ assert messages_resumed[: len(messages_before)] == messages_before+ assert "after compaction" in messages_resumed+ assert len(messages_resumed) == 2 * n_turns + 2++ async def test_compaction_is_idempotent(self):+ conversation, _, _ = await self._seed_conversation(3)++ first = await sync_to_async(compact_thread)(str(conversation.id))+ assert first.compacted is True++ second = await sync_to_async(compact_thread)(str(conversation.id))+ assert second.compacted is False+ assert second.checkpoints_deleted == 0++ after = await _table_counts(str(conversation.id))+ assert after["checkpoints"] == 1+ assert await self._message_contents(conversation) == [+ "question 0",+ "reply to message 1",+ "question 1",+ "reply to message 3",+ "question 2",+ "reply to message 5",+ ]++ async def test_compaction_ignores_higher_id_null_checkpoint_placeholder(self):+ conversation, _, _ = await self._seed_conversation(2)+ messages_before = await self._message_contents(conversation)+ real_tip = (+ await ConversationCheckpoint.objects.filter(thread_id=conversation.id, checkpoint__isnull=False)+ .order_by("-id")+ .afirst()+ )++ # A `put_writes` placeholder: higher id than the real tip, but no checkpoint JSON yet.+ placeholder = await ConversationCheckpoint.objects.acreate(+ id=str(uuid6()),+ thread=conversation,+ checkpoint_ns="",+ parent_checkpoint=real_tip,+ checkpoint=None,+ )+ assert str(placeholder.id) > str(real_tip.id), "placeholder must sort above the real tip to exercise the bug"++ result = await sync_to_async(compact_thread)(str(conversation.id))+ assert result.compacted is True++ # The real state survives and still loads; the null placeholder was never treated as the tip.+ assert await self._message_contents(conversation) == messages_before+ surviving_real = await ConversationCheckpoint.objects.filter(+ thread_id=conversation.id, checkpoint__isnull=False+ ).acount()+ assert surviving_real == 1++ async def test_compaction_skips_tip_with_pending_sends(self):+ conversation, _, _ = await self._seed_conversation(2)+ tip = (+ await ConversationCheckpoint.objects.filter(thread_id=conversation.id, checkpoint__isnull=False)+ .order_by("-id")+ .afirst()+ )+ assert tip.parent_checkpoint_id is not None+ await ConversationCheckpointWrite.objects.acreate(+ checkpoint_id=tip.parent_checkpoint_id,+ task_id=uuid.uuid4(),+ idx=0,+ channel=TASKS,+ type="msgpack",+ blob=b"",+ )++ before = await _table_counts(str(conversation.id))+ result = await sync_to_async(compact_thread)(str(conversation.id))++ assert result.compacted is False+ after = await _table_counts(str(conversation.id))+ assert after["checkpoints"] == before["checkpoints"], "tip with pending sends must be untouched"++ @parameterized.expand(+ [+ ("in_progress", {"status": Conversation.Status.IN_PROGRESS}),+ ("canceling", {"status": Conversation.Status.CANCELING}),+ ("pending_approval", {"approval_decisions": {"p1": {"decision_status": "pending"}}}),+ ]+ )+ async def test_compaction_skips_unsafe_conversations(self, _name: str, unsafe_fields: dict):+ conversation, _, _ = await self._seed_conversation(3)+ await Conversation.objects.filter(pk=conversation.id).aupdate(**unsafe_fields)++ before = await _table_counts(str(conversation.id))+ result = await sync_to_async(compact_thread)(str(conversation.id))++ assert result.compacted is False+ after = await _table_counts(str(conversation.id))+ assert after["checkpoints"] == before["checkpoints"], "unsafe conversation must be untouched"diff --git a/posthog/admin/admins/conversation_admin.py b/posthog/admin/admins/conversation_admin.pynew file mode 100644index 000000000000..130657d0cf11--- /dev/null+++ b/posthog/admin/admins/conversation_admin.py@@ -0,0 +1,52 @@+from django.contrib import admin, messages+from django.urls import reverse+from django.utils.html import format_html++from products.posthog_ai.backend.models.assistant import Conversation++from ee.hogai.django_checkpoint.compaction import compact_thread++[email protected](Conversation)+class ConversationAdmin(admin.ModelAdmin):+ list_display = ("id", "team_link", "user", "status", "type", "title", "updated_at")+ list_select_related = ("team", "user")+ list_filter = ("status", "type")+ search_fields = ("id", "team__name", "user__email")+ autocomplete_fields = ("team", "user")+ ordering = ("-updated_at",)+ actions = ["compact_checkpoints"]++ def has_add_permission(self, request) -> bool:+ return False++ def has_delete_permission(self, request, obj=None) -> bool:+ # Conversation is soft-deleted by the app; don't expose a cascading hard-delete here.+ return False++ @admin.display(description="Team")+ def team_link(self, conversation: Conversation):+ return format_html(+ '<a href="{}">{}</a>',+ reverse("admin:posthog_team_change", args=[conversation.team_id]),+ conversation.team.name,+ )++ @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.+ compacted = skipped = checkpoints = blobs = 0+ for conversation in queryset:+ result = compact_thread(str(conversation.id))+ if result.compacted:+ compacted += 1+ checkpoints += result.checkpoints_deleted+ blobs += result.blobs_deleted+ else:+ skipped += 1+ 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).",+ messages.SUCCESS if compacted else messages.WARNING,+ )