: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): schedule the checkpoint compaction sweep daily (#66323)
Paul D'Ambraf2040f0f9caf
diff --git a/docs/internal/dev-env-vars.md b/docs/internal/dev-env-vars.mdindex 3cdea4700270..98c8aeb0925c 100644--- a/docs/internal/dev-env-vars.md+++ b/docs/internal/dev-env-vars.md@@ -43,4 +43,6 @@ CLOUD_DEPLOYMENT=E2EDo **not** set `CLOUD_DEPLOYMENT=US` and unset `DEBUG` to get around the guard — unsetting `DEBUG` then trips the sandbox-provider guards (`docker` / `MODAL_DOCKER` require `DEBUG`), and you end up playing whack-a-mole between the two.Code that branches on the literal region (`get_instance_region()`, `region == "US"`) will see `"E2E"`; for region-specific work, override it per-test with `@override_settings(CLOUD_DEPLOYMENT="US")` (tests are exempt from the guard).+`COMPACT_IN_REGION` controls which Cloud region registers the daily AI checkpoint compaction schedule. It defaults to `US`; set it explicitly only when moving the rollout to another region.+See also [sandboxes-setup-guide.md](sandboxes-setup-guide.md) for the PostHog Code sandbox providers.diff --git a/ee/hogai/django_checkpoint/compaction.py b/ee/hogai/django_checkpoint/compaction.pyindex 08837c073869..519f7957302a 100644--- a/ee/hogai/django_checkpoint/compaction.py+++ b/ee/hogai/django_checkpoint/compaction.py@@ -181,9 +181,11 @@ def compact_conversation(thread_id: str) -> CompactionResult: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()+ namespaces = sorted(+ ConversationCheckpoint.objects.filter(thread_id=thread_id).values_list("checkpoint_ns", flat=True).distinct(),+ key=lambda checkpoint_ns: checkpoint_ns == "",)+ # Compact the root last so a partial failure leaves the conversation eligible for a later sweep.# 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:diff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.pyindex 987b2fbf86fb..81108fdacc3d 100644--- a/posthog/settings/base_variables.py+++ b/posthog/settings/base_variables.py@@ -45,6 +45,7 @@ Possible values:- `E2E` for **e2e tests**.- Unset for **self-hosted** environments."""+COMPACT_IN_REGION: str = get_from_env("COMPACT_IN_REGION", "US")SELF_CAPTURE: bool = get_from_env("SELF_CAPTURE", DEBUG and not DEMO, type_cast=str_to_bool)E2E_TESTING: bool = get_from_env("E2E_TESTING", False, type_cast=str_to_booldiff --git a/posthog/temporal/ai/checkpoint_compaction/activities.py b/posthog/temporal/ai/checkpoint_compaction/activities.pyindex 7549d797ce61..c39eaa1fe606 100644--- a/posthog/temporal/ai/checkpoint_compaction/activities.py+++ b/posthog/temporal/ai/checkpoint_compaction/activities.py@@ -9,7 +9,7 @@ from posthog.temporal.ai.checkpoint_compaction.types import ()from posthog.temporal.common.logger import get_write_only_logger-from ee.hogai.django_checkpoint.compaction import compact_thread, select_compactable_conversation_ids+from ee.hogai.django_checkpoint.compaction import compact_conversation, select_compactable_conversation_idsLOGGER = get_write_only_logger()@@ -34,7 +34,7 @@ async def compact_checkpoint_conversations(input: CompactionBatch) -> CompactBatblobs_deleted = 0for conversation_id in input.conversation_ids:try:- outcome = compact_thread(conversation_id)+ outcome = compact_conversation(conversation_id)except Exception:# One poison thread must not sink the whole batch (and with it the daily sweep).conversations_failed += 1diff --git a/posthog/temporal/ai/checkpoint_compaction/schedule.py b/posthog/temporal/ai/checkpoint_compaction/schedule.pynew file mode 100644index 000000000000..97284027d557--- /dev/null+++ b/posthog/temporal/ai/checkpoint_compaction/schedule.py@@ -0,0 +1,42 @@+from datetime import timedelta++from django.conf import settings++from temporalio.client import (+ Client,+ Schedule,+ ScheduleActionStartWorkflow,+ ScheduleIntervalSpec,+ ScheduleOverlapPolicy,+ SchedulePolicy,+ ScheduleSpec,+)++from posthog.temporal.ai.checkpoint_compaction.types import CompactionSweepInput+from posthog.temporal.ai.checkpoint_compaction.workflow import CheckpointCompactionWorkflow+from posthog.temporal.common.schedule import a_create_schedule, a_schedule_exists, a_update_schedule++CHECKPOINT_COMPACTION_SCHEDULE_ID = "checkpoint-compaction-sweep-schedule"+++def should_register_checkpoint_compaction_schedule() -> bool:+ return settings.CLOUD_DEPLOYMENT == settings.COMPACT_IN_REGION+++async def create_checkpoint_compaction_schedule(client: Client) -> None:+ schedule = Schedule(+ action=ScheduleActionStartWorkflow(+ CheckpointCompactionWorkflow.get_name(),+ CompactionSweepInput().model_dump(),+ id=CHECKPOINT_COMPACTION_SCHEDULE_ID,+ task_queue=settings.MAX_AI_TASK_QUEUE,+ ),+ spec=ScheduleSpec(intervals=[ScheduleIntervalSpec(every=timedelta(days=1))]),+ # A sweep can continue-as-new for a while; never let a slow run overlap the next day's.+ policy=SchedulePolicy(overlap=ScheduleOverlapPolicy.SKIP),+ )++ if await a_schedule_exists(client, CHECKPOINT_COMPACTION_SCHEDULE_ID):+ await a_update_schedule(client, CHECKPOINT_COMPACTION_SCHEDULE_ID, schedule)+ else:+ await a_create_schedule(client, CHECKPOINT_COMPACTION_SCHEDULE_ID, schedule, trigger_immediately=False)diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.pyindex f2de97a6c9e2..96ee5838c64f 100644--- a/posthog/temporal/schedule.py+++ b/posthog/temporal/schedule.py@@ -20,6 +20,10 @@ from temporalio.client import (ScheduleSpec,)+from posthog.temporal.ai.checkpoint_compaction.schedule import (+ create_checkpoint_compaction_schedule,+ should_register_checkpoint_compaction_schedule,+)from posthog.temporal.ai_observability.eval_reports.schedule import (create_count_trigger_schedule,create_eval_reports_schedule,@@ -838,6 +842,8 @@ if settings.CLOUD_DEPLOYMENT:schedules.append(create_replay_vision_gemini_cleanup_sweep_schedule)schedules.append(create_run_usage_reports_schedule)schedules.append(create_finalize_usage_reports_schedule)+ if should_register_checkpoint_compaction_schedule():+ schedules.append(create_checkpoint_compaction_schedule)if settings.EE_AVAILABLE:schedules.append(create_schedule_all_subscriptions_schedule)diff --git a/posthog/temporal/tests/ai/test_checkpoint_compaction_activities.py b/posthog/temporal/tests/ai/test_checkpoint_compaction_activities.pyindex fa22eef38407..1f78ebb586b6 100644--- a/posthog/temporal/tests/ai/test_checkpoint_compaction_activities.py+++ b/posthog/temporal/tests/ai/test_checkpoint_compaction_activities.py@@ -22,18 +22,28 @@ 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": {}},- )+ for checkpoint_ns in ("", "tools"):+ parent = None+ for _ in range(3):+ parent = ConversationCheckpoint.objects.create(+ thread=conversation,+ checkpoint_ns=checkpoint_ns,+ parent_checkpoint=parent,+ checkpoint={"channel_versions": {}},+ )Conversation.objects.filter(pk=conversation.id).update(updated_at=timezone.now() - timedelta(days=8))return conversation+@sync_to_async+def _checkpoint_namespaces(conversation_id: str) -> list[str]:+ return list(+ ConversationCheckpoint.objects.filter(thread_id=conversation_id)+ .order_by("checkpoint_ns")+ .values_list("checkpoint_ns", flat=True)+ )++async def test_select_then_compact_activities_end_to_end(ateam, auser, activity_environment):conversation = await sync_to_async(_seed_compactable)(ateam, auser)@@ -46,28 +56,28 @@ async def test_select_then_compact_activities_end_to_end(ateam, auser, activity_)assert result.conversations_compacted == 1- assert result.checkpoints_deleted == 2+ assert result.checkpoints_deleted == 4- remaining = await sync_to_async(ConversationCheckpoint.objects.filter(thread_id=conversation.id).count)()- assert remaining == 1+ remaining_namespaces = await _checkpoint_namespaces(str(conversation.id))+ assert remaining_namespaces == ["", "tools"]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+ real_compact_conversation = compaction.compact_conversation- def flaky_compact_thread(thread_id, *args, **kwargs):+ def flaky_compact_conversation(thread_id):if thread_id == str(poison.id):raise RuntimeError("boom")- return real_compact_thread(thread_id, *args, **kwargs)+ return real_compact_conversation(thread_id)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,+ "posthog.temporal.ai.checkpoint_compaction.activities.compact_conversation",+ side_effect=flaky_compact_conversation,),):result = await activity_environment.run(@@ -78,5 +88,5 @@ async def test_one_poison_thread_does_not_sink_the_batch(ateam, auser, activity_# The poison thread is counted and skipped; the healthy thread that follows it still compacts.assert result.conversations_failed == 1assert 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+ assert await sync_to_async(ConversationCheckpoint.objects.filter(thread_id=healthy.id).count)() == 2+ assert await sync_to_async(ConversationCheckpoint.objects.filter(thread_id=poison.id).count)() == 6diff --git a/posthog/temporal/tests/ai/test_checkpoint_compaction_schedule.py b/posthog/temporal/tests/ai/test_checkpoint_compaction_schedule.pynew file mode 100644index 000000000000..1c2c29e92e68--- /dev/null+++ b/posthog/temporal/tests/ai/test_checkpoint_compaction_schedule.py@@ -0,0 +1,24 @@+from django.test import override_settings++from parameterized import parameterized++from posthog.temporal.ai.checkpoint_compaction.schedule import should_register_checkpoint_compaction_schedule+++class TestCheckpointCompactionSchedule:+ @parameterized.expand(+ [+ ("US", "US", True),+ ("EU", "US", False),+ (None, "US", False),+ ("EU", "EU", True),+ ]+ )+ def test_registers_only_in_configured_cloud_region(+ self, cloud_deployment: str | None, compaction_region: str, expected: bool+ ) -> None:+ with override_settings(+ CLOUD_DEPLOYMENT=cloud_deployment,+ COMPACT_IN_REGION=compaction_region,+ ):+ assert should_register_checkpoint_compaction_schedule() is expected