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(llma): run checkpoint compaction in a batched Temporal workflow (#66322)

Paul D'Ambracb21dbec498f
diff --git a/posthog/temporal/ai/__init__.py b/posthog/temporal/ai/__init__.py
index 2b36137aa202..720d3a9122dc 100644
--- a/posthog/temporal/ai/__init__.py
+++ b/posthog/temporal/ai/__init__.py
@@ -5,6 +5,7 @@ from posthog.temporal.ai.chat_agent import (
process_chat_agent_activity,
process_conversation_activity,
)
+from posthog.temporal.ai.checkpoint_compaction import CHECKPOINT_COMPACTION_ACTIVITIES, CHECKPOINT_COMPACTION_WORKFLOWS
from posthog.temporal.ai.research_agent import ResearchAgentWorkflow, process_research_agent_activity
from posthog.temporal.ai.slack_app import SLACK_APP_ACTIVITIES
from posthog.temporal.ai.slack_app.posthog_code_slack_interactivity import (
@@ -51,6 +52,7 @@ AI_WORKFLOWS = [
ResearchAgentWorkflow,
SummarizeLLMTracesWorkflow,
AnomalyInvestigationWorkflow,
+ *CHECKPOINT_COMPACTION_WORKFLOWS,
]
AI_ACTIVITIES = [
@@ -62,6 +64,7 @@ AI_ACTIVITIES = [
process_research_agent_activity,
summarize_llm_traces_activity,
investigate_anomaly_activity,
+ *CHECKPOINT_COMPACTION_ACTIVITIES,
]
__all__ = [
diff --git a/posthog/temporal/ai/checkpoint_compaction/__init__.py b/posthog/temporal/ai/checkpoint_compaction/__init__.py
new file mode 100644
index 000000000000..27257636b5a3
--- /dev/null
+++ b/posthog/temporal/ai/checkpoint_compaction/__init__.py
@@ -0,0 +1,8 @@
+from posthog.temporal.ai.checkpoint_compaction.activities import (
+ compact_checkpoint_conversations,
+ select_checkpoint_compaction_batch,
+)
+from posthog.temporal.ai.checkpoint_compaction.workflow import CheckpointCompactionWorkflow
+
+CHECKPOINT_COMPACTION_WORKFLOWS = [CheckpointCompactionWorkflow]
+CHECKPOINT_COMPACTION_ACTIVITIES = [select_checkpoint_compaction_batch, compact_checkpoint_conversations]
diff --git a/posthog/temporal/ai/checkpoint_compaction/activities.py b/posthog/temporal/ai/checkpoint_compaction/activities.py
new file mode 100644
index 000000000000..7549d797ce61
--- /dev/null
+++ b/posthog/temporal/ai/checkpoint_compaction/activities.py
@@ -0,0 +1,63 @@
+from temporalio import activity
+
+from posthog.sync import database_sync_to_async
+from posthog.temporal.ai.checkpoint_compaction.types import (
+ MAX_COMPACTION_BATCH_SIZE,
+ CompactBatchResult,
+ CompactionBatch,
+ SelectBatchInput,
+)
+from posthog.temporal.common.logger import get_write_only_logger
+
+from ee.hogai.django_checkpoint.compaction import compact_thread, select_compactable_conversation_ids
+
+LOGGER = get_write_only_logger()
+
+
[email protected](name="select-checkpoint-compaction-batch")
+async def select_checkpoint_compaction_batch(input: SelectBatchInput) -> CompactionBatch:
+ limit = min(input.batch_size, MAX_COMPACTION_BATCH_SIZE)
+ conversation_ids = await database_sync_to_async(select_compactable_conversation_ids, thread_sensitive=False)(
+ limit=limit, after_id=input.after_id, idle_days=input.idle_days
+ )
+ ids = [str(conversation_id) for conversation_id in conversation_ids]
+ LOGGER.bind().info("Selected checkpoint compaction batch", count=len(ids), after_id=input.after_id)
+ return CompactionBatch(conversation_ids=ids)
+
+
[email protected](name="compact-checkpoint-conversations")
+async def compact_checkpoint_conversations(input: CompactionBatch) -> CompactBatchResult:
+ def _compact() -> CompactBatchResult:
+ conversations_compacted = 0
+ conversations_failed = 0
+ checkpoints_deleted = 0
+ blobs_deleted = 0
+ for conversation_id in input.conversation_ids:
+ try:
+ outcome = compact_thread(conversation_id)
+ except Exception:
+ # One poison thread must not sink the whole batch (and with it the daily sweep).
+ conversations_failed += 1
+ LOGGER.bind().exception("Checkpoint compaction failed", conversation_id=conversation_id)
+ continue
+ if outcome.compacted:
+ conversations_compacted += 1
+ checkpoints_deleted += outcome.checkpoints_deleted
+ blobs_deleted += outcome.blobs_deleted
+ return CompactBatchResult(
+ conversations_compacted=conversations_compacted,
+ conversations_failed=conversations_failed,
+ checkpoints_deleted=checkpoints_deleted,
+ blobs_deleted=blobs_deleted,
+ )
+
+ result = await database_sync_to_async(_compact, thread_sensitive=False)()
+ LOGGER.bind().info(
+ "Compacted checkpoint conversations",
+ requested=len(input.conversation_ids),
+ compacted=result.conversations_compacted,
+ failed=result.conversations_failed,
+ checkpoints_deleted=result.checkpoints_deleted,
+ blobs_deleted=result.blobs_deleted,
+ )
+ return result
diff --git a/posthog/temporal/ai/checkpoint_compaction/types.py b/posthog/temporal/ai/checkpoint_compaction/types.py
new file mode 100644
index 000000000000..c4ff5512994a
--- /dev/null
+++ b/posthog/temporal/ai/checkpoint_compaction/types.py
@@ -0,0 +1,38 @@
+from pydantic import BaseModel
+
+MAX_COMPACTION_BATCH_SIZE = 200
+
+
+class CompactionProgress(BaseModel):
+ """Accumulated state carried across continue-as-new executions."""
+
+ cursor: str | None = None
+ conversations_compacted: int = 0
+ conversations_failed: int = 0
+ checkpoints_deleted: int = 0
+ blobs_deleted: int = 0
+
+
+class CompactionSweepInput(BaseModel):
+ batch_size: int = 100
+ # None flows through to select_compactable_conversation_ids, which resolves the window from
+ # CHECKPOINT_COMPACTION_IDLE_DAYS — the single source of truth.
+ idle_days: int | None = None
+ progress: CompactionProgress | None = None
+
+
+class SelectBatchInput(BaseModel):
+ batch_size: int
+ idle_days: int | None = None
+ after_id: str | None = None
+
+
+class CompactionBatch(BaseModel):
+ conversation_ids: list[str]
+
+
+class CompactBatchResult(BaseModel):
+ conversations_compacted: int = 0
+ conversations_failed: int = 0
+ checkpoints_deleted: int = 0
+ blobs_deleted: int = 0
diff --git a/posthog/temporal/ai/checkpoint_compaction/workflow.py b/posthog/temporal/ai/checkpoint_compaction/workflow.py
new file mode 100644
index 000000000000..765a7b1e220f
--- /dev/null
+++ b/posthog/temporal/ai/checkpoint_compaction/workflow.py
@@ -0,0 +1,68 @@
+from datetime import timedelta
+
+from temporalio import common, workflow
+
+from posthog.temporal.ai.checkpoint_compaction.activities import (
+ compact_checkpoint_conversations,
+ select_checkpoint_compaction_batch,
+)
+from posthog.temporal.ai.checkpoint_compaction.types import (
+ CompactBatchResult,
+ CompactionBatch,
+ CompactionProgress,
+ CompactionSweepInput,
+ SelectBatchInput,
+)
+from posthog.temporal.common.base import PostHogWorkflow
+
+
[email protected](name="checkpoint-compaction-sweep")
+class CheckpointCompactionWorkflow(PostHogWorkflow):
+ inputs_cls = CompactionSweepInput
+ inputs_optional = True
+
+ @workflow.run
+ async def run(self, input: CompactionSweepInput) -> CompactionProgress:
+ progress = input.progress or CompactionProgress()
+
+ while True:
+ batch: CompactionBatch = await workflow.execute_activity(
+ select_checkpoint_compaction_batch,
+ SelectBatchInput(
+ batch_size=input.batch_size,
+ idle_days=input.idle_days,
+ after_id=progress.cursor,
+ ),
+ start_to_close_timeout=timedelta(minutes=5),
+ schedule_to_close_timeout=timedelta(minutes=15),
+ retry_policy=common.RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=30)),
+ )
+
+ if not batch.conversation_ids:
+ return progress
+
+ result: CompactBatchResult = await workflow.execute_activity(
+ compact_checkpoint_conversations,
+ batch,
+ start_to_close_timeout=timedelta(minutes=10),
+ schedule_to_close_timeout=timedelta(minutes=30),
+ retry_policy=common.RetryPolicy(maximum_attempts=3, initial_interval=timedelta(seconds=30)),
+ )
+
+ progress.conversations_compacted += result.conversations_compacted
+ progress.conversations_failed += result.conversations_failed
+ progress.checkpoints_deleted += result.checkpoints_deleted
+ progress.blobs_deleted += result.blobs_deleted
+ # The selection filter excludes compacted threads, so advancing past the last id we
+ # saw also steps over any threads we skipped this run (e.g. pending approval),
+ # guaranteeing the cursor always moves forward and the sweep terminates.
+ progress.cursor = batch.conversation_ids[-1]
+
+ if workflow.info().is_continue_as_new_suggested():
+ workflow.continue_as_new(
+ CompactionSweepInput(
+ batch_size=input.batch_size,
+ idle_days=input.idle_days,
+ progress=progress,
+ )
+ )
diff --git a/posthog/temporal/tests/ai/test_checkpoint_compaction_activities.py b/posthog/temporal/tests/ai/test_checkpoint_compaction_activities.py
new file mode 100644
index 000000000000..fa22eef38407
--- /dev/null
+++ b/posthog/temporal/tests/ai/test_checkpoint_compaction_activities.py
@@ -0,0 +1,82 @@
+from datetime import timedelta
+
+import pytest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from asgiref.sync import sync_to_async
+
+from posthog.temporal.ai.checkpoint_compaction.activities import (
+ compact_checkpoint_conversations,
+ select_checkpoint_compaction_batch,
+)
+from posthog.temporal.ai.checkpoint_compaction.types import CompactionBatch, SelectBatchInput
+
+from products.posthog_ai.backend.models.assistant import Conversation, ConversationCheckpoint
+
+from ee.hogai.django_checkpoint import compaction
+
+pytestmark = [pytest.mark.django_db(transaction=True), pytest.mark.asyncio]
+
+
+def _seed_compactable(team, user) -> Conversation:
+ conversation = Conversation.objects.create(team=team, user=user)
+ parent = None
+ for _ in range(3):
+ parent = ConversationCheckpoint.objects.create(
+ thread=conversation,
+ checkpoint_ns="",
+ parent_checkpoint=parent,
+ checkpoint={"channel_versions": {}},
+ )
+ Conversation.objects.filter(pk=conversation.id).update(updated_at=timezone.now() - timedelta(days=8))
+ return conversation
+
+
+async def test_select_then_compact_activities_end_to_end(ateam, auser, activity_environment):
+ conversation = await sync_to_async(_seed_compactable)(ateam, auser)
+
+ with patch.object(compaction, "CHECKPOINT_COMPACTION_MAX_TEAM_ID", ateam.id):
+ batch = await activity_environment.run(select_checkpoint_compaction_batch, SelectBatchInput(batch_size=10))
+ assert batch.conversation_ids == [str(conversation.id)]
+
+ result = await activity_environment.run(
+ compact_checkpoint_conversations, CompactionBatch(conversation_ids=batch.conversation_ids)
+ )
+
+ assert result.conversations_compacted == 1
+ assert result.checkpoints_deleted == 2
+
+ remaining = await sync_to_async(ConversationCheckpoint.objects.filter(thread_id=conversation.id).count)()
+ assert remaining == 1
+
+
+async def test_one_poison_thread_does_not_sink_the_batch(ateam, auser, activity_environment):
+ healthy = await sync_to_async(_seed_compactable)(ateam, auser)
+ poison = await sync_to_async(_seed_compactable)(ateam, auser)
+
+ real_compact_thread = compaction.compact_thread
+
+ def flaky_compact_thread(thread_id, *args, **kwargs):
+ if thread_id == str(poison.id):
+ raise RuntimeError("boom")
+ return real_compact_thread(thread_id, *args, **kwargs)
+
+ with (
+ patch.object(compaction, "CHECKPOINT_COMPACTION_MAX_TEAM_ID", ateam.id),
+ patch(
+ "posthog.temporal.ai.checkpoint_compaction.activities.compact_thread",
+ side_effect=flaky_compact_thread,
+ ),
+ ):
+ result = await activity_environment.run(
+ compact_checkpoint_conversations,
+ CompactionBatch(conversation_ids=[str(poison.id), str(healthy.id)]),
+ )
+
+ # The poison thread is counted and skipped; the healthy thread that follows it still compacts.
+ assert result.conversations_failed == 1
+ assert result.conversations_compacted == 1
+ assert await sync_to_async(ConversationCheckpoint.objects.filter(thread_id=healthy.id).count)() == 1
+ assert await sync_to_async(ConversationCheckpoint.objects.filter(thread_id=poison.id).count)() == 3
diff --git a/posthog/temporal/tests/ai/test_checkpoint_compaction_workflow.py b/posthog/temporal/tests/ai/test_checkpoint_compaction_workflow.py
new file mode 100644
index 000000000000..d05c704a7558
--- /dev/null
+++ b/posthog/temporal/tests/ai/test_checkpoint_compaction_workflow.py
@@ -0,0 +1,78 @@
+import uuid
+
+import pytest
+
+import temporalio.worker
+from temporalio import activity
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import Worker
+
+from posthog.temporal.ai.checkpoint_compaction.types import (
+ CompactBatchResult,
+ CompactionBatch,
+ CompactionProgress,
+ CompactionSweepInput,
+ SelectBatchInput,
+)
+from posthog.temporal.ai.checkpoint_compaction.workflow import CheckpointCompactionWorkflow
+
+
+async def _run_with_activities(select_activity, compact_activity, sweep_input: CompactionSweepInput):
+ task_queue = str(uuid.uuid4())
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ async with Worker(
+ env.client,
+ task_queue=task_queue,
+ workflows=[CheckpointCompactionWorkflow],
+ activities=[select_activity, compact_activity],
+ workflow_runner=temporalio.worker.UnsandboxedWorkflowRunner(),
+ ):
+ result = await env.client.execute_workflow(
+ CheckpointCompactionWorkflow.run,
+ sweep_input,
+ id=str(uuid.uuid4()),
+ task_queue=task_queue,
+ )
+ return CompactionProgress.model_validate(result)
+
+
+async def test_sweep_drains_every_page_and_aggregates_totals():
+ pages: dict[str | None, list[str]] = {None: ["a", "b"], "b": ["c"], "c": []}
+ compacted_batches: list[list[str]] = []
+
+ @activity.defn(name="select-checkpoint-compaction-batch")
+ async def select_mocked(input: SelectBatchInput) -> CompactionBatch:
+ return CompactionBatch(conversation_ids=pages[input.after_id])
+
+ @activity.defn(name="compact-checkpoint-conversations")
+ async def compact_mocked(input: CompactionBatch) -> CompactBatchResult:
+ compacted_batches.append(list(input.conversation_ids))
+ n = len(input.conversation_ids)
+ return CompactBatchResult(conversations_compacted=n, checkpoints_deleted=2 * n, blobs_deleted=3 * n)
+
+ progress = await _run_with_activities(select_mocked, compact_mocked, CompactionSweepInput(batch_size=2))
+
+ # Cursor follows the last id of each page, so pages are visited in order and the sweep stops
+ # once an empty page comes back.
+ assert compacted_batches == [["a", "b"], ["c"]]
+ assert progress.conversations_compacted == 3
+ assert progress.checkpoints_deleted == 6
+ assert progress.blobs_deleted == 9
+ assert progress.cursor == "c"
+
+
+async def test_sweep_with_nothing_to_compact_is_a_noop():
+ @activity.defn(name="select-checkpoint-compaction-batch")
+ async def select_empty(input: SelectBatchInput) -> CompactionBatch:
+ return CompactionBatch(conversation_ids=[])
+
+ @activity.defn(name="compact-checkpoint-conversations")
+ async def compact_never(input: CompactionBatch) -> CompactBatchResult:
+ raise AssertionError("compaction should not run when there is nothing to compact")
+
+ progress = await _run_with_activities(select_empty, compact_never, CompactionSweepInput())
+
+ assert progress.conversations_compacted == 0
+ assert progress.cursor is None
diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.py
index 2c4078dcabf1..257e12ca120b 100644
--- a/posthog/temporal/tests/ai/test_module_integrity.py
+++ b/posthog/temporal/tests/ai/test_module_integrity.py
@@ -25,6 +25,7 @@ class TestAITemporalModuleIntegrity:
"ResearchAgentWorkflow",
"SummarizeLLMTracesWorkflow",
"AnomalyInvestigationWorkflow",
+ "CheckpointCompactionWorkflow",
]
actual_workflow_names = [workflow.__name__ for workflow in ai.AI_WORKFLOWS]
assert len(actual_workflow_names) == len(expected_workflows), (
@@ -51,6 +52,8 @@ class TestAITemporalModuleIntegrity:
"process_research_agent_activity",
"summarize_llm_traces_activity",
"investigate_anomaly_activity",
+ "select_checkpoint_compaction_batch",
+ "compact_checkpoint_conversations",
]
actual_activity_names = [activity.__name__ for activity in ai.AI_ACTIVITIES]
assert len(actual_activity_names) == len(expected_activities), (