: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(canvas): move canvas builds from Celery to Temporal behind a feature flag (#90020)
Peter Kirkhamc0a3fb2af448
diff --git a/.github/workflows/container-images-cd.yml b/.github/workflows/container-images-cd.ymlindex ccf1f99baf1c..6878f1f2cdd0 100644--- a/.github/workflows/container-images-cd.yml+++ b/.github/workflows/container-images-cd.yml@@ -474,7 +474,7 @@ jobs:- name: Check for changes that affect general purpose temporal workerid: check_changes_general_purpose_temporal_workerrun: |- if git diff --name-only HEAD^ HEAD | grep -qE '^products/exports/backend/temporal/subscriptions|^products/engineering_analytics/backend/|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/(ai_observability|llm_analytics)|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/delete_teams|^posthog/temporal/ingestion_acceptance_test|^posthog/temporal/backfill_group_type_created_at|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; then+ if git diff --name-only HEAD^ HEAD | grep -qE '^products/exports/backend/temporal/subscriptions|^products/engineering_analytics/backend/|^products/canvas/backend/|^posthog/temporal/common|^posthog/temporal/session_recordings|^posthog/temporal/proxy_service|^posthog/temporal/(ai_observability|llm_analytics)|^posthog/temporal/product_analytics|^posthog/temporal/delete_persons|^posthog/temporal/delete_teams|^posthog/temporal/ingestion_acceptance_test|^posthog/temporal/backfill_group_type_created_at|^posthog/management/commands/start_temporal_worker.py$|^pyproject.toml$|^bin/temporal-django-worker$|^posthog/clickhouse/migrations/'; thenecho "changed=true" >> $GITHUB_OUTPUTelseecho "changed=false" >> $GITHUB_OUTPUTdiff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.pyindex 620433bb193c..eb655cc43c6a 100644--- a/posthog/management/commands/start_temporal_worker.py+++ b/posthog/management/commands/start_temporal_worker.py@@ -163,6 +163,10 @@ from products.business_knowledge.backend.temporal import (ACTIVITIES as BUSINESS_KNOWLEDGE_ACTIVITIES,WORKFLOWS as BUSINESS_KNOWLEDGE_WORKFLOWS,)+from products.canvas.backend.temporal.registry import (+ ACTIVITIES as CANVAS_BUILD_ACTIVITIES,+ WORKFLOWS as CANVAS_BUILD_WORKFLOWS,+)from products.context_layer.backend.temporal import (ACTIVITIES as CONTEXT_LAYER_ACTIVITIES,WORKFLOWS as CONTEXT_LAYER_WORKFLOWS,@@ -365,6 +369,13 @@ _task_queue_specs = [GROWTH_WORKFLOWS,GROWTH_ACTIVITIES,),+ # Canvas builds. CANVAS_BUILD_TASK_QUEUE defaults to the general-purpose queue name (so it merges+ # into that fleet until a dedicated worker exists).+ (+ settings.CANVAS_BUILD_TASK_QUEUE,+ CANVAS_BUILD_WORKFLOWS,+ CANVAS_BUILD_ACTIVITIES,+ ),(settings.EXPERIMENTS_RECALCULATION_TASK_QUEUE,EXPERIMENTS_RECALCULATION_WORKFLOWS,diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.pyindex 2c829c6356dc..b03e9b639960 100644--- a/posthog/settings/temporal.py+++ b/posthog/settings/temporal.py@@ -212,6 +212,12 @@ GENERAL_PURPOSE_TASK_QUEUE = _set_temporal_task_queue("general-purpose-task-queuSIGNUP_ENRICHMENT_TASK_QUEUE = _set_temporal_task_queue(os.getenv("SIGNUP_ENRICHMENT_TASK_QUEUE", "general-purpose-task-queue"))+# Defaults to the general-purpose fleet so dispatch always has a live worker. Routing canvas+# builds to a dedicated, separately-scalable worker takes two steps in order: deploy a worker+# fleet polling "canvas-build-task-queue" (a charts change), then set this env on the+# dispatching services. Setting it first strands builds on a pollerless queue until the+# workflow execution timeout closes them.+CANVAS_BUILD_TASK_QUEUE = _set_temporal_task_queue(os.getenv("CANVAS_BUILD_TASK_QUEUE", "general-purpose-task-queue"))EXPERIMENTS_RECALCULATION_TASK_QUEUE = _set_temporal_task_queue("experiments-recalculation-task-queue")HEALTH_CHECK_TASK_QUEUE = _set_temporal_task_queue("health-check-task-queue")DUCKLAKE_TASK_QUEUE = _set_temporal_task_queue("ducklake-task-queue")diff --git a/products/canvas/backend/build_service.py b/products/canvas/backend/build_service.pyindex dafc0e280b77..71848b8e6305 100644--- a/products/canvas/backend/build_service.py+++ b/products/canvas/backend/build_service.py@@ -33,6 +33,7 @@ from django.db.models import Qfrom django.utils import timezoneimport structlog+import posthoganalyticsfrom prometheus_client import Counter, Gauge, Histogramfrom posthog.event_usage import groups@@ -69,6 +70,10 @@ MAX_ACTIVE_CANVAS_BUILDS_PER_TEAM = 20MAX_PINNED_BUILDS_PER_CANVAS = 10MAX_BUILD_ATTEMPTS = 3+# Rollout gate: flagged-in teams dispatch builds to Temporal instead of the shared+# long_running Celery queue. Evaluation failure keeps the Celery path.+CANVAS_BUILDS_ON_TEMPORAL_FLAG = "canvas-builds-on-temporal"+CANVAS_BUILD_OUTCOMES = Counter("posthog_canvas_build_outcomes_total", "Canvas build terminal outcomes", ["outcome", "code"])@@ -403,9 +408,39 @@ def _enqueue_build(build: CanvasBuild) -> None:from products.canvas.backend.tasks import process_canvas_build # noqa: PLC0415 — avoids a task/service import cycleCanvasBuild.objects.unscoped().filter(id=build.id).update(enqueued_at=timezone.now())+ if _dispatch_build_to_temporal(build):+ returnprocess_canvas_build.delay(build.team_id, str(build.id))+def _dispatch_build_to_temporal(build: CanvasBuild) -> bool:+ """Hand the build to Temporal when the team is flagged in; False falls back to Celery.++ Any failure (flag evaluation or workflow start) falls back, so a Temporal or+ flag-service outage degrades to the Celery path instead of dropping builds.+ """+ try:+ if not posthoganalytics.feature_enabled(+ CANVAS_BUILDS_ON_TEMPORAL_FLAG,+ str(build.team.uuid),+ only_evaluate_locally=False,+ send_feature_flag_events=False,+ ):+ return False+ except Exception:+ logger.exception("canvas_build_temporal_flag_check_failed", build_id=str(build.id))+ return False+ # Deferred so the Temporal client stays off the web/Celery import path when the flag is off.+ from products.canvas.backend.temporal.client import execute_canvas_build_workflow # noqa: PLC0415++ try:+ execute_canvas_build_workflow(build.team_id, str(build.id))+ except Exception:+ logger.exception("canvas_build_temporal_dispatch_failed", build_id=str(build.id))+ return False+ return True++def publish_source_project(canvas: Canvas,*,@@ -973,7 +1008,16 @@ def run_canvas_build(team_id: int, build_id: str) -> None:manifest=manifest,diagnostics=diagnostics,):- object_storage.delete_objects(uploaded_keys)+ # A lost race can mean another attempt of this SAME build finalized READY first+ # (its lease lapsed mid-upload and a redelivery overtook it). The artifact prefix+ # is deterministic per build id, so the winner's manifest references exactly these+ # keys — deleting them would break the ready build. Only clean up when the build+ # ended in a non-ready state (cancelled or superseded by a newer version).+ current_status = (+ CanvasBuild.objects.for_team(build.team_id).filter(id=build.id).values_list("status", flat=True).first()+ )+ if current_status != CanvasBuild.STATUS_READY:+ object_storage.delete_objects(uploaded_keys)CANVAS_BUILD_OUTCOMES.labels(outcome="failed", code="superseded_during_build").inc()returnCANVAS_BUILD_OUTCOMES.labels(outcome="ready", code="").inc()diff --git a/products/canvas/backend/temporal/__init__.py b/products/canvas/backend/temporal/__init__.pynew file mode 100644index 000000000000..bd777b1abefd--- /dev/null+++ b/products/canvas/backend/temporal/__init__.py@@ -0,0 +1,5 @@+"""Temporal workflow for canvas builds.++Dispatch is gated by the ``canvas-builds-on-temporal`` feature flag in+``build_service._enqueue_build``; the Celery task remains the fallback path.+"""diff --git a/products/canvas/backend/temporal/activities.py b/products/canvas/backend/temporal/activities.pynew file mode 100644index 000000000000..29ba20bfe63a--- /dev/null+++ b/products/canvas/backend/temporal/activities.py@@ -0,0 +1,27 @@+"""Temporal activity for running one canvas build.++The activity is a thin wrapper over ``build_service.run_canvas_build``, which owns the+whole build lifecycle (claiming, lease renewal, terminal states) and is idempotent:+finished builds are a no-op, so activity retries and duplicate deliveries are safe.+"""++from temporalio import activity++from posthog.dataclasses import frozen+from posthog.temporal.common.utils import asyncify+++@frozen+class CanvasBuildInput:+ team_id: int+ build_id: str+++@asyncify+def run_canvas_build_activity(input: CanvasBuildInput) -> None:+ from products.canvas.backend.build_service import ( # noqa: PLC0415 — keeps the heavy build service off the import path+ run_canvas_build,+ )++ run_canvas_build(input.team_id, input.build_id)diff --git a/products/canvas/backend/temporal/client.py b/products/canvas/backend/temporal/client.pynew file mode 100644index 000000000000..581b033a12cc--- /dev/null+++ b/products/canvas/backend/temporal/client.py@@ -0,0 +1,57 @@+"""Temporal client helper for starting the canvas build workflow.++Modeled on ``products/stamphog/backend/temporal/client.py``: a thin fire-and-forget+bridge from Django (``transaction.on_commit`` in the build service) into Temporal.+"""++import logging+from datetime import timedelta++from django.conf import settings++from asgiref.sync import async_to_sync+from temporalio.common import RetryPolicy, WorkflowIDReusePolicy+from temporalio.exceptions import WorkflowAlreadyStartedError++from posthog.temporal.common.client import async_connect++from products.canvas.backend.temporal.activities import CanvasBuildInput++logger = logging.getLogger(__name__)++CANVAS_BUILD_WORKFLOW = "canvas-build"++# Bounds the whole workflow so an execution stranded on a queue with no pollers closes+# instead of blocking its build forever: the sweeper's redelivery is a no-op while a+# workflow with the build's id is open (ALLOW_DUPLICATE only permits reuse after close).+# Sized past the activity's worst case (3 attempts x 330s start_to_close plus backoff).+CANVAS_BUILD_WORKFLOW_TIMEOUT = timedelta(minutes=20)+++@async_to_sync+async def execute_canvas_build_workflow(team_id: int, build_id: str) -> None:+ """Start the ``canvas-build`` workflow for a queued CanvasBuild.++ Fire-and-forget. The workflow id is the build id, so a duplicate dispatch (the+ sweeper re-delivering a stale queued build whose workflow is in fact alive) is a+ no-op while a workflow with that id runs; a sequential re-dispatch of the same+ build (the retry action) starts fresh under ALLOW_DUPLICATE.+ """+ client = await async_connect()+ try:+ await client.start_workflow(+ CANVAS_BUILD_WORKFLOW,+ CanvasBuildInput(team_id=team_id, build_id=build_id),+ id=f"canvas-build-{build_id}",+ id_reuse_policy=WorkflowIDReusePolicy.ALLOW_DUPLICATE,+ task_queue=settings.CANVAS_BUILD_TASK_QUEUE,+ execution_timeout=CANVAS_BUILD_WORKFLOW_TIMEOUT,+ # Retries live on the activity; a workflow retry would re-run a build whose+ # row run_canvas_build already moved to a terminal state.+ retry_policy=RetryPolicy(maximum_attempts=1),+ )+ except WorkflowAlreadyStartedError:+ logger.info(+ "canvas_build_workflow_already_running",+ extra={"team_id": team_id, "build_id": build_id},+ )diff --git a/products/canvas/backend/temporal/registry.py b/products/canvas/backend/temporal/registry.pynew file mode 100644index 000000000000..fe3557cd7609--- /dev/null+++ b/products/canvas/backend/temporal/registry.py@@ -0,0 +1,18 @@+"""Workflow and activity registration lists for the canvas build Temporal worker.++Stable import target for the worker wiring:+``from products.canvas.backend.temporal.registry import WORKFLOWS, ACTIVITIES``.+Imported directly (like ``backend.tasks`` for Celery) because canvas is not an+isolated product yet; once it is, this moves behind ``facade/temporal.py``.+"""++from __future__ import annotations++from products.canvas.backend.temporal.activities import run_canvas_build_activity+from products.canvas.backend.temporal.workflow import CanvasBuildWorkflow++WORKFLOWS = [CanvasBuildWorkflow]++ACTIVITIES = [run_canvas_build_activity]++__all__ = ["WORKFLOWS", "ACTIVITIES"]diff --git a/products/canvas/backend/temporal/workflow.py b/products/canvas/backend/temporal/workflow.pynew file mode 100644index 000000000000..3a52a5a42720--- /dev/null+++ b/products/canvas/backend/temporal/workflow.py@@ -0,0 +1,45 @@+"""Canvas build workflow: a single activity that runs the whole build.++Durable execution replaces the Celery-era recovery machinery: a lost dispatch or a+dead worker is retried by the Temporal server within the activity retry policy,+instead of waiting for the periodic sweeper to notice a stale ``enqueued_at``.+"""++from datetime import timedelta++import temporalio.workflow+from temporalio import workflow+from temporalio.common import RetryPolicy++from posthog.temporal.common.base import PostHogWorkflow++with temporalio.workflow.unsafe.imports_passed_through():+ from products.canvas.backend.temporal.activities import CanvasBuildInput, run_canvas_build_activity++# Mirrors the Celery task's time_limit=330: the build itself is bounded by a 45s+# sandbox execution timeout, the rest is object-storage reads and artifact uploads.+BUILD_ACTIVITY_TIMEOUT = timedelta(seconds=330)++# run_canvas_build handles build failures internally (terminal STATUS_FAILED rows) and+# only raises for infrastructure errors worth retrying, e.g. object-storage reads; it+# also caps total executions per build at MAX_BUILD_ATTEMPTS via attempt_count.+BUILD_ACTIVITY_RETRY_POLICY = RetryPolicy(+ maximum_attempts=3,+ initial_interval=timedelta(seconds=5),+ backoff_coefficient=2.0,+ maximum_interval=timedelta(minutes=1),+)++[email protected](name="canvas-build")+class CanvasBuildWorkflow(PostHogWorkflow):+ inputs_cls = CanvasBuildInput++ @workflow.run+ async def run(self, input: CanvasBuildInput) -> None:+ await workflow.execute_activity(+ run_canvas_build_activity,+ input,+ start_to_close_timeout=BUILD_ACTIVITY_TIMEOUT,+ retry_policy=BUILD_ACTIVITY_RETRY_POLICY,+ )diff --git a/products/canvas/backend/tests/test_build_service.py b/products/canvas/backend/tests/test_build_service.pyindex f6224573f630..c691da2c762a 100644--- a/products/canvas/backend/tests/test_build_service.py+++ b/products/canvas/backend/tests/test_build_service.py@@ -258,6 +258,29 @@ class TestRunCanvasBuild(BuildServiceBaseTest):assert build.status == CanvasBuild.STATUS_FAILEDassert self.canvas.published_build_id is None+ def test_losing_finalize_race_to_ready_winner_keeps_shared_artifacts(self) -> None:+ # Two attempts of the SAME build share the deterministic artifact prefix. When a+ # redelivered attempt finalizes READY while a stalled attempt is still uploading,+ # the loser must not delete the keys — the winner's manifest references them.+ build = self._publish()+ prefix = build_service.artifact_object_prefix(self.team.id, build.canvas_id, build.id)++ def winner_finalizes_mid_build(project: dict) -> dict:+ CanvasBuild.objects.unscoped().filter(id=build.id).update(+ status=CanvasBuild.STATUS_READY,+ artifact_object_prefix=prefix,+ finished_at=timezone.now(),+ lease_expires_at=None,+ )+ return _builder_result({"index.html": "<html></html>"})++ with patch.object(build_service, "run_cloud_builder", side_effect=winner_finalizes_mid_build):+ build_service.run_canvas_build(self.team.id, str(build.id))++ assert self.storage.objects[f"{prefix}/index.html"] == b"<html></html>"+ build.refresh_from_db()+ assert build.status == CanvasBuild.STATUS_READY+@parameterized.expand([("ready", _builder_result({"index.html": "<html></html>"}), []),@@ -288,6 +311,38 @@ class TestRunCanvasBuild(BuildServiceBaseTest):assert properties["build_id"] == str(build.id)+class TestBuildDispatch(BuildServiceBaseTest):+ def test_flagged_in_team_dispatches_to_temporal_instead_of_celery(self) -> None:+ with (+ patch.object(build_service.posthoganalytics, "feature_enabled", return_value=True),+ patch("products.canvas.backend.temporal.client.execute_canvas_build_workflow") as start_workflow,+ self.captureOnCommitCallbacks(execute=True),+ ):+ build = self._publish()+ start_workflow.assert_called_once_with(self.team.id, str(build.id))+ self.enqueue.assert_not_called()++ @parameterized.expand(+ [+ ("flag_check_fails", RuntimeError("flag service down"), None),+ ("workflow_start_fails", True, RuntimeError("temporal down")),+ ]+ )+ def test_temporal_failure_falls_back_to_celery(+ self, _name: str, flag_result: bool | Exception, workflow_error: Exception | None+ ) -> None:+ with (+ patch.object(build_service.posthoganalytics, "feature_enabled", side_effect=[flag_result]),+ patch(+ "products.canvas.backend.temporal.client.execute_canvas_build_workflow",+ side_effect=workflow_error,+ ),+ self.captureOnCommitCallbacks(execute=True),+ ):+ build = self._publish()+ self.enqueue.assert_called_once_with(self.team.id, str(build.id))++class TestSweeper(BuildServiceBaseTest):def test_lease_expired_building_is_requeued_then_failed(self):build = self._publish()diff --git a/tach.toml b/tach.tomlindex 29362e49c3ea..4c47f3239b39 100644--- a/tach.toml+++ b/tach.toml@@ -886,6 +886,10 @@ expose = ["backend\\.teaching.*","backend\\.artifacts.*","backend\\.tasks.*",+ # Temporal wiring the worker registers (start_temporal_worker.py) — the+ # canvas analog of the backend.tasks Celery registration above. Canvas is+ # not isolated yet, so this stays a legacy leak rather than a facade expose.+ "backend\\.temporal\\.registry.*",]from = ["products.canvas",