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(deployments): add real TemporalWorkflowAdapter (#58581)

Richard Solomou7087efcd1039
diff --git a/products/deployments/backend/adapters/__init__.py b/products/deployments/backend/adapters/__init__.py
index 217b7d71f610..5d7d6c0ac39a 100644
--- a/products/deployments/backend/adapters/__init__.py
+++ b/products/deployments/backend/adapters/__init__.py
@@ -21,7 +21,7 @@ from .cloudflare import (
)
from .github import GitHubAdapter, GitHubBranch, GitHubError, GitHubRepository, NullGitHubAdapter, get_github_adapter
from .microlink import NullScreenshotAdapter, ScreenshotAdapter, get_screenshot_adapter
-from .temporal import NullWorkflowAdapter, WorkflowAdapter, WorkflowError, get_workflow_adapter
+from .temporal import NullWorkflowAdapter, TemporalWorkflowAdapter, WorkflowAdapter, WorkflowError, get_workflow_adapter
__all__ = [
"CloudflareAdapter",
@@ -36,6 +36,7 @@ __all__ = [
"NullScreenshotAdapter",
"NullWorkflowAdapter",
"ScreenshotAdapter",
+ "TemporalWorkflowAdapter",
"WorkflowAdapter",
"WorkflowError",
"get_cloudflare_adapter",
diff --git a/products/deployments/backend/adapters/temporal.py b/products/deployments/backend/adapters/temporal.py
index fc34f5817622..dba56d547441 100644
--- a/products/deployments/backend/adapters/temporal.py
+++ b/products/deployments/backend/adapters/temporal.py
@@ -1,8 +1,8 @@
"""Temporal workflow adapter boundary.
-Build/Infra stream owns the real implementation (a thin wrapper around
-the Temporal Python SDK). We declare the Protocol they implement against
-and a Null stub for tests.
+Declares the Protocol the rest of the product depends on, a Null stub
+for tests and dev, and `TemporalWorkflowAdapter` — the real implementation
+that talks to a Temporal cluster.
We only ever:
- Start a build workflow when a Deployment is created (one `start_build`
@@ -16,14 +16,30 @@ internal API — we never poll Temporal.
from __future__ import annotations
+import asyncio
from dataclasses import dataclass
from importlib import import_module
from typing import Protocol
from django.conf import settings
+import structlog
+from temporalio.client import WorkflowHandle as TemporalWorkflowHandle
+from temporalio.common import RetryPolicy
+from temporalio.service import RPCError, RPCStatusCode
+
+from posthog.temporal.common.client import sync_connect
+
from ..domain.contracts import BuildInput
+# Workflow type name registered by the deployments Temporal worker. The
+# worker chart isn't deployed yet; flipping `DEPLOYMENTS_WORKFLOW_ADAPTER`
+# to this adapter before that lands means workflows get queued and sit
+# unprocessed until the worker comes online.
+DEPLOYMENT_BUILD_WORKFLOW = "deployment-build"
+
+logger = structlog.get_logger(__name__)
+
@dataclass(frozen=True)
class WorkflowHandle:
@@ -55,7 +71,95 @@ class NullWorkflowAdapter:
return None
+class TemporalWorkflowAdapter:
+ """Workflow adapter backed by the real Temporal cluster.
+
+ Inert until both:
+ - `DEPLOYMENTS_WORKFLOW_ADAPTER` env var points at this class
+ (otherwise `get_workflow_adapter()` returns the Null stub).
+ - A deployments Temporal worker is running on `DEPLOYMENTS_TASK_QUEUE`
+ and has registered the `deployment-build` workflow type.
+
+ Until the worker lands, flipping the env var still "works" — workflows
+ get queued and sit unprocessed. That's a useful intermediate state
+ for observability, not a regression.
+
+ `start_build` is called synchronously from the public POST handler,
+ so we use `sync_connect` + `asyncio.run` rather than async views.
+ Same pattern as `posthog/api/proxy_record.py`.
+ """
+
+ def _task_queue(self) -> str:
+ task_queue = getattr(settings, "DEPLOYMENTS_TASK_QUEUE", "")
+ if not task_queue:
+ raise WorkflowError("TemporalWorkflowAdapter is missing setting: DEPLOYMENTS_TASK_QUEUE.")
+ return task_queue
+
+ def _max_attempts(self) -> int:
+ # Temporal-level retry budget for the workflow itself. Activity
+ # retries inside the workflow are configured separately by the
+ # worker. Defaults to the cluster-wide setting so this matches
+ # the rest of PostHog's Temporal usage.
+ return int(getattr(settings, "TEMPORAL_WORKFLOW_MAX_ATTEMPTS", "3"))
+
+ def start_build(self, *, workflow_input: BuildInput) -> WorkflowHandle:
+ task_queue = self._task_queue()
+ max_attempts = self._max_attempts()
+ workflow_id = f"deployment-{workflow_input.deployment_id}"
+
+ try:
+ client = sync_connect()
+ handle: TemporalWorkflowHandle = asyncio.run(
+ client.start_workflow(
+ DEPLOYMENT_BUILD_WORKFLOW,
+ workflow_input,
+ id=workflow_id,
+ task_queue=task_queue,
+ retry_policy=RetryPolicy(maximum_attempts=max_attempts),
+ )
+ )
+ except RPCError as err:
+ logger.warning("temporal_start_workflow_failed", workflow_id=workflow_id, error=str(err))
+ raise WorkflowError(f"Failed to start deployment workflow: {err}") from err
+
+ run_id = handle.result_run_id or handle.first_execution_run_id or ""
+ if not run_id:
+ # Temporal always returns one of these; the empty fallback
+ # exists so the caller's persist step has something to write,
+ # not because we expect to hit it.
+ logger.warning("temporal_start_workflow_no_run_id", workflow_id=workflow_id)
+ return WorkflowHandle(workflow_id=workflow_id, run_id=run_id)
+
+ def signal_cancel(self, *, workflow_id: str) -> None:
+ try:
+ client = sync_connect()
+
+ async def _cancel() -> None:
+ handle = client.get_workflow_handle(workflow_id)
+ await handle.cancel()
+
+ asyncio.run(_cancel())
+ except RPCError as err:
+ # Workflow already finished or doesn't exist → not an error
+ # from the user's perspective; the cancel is a no-op. Match
+ # on the structured status code rather than the message text,
+ # which can vary across SDK versions or locales. Other RPC
+ # failures bubble up so the viewset can surface them.
+ if err.status == RPCStatusCode.NOT_FOUND:
+ logger.info("temporal_cancel_workflow_not_found", workflow_id=workflow_id)
+ return
+ logger.warning("temporal_cancel_workflow_failed", workflow_id=workflow_id, error=str(err))
+ raise WorkflowError(f"Failed to cancel deployment workflow: {err}") from err
+
+
def get_workflow_adapter() -> WorkflowAdapter:
+ """Resolve the adapter implementation from settings.
+
+ Reads `settings.DEPLOYMENTS_WORKFLOW_ADAPTER` as a `"module.path:ClassName"`
+ string; if unset, returns `NullWorkflowAdapter`. Wire the real
+ implementation in by setting this env var to
+ `products.deployments.backend.adapters.temporal:TemporalWorkflowAdapter`.
+ """
path = getattr(settings, "DEPLOYMENTS_WORKFLOW_ADAPTER", None)
if not path:
return NullWorkflowAdapter()
diff --git a/products/deployments/backend/test/test_temporal_adapter.py b/products/deployments/backend/test/test_temporal_adapter.py
new file mode 100644
index 000000000000..7514545d71ba
--- /dev/null
+++ b/products/deployments/backend/test/test_temporal_adapter.py
@@ -0,0 +1,135 @@
+from __future__ import annotations
+
+from uuid import UUID
+
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from django.test import SimpleTestCase, override_settings
+
+from parameterized import parameterized
+from temporalio.service import RPCError, RPCStatusCode
+
+from products.deployments.backend.adapters.temporal import (
+ DEPLOYMENT_BUILD_WORKFLOW,
+ TemporalWorkflowAdapter,
+ WorkflowError,
+)
+from products.deployments.backend.domain.contracts import BuildInput
+from products.deployments.backend.domain.trigger import TriggerKind
+
+BUILD_INPUT = BuildInput(
+ deployment_id=UUID("00000000-0000-7000-8000-000000000001"),
+ project_id=UUID("00000000-0000-7000-8000-000000000002"),
+ team_id=1,
+ repo_url="https://github.com/example/repo",
+ branch="main",
+ commit_sha="abc123",
+ github_access_token=None,
+ build_command=None,
+ output_dir="dist",
+ framework=None,
+ inject_posthog_snippet=False,
+ cloudflare_project_name="hogdev-1-myapp",
+ trigger_kind=TriggerKind.GIT,
+)
+
+
+def _make_rpc_error(message: str, status: RPCStatusCode = RPCStatusCode.UNKNOWN) -> RPCError:
+ # RPCError's third positional arg (raw_proto) is bytes, not str.
+ return RPCError(message, status, b"")
+
+
+@override_settings(DEPLOYMENTS_TASK_QUEUE="deployments-task-queue", TEMPORAL_WORKFLOW_MAX_ATTEMPTS="5")
+class TestTemporalWorkflowAdapter(SimpleTestCase):
+ @patch("products.deployments.backend.adapters.temporal.sync_connect")
+ def test_start_build_invokes_temporal_with_correct_arguments(self, mock_connect: MagicMock) -> None:
+ handle = MagicMock()
+ handle.first_execution_run_id = "run-abc"
+ handle.result_run_id = None
+ client = MagicMock()
+ client.start_workflow = AsyncMock(return_value=handle)
+ mock_connect.return_value = client
+
+ result = TemporalWorkflowAdapter().start_build(workflow_input=BUILD_INPUT)
+
+ self.assertEqual(result.workflow_id, f"deployment-{BUILD_INPUT.deployment_id}")
+ self.assertEqual(result.run_id, "run-abc")
+ client.start_workflow.assert_awaited_once()
+ call = client.start_workflow.await_args
+ self.assertEqual(call.args[0], DEPLOYMENT_BUILD_WORKFLOW)
+ self.assertEqual(call.args[1], BUILD_INPUT)
+ self.assertEqual(call.kwargs["id"], f"deployment-{BUILD_INPUT.deployment_id}")
+ self.assertEqual(call.kwargs["task_queue"], "deployments-task-queue")
+ self.assertEqual(call.kwargs["retry_policy"].maximum_attempts, 5)
+
+ @patch("products.deployments.backend.adapters.temporal.sync_connect")
+ def test_start_build_prefers_result_run_id_when_available(self, mock_connect: MagicMock) -> None:
+ handle = MagicMock()
+ handle.result_run_id = "run-result"
+ handle.first_execution_run_id = "run-first"
+ client = MagicMock()
+ client.start_workflow = AsyncMock(return_value=handle)
+ mock_connect.return_value = client
+
+ result = TemporalWorkflowAdapter().start_build(workflow_input=BUILD_INPUT)
+ self.assertEqual(result.run_id, "run-result")
+
+ @patch("products.deployments.backend.adapters.temporal.sync_connect")
+ def test_start_build_wraps_rpc_error_in_workflow_error(self, mock_connect: MagicMock) -> None:
+ client = MagicMock()
+ client.start_workflow = AsyncMock(side_effect=_make_rpc_error("temporal unreachable"))
+ mock_connect.return_value = client
+
+ with self.assertRaises(WorkflowError) as cm:
+ TemporalWorkflowAdapter().start_build(workflow_input=BUILD_INPUT)
+ self.assertIn("temporal unreachable", str(cm.exception))
+
+ def test_start_build_raises_when_task_queue_setting_missing(self) -> None:
+ with override_settings(DEPLOYMENTS_TASK_QUEUE=""):
+ with self.assertRaises(WorkflowError) as cm:
+ TemporalWorkflowAdapter().start_build(workflow_input=BUILD_INPUT)
+ self.assertIn("DEPLOYMENTS_TASK_QUEUE", str(cm.exception))
+
+ @patch("products.deployments.backend.adapters.temporal.sync_connect")
+ def test_signal_cancel_calls_handle_cancel(self, mock_connect: MagicMock) -> None:
+ handle = MagicMock()
+ handle.cancel = AsyncMock()
+ client = MagicMock()
+ client.get_workflow_handle = MagicMock(return_value=handle)
+ mock_connect.return_value = client
+
+ TemporalWorkflowAdapter().signal_cancel(workflow_id="deployment-abc")
+
+ client.get_workflow_handle.assert_called_once_with("deployment-abc")
+ handle.cancel.assert_awaited_once()
+
+ # Drive signal_cancel's NOT_FOUND detection from the structured
+ # RPCStatusCode rather than the message string — including the case
+ # where the message *contains* "not found" but the status is wrong
+ # (which should still raise), proving the substring-match path is
+ # gone.
+ @parameterized.expand(
+ [
+ ("not_found_with_canonical_message", RPCStatusCode.NOT_FOUND, "workflow execution not found", False),
+ ("not_found_with_different_message", RPCStatusCode.NOT_FOUND, "execution does not exist", False),
+ ("unknown_error", RPCStatusCode.UNKNOWN, "internal server error", True),
+ ("unavailable_with_not_found_substring", RPCStatusCode.UNAVAILABLE, "task queue not found", True),
+ ]
+ )
+ @patch("products.deployments.backend.adapters.temporal.sync_connect")
+ def test_signal_cancel_status_code_drives_behaviour(
+ self, _name: str, status: RPCStatusCode, message: str, should_raise: bool, mock_connect: MagicMock
+ ) -> None:
+ handle = MagicMock()
+ handle.cancel = AsyncMock(side_effect=_make_rpc_error(message, status))
+ client = MagicMock()
+ client.get_workflow_handle = MagicMock(return_value=handle)
+ mock_connect.return_value = client
+
+ if should_raise:
+ with self.assertRaises(WorkflowError) as cm:
+ TemporalWorkflowAdapter().signal_cancel(workflow_id="deployment-abc")
+ self.assertIn(message, str(cm.exception))
+ else:
+ # No exception — the workflow finished or never existed.
+ TemporalWorkflowAdapter().signal_cancel(workflow_id="deployment-abc")