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 build workflow + activities + worker registration (#58590)

Richard Solomoueb08d1adea71
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index f978c2bc2b03..406d55d41380 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -165,6 +165,10 @@ from products.batch_exports.backend.temporal import (
ACTIVITIES as BATCH_EXPORTS_ACTIVITIES,
WORKFLOWS as BATCH_EXPORTS_WORKFLOWS,
)
+from products.deployments.backend.temporal import (
+ ACTIVITIES as DEPLOYMENTS_ACTIVITIES,
+ WORKFLOWS as DEPLOYMENTS_WORKFLOWS,
+)
from products.logs.backend.temporal import (
ACTIVITIES as LOGS_ALERTING_ACTIVITIES,
WORKFLOWS as LOGS_ALERTING_WORKFLOWS,
@@ -345,6 +349,11 @@ _task_queue_specs = [
LOGS_ALERTING_WORKFLOWS,
LOGS_ALERTING_ACTIVITIES,
),
+ (
+ settings.DEPLOYMENTS_TASK_QUEUE,
+ DEPLOYMENTS_WORKFLOWS,
+ DEPLOYMENTS_ACTIVITIES,
+ ),
]
# Note: When running locally, many task queues resolve to the same queue name.
diff --git a/posthog/settings/web.py b/posthog/settings/web.py
index 24f00af64e6c..e682ba110ed7 100644
--- a/posthog/settings/web.py
+++ b/posthog/settings/web.py
@@ -599,6 +599,12 @@ DEPLOYMENTS_CLOUDFLARE_API_TOKEN = get_from_env("DEPLOYMENTS_CLOUDFLARE_API_TOKE
DEPLOYMENTS_HOG_DEV_ZONE_ID = get_from_env("DEPLOYMENTS_HOG_DEV_ZONE_ID", "")
DEPLOYMENTS_CLOUDFLARE_PROJECT_PREFIX = get_from_env("DEPLOYMENTS_CLOUDFLARE_PROJECT_PREFIX", "hogdev-")
+# Base URL the deployments Temporal worker uses when calling back into
+# the internal API. Worker pods in the same cluster set this to the
+# cluster-internal Service URL (e.g. http://posthog-web-django.posthog
+# .svc.cluster.local:8000). Empty value falls back to SITE_URL.
+DEPLOYMENTS_INTERNAL_API_BASE_URL = get_from_env("DEPLOYMENTS_INTERNAL_API_BASE_URL", "")
+
# Domain Connect (automated DNS configuration)
DOMAIN_CONNECT_PRIVATE_KEY: str | None = os.getenv("DOMAIN_CONNECT_PRIVATE_KEY", "").replace("\\n", "\n") or None
DOMAIN_CONNECT_KEY_ID: str = os.getenv("DOMAIN_CONNECT_KEY_ID", "_dcpubkeyv1")
diff --git a/products/deployments/backend/adapters/temporal.py b/products/deployments/backend/adapters/temporal.py
index dba56d547441..5320ae346886 100644
--- a/products/deployments/backend/adapters/temporal.py
+++ b/products/deployments/backend/adapters/temporal.py
@@ -26,6 +26,7 @@ from django.conf import settings
import structlog
from temporalio.client import WorkflowHandle as TemporalWorkflowHandle
from temporalio.common import RetryPolicy
+from temporalio.exceptions import WorkflowAlreadyStartedError
from temporalio.service import RPCError, RPCStatusCode
from posthog.temporal.common.client import sync_connect
@@ -118,6 +119,14 @@ class TemporalWorkflowAdapter:
retry_policy=RetryPolicy(maximum_attempts=max_attempts),
)
)
+ except WorkflowAlreadyStartedError as err:
+ # WorkflowAlreadyStartedError doesn't inherit from RPCError —
+ # they share TemporalError as the common ancestor but sit on
+ # different branches. Caught separately so a deterministic
+ # workflow-id collision (HTTP retry, mid-transaction retry)
+ # surfaces with a clear error rather than a 500.
+ logger.info("temporal_start_workflow_already_started", workflow_id=workflow_id)
+ raise WorkflowError(f"Deployment workflow already running: {err}") from err
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
diff --git a/products/deployments/backend/temporal/__init__.py b/products/deployments/backend/temporal/__init__.py
new file mode 100644
index 000000000000..328d39109bf2
--- /dev/null
+++ b/products/deployments/backend/temporal/__init__.py
@@ -0,0 +1,32 @@
+"""Temporal workflows + activities for the Deployments product.
+
+The `start_temporal_worker` management command imports `WORKFLOWS` and
+`ACTIVITIES` from here and registers them on the `deployments-task-queue`.
+"""
+
+from .activities import (
+ build_site,
+ clone_repo,
+ initialize_build,
+ install_dependencies,
+ mark_failed,
+ mark_ready,
+ start_building,
+ upload_artifacts,
+)
+from .build_workflow import DeploymentBuildWorkflow
+
+WORKFLOWS = [DeploymentBuildWorkflow]
+
+ACTIVITIES = [
+ initialize_build,
+ clone_repo,
+ install_dependencies,
+ start_building,
+ build_site,
+ upload_artifacts,
+ mark_ready,
+ mark_failed,
+]
+
+__all__ = ["ACTIVITIES", "WORKFLOWS", "DeploymentBuildWorkflow"]
diff --git a/products/deployments/backend/temporal/activities.py b/products/deployments/backend/temporal/activities.py
new file mode 100644
index 000000000000..415c6348c4d9
--- /dev/null
+++ b/products/deployments/backend/temporal/activities.py
@@ -0,0 +1,182 @@
+"""Activities for the Deployments build workflow.
+
+This is the v1 scaffolding: every activity posts an event/transition so
+the timeline + state machine work end-to-end, but the actual build
+steps (clone, install, build, upload) are stubs. The real work lives
+behind hogland sandbox provisioning in a follow-up PR — see
+`.notes/deployments-substrate.md` for why we run user code in a
+Firecracker microVM, not directly in this worker pod.
+
+Each activity returns quickly. Temporal handles retries; we don't
+retry inside.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from dataclasses import dataclass
+from uuid import UUID
+
+from temporalio import activity
+
+from ..domain.status import Status
+from ..domain.trigger import ErrorStep
+from .internal_api import post_event, post_transition
+
+
+@dataclass(frozen=True)
+class StepInput:
+ """Common shape for build-step activities.
+
+ Carries every field from `BuildInput` that any activity may need —
+ `github_access_token` and `build_command` are unused by the current
+ stub activities but the real `clone_repo` / `build_site` will read
+ them. Locking the shape in now means swapping the stubs for real
+ activities is a body-only change, not a signature change.
+ """
+
+ deployment_id: UUID
+ cloudflare_project_name: str
+ repo_url: str
+ branch: str
+ commit_sha: str
+ output_dir: str
+ github_access_token: str | None
+ build_command: str | None
+
+
+@dataclass(frozen=True)
+class MarkReadyInput:
+ deployment_id: UUID
+ deployment_url: str
+ cloudflare_deployment_id: str | None
+
+
+@dataclass(frozen=True)
+class MarkFailedInput:
+ deployment_id: UUID
+ error_message: str
+ error_step: ErrorStep
+
+
+# Stub sleep durations — keep small enough that test runs don't drag,
+# big enough that the timeline UI shows something happening when this
+# is running against a real cluster.
+_STUB_STEP_SLEEP_SECONDS = 0.5
+
+
[email protected](name="deployment-build.initialize")
+async def initialize_build(payload: StepInput) -> None:
+ """Move the deployment from QUEUED to INITIALIZING."""
+ await post_transition(deployment_id=payload.deployment_id, status=Status.INITIALIZING)
+ await post_event(
+ deployment_id=payload.deployment_id,
+ event_type="status_changed",
+ payload={"to": Status.INITIALIZING.value},
+ )
+
+
[email protected](name="deployment-build.clone")
+async def clone_repo(payload: StepInput) -> None:
+ """STUB: pretend to clone `payload.repo_url` at `payload.commit_sha`."""
+ await post_event(
+ deployment_id=payload.deployment_id,
+ event_type="clone_started",
+ payload={"repo_url": payload.repo_url, "branch": payload.branch, "commit_sha": payload.commit_sha},
+ )
+ await asyncio.sleep(_STUB_STEP_SLEEP_SECONDS)
+ await post_event(deployment_id=payload.deployment_id, event_type="clone_complete")
+
+
[email protected](name="deployment-build.install")
+async def install_dependencies(payload: StepInput) -> None:
+ """STUB: pretend to install dependencies."""
+ await post_event(deployment_id=payload.deployment_id, event_type="install_started")
+ await asyncio.sleep(_STUB_STEP_SLEEP_SECONDS)
+ await post_event(deployment_id=payload.deployment_id, event_type="install_complete")
+
+
[email protected](name="deployment-build.start_building")
+async def start_building(payload: StepInput) -> None:
+ """Move the deployment from INITIALIZING to BUILDING."""
+ await post_transition(deployment_id=payload.deployment_id, status=Status.BUILDING)
+ await post_event(
+ deployment_id=payload.deployment_id,
+ event_type="status_changed",
+ payload={"to": Status.BUILDING.value},
+ )
+
+
[email protected](name="deployment-build.build")
+async def build_site(payload: StepInput) -> None:
+ """STUB: pretend to run the build."""
+ await post_event(deployment_id=payload.deployment_id, event_type="build_started")
+ await asyncio.sleep(_STUB_STEP_SLEEP_SECONDS)
+ await post_event(
+ deployment_id=payload.deployment_id,
+ event_type="build_complete",
+ payload={"output_dir": payload.output_dir},
+ )
+
+
[email protected](name="deployment-build.upload")
+async def upload_artifacts(payload: StepInput) -> str:
+ """STUB: pretend to upload to Cloudflare Pages.
+
+ Returns a synthetic deployment URL so the workflow can complete.
+ The real adapter will return Cloudflare's actual deployment URL
+ once the upload step is implemented (hogland-side).
+ """
+ await post_event(deployment_id=payload.deployment_id, event_type="upload_started")
+ await asyncio.sleep(_STUB_STEP_SLEEP_SECONDS)
+ synthetic_url = f"https://{payload.cloudflare_project_name}.pages.dev"
+ await post_event(
+ deployment_id=payload.deployment_id,
+ event_type="upload_complete",
+ payload={"deployment_url": synthetic_url, "stub": True},
+ )
+ return synthetic_url
+
+
[email protected](name="deployment-build.mark_ready")
+async def mark_ready(payload: MarkReadyInput) -> None:
+ """Move the deployment from BUILDING to READY."""
+ await post_transition(
+ deployment_id=payload.deployment_id,
+ status=Status.READY,
+ deployment_url=payload.deployment_url,
+ cloudflare_deployment_id=payload.cloudflare_deployment_id,
+ )
+ await post_event(
+ deployment_id=payload.deployment_id,
+ event_type="status_changed",
+ payload={"to": Status.READY.value, "deployment_url": payload.deployment_url},
+ )
+
+
[email protected](name="deployment-build.mark_failed")
+async def mark_failed(payload: MarkFailedInput) -> None:
+ """Move the deployment from a non-terminal status to ERROR.
+
+ Best-effort: the workflow calls this in an exception handler. If
+ posting the transition itself fails (e.g. internal API down), the
+ activity raises and Temporal retries. If we exhaust retries, the
+ workflow run is left in whatever non-terminal status it was in when
+ the original error fired — a janitor sweep would need to catch that
+ separately, but that's out of scope for v1.
+ """
+ await post_transition(
+ deployment_id=payload.deployment_id,
+ status=Status.ERROR,
+ error_message=payload.error_message,
+ error_step=payload.error_step,
+ )
+ await post_event(
+ deployment_id=payload.deployment_id,
+ event_type="status_changed",
+ payload={
+ "to": Status.ERROR.value,
+ "error_step": payload.error_step.value,
+ "error_message": payload.error_message,
+ },
+ )
diff --git a/products/deployments/backend/temporal/build_workflow.py b/products/deployments/backend/temporal/build_workflow.py
new file mode 100644
index 000000000000..7ddae8f29d99
--- /dev/null
+++ b/products/deployments/backend/temporal/build_workflow.py
@@ -0,0 +1,139 @@
+"""Temporal workflow that drives a single deployment build.
+
+Orchestrates the stub activities in `activities.py`. Real build work
+(clone / install / build / upload) is stubbed at the activity level
+pending hogland integration — this file shouldn't change when that
+lands; only the underlying activities will.
+
+The workflow id is `deployment-{deployment_id}` (set by the Django-side
+`TemporalWorkflowAdapter.start_build`). The workflow type is
+`"deployment-build"`.
+
+Each activity gets its own retry policy:
+- Initialize / mark_ready / mark_failed / start_building → API calls
+ to ourselves, retry liberally.
+- Build steps (clone / install / build / upload) → retry once, since
+ they're stubs today but will run real user code in a sandbox once
+ hogland lands. Retrying a flaky `npm install` is fine; retrying a
+ build that hit a real compile error wastes minutes.
+
+On any activity failure, the workflow posts an `ERROR` transition with
+the right `error_step` and re-raises so Temporal records the run as
+failed.
+"""
+
+from __future__ import annotations
+
+from datetime import timedelta
+
+from temporalio import workflow
+from temporalio.common import RetryPolicy
+from temporalio.exceptions import ActivityError
+
+from ..domain.contracts import BuildInput
+from ..domain.trigger import ErrorStep
+from .activities import (
+ MarkFailedInput,
+ MarkReadyInput,
+ StepInput,
+ build_site,
+ clone_repo,
+ initialize_build,
+ install_dependencies,
+ mark_failed,
+ mark_ready,
+ start_building,
+ upload_artifacts,
+)
+
+# API-call activities (`initialize`, `start_building`, `mark_*`) are
+# cheap idempotent posts to the internal HTTP API. Build-step activities
+# do real work and are expensive to retry. Different retry profiles.
+_API_RETRY = RetryPolicy(maximum_attempts=5, initial_interval=timedelta(seconds=1))
+_BUILD_RETRY = RetryPolicy(maximum_attempts=2, initial_interval=timedelta(seconds=2))
+
+_API_TIMEOUT = timedelta(seconds=30)
+_BUILD_TIMEOUT = timedelta(minutes=10)
+
+
[email protected](name="deployment-build")
+class DeploymentBuildWorkflow:
+ """One run per Deployment row.
+
+ Posts status transitions through QUEUED → INITIALIZING → BUILDING →
+ READY (or ERROR on any failure). Activities post to the internal
+ API; this workflow never writes to the DB directly.
+ """
+
+ @workflow.run
+ async def run(self, payload: BuildInput) -> None:
+ step = StepInput(
+ deployment_id=payload.deployment_id,
+ cloudflare_project_name=payload.cloudflare_project_name,
+ repo_url=payload.repo_url,
+ branch=payload.branch,
+ commit_sha=payload.commit_sha,
+ output_dir=payload.output_dir,
+ github_access_token=payload.github_access_token,
+ build_command=payload.build_command,
+ )
+
+ # `current_step` tracks which build phase is in flight so we
+ # can mark_failed with the right error_step if anything raises.
+ current_step = ErrorStep.DISPATCH
+ try:
+ await workflow.execute_activity(
+ initialize_build, step, start_to_close_timeout=_API_TIMEOUT, retry_policy=_API_RETRY
+ )
+
+ current_step = ErrorStep.CLONE
+ await workflow.execute_activity(
+ clone_repo, step, start_to_close_timeout=_BUILD_TIMEOUT, retry_policy=_BUILD_RETRY
+ )
+
+ current_step = ErrorStep.INSTALL
+ await workflow.execute_activity(
+ install_dependencies, step, start_to_close_timeout=_BUILD_TIMEOUT, retry_policy=_BUILD_RETRY
+ )
+
+ # `start_building` is the gateway to the BUILD phase — a
+ # failure transitioning into building should report
+ # `error_step=build`, not `install`.
+ current_step = ErrorStep.BUILD
+ await workflow.execute_activity(
+ start_building, step, start_to_close_timeout=_API_TIMEOUT, retry_policy=_API_RETRY
+ )
+
+ await workflow.execute_activity(
+ build_site, step, start_to_close_timeout=_BUILD_TIMEOUT, retry_policy=_BUILD_RETRY
+ )
+
+ current_step = ErrorStep.PUBLISH
+ deployment_url = await workflow.execute_activity(
+ upload_artifacts, step, start_to_close_timeout=_BUILD_TIMEOUT, retry_policy=_BUILD_RETRY
+ )
+
+ await workflow.execute_activity(
+ mark_ready,
+ MarkReadyInput(
+ deployment_id=payload.deployment_id,
+ deployment_url=deployment_url,
+ # No CF deployment id yet — populated once the real
+ # upload activity returns one.
+ cloudflare_deployment_id=None,
+ ),
+ start_to_close_timeout=_API_TIMEOUT,
+ retry_policy=_API_RETRY,
+ )
+ except ActivityError as err:
+ await workflow.execute_activity(
+ mark_failed,
+ MarkFailedInput(
+ deployment_id=payload.deployment_id,
+ error_message=str(err),
+ error_step=current_step,
+ ),
+ start_to_close_timeout=_API_TIMEOUT,
+ retry_policy=_API_RETRY,
+ )
+ raise
diff --git a/products/deployments/backend/temporal/internal_api.py b/products/deployments/backend/temporal/internal_api.py
new file mode 100644
index 000000000000..7dd3de168155
--- /dev/null
+++ b/products/deployments/backend/temporal/internal_api.py
@@ -0,0 +1,113 @@
+"""Thin HTTP client the build worker uses to call the Deployments internal API.
+
+The internal endpoints (`POST /api/internal/deployments/{id}/transitions/`
+and `.../events/`) live in `products/deployments/backend/api/internal.py`.
+The worker uses them to advance the deployment's state machine and to
+append timeline events as activities run.
+
+Auth is the shared `X-Internal-Api-Secret` header. URL is configurable
+via `DEPLOYMENTS_INTERNAL_API_BASE_URL` so the worker can target the
+cluster-internal Service rather than the public ingress.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+from uuid import UUID
+
+from django.conf import settings
+
+import httpx
+from temporalio.exceptions import ApplicationError
+
+from ..domain.status import Status
+from ..domain.trigger import ErrorStep
+
+# Tight enough that activity heartbeats from a hung internal API surface
+# fast, but generous enough to ride out a routine pod restart.
+INTERNAL_API_TIMEOUT_SECONDS = 15
+
+
+class InternalApiError(Exception):
+ """Raised when the internal API returns a non-2xx response."""
+
+
+def _raise_for_status(*, method: str, path: str, status_code: int, body: str) -> None:
+ """Raise the right exception type for a non-2xx response.
+
+ 4xx indicates a client error (invalid transition, missing row, auth
+ failure) — retrying won't help, so raise as a non-retryable
+ `ApplicationError` so Temporal stops immediately. 5xx is a server
+ error or transient infra failure; raise the plain `InternalApiError`
+ so Temporal's retry policy kicks in.
+ """
+ message = f"Internal API {method} {path} failed: {status_code} {body[:200]}"
+ if 400 <= status_code < 500:
+ raise ApplicationError(message, type="InternalApiClientError", non_retryable=True)
+ raise InternalApiError(message)
+
+
+def _base_url() -> str:
+ base = getattr(settings, "DEPLOYMENTS_INTERNAL_API_BASE_URL", "") or getattr(settings, "SITE_URL", "")
+ if not base:
+ # Missing env vars won't fix themselves between retries — raise
+ # a non-retryable error so the activity fails immediately rather
+ # than burning the full _API_RETRY budget on a misconfiguration.
+ raise ApplicationError(
+ "Missing setting: DEPLOYMENTS_INTERNAL_API_BASE_URL (or SITE_URL). "
+ "The deployments worker needs a URL to call back to the web pods.",
+ type="InternalApiConfigError",
+ non_retryable=True,
+ )
+ return base.rstrip("/")
+
+
+def _headers() -> dict[str, str]:
+ secret = getattr(settings, "INTERNAL_API_SECRET", "")
+ if not secret:
+ raise ApplicationError(
+ "Missing setting: INTERNAL_API_SECRET.",
+ type="InternalApiConfigError",
+ non_retryable=True,
+ )
+ return {"X-Internal-Api-Secret": secret, "Content-Type": "application/json"}
+
+
+async def post_transition(
+ *,
+ deployment_id: UUID | str,
+ status: Status,
+ cloudflare_deployment_id: str | None = None,
+ deployment_url: str | None = None,
+ error_message: str | None = None,
+ error_step: ErrorStep | None = None,
+) -> None:
+ """Post a status transition to the internal API."""
+ body: dict[str, Any] = {"status": status.value}
+ if cloudflare_deployment_id:
+ body["cloudflare_deployment_id"] = cloudflare_deployment_id
+ if deployment_url:
+ body["deployment_url"] = deployment_url
+ if error_message:
+ body["error_message"] = error_message
+ if error_step is not None:
+ body["error_step"] = error_step.value
+
+ url = f"{_base_url()}/api/internal/deployments/{deployment_id}/transitions/"
+ async with httpx.AsyncClient(timeout=INTERNAL_API_TIMEOUT_SECONDS) as client:
+ response = await client.post(url, json=body, headers=_headers())
+ if not response.is_success:
+ _raise_for_status(method="POST", path="transitions", status_code=response.status_code, body=response.text)
+
+
+async def post_event(*, deployment_id: UUID | str, event_type: str, payload: dict[str, Any] | None = None) -> None:
+ """Append a timeline event for the deployment."""
+ body: dict[str, Any] = {"event_type": event_type}
+ if payload is not None:
+ body["payload"] = payload
+
+ url = f"{_base_url()}/api/internal/deployments/{deployment_id}/events/"
+ async with httpx.AsyncClient(timeout=INTERNAL_API_TIMEOUT_SECONDS) as client:
+ response = await client.post(url, json=body, headers=_headers())
+ if not response.is_success:
+ _raise_for_status(method="POST", path="events", status_code=response.status_code, body=response.text)
diff --git a/products/deployments/backend/test/test_build_workflow_activities.py b/products/deployments/backend/test/test_build_workflow_activities.py
new file mode 100644
index 000000000000..b1a58ba0efcb
--- /dev/null
+++ b/products/deployments/backend/test/test_build_workflow_activities.py
@@ -0,0 +1,137 @@
+from __future__ import annotations
+
+from uuid import UUID
+
+import pytest
+from unittest.mock import AsyncMock, patch
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.deployments.backend.domain.status import Status
+from products.deployments.backend.domain.trigger import ErrorStep
+from products.deployments.backend.temporal.activities import (
+ MarkFailedInput,
+ MarkReadyInput,
+ StepInput,
+ build_site,
+ clone_repo,
+ initialize_build,
+ install_dependencies,
+ mark_failed,
+ mark_ready,
+ start_building,
+ upload_artifacts,
+)
+
+DEPLOYMENT_ID = UUID("00000000-0000-7000-8000-000000000001")
+STEP = StepInput(
+ deployment_id=DEPLOYMENT_ID,
+ cloudflare_project_name="hogdev-1-myapp",
+ repo_url="https://github.com/example/repo",
+ branch="main",
+ commit_sha="abc123",
+ output_dir="dist",
+ github_access_token=None,
+ build_command=None,
+)
+
+
+class TestBuildActivities(SimpleTestCase):
+ @pytest.mark.asyncio
+ async def test_initialize_build_posts_initializing_transition(self) -> None:
+ with (
+ patch("products.deployments.backend.temporal.activities.post_transition", new=AsyncMock()) as t,
+ patch("products.deployments.backend.temporal.activities.post_event", new=AsyncMock()) as e,
+ ):
+ await initialize_build(STEP)
+
+ t.assert_awaited_once_with(deployment_id=DEPLOYMENT_ID, status=Status.INITIALIZING)
+ e.assert_awaited_once()
+ # Event payload mirrors the transition.
+ assert e.await_args is not None
+ kwargs = e.await_args.kwargs
+ self.assertEqual(kwargs["deployment_id"], DEPLOYMENT_ID)
+ self.assertEqual(kwargs["event_type"], "status_changed")
+ self.assertEqual(kwargs["payload"], {"to": "initializing"})
+
+ @pytest.mark.asyncio
+ async def test_start_building_posts_building_transition(self) -> None:
+ with (
+ patch("products.deployments.backend.temporal.activities.post_transition", new=AsyncMock()) as t,
+ patch("products.deployments.backend.temporal.activities.post_event", new=AsyncMock()),
+ ):
+ await start_building(STEP)
+ t.assert_awaited_once_with(deployment_id=DEPLOYMENT_ID, status=Status.BUILDING)
+
+ @pytest.mark.asyncio
+ async def test_mark_ready_propagates_deployment_url(self) -> None:
+ payload = MarkReadyInput(
+ deployment_id=DEPLOYMENT_ID,
+ deployment_url="https://hogdev-1-myapp.pages.dev",
+ cloudflare_deployment_id="d1",
+ )
+ with (
+ patch("products.deployments.backend.temporal.activities.post_transition", new=AsyncMock()) as t,
+ patch("products.deployments.backend.temporal.activities.post_event", new=AsyncMock()),
+ ):
+ await mark_ready(payload)
+ t.assert_awaited_once_with(
+ deployment_id=DEPLOYMENT_ID,
+ status=Status.READY,
+ deployment_url="https://hogdev-1-myapp.pages.dev",
+ cloudflare_deployment_id="d1",
+ )
+
+ @pytest.mark.asyncio
+ async def test_mark_failed_propagates_error_step(self) -> None:
+ payload = MarkFailedInput(deployment_id=DEPLOYMENT_ID, error_message="kaboom", error_step=ErrorStep.BUILD)
+ with (
+ patch("products.deployments.backend.temporal.activities.post_transition", new=AsyncMock()) as t,
+ patch("products.deployments.backend.temporal.activities.post_event", new=AsyncMock()) as e,
+ ):
+ await mark_failed(payload)
+ t.assert_awaited_once_with(
+ deployment_id=DEPLOYMENT_ID,
+ status=Status.ERROR,
+ error_message="kaboom",
+ error_step=ErrorStep.BUILD,
+ )
+ # Event payload includes the error step + message for the timeline.
+ assert e.await_args is not None
+ kwargs = e.await_args.kwargs
+ self.assertEqual(kwargs["payload"]["error_step"], "build")
+ self.assertEqual(kwargs["payload"]["error_message"], "kaboom")
+
+ @parameterized.expand(
+ [
+ ("clone_repo", clone_repo),
+ ("install_dependencies", install_dependencies),
+ ("build_site", build_site),
+ ]
+ )
+ @pytest.mark.asyncio
+ async def test_build_step_stub_only_emits_events(self, _name: str, activity) -> None:
+ # The build-step stubs don't post transitions — those are the
+ # responsibility of initialize_build / start_building / mark_*.
+ # Each stub only emits events for the timeline.
+ with (
+ patch("products.deployments.backend.temporal.activities.post_transition", new=AsyncMock()) as t,
+ patch("products.deployments.backend.temporal.activities.post_event", new=AsyncMock()) as e,
+ ):
+ await activity(STEP)
+ t.assert_not_awaited()
+ self.assertGreaterEqual(e.await_count, 1)
+
+ @pytest.mark.asyncio
+ async def test_upload_artifacts_returns_synthetic_pages_url(self) -> None:
+ with (
+ patch("products.deployments.backend.temporal.activities.post_transition", new=AsyncMock()),
+ patch("products.deployments.backend.temporal.activities.post_event", new=AsyncMock()),
+ ):
+ url = await upload_artifacts(STEP)
+ # Until the hogland-backed real upload lands, this is a known
+ # placeholder so the workflow can complete end-to-end. The
+ # placeholder shape mirrors what CF would return.
+ self.assertEqual(url, "https://hogdev-1-myapp.pages.dev")
diff --git a/products/deployments/backend/test/test_temporal_adapter.py b/products/deployments/backend/test/test_temporal_adapter.py
index 7514545d71ba..7451d393b37c 100644
--- a/products/deployments/backend/test/test_temporal_adapter.py
+++ b/products/deployments/backend/test/test_temporal_adapter.py
@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
from django.test import SimpleTestCase, override_settings
from parameterized import parameterized
+from temporalio.exceptions import WorkflowAlreadyStartedError
from temporalio.service import RPCError, RPCStatusCode
from products.deployments.backend.adapters.temporal import (
@@ -84,6 +85,20 @@ class TestTemporalWorkflowAdapter(SimpleTestCase):
TemporalWorkflowAdapter().start_build(workflow_input=BUILD_INPUT)
self.assertIn("temporal unreachable", str(cm.exception))
+ @patch("products.deployments.backend.adapters.temporal.sync_connect")
+ def test_start_build_wraps_workflow_already_started_in_workflow_error(self, mock_connect: MagicMock) -> None:
+ # `WorkflowAlreadyStartedError` doesn't inherit from `RPCError` —
+ # exercised separately so the catch in start_build stays correct.
+ client = MagicMock()
+ client.start_workflow = AsyncMock(
+ side_effect=WorkflowAlreadyStartedError(workflow_id="deployment-abc", workflow_type="deployment-build")
+ )
+ mock_connect.return_value = client
+
+ with self.assertRaises(WorkflowError) as cm:
+ TemporalWorkflowAdapter().start_build(workflow_input=BUILD_INPUT)
+ self.assertIn("already running", 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: