: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(posthog-ai): backfill LangGraph conversations into tasks (#101961)
Jake Ruth211beba7e5d6
diff --git a/posthog/management/commands/execute_temporal_workflow.py b/posthog/management/commands/execute_temporal_workflow.pyindex 9181f504c16b..f9585134c95d 100644--- a/posthog/management/commands/execute_temporal_workflow.py+++ b/posthog/management/commands/execute_temporal_workflow.py@@ -31,6 +31,7 @@ from posthog.temporal.weekly_digest import WORKFLOWS as WEEKLY_DIGEST_WORKFLOWSfrom products.batch_exports.backend.temporal import WORKFLOWS as BATCH_EXPORT_WORKFLOWSfrom products.error_tracking.backend.facade.temporal import WORKFLOWS as ERROR_TRACKING_WORKFLOWSfrom products.logs.backend.temporal.retention_entitlements import WORKFLOWS as LOGS_RETENTION_ENTITLEMENTS_WORKFLOWS+from products.posthog_ai.backend.temporal.backfill import WORKFLOWS as CONVERSATION_BACKFILL_WORKFLOWSfrom products.warehouse_sources.backend.facade.temporal import WORKFLOWS as DATA_IMPORT_WORKFLOWSfrom products.web_analytics.backend.temporal import WORKFLOWS as WA_DIGEST_WORKFLOWS@@ -144,6 +145,7 @@ class Command(BaseCommand):+ USAGE_REPORTS_WORKFLOWS+ QUOTA_LIMITING_WORKFLOWS+ AI_WORKFLOWS+ + CONVERSATION_BACKFILL_WORKFLOWS+ SALESFORCE_ENRICHMENT_WORKFLOWS+ TEST_WORKFLOWS+ DELETE_RECORDINGS_WORKFLOWSdiff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 5130ba4ee328..0577260ab5e7 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -239,6 +239,10 @@ from products.notebooks.backend.facade.temporal import (ACTIVITIES as NOTEBOOKS_ACTIVITIES,WORKFLOWS as NOTEBOOKS_WORKFLOWS,)+from products.posthog_ai.backend.temporal.backfill import (+ ACTIVITIES as CONVERSATION_BACKFILL_ACTIVITIES,+ WORKFLOWS as CONVERSATION_BACKFILL_WORKFLOWS,+)from products.product_analytics.backend.facade.temporal import (ACTIVITIES as PRODUCT_ANALYTICS_ACTIVITIES,WORKFLOWS as PRODUCT_ANALYTICS_WORKFLOWS,@@ -349,6 +353,7 @@ _task_queue_specs = [+ CLEANUP_PROPDEFS_WORKFLOWS+ [BackfillMaterializedPropertiesBatchWorkflow]+ BACKFILL_GROUP_TYPE_CREATED_AT_WORKFLOWS+ + CONVERSATION_BACKFILL_WORKFLOWS+ INGESTION_ACCEPTANCE_TEST_WORKFLOWS+ WAREHOUSE_SOURCES_QUEUE_PARTITION_WORKFLOWS+ SYNC_EVENTS_RETENTION_WORKFLOWS@@ -373,6 +378,7 @@ _task_queue_specs = [+ CLEANUP_PROPDEFS_ACTIVITIES+ BACKFILL_MATERIALIZED_PROPERTY_ACTIVITIES+ BACKFILL_GROUP_TYPE_CREATED_AT_ACTIVITIES+ + CONVERSATION_BACKFILL_ACTIVITIES+ INGESTION_ACCEPTANCE_TEST_ACTIVITIES+ WAREHOUSE_SOURCES_QUEUE_PARTITION_ACTIVITIES+ SYNC_EVENTS_RETENTION_ACTIVITIESdiff --git a/posthog/management/commands/start_temporal_workflow.py b/posthog/management/commands/start_temporal_workflow.pyindex def6545cd094..ad19107fba04 100644--- a/posthog/management/commands/start_temporal_workflow.py+++ b/posthog/management/commands/start_temporal_workflow.py@@ -31,6 +31,7 @@ from posthog.temporal.weekly_digest import WORKFLOWS as WEEKLY_DIGEST_WORKFLOWSfrom products.batch_exports.backend.temporal import WORKFLOWS as BATCH_EXPORT_WORKFLOWSfrom products.error_tracking.backend.facade.temporal import WORKFLOWS as ERROR_TRACKING_WORKFLOWSfrom products.logs.backend.temporal.retention_entitlements import WORKFLOWS as LOGS_RETENTION_ENTITLEMENTS_WORKFLOWS+from products.posthog_ai.backend.temporal.backfill import WORKFLOWS as CONVERSATION_BACKFILL_WORKFLOWSfrom products.warehouse_sources.backend.facade.temporal import WORKFLOWS as DATA_IMPORT_WORKFLOWSfrom products.web_analytics.backend.temporal import WORKFLOWS as WA_DIGEST_WORKFLOWS@@ -144,6 +145,7 @@ class Command(BaseCommand):+ USAGE_REPORTS_WORKFLOWS+ QUOTA_LIMITING_WORKFLOWS+ AI_WORKFLOWS+ + CONVERSATION_BACKFILL_WORKFLOWS+ SALESFORCE_ENRICHMENT_WORKFLOWS+ SYNC_PERSON_DISTINCT_IDS_WORKFLOWS+ TEST_WORKFLOWSdiff --git a/products/posthog_ai/backend/temporal/activities.py b/products/posthog_ai/backend/temporal/activities.pyindex 71d576a136e4..ea5ff47184bd 100644--- a/products/posthog_ai/backend/temporal/activities.py+++ b/products/posthog_ai/backend/temporal/activities.py@@ -20,8 +20,14 @@ class MirrorConversationInputs:conversation_id: str+@dataclass(frozen=True)+class MirrorActivityResult:+ skipped_reason: str | None+ appended_frames: int++@activity.defn-async def mirror_conversation_to_task_activity(inputs: MirrorConversationInputs) -> None:+async def mirror_conversation_to_task_activity(inputs: MirrorConversationInputs) -> MirrorActivityResult:team = await Team.objects.aget(id=inputs.team_id)user = await User.objects.aget(id=inputs.user_id)if not await sync_to_async(has_conversation_task_mirror_feature_flag)(team, user):@@ -34,3 +40,4 @@ async def mirror_conversation_to_task_activity(inputs: MirrorConversationInputs)skipped_reason=result.skipped_reason,appended_frames=result.appended_frames,)+ return MirrorActivityResult(skipped_reason=result.skipped_reason, appended_frames=result.appended_frames)diff --git a/products/posthog_ai/backend/temporal/backfill.py b/products/posthog_ai/backend/temporal/backfill.pynew file mode 100644index 000000000000..cb9ffa965417--- /dev/null+++ b/products/posthog_ai/backend/temporal/backfill.py@@ -0,0 +1,213 @@+"""Backfill loop: walk every LangGraph conversation that has no task and copy it into one.++The conversation table is the progress table: a copied conversation gets a task, so "not done" is+"no task". The loop carries only a cursor and counters, and continues as new after every page so+history never grows. A restart from the top is correct, just slower; pass `start_after` to resume+from the last cursor the loop logged.+"""++import asyncio+from dataclasses import replace+from datetime import timedelta++from temporalio import activity, workflow+from temporalio.common import RetryPolicy+from temporalio.exceptions import is_cancelled_exception++from posthog.dataclasses import frozen+from posthog.sync import database_sync_to_async+from posthog.temporal.common.base import PostHogWorkflow++from products.posthog_ai.backend.models.assistant import Conversation+from products.posthog_ai.backend.temporal.activities import (+ MirrorActivityResult,+ MirrorConversationInputs,+ mirror_conversation_to_task_activity,+)++BACKFILL_WORKFLOW_NAME = "backfill-conversation-tasks"++LIST_ACTIVITY_TIMEOUT = timedelta(seconds=60)+COPY_ACTIVITY_TIMEOUT = timedelta(minutes=5)+ACTIVITY_RETRY_POLICY = RetryPolicy(maximum_attempts=3)+# One page of ids crosses the activity boundary as a Temporal payload, and each copy adds a+# handful of history events, so the page also bounds the history of one run.+MIN_BATCH_SIZE = 1+MAX_BATCH_SIZE = 2000+MIN_CONCURRENCY = 1+MAX_CONCURRENCY = 200+FLAG_OFF_REASON = "flag"+++@frozen+class ConversationBackfillInputs:+ start_after: str | None = None+ batch_size: int = 500+ concurrency: int = 16+ dry_run: bool = False+ pause_seconds: float = 0.0+ seen: int = 0+ copied: int = 0+ skipped: int = 0+ failed: int = 0+++@frozen+class BackfillCandidate:+ conversation_id: str+ team_id: int+ user_id: int+++@frozen+class ListCandidatesInputs:+ start_after: str | None+ limit: int+++@frozen+class ListCandidatesOutput:+ candidates: list[BackfillCandidate]+ next_cursor: str | None+ exhausted: bool+++@frozen+class ConversationBackfillSummary:+ seen: int+ copied: int+ skipped: int+ failed: int+ last_cursor: str | None+ # "exhausted" when the walk reached the end, "kill_switch" when every copy in a page was+ # refused by the flag.+ stopped_because: str+++def list_candidates(inputs: ListCandidatesInputs) -> ListCandidatesOutput:+ queryset = Conversation.objects.filter(+ agent_runtime=Conversation.AgentRuntime.LANGGRAPH,+ type=Conversation.Type.ASSISTANT,+ task_id__isnull=True,+ deleted=False,+ is_internal=False,+ )+ if inputs.start_after is not None:+ queryset = queryset.filter(id__gt=inputs.start_after)+ # The primary key index already orders the walk; ordering by anything else sorts every+ # remaining row on each page.+ rows = list(queryset.order_by("id").values_list("id", "team_id", "user_id")[: inputs.limit])+ candidates = [+ BackfillCandidate(conversation_id=str(conversation_id), team_id=team_id, user_id=user_id)+ for conversation_id, team_id, user_id in rows+ ]+ next_cursor = candidates[-1].conversation_id if candidates else inputs.start_after+ return ListCandidatesOutput(candidates=candidates, next_cursor=next_cursor, exhausted=len(rows) < inputs.limit)+++async def list_conversations_to_backfill_activity(inputs: ListCandidatesInputs) -> ListCandidatesOutput:+ return await database_sync_to_async(list_candidates, thread_sensitive=False)(inputs)++[email protected](name=BACKFILL_WORKFLOW_NAME)+class ConversationBackfillWorkflow(PostHogWorkflow):+ inputs_cls = ConversationBackfillInputs++ @workflow.run+ async def run(self, inputs: ConversationBackfillInputs) -> ConversationBackfillSummary:+ batch_size = min(max(inputs.batch_size, MIN_BATCH_SIZE), MAX_BATCH_SIZE)+ concurrency = min(max(inputs.concurrency, MIN_CONCURRENCY), MAX_CONCURRENCY)++ page = await workflow.execute_activity(+ list_conversations_to_backfill_activity,+ ListCandidatesInputs(start_after=inputs.start_after, limit=batch_size),+ start_to_close_timeout=LIST_ACTIVITY_TIMEOUT,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )++ copied = skipped = failed = 0+ flag_off = 0+ if page.candidates and not inputs.dry_run:+ results = await self._copy_page(page.candidates, concurrency)+ for candidate, result in zip(page.candidates, results):+ if isinstance(result, BaseException):+ if is_cancelled_exception(result):+ raise result+ failed += 1+ workflow.logger.warning(+ "conversation_backfill.copy_failed",+ extra={"conversation_id": candidate.conversation_id, "error": str(result)[:500]},+ )+ elif result.skipped_reason is None:+ copied += 1+ else:+ skipped += 1+ flag_off += result.skipped_reason == FLAG_OFF_REASON++ progress = replace(+ inputs,+ start_after=page.next_cursor,+ seen=inputs.seen + len(page.candidates),+ copied=inputs.copied + copied,+ skipped=inputs.skipped + skipped,+ failed=inputs.failed + failed,+ )+ workflow.logger.info(+ "conversation_backfill.page_done",+ extra={+ "cursor": progress.start_after,+ "page_size": len(page.candidates),+ "seen": progress.seen,+ "copied": progress.copied,+ "skipped": progress.skipped,+ "failed": progress.failed,+ "dry_run": inputs.dry_run,+ },+ )++ # A page where the flag refused every copy means the kill switch is off. Walking on+ # would read every remaining conversation for nothing.+ if page.candidates and flag_off == len(page.candidates):+ return self._summary(progress, "kill_switch")+ if page.exhausted:+ return self._summary(progress, "exhausted")++ if inputs.pause_seconds > 0:+ await workflow.sleep(timedelta(seconds=inputs.pause_seconds))+ workflow.continue_as_new(progress)++ async def _copy_page(+ self, candidates: list[BackfillCandidate], concurrency: int+ ) -> list[MirrorActivityResult | BaseException]:+ slots = asyncio.Semaphore(concurrency)++ async def copy(candidate: BackfillCandidate) -> MirrorActivityResult:+ async with slots:+ return await workflow.execute_activity(+ mirror_conversation_to_task_activity,+ MirrorConversationInputs(+ team_id=candidate.team_id,+ user_id=candidate.user_id,+ conversation_id=candidate.conversation_id,+ ),+ start_to_close_timeout=COPY_ACTIVITY_TIMEOUT,+ retry_policy=ACTIVITY_RETRY_POLICY,+ )++ return await asyncio.gather(*(copy(candidate) for candidate in candidates), return_exceptions=True)++ @staticmethod+ def _summary(progress: ConversationBackfillInputs, stopped_because: str) -> ConversationBackfillSummary:+ return ConversationBackfillSummary(+ seen=progress.seen,+ copied=progress.copied,+ skipped=progress.skipped,+ failed=progress.failed,+ last_cursor=progress.start_after,+ stopped_because=stopped_because,+ )+++WORKFLOWS = [ConversationBackfillWorkflow]+ACTIVITIES = [list_conversations_to_backfill_activity, mirror_conversation_to_task_activity]diff --git a/products/posthog_ai/backend/tests/test_conversation_backfill.py b/products/posthog_ai/backend/tests/test_conversation_backfill.pynew file mode 100644index 000000000000..3637fe7ad3d8--- /dev/null+++ b/products/posthog_ai/backend/tests/test_conversation_backfill.py@@ -0,0 +1,189 @@+import uuid+import asyncio+from dataclasses import dataclass, field++import pytest+from posthog.test.base import APIBaseTest++from temporalio import activity+from temporalio.exceptions import ApplicationError+from temporalio.testing import WorkflowEnvironment+from temporalio.worker import UnsandboxedWorkflowRunner, Worker++from products.posthog_ai.backend.models.assistant import Conversation+from products.posthog_ai.backend.temporal.activities import MirrorActivityResult, MirrorConversationInputs+from products.posthog_ai.backend.temporal.backfill import (+ BackfillCandidate,+ ConversationBackfillInputs,+ ConversationBackfillWorkflow,+ ListCandidatesInputs,+ ListCandidatesOutput,+ list_candidates,+)+from products.tasks.backend.models import Task+++class TestListCandidates(APIBaseTest):+ def _conversation(self, **overrides) -> Conversation:+ fields = {"user": self.user, "team": self.team, "agent_runtime": Conversation.AgentRuntime.LANGGRAPH}+ fields.update(overrides)+ return Conversation.objects.create(**fields)++ def _page(self, start_after: str | None = None, limit: int = 10) -> ListCandidatesOutput:+ return list_candidates(ListCandidatesInputs(start_after=start_after, limit=limit))++ def test_lists_only_langgraph_assistant_chats_without_a_task(self) -> None:+ eligible = self._conversation()+ task = Task.objects.create(+ team=self.team, title="t", description="", origin_product=Task.OriginProduct.POSTHOG_AI+ )+ self._conversation(task=task)+ self._conversation(agent_runtime=Conversation.AgentRuntime.SANDBOX)+ self._conversation(deleted=True)+ self._conversation(is_internal=True)+ self._conversation(type=Conversation.Type.TOOL_CALL)++ page = self._page()++ assert page.candidates == [+ BackfillCandidate(conversation_id=str(eligible.id), team_id=self.team.id, user_id=self.user.id)+ ]+ assert page.next_cursor == str(eligible.id)+ assert page.exhausted is True++ def test_pages_in_id_order_from_the_cursor(self) -> None:+ ids = sorted(str(self._conversation().id) for _ in range(3))++ first = self._page(limit=2)+ assert [c.conversation_id for c in first.candidates] == ids[:2]+ assert first.next_cursor == ids[1]+ assert first.exhausted is False++ second = self._page(start_after=first.next_cursor, limit=2)+ assert [c.conversation_id for c in second.candidates] == ids[2:]+ assert second.exhausted is True++ empty = self._page(start_after=second.next_cursor, limit=2)+ assert empty.candidates == []+ assert empty.next_cursor == ids[2]+ assert empty.exhausted is True+++@dataclass(frozen=False)+class FakeCopies:+ pages: list[list[str]]+ # conversation id -> "copied" | a skipped reason | "error"+ outcomes: dict[str, str] = field(default_factory=dict)+ copied_ids: list[str] = field(default_factory=list)+ in_flight: int = 0+ max_in_flight: int = 0++ def activities(self) -> list:+ fake = self++ @activity.defn(name="list_conversations_to_backfill_activity")+ async def list_activity(inputs: ListCandidatesInputs) -> ListCandidatesOutput:+ page_index = 0 if inputs.start_after is None else fake._page_after(inputs.start_after)+ ids = fake.pages[page_index] if page_index < len(fake.pages) else []+ candidates = [BackfillCandidate(conversation_id=i, team_id=1, user_id=1) for i in ids]+ return ListCandidatesOutput(+ candidates=candidates,+ next_cursor=ids[-1] if ids else inputs.start_after,+ exhausted=len(ids) < inputs.limit,+ )++ @activity.defn(name="mirror_conversation_to_task_activity")+ async def copy_activity(inputs: MirrorConversationInputs) -> MirrorActivityResult:+ fake.in_flight += 1+ fake.max_in_flight = max(fake.max_in_flight, fake.in_flight)+ try:+ await asyncio.sleep(0.01)+ fake.copied_ids.append(inputs.conversation_id)+ outcome = fake.outcomes.get(inputs.conversation_id, "copied")+ if outcome == "error":+ raise ApplicationError("boom", non_retryable=True)+ if outcome == "copied":+ return MirrorActivityResult(skipped_reason=None, appended_frames=2)+ return MirrorActivityResult(skipped_reason=outcome, appended_frames=0)+ finally:+ fake.in_flight -= 1++ return [list_activity, copy_activity]++ def _page_after(self, cursor: str) -> int:+ for index, page in enumerate(self.pages):+ if page and page[-1] == cursor:+ return index + 1+ return len(self.pages)+++async def _run(fake: FakeCopies, inputs: ConversationBackfillInputs):+ async with (+ await WorkflowEnvironment.start_time_skipping() as env,+ Worker(+ env.client,+ task_queue="backfill-test",+ workflows=[ConversationBackfillWorkflow],+ activities=fake.activities(),+ workflow_runner=UnsandboxedWorkflowRunner(),+ ),+ ):+ return await env.client.execute_workflow(+ ConversationBackfillWorkflow.run,+ inputs,+ id=str(uuid.uuid4()),+ task_queue="backfill-test",+ )+++async def test_walks_every_page_and_counts_each_outcome() -> None:+ fake = FakeCopies(pages=[["a", "b"], ["c", "d"], ["e"]], outcomes={"b": "no_messages", "d": "error"})++ summary = await _run(fake, ConversationBackfillInputs(batch_size=2, concurrency=2))++ assert sorted(fake.copied_ids) == ["a", "b", "c", "d", "e"]+ assert (summary.seen, summary.copied, summary.skipped, summary.failed) == (5, 3, 1, 1)+ assert summary.last_cursor == "e"+ assert summary.stopped_because == "exhausted"+++async def test_keeps_at_most_concurrency_copies_in_flight() -> None:+ fake = FakeCopies(pages=[["a", "b", "c", "d", "e", "f"]])++ await _run(fake, ConversationBackfillInputs(batch_size=6, concurrency=2))++ assert fake.max_in_flight == 2+++async def test_dry_run_reads_pages_but_copies_nothing() -> None:+ fake = FakeCopies(pages=[["a", "b"], ["c"]])++ summary = await _run(fake, ConversationBackfillInputs(batch_size=2, dry_run=True))++ assert fake.copied_ids == []+ assert (summary.seen, summary.copied) == (3, 0)+ assert summary.stopped_because == "exhausted"+++async def test_stops_when_the_kill_switch_refuses_a_whole_page() -> None:+ fake = FakeCopies(pages=[["a", "b"], ["c", "d"]], outcomes={"a": "flag", "b": "flag"})++ summary = await _run(fake, ConversationBackfillInputs(batch_size=2))++ assert sorted(fake.copied_ids) == ["a", "b"]+ assert summary.stopped_because == "kill_switch"+ assert summary.last_cursor == "b"+++async def test_resumes_from_the_given_cursor() -> None:+ fake = FakeCopies(pages=[["a", "b"], ["c", "d"]])++ summary = await _run(fake, ConversationBackfillInputs(start_after="b", batch_size=2))++ assert sorted(fake.copied_ids) == ["c", "d"]+ assert summary.seen == 2