: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 eligibility, team allowlist, and safety guards (#66321)
Paul D'Ambra2c877f759cd6
diff --git a/ee/hogai/django_checkpoint/compaction.py b/ee/hogai/django_checkpoint/compaction.pyindex 604983ad2c67..08837c073869 100644--- a/ee/hogai/django_checkpoint/compaction.py+++ b/ee/hogai/django_checkpoint/compaction.py@@ -1,7 +1,10 @@from dataclasses import dataclass+from datetime import timedelta+from typing import Literalfrom django.db import transactionfrom django.db.models import Q+from django.utils import timezonefrom langgraph.checkpoint.serde.types import TASKS@@ -12,6 +15,15 @@ from products.posthog_ai.backend.models.assistant import (ConversationCheckpointWrite,)+# Opt-in gate for the compaction sweep. Either an int (compact teams whose id is this value or+# lower) or "*" (compact every team). Start narrow and raise the number to widen the rollout.+CHECKPOINT_COMPACTION_MAX_TEAM_ID: int | Literal["*"] = 2++# A conversation is eligible once it has had no activity for at least this long. Anchored in the+# observed return behaviour: ~99.6% of resumes happen within a week, and compaction keeps even+# later returns fully resumable.+CHECKPOINT_COMPACTION_IDLE_DAYS = 7+@dataclass(frozen=True)class CompactionResult:@@ -29,6 +41,39 @@ class CompactionResult:)+def _max_team_id() -> int | None:+ """The inclusive max team id to compact, or None when every team is enabled."""+ return None if CHECKPOINT_COMPACTION_MAX_TEAM_ID == "*" else CHECKPOINT_COMPACTION_MAX_TEAM_ID+++def select_compactable_conversation_ids(+ limit: int,+ after_id: str | None = None,+ idle_days: int | None = None,+) -> list[str]:+ """Return ids of conversations on enabled teams that are safe and worth compacting.++ "Worth compacting" means the root namespace still has more than one checkpoint — i.e. a root+ checkpoint that has a parent. An already-compacted thread (a single parentless tip) is+ excluded, so a daily sweep does not re-process it. Pending-approval threads can still slip+ through this coarse filter; `compact_thread` is the safety net that skips them.++ `idle_days=None` uses CHECKPOINT_COMPACTION_IDLE_DAYS — the one place the window is resolved."""+ cutoff = timezone.now() - timedelta(days=idle_days if idle_days is not None else CHECKPOINT_COMPACTION_IDLE_DAYS)+ qs = Conversation.objects.filter(+ status=Conversation.Status.IDLE,+ updated_at__lt=cutoff,+ checkpoints__checkpoint_ns="",+ checkpoints__parent_checkpoint__isnull=False,+ )+ cap = _max_team_id()+ if cap is not None:+ qs = qs.filter(team_id__lte=cap)+ if after_id is not None:+ qs = qs.filter(id__gt=after_id)+ return list(qs.order_by("id").values_list("id", flat=True).distinct()[:limit])++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.@@ -62,7 +107,11 @@ def compact_thread(thread_id: str, checkpoint_ns: str = "") -> CompactionResult:Only checkpoints strictly older than the chosen tip are deleted, so a thread that resumesbetween selecting the tip and deleting is never corrupted (the newer checkpoint is left in- place and its parent chain stays valid)."""+ place and its parent chain stays valid).++ This is the pure primitive: it has no team awareness. The rollout allowlist is enforced by+ the sweep at selection (`select_compactable_conversation_ids`); on-demand callers (e.g. the+ Django admin action) deliberately compact any conversation they are handed."""with transaction.atomic():# nosemgrep: idor-lookup-without-team (internal LangGraph checkpoint maintenance)conversation = Conversation.objects.select_for_update().filter(pk=thread_id).first()diff --git a/ee/hogai/django_checkpoint/test/test_compaction_eligibility.py b/ee/hogai/django_checkpoint/test/test_compaction_eligibility.pynew file mode 100644index 000000000000..c573bb1c104f--- /dev/null+++ b/ee/hogai/django_checkpoint/test/test_compaction_eligibility.py@@ -0,0 +1,73 @@+# type: ignore++from datetime import timedelta++from posthog.test.base import NonAtomicBaseTest+from unittest.mock import patch++from django.utils import timezone++from products.posthog_ai.backend.models.assistant import Conversation, ConversationCheckpoint++from ee.hogai.django_checkpoint import compaction+from ee.hogai.django_checkpoint.compaction import select_compactable_conversation_ids+++class TestCompactionEligibility(NonAtomicBaseTest):+ CLASS_DATA_LEVEL_SETUP = False++ def _make_thread(+ self,+ *,+ status: str = Conversation.Status.IDLE,+ idle_days: int = 8,+ root_checkpoints: int = 2,+ subgraph_only: bool = False,+ ) -> Conversation:+ conversation = Conversation.objects.create(user=self.user, team=self.team, status=status)+ ns = "sub" if subgraph_only else ""+ parent = None+ for _ in range(root_checkpoints):+ parent = ConversationCheckpoint.objects.create(+ thread=conversation, checkpoint_ns=ns, parent_checkpoint=parent+ )+ Conversation.objects.filter(pk=conversation.id).update(updated_at=timezone.now() - timedelta(days=idle_days))+ return conversation++ def test_wildcard_allowlist_compacts_any_team(self):+ eligible = self._make_thread()++ with patch.object(compaction, "CHECKPOINT_COMPACTION_MAX_TEAM_ID", "*"):+ assert select_compactable_conversation_ids(limit=100) == [eligible.id]++ def test_selects_only_idle_aged_multi_checkpoint_threads(self):+ eligible = self._make_thread()+ self._make_thread(idle_days=0) # too recent+ self._make_thread(status=Conversation.Status.IN_PROGRESS) # mid-run+ self._make_thread(root_checkpoints=1) # already compacted+ self._make_thread(subgraph_only=True) # no root chain to compact++ with patch.object(compaction, "CHECKPOINT_COMPACTION_MAX_TEAM_ID", self.team.id):+ selected = select_compactable_conversation_ids(limit=100)++ assert selected == [eligible.id]++ def test_team_allowlist_excludes_teams_above_the_limit(self):+ self._make_thread()++ with patch.object(compaction, "CHECKPOINT_COMPACTION_MAX_TEAM_ID", self.team.id - 1):+ assert select_compactable_conversation_ids(limit=100) == []++ def test_after_id_cursor_paginates(self):+ self._make_thread()+ self._make_thread()++ with patch.object(compaction, "CHECKPOINT_COMPACTION_MAX_TEAM_ID", self.team.id):+ ordered = select_compactable_conversation_ids(limit=100)+ assert len(ordered) == 2++ first_page = select_compactable_conversation_ids(limit=1)+ assert first_page == [ordered[0]]++ second_page = select_compactable_conversation_ids(limit=1, after_id=ordered[0])+ assert second_page == [ordered[1]]