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(alerts): add noop evaluation and delivery workflows (#97471)

Jon McCallumf59e30f7aa7d
diff --git a/docs/internal/alerts-product-temporal.md b/docs/internal/alerts-product-temporal.md
new file mode 100644
index 000000000000..537ef8877596
--- /dev/null
+++ b/docs/internal/alerts-product-temporal.md
@@ -0,0 +1,47 @@
+# Alerts noop workers
+
+The Alerts product registers two queues through `products/alerts/backend/facade/temporal.py` and the shared `start_temporal_worker` command:
+
+| Setting in `posthog/settings/temporal.py` | Queue | Workflow |
+| ----------------------------------------- | -------------------------------------- | -------------------------- |
+| `ALERTS_PRODUCT_EVALUATION_TASK_QUEUE` | `alerts-product-evaluation-task-queue` | `alerts-product-check-due` |
+| `ALERTS_PRODUCT_DELIVERY_TASK_QUEUE` | `alerts-product-delivery-task-queue` | `alerts-product-deliver` |
+
+These queue names are hardcoded and stay separate even with `DEBUG=True`.
+Start one worker for each queue:
+
+```bash
+python manage.py start_temporal_worker --task-queue alerts-product-evaluation-task-queue --metrics-port 8102
+python manage.py start_temporal_worker --task-queue alerts-product-delivery-task-queue --metrics-port 8103
+```
+
+Give every worker its own `--metrics-port`.
+The option defaults to 8001, which the shared development worker already binds, so a worker that keeps the default stops with `Address already in use`.
+The shared development worker does not poll these queues.
+See [Temporal development guidance](../../posthog/temporal/README.md) for worker setup.
+
+No schedule exists yet, so start an evaluation run by hand.
+The `execute_temporal_workflow` and `start_temporal_workflow` commands do not know these workflows and reject the name, so use the Temporal CLI in the dev stack:
+
+```bash
+docker exec posthog-temporal-admin-tools-1 \
+ temporal workflow start --address temporal:7233 --namespace default \
+ --task-queue alerts-product-evaluation-task-queue \
+ --type alerts-product-check-due \
+ --workflow-id "alerts-product-check-due-manual-$(date +%Y%m%d%H%M%S)" \
+ --input '{}'
+```
+
+The empty `--input '{}'` becomes the empty `AlertsProductInputs`.
+Watch the evaluation run and its delivery child in the Temporal UI at <http://localhost:8081>.
+
+Both workflows accept an empty `AlertsProductInputs` dataclass and run an empty activity with no I/O.
+Each activity has a 10-second start-to-close timeout, a 30-second schedule-to-close timeout, and at most three attempts.
+Evaluation starts one delivery child on the delivery queue and waits for confirmation that it started, without waiting for completion.
+The child ID includes the evaluation run ID, so repeated runs of the same evaluation workflow ID start different children.
+`ParentClosePolicy.ABANDON` lets delivery continue after evaluation closes.
+Delivery has a one-minute execution timeout for the noop.
+Real notification delivery guarantees remain undecided.
+
+This registration does not create schedules or deploy workers.
+Schedule registration will set the evaluation workflow's 50-second execution timeout separately.
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 1c44ccb0348e..cc7a9247fa8c 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -151,6 +151,12 @@ from posthog.temporal.weekly_digest import (
WORKFLOWS as WEEKLY_DIGEST_WORKFLOWS,
)
+from products.alerts.backend.facade.temporal import (
+ DELIVERY_ACTIVITIES as ALERTS_PRODUCT_DELIVERY_ACTIVITIES,
+ DELIVERY_WORKFLOWS as ALERTS_PRODUCT_DELIVERY_WORKFLOWS,
+ EVALUATION_ACTIVITIES as ALERTS_PRODUCT_EVALUATION_ACTIVITIES,
+ EVALUATION_WORKFLOWS as ALERTS_PRODUCT_EVALUATION_WORKFLOWS,
+)
from products.batch_exports.backend.temporal import (
ACTIVITIES as BATCH_EXPORTS_ACTIVITIES,
WORKFLOWS as BATCH_EXPORTS_WORKFLOWS,
@@ -537,6 +543,16 @@ _task_queue_specs = [
STAMPHOG_WORKFLOWS,
STAMPHOG_ACTIVITIES,
),
+ (
+ settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,
+ ALERTS_PRODUCT_EVALUATION_WORKFLOWS,
+ ALERTS_PRODUCT_EVALUATION_ACTIVITIES,
+ ),
+ (
+ settings.ALERTS_PRODUCT_DELIVERY_TASK_QUEUE,
+ ALERTS_PRODUCT_DELIVERY_WORKFLOWS,
+ ALERTS_PRODUCT_DELIVERY_ACTIVITIES,
+ ),
]
# Note: When running locally, many task queues resolve to the same queue name.
diff --git a/posthog/management/commands/test/test_start_temporal_worker.py b/posthog/management/commands/test/test_start_temporal_worker.py
index 5cee1d32daa6..c3691c4a4e0a 100644
--- a/posthog/management/commands/test/test_start_temporal_worker.py
+++ b/posthog/management/commands/test/test_start_temporal_worker.py
@@ -1,16 +1,26 @@
+from collections.abc import Callable, Sequence
+
import pytest
from django.conf import settings
from posthog.management.commands.start_temporal_worker import (
+ ACTIVITIES_DICT,
DATA_SYNC_WORKFLOWS,
WA_DIGEST_ACTIVITIES,
WA_DIGEST_WORKFLOWS,
WEEKLY_DIGEST_WORKFLOWS,
+ WORKFLOWS_DICT,
_task_queue_specs,
workflows_include_data_import_syncs,
)
+from products.alerts.backend.facade.temporal import (
+ DELIVERY_ACTIVITIES,
+ DELIVERY_WORKFLOWS,
+ EVALUATION_ACTIVITIES,
+ EVALUATION_WORKFLOWS,
+)
from products.wizard.backend.facade.temporal import (
ACTIVITIES as WIZARD_ACTIVITIES,
WORKFLOWS as WIZARD_WORKFLOWS,
@@ -21,18 +31,21 @@ class _NotADataSyncWorkflow:
pass
-def test_wizard_queue_registers_workflows_and_activities() -> None:
- entries = [
- (workflows, activities)
- for queue, workflows, activities in _task_queue_specs
- if queue == settings.WIZARD_TASK_QUEUE
- ]
- workflows = {workflow for registered_workflows, _ in entries for workflow in registered_workflows}
- activities = {activity for _, registered_activities in entries for activity in registered_activities}
- assert WIZARD_WORKFLOWS
- assert WIZARD_ACTIVITIES
- assert set(WIZARD_WORKFLOWS) <= workflows
- assert set(WIZARD_ACTIVITIES) <= activities
+ "task_queue,expected_workflows,expected_activities",
+ [
+ (settings.WIZARD_TASK_QUEUE, WIZARD_WORKFLOWS, WIZARD_ACTIVITIES),
+ ("alerts-product-evaluation-task-queue", EVALUATION_WORKFLOWS, EVALUATION_ACTIVITIES),
+ ("alerts-product-delivery-task-queue", DELIVERY_WORKFLOWS, DELIVERY_ACTIVITIES),
+ ],
+)
+def test_queue_registers_workflows_and_activities(
+ task_queue: str, expected_workflows: Sequence[type], expected_activities: Sequence[Callable[..., object]]
+) -> None:
+ assert expected_workflows
+ assert expected_activities
+ assert set(expected_workflows) <= WORKFLOWS_DICT[task_queue]
+ assert set(expected_activities) <= ACTIVITIES_DICT[task_queue]
# Data-import sources import vendor SDKs (google-ads, etc.) that register protobuf descriptors into a
diff --git a/posthog/settings/temporal.py b/posthog/settings/temporal.py
index a669071b2edb..8f8c7e32f45c 100644
--- a/posthog/settings/temporal.py
+++ b/posthog/settings/temporal.py
@@ -265,6 +265,9 @@ TEST_TASK_QUEUE = _set_temporal_task_queue("test-task-queue")
BILLING_TASK_QUEUE = _set_temporal_task_queue("billing-task-queue")
VIDEO_EXPORT_TASK_QUEUE = _set_temporal_task_queue("video-export-task-queue")
ANALYTICS_PLATFORM_TASK_QUEUE = _set_temporal_task_queue("analytics-platform-task-queue")
+# Keep the two noop fleets separate in local development as well as deployed environments.
+ALERTS_PRODUCT_EVALUATION_TASK_QUEUE = "alerts-product-evaluation-task-queue"
+ALERTS_PRODUCT_DELIVERY_TASK_QUEUE = "alerts-product-delivery-task-queue"
SESSION_REPLAY_TASK_QUEUE = _set_temporal_task_queue("session-replay-task-queue")
REPLAY_VISION_TASK_QUEUE = _set_temporal_task_queue("replay-vision-task-queue")
# The XGBoost-based session surfacing scoring sweep runs on the session-replay
diff --git a/products/alerts/backend/facade/temporal.py b/products/alerts/backend/facade/temporal.py
new file mode 100644
index 000000000000..f12f07dc56a4
--- /dev/null
+++ b/products/alerts/backend/facade/temporal.py
@@ -0,0 +1,8 @@
+from products.alerts.backend.temporal.workflows import (
+ DELIVERY_ACTIVITIES,
+ DELIVERY_WORKFLOWS,
+ EVALUATION_ACTIVITIES,
+ EVALUATION_WORKFLOWS,
+)
+
+__all__ = ["DELIVERY_ACTIVITIES", "DELIVERY_WORKFLOWS", "EVALUATION_ACTIVITIES", "EVALUATION_WORKFLOWS"]
diff --git a/products/alerts/backend/temporal/workflows.py b/products/alerts/backend/temporal/workflows.py
new file mode 100644
index 000000000000..145863eb1e08
--- /dev/null
+++ b/products/alerts/backend/temporal/workflows.py
@@ -0,0 +1,68 @@
+import datetime as dt
+
+from temporalio import activity, workflow
+from temporalio.common import RetryPolicy
+
+from posthog.dataclasses import frozen
+from posthog.temporal.common.base import PostHogWorkflow
+
+with workflow.unsafe.imports_passed_through():
+ from django.conf import settings
+
+
+@frozen
+class AlertsProductInputs:
+ pass
+
+
+async def alerts_product_check_due_activity() -> None:
+ pass
+
+
+async def alerts_product_deliver_activity() -> None:
+ pass
+
+
[email protected](name="alerts-product-deliver")
+class AlertsProductDeliverWorkflow(PostHogWorkflow):
+ inputs_cls = AlertsProductInputs
+
+ @workflow.run
+ async def run(self, inputs: AlertsProductInputs) -> None:
+ await workflow.execute_activity(
+ alerts_product_deliver_activity,
+ start_to_close_timeout=dt.timedelta(seconds=10),
+ schedule_to_close_timeout=dt.timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+
+
[email protected](name="alerts-product-check-due")
+class AlertsProductCheckDueWorkflow(PostHogWorkflow):
+ inputs_cls = AlertsProductInputs
+
+ @workflow.run
+ async def run(self, inputs: AlertsProductInputs) -> None:
+ await workflow.execute_activity(
+ alerts_product_check_due_activity,
+ start_to_close_timeout=dt.timedelta(seconds=10),
+ schedule_to_close_timeout=dt.timedelta(seconds=30),
+ retry_policy=RetryPolicy(maximum_attempts=3),
+ )
+ # Delivery must outlive the tick, so wait for start confirmation without awaiting the handle.
+ await workflow.start_child_workflow(
+ AlertsProductDeliverWorkflow.run,
+ inputs,
+ id=f"alerts-product-deliver-{workflow.info().run_id}",
+ task_queue=settings.ALERTS_PRODUCT_DELIVERY_TASK_QUEUE,
+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,
+ execution_timeout=dt.timedelta(minutes=1),
+ )
+
+
+EVALUATION_WORKFLOWS = [AlertsProductCheckDueWorkflow]
+EVALUATION_ACTIVITIES = [alerts_product_check_due_activity]
+DELIVERY_WORKFLOWS = [AlertsProductDeliverWorkflow]
+DELIVERY_ACTIVITIES = [alerts_product_deliver_activity]
diff --git a/products/alerts/backend/tests/test_temporal_workflows.py b/products/alerts/backend/tests/test_temporal_workflows.py
new file mode 100644
index 000000000000..7d6288335024
--- /dev/null
+++ b/products/alerts/backend/tests/test_temporal_workflows.py
@@ -0,0 +1,146 @@
+import uuid
+import asyncio
+import logging
+import datetime as dt
+from collections.abc import AsyncIterator
+from typing import Literal
+
+import pytest
+
+from django.conf import settings
+
+import pytest_asyncio
+from temporalio import activity, workflow
+from temporalio.api.enums.v1 import EventType
+from temporalio.client import WorkflowExecutionStatus, WorkflowFailureError
+from temporalio.exceptions import ApplicationError, TerminatedError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import UnsandboxedWorkflowRunner, Worker
+
+from products.alerts.backend.facade.temporal import (
+ DELIVERY_ACTIVITIES,
+ DELIVERY_WORKFLOWS,
+ EVALUATION_ACTIVITIES,
+ EVALUATION_WORKFLOWS,
+)
+from products.alerts.backend.temporal.workflows import AlertsProductCheckDueWorkflow, AlertsProductInputs
+
+
[email protected](name="test-alerts-product-close-after-child-start")
+class CloseAfterChildStartWorkflow:
+ @workflow.run
+ async def run(self, close_mode: str) -> None:
+ await AlertsProductCheckDueWorkflow().run(AlertsProductInputs())
+ await workflow.execute_activity("test_confirm_child_start", start_to_close_timeout=dt.timedelta(seconds=5))
+ if close_mode == "failed":
+ raise ApplicationError("Test parent failure", non_retryable=True)
+ await workflow.wait_condition(lambda: False)
+
+
+@pytest_asyncio.fixture(scope="module")
+async def environment() -> AsyncIterator[WorkflowEnvironment]:
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ yield env
+
+
+async def test_each_tick_starts_independent_delivery(
+ environment: WorkflowEnvironment, caplog: pytest.LogCaptureFixture
+) -> None:
+ caplog.set_level(logging.INFO, logger="temporalio.activity")
+ caplog.set_level(logging.INFO, logger="temporalio.workflow")
+ client = environment.client
+ workflow_id = str(uuid.uuid4())
+ child_ids: set[str] = set()
+
+ async with Worker(
+ client,
+ task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,
+ workflows=EVALUATION_WORKFLOWS,
+ activities=EVALUATION_ACTIVITIES,
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ for _ in range(2):
+ parent = await client.start_workflow(
+ "alerts-product-check-due",
+ AlertsProductInputs(),
+ id=workflow_id,
+ task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,
+ execution_timeout=dt.timedelta(seconds=10),
+ )
+ assert await parent.result() is None
+ history = await parent.fetch_history()
+ children = [
+ event.child_workflow_execution_started_event_attributes
+ for event in history.events
+ if event.event_type == EventType.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_STARTED
+ ]
+ assert len(children) == 1
+ child_id = children[0].workflow_execution.workflow_id
+ assert parent.first_execution_run_id is not None
+ assert parent.first_execution_run_id in child_id
+ assert children[0].workflow_type.name == "alerts-product-deliver"
+ child_ids.add(child_id)
+ child = await client.get_workflow_handle(child_id).describe()
+ assert child.task_queue == settings.ALERTS_PRODUCT_DELIVERY_TASK_QUEUE
+ assert child.status == WorkflowExecutionStatus.RUNNING
+
+ assert len(child_ids) == 2
+ async with Worker(
+ client,
+ task_queue=settings.ALERTS_PRODUCT_DELIVERY_TASK_QUEUE,
+ workflows=DELIVERY_WORKFLOWS,
+ activities=DELIVERY_ACTIVITIES,
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ for child_id in child_ids:
+ assert await client.get_workflow_handle(child_id).result() is None
+
+
[email protected]("close_mode", ["failed", "terminated"])
+async def test_delivery_survives_parent_closure(
+ environment: WorkflowEnvironment, caplog: pytest.LogCaptureFixture, close_mode: Literal["failed", "terminated"]
+) -> None:
+ caplog.set_level(logging.INFO, logger="temporalio.activity")
+ caplog.set_level(logging.INFO, logger="temporalio.workflow")
+ client = environment.client
+ child_started = asyncio.Event()
+
+ @activity.defn(name="test_confirm_child_start")
+ async def confirm_child_start() -> None:
+ child_started.set()
+
+ async with Worker(
+ client,
+ task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,
+ workflows=[CloseAfterChildStartWorkflow],
+ activities=[*EVALUATION_ACTIVITIES, confirm_child_start],
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ parent = await client.start_workflow(
+ CloseAfterChildStartWorkflow.run,
+ close_mode,
+ id=str(uuid.uuid4()),
+ task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,
+ execution_timeout=dt.timedelta(seconds=10),
+ )
+ await asyncio.wait_for(child_started.wait(), timeout=10)
+ child_id = f"alerts-product-deliver-{parent.first_execution_run_id}"
+
+ if close_mode == "terminated":
+ await parent.terminate()
+ with pytest.raises(WorkflowFailureError) as failure:
+ await parent.result()
+ assert isinstance(failure.value.cause, ApplicationError if close_mode == "failed" else TerminatedError)
+
+ child = client.get_workflow_handle(child_id)
+ assert (await child.describe()).status == WorkflowExecutionStatus.RUNNING
+ async with Worker(
+ client,
+ task_queue=settings.ALERTS_PRODUCT_DELIVERY_TASK_QUEUE,
+ workflows=DELIVERY_WORKFLOWS,
+ activities=DELIVERY_ACTIVITIES,
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ assert await child.result() is None
diff --git a/products/alerts/product.yaml b/products/alerts/product.yaml
index 6d9e51ae62a0..0b74b2e50b64 100644
--- a/products/alerts/product.yaml
+++ b/products/alerts/product.yaml
@@ -1,3 +1,4 @@
name: Alerts
owners:
- team-analytics-platform
+ - team-apm