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): page source dispatchers from the tick (#101675)

Jon McCallumab32e5ea8d67
diff --git a/docs/internal/alerts-product-temporal.md b/docs/internal/alerts-product-temporal.md
index 0990fbf3f06a..48db32e0256d 100644
--- a/docs/internal/alerts-product-temporal.md
+++ b/docs/internal/alerts-product-temporal.md
@@ -5,13 +5,14 @@ The Alerts product registers three queues through `products/alerts/backend/facad
| Setting in `posthog/settings/temporal.py` | Queue | Workflow |
| ------------------------------------------------ | ------------------------------------------------ | ---------------------------- |
| `ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE` | `alerts-product-shared-orchestration-task-queue` | `alerts-product-orchestrate` |
-| `ALERTS_PRODUCT_EVALUATION_TASK_QUEUE` | `alerts-product-evaluation-task-queue` | `alerts-product-check-due` |
+| `ALERTS_PRODUCT_EVALUATION_TASK_QUEUE` | `alerts-product-evaluation-task-queue` | `alerts-product-evaluate` |
| `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`.
Shared orchestration registers the orchestration workflow and a synthetic demand-discovery activity.
-Each schedule tick starts orchestration, which discovers demand before awaiting an evaluation child on the evaluation queue.
-Evaluation runs the probe and starts its independent delivery child on the delivery queue.
+The evaluation queue registers the source dispatcher, the evaluation workflow (`alerts-product-evaluate`) and the probe activity.
+Each schedule tick starts orchestration, which discovers demand once and then pages source dispatchers until the demand is exhausted or its dispatch budget is spent.
+Each dispatcher starts one evaluation child for its source. Evaluation runs the probe and starts its independent delivery child on the delivery queue.
Start one worker for each queue:
```bash
@@ -60,7 +61,7 @@ If the dev schedule does not exist yet, start all three workers before the first
Existing pause state is preserved. Resume only after all three workers are ready, then verify the complete workflow chain.
To stop future starts, pause the schedule. Keep all three workers running until orchestration, evaluation, and delivery work drains.
-For rollback, restore the previous schedule action (`alerts-product-check-due` on the evaluation queue) after draining, then roll back the code.
+For rollback, restore the previous schedule action (the evaluation workflow started directly on the evaluation queue, named `alerts-product-check-due` before the rename below) after draining, then roll back the code.
Do not reconcile with the new code after restoring the old action: reconciliation would route back to orchestration.
Pausing or changing the schedule does not move or stop queued or running workflows.
@@ -79,12 +80,12 @@ docker exec posthog-temporal-admin-tools-1 \
--input '{}'
```
-The empty `--input '{}'` becomes the empty `AlertsProductInputs`.
-Watch orchestration, its evaluation child, and the delivery grandchild in the Temporal UI at <http://localhost:8081>.
+The empty `--input '{}'` becomes an `OrchestrateInputs` with every field defaulted.
+Watch orchestration, its source dispatcher children, their evaluation children, and the delivery great-grandchildren in the Temporal UI at <http://localhost:8081>.
-All three workflows accept an empty `AlertsProductInputs` dataclass.
-Orchestration awaits one evaluation child, with a 40-second execution timeout and one workflow attempt.
-The evaluation child ID includes the orchestration run ID, so each tick starts a distinct evaluation.
+Evaluation and delivery accept an empty `AlertsProductInputs` dataclass; orchestration accepts `OrchestrateInputs` with all fields defaulted.
+Orchestration pages source dispatchers, which start evaluation children with a 40-second execution timeout and one workflow attempt.
+Evaluation child IDs carry the tick ID, source and page, so each tick starts distinct evaluations.
Evaluation runs a Postgres connectivity probe; delivery runs an empty activity with no I/O.
Evaluation and delivery activities each have a 10-second start-to-close timeout and a 30-second schedule-to-close timeout.
Evaluation has one attempt; delivery retains at most three attempts.
@@ -94,6 +95,41 @@ The child ID includes the evaluation run ID, so repeated runs of the same evalua
Delivery has a one-minute execution timeout for the noop.
Real notification delivery guarantees remain undecided.
+## Names
+
+The evaluation workflow is `alerts-product-evaluate` (class `AlertsProductEvaluateWorkflow`), the probe activity is `alerts_product_probe_postgres_activity`, and the schedule is registered by `create_alerts_product_tick_schedule`.
+These replace `alerts-product-check-due`, `alerts_product_check_due_activity` and `create_alerts_product_check_due_schedule`: discovery finds what is due and dispatchers hand it out, so this workflow only evaluates.
+A workflow type rename breaks runs of the old type that are in flight at deploy time: no worker knows the old name, so they fail. Dev evaluations live under 40 seconds, and production is off.
+The schedule ID stays `alerts-product-check-due-schedule`. Registration does not delete schedules, so a new ID would leave two schedules until someone deleted the old one by hand.
+
+## Tick loop and source dispatchers
+
+One tick is one `alerts-product-orchestrate` execution. It takes an `OrchestrateInputs`; the schedule passes `{}` and every field defaults.
+The first run records the tick cutoff (the scheduled start time, or the workflow start time for manual runs) and a deadline 45 seconds after the run started.
+Discovery runs once per tick. The loop then starts one `alerts-product-source-dispatch` child per source with demand, ID `{tick_id}-{source}-p{page}`, on the evaluation queue.
+Dispatchers are part of the tick: the orchestrator awaits each dispatcher's report and keeps the default `TERMINATE` close policy on that edge.
+Each dispatcher has one attempt and an execution timeout of 30 seconds, or the time left before the tick's hard stop minus one second, whichever is shorter.
+The hard stop is the run's own execution timeout when it has one, and the budget plus five seconds otherwise. Both deadlines travel in the input across continued runs.
+
+The orchestrator passes a dispatcher every remaining ID for its source. The dispatcher decides how much to take and returns the rest.
+Today it takes everything: no adapter has said yet how many alerts one evaluation can hold, so nothing remains and a tick is one page.
+The limit that will matter is the evaluation workflow's own history, which depends on the adapter's query shape; it arrives with the first real adapter.
+It starts one `alerts-product-evaluate` child, ID `{dispatcher_id}-eval`, with `ParentClosePolicy.ABANDON`, a 40-second execution timeout and one attempt.
+It waits for the child to start, never for it to finish, then returns the dispatched count and the remaining IDs.
+Members are not passed to evaluation yet: evaluation keeps the probe path until claims exist.
+
+After every page the orchestrator records a `TickPage` (page, run ID, dispatched, remaining).
+When nothing remains it returns `OrchestrateResult(remaining=0, deadline_reached=False)`.
+Before each page after the first, it checks the deadline. When work remains and the deadline has passed, or fewer than two seconds remain before the hard stop, it returns cleanly with the remaining count and `deadline_reached=True`; the next minute's tick discovers that work again.
+A tick always runs its first page: the deadline is a stop rule, not an admission rule.
+A tick that exits with remaining work is a load signal. A tick that hits the schedule's 50-second execution timeout is a breakage signal: a clean exit never times out.
+The orchestrator calls `continue_as_new` only when Temporal reports `is_continue_as_new_suggested()`. The continued run receives the cutoff, deadline, demand and pages in its input and does not rerun discovery.
+The schedule's execution timeout spans continued runs, so a rollover cannot extend the tick.
+
+A dispatcher that overruns times out before the tick's hard stop, and the tick fails with that child error rather than being terminated mid-page. Evaluations already started by earlier dispatchers, and their delivery children, are abandoned and complete on their own.
+If the tick is terminated or times out anyway, Temporal terminates its in-flight dispatchers after the tick closes.
+The previous `workflow.patched` gate around discovery is gone: the loop cannot run without discovery, and dev histories live under a minute.
+
## Synthetic demand discovery
The first orchestration activity, `alerts_product_discover_demand_activity`, accepts a timezone-aware ISO-8601 cutoff.
@@ -101,13 +137,14 @@ Scheduled runs use `TemporalScheduledStartTime`; manual runs use the workflow st
Activity retries retain the same cutoff rather than reading the activity's clock.
The activity returns an `AlertDemand` containing configuration IDs grouped by the shared `SourceKind` enum (`logs` and `insight`).
Only nonempty groups are returned. Discovery does not reserve or claim IDs.
+Each source is bounded to `DISCOVERY_LIMIT_PER_SOURCE` IDs (1,000) so the manifest stays near 40 KB per source, under the repository's 256 KB rule for Temporal payload fields.
+`omitted_by_source` counts the due IDs left out. The tick adds that count to its `remaining` result, and the next tick discovers that work again.
For now, `logic/demand.py` supplies deterministic synthetic configurations relative to that cutoff:
two eligible logs configurations and one eligible insight configuration, plus future and disabled configurations that are excluded.
There are no configuration-table reads, new database entities, or real evaluations of these IDs.
-The result is visible in the activity history; orchestration still runs the existing independent probe/delivery smoke path without passing it synthetic IDs.
-Source-specific child workflows, batching, TTL claims, and continuation are not implemented here.
-The discovery command is patch-gated so existing workflow histories still replay without it.
+The result feeds the tick loop above. Evaluation still runs the probe/delivery smoke path without receiving synthetic IDs.
+TTL claims are not implemented here.
Discovery has a five-second start-to-close timeout, a ten-second schedule-to-close timeout, and at most three attempts.
## Postgres connectivity probe
diff --git a/posthog/temporal/schedule.py b/posthog/temporal/schedule.py
index fa88172815ad..9056f0b67527 100644
--- a/posthog/temporal/schedule.py
+++ b/posthog/temporal/schedule.py
@@ -78,7 +78,7 @@ from posthog.temporal.warehouse_sources_queue_partition_management.schedule impo
)
from posthog.temporal.weekly_digest.types import WeeklyDigestInput
-from products.alerts.backend.facade.temporal import create_alerts_product_check_due_schedule
+from products.alerts.backend.facade.temporal import create_alerts_product_tick_schedule
from products.billing_alerts.backend.temporal.schedule import create_schedule_due_billing_alert_checks_schedule
from products.business_knowledge.backend.temporal.schedule import (
create_business_knowledge_learning_coordinator_schedule,
@@ -932,7 +932,7 @@ schedules = [
create_error_tracking_weekly_digest_schedule,
create_wa_weekly_digest_schedule,
create_wa_digest_notification_schedule,
- create_alerts_product_check_due_schedule,
+ create_alerts_product_tick_schedule,
create_logs_alert_check_schedule,
create_logs_volume_tick_schedule,
create_schedule_due_alert_checks_schedule,
diff --git a/products/alerts/backend/facade/contracts.py b/products/alerts/backend/facade/contracts.py
index 082f8f339aee..5d7398bf3bf9 100644
--- a/products/alerts/backend/facade/contracts.py
+++ b/products/alerts/backend/facade/contracts.py
@@ -7,6 +7,7 @@ contract check watches this file to decide whether they must retest.
from __future__ import annotations
+from dataclasses import field
from enum import StrEnum
from typing import Any, Final, NotRequired, TypedDict
from uuid import UUID
@@ -26,7 +27,58 @@ class DemandDiscoveryInputs:
@frozen
class AlertDemand:
+ """Due configuration IDs per source, bounded so the payload stays small. `omitted_by_source` counts
+ what discovery left out; that work is due again next tick."""
+
configuration_ids_by_source: dict[SourceKind, list[str]]
+ omitted_by_source: dict[SourceKind, int] = field(default_factory=dict)
+
+
+@frozen
+class SourceDispatchInputs:
+ """Everything the tick knows about one source. The dispatcher decides how much of it to take."""
+
+ tick_id: str
+ source: SourceKind
+ page: int
+ configuration_ids: list[str]
+
+
+@frozen
+class SourceDispatchReport:
+ source: SourceKind
+ page: int
+ dispatched: int
+ remaining_ids: list[str]
+ evaluation_workflow_id: str | None
+
+
+@frozen
+class TickPage:
+ page: int
+ run_id: str
+ dispatched: int
+ remaining: int
+
+
+@frozen
+class OrchestrateInputs:
+ """Empty on the first run. A continued run carries the tick's cutoff, deadlines, demand and pages."""
+
+ cutoff: str | None = None
+ deadline: str | None = None # stop starting pages after this
+ hard_deadline: str | None = None # the execution timeout lands here; no page may run past it
+ page: int = 0
+ demand: dict[SourceKind, list[str]] | None = None
+ pages: list[TickPage] | None = None
+ omitted: int = 0 # due work discovery left out of the bounded manifest; counted as remaining
+
+
+@frozen
+class OrchestrateResult:
+ pages: list[TickPage]
+ remaining: int
+ deadline_reached: bool
class DestinationType(StrEnum):
diff --git a/products/alerts/backend/facade/temporal.py b/products/alerts/backend/facade/temporal.py
index 538783bbae04..410cc6f95fb3 100644
--- a/products/alerts/backend/facade/temporal.py
+++ b/products/alerts/backend/facade/temporal.py
@@ -1,4 +1,4 @@
-from products.alerts.backend.temporal.schedule import create_alerts_product_check_due_schedule
+from products.alerts.backend.temporal.schedule import create_alerts_product_tick_schedule
from products.alerts.backend.temporal.telemetry import AlertsProductTelemetryInterceptor
from products.alerts.backend.temporal.workflows import (
DELIVERY_ACTIVITIES,
@@ -17,5 +17,5 @@ __all__ = [
"SHARED_ORCHESTRATION_ACTIVITIES",
"SHARED_ORCHESTRATION_WORKFLOWS",
"AlertsProductTelemetryInterceptor",
- "create_alerts_product_check_due_schedule",
+ "create_alerts_product_tick_schedule",
]
diff --git a/products/alerts/backend/logic/demand.py b/products/alerts/backend/logic/demand.py
index 13c9d1d74989..eaa08a261e45 100644
--- a/products/alerts/backend/logic/demand.py
+++ b/products/alerts/backend/logic/demand.py
@@ -44,13 +44,26 @@ def _synthetic_configurations(cutoff: dt.datetime) -> tuple[_SyntheticConfigurat
)
-def discover_synthetic_demand(cutoff: str) -> AlertDemand:
+# IDs per source in one manifest. A UUID is about 40 bytes in JSON, so this keeps each source near 40 KB,
+# well under the repository's 256 KB rule for Temporal payload fields. Work left out is due again next tick.
+DISCOVERY_LIMIT_PER_SOURCE = 1000
+
+
+def discover_synthetic_demand(cutoff: str, limit_per_source: int = DISCOVERY_LIMIT_PER_SOURCE) -> AlertDemand:
cutoff_time = dt.datetime.fromisoformat(cutoff)
if cutoff_time.utcoffset() is None:
raise ValueError("Demand discovery cutoff must include a timezone")
+ if limit_per_source < 1:
+ raise ValueError("Demand discovery limit must be at least 1")
configuration_ids_by_source: dict[SourceKind, list[str]] = {}
+ omitted_by_source: dict[SourceKind, int] = {}
for configuration in _synthetic_configurations(cutoff_time):
- if configuration.enabled and configuration.next_check_at <= cutoff_time:
- configuration_ids_by_source.setdefault(configuration.source_kind, []).append(configuration.id)
- return AlertDemand(configuration_ids_by_source=configuration_ids_by_source)
+ if not configuration.enabled or configuration.next_check_at > cutoff_time:
+ continue
+ ids = configuration_ids_by_source.setdefault(configuration.source_kind, [])
+ if len(ids) < limit_per_source:
+ ids.append(configuration.id)
+ else:
+ omitted_by_source[configuration.source_kind] = omitted_by_source.get(configuration.source_kind, 0) + 1
+ return AlertDemand(configuration_ids_by_source=configuration_ids_by_source, omitted_by_source=omitted_by_source)
diff --git a/products/alerts/backend/temporal/schedule.py b/products/alerts/backend/temporal/schedule.py
index 763485c1b0b6..e07f1d30f621 100644
--- a/products/alerts/backend/temporal/schedule.py
+++ b/products/alerts/backend/temporal/schedule.py
@@ -14,7 +14,7 @@ if TYPE_CHECKING:
SCHEDULE_ID = "alerts-product-check-due-schedule"
-async def create_alerts_product_check_due_schedule(client: "Client") -> None:
+async def create_alerts_product_tick_schedule(client: "Client") -> None:
if settings.CLOUD_DEPLOYMENT != "DEV":
return
diff --git a/products/alerts/backend/temporal/workflows.py b/products/alerts/backend/temporal/workflows.py
index b27381073304..6a43b4cc74f0 100644
--- a/products/alerts/backend/temporal/workflows.py
+++ b/products/alerts/backend/temporal/workflows.py
@@ -1,4 +1,7 @@
+import asyncio
import datetime as dt
+from collections.abc import Callable
+from dataclasses import replace
from temporalio import activity, workflow
from temporalio.common import RetryPolicy, SearchAttributeKey
@@ -13,13 +16,31 @@ with workflow.unsafe.imports_passed_through():
from asgiref.sync import sync_to_async
- from products.alerts.backend.facade.contracts import AlertDemand, DemandDiscoveryInputs
+ from products.alerts.backend.facade.contracts import (
+ AlertDemand,
+ DemandDiscoveryInputs,
+ OrchestrateInputs,
+ OrchestrateResult,
+ SourceDispatchInputs,
+ SourceDispatchReport,
+ TickPage,
+ )
from products.alerts.backend.logic.demand import discover_synthetic_demand
from products.alerts.backend.temporal.postgres import check_postgres_connection
POSTGRES_PROBE_FAILURE = "AlertsProductPostgresProbeFailure"
+# A tick stops starting pages once this much of its minute is spent. The schedule's 50-second
+# execution timeout is the backstop, and it spans continued runs.
+TICK_DISPATCH_BUDGET = dt.timedelta(seconds=45)
+# Where the hard stop is assumed when the run has no execution timeout of its own.
+TICK_HARD_STOP_MARGIN = dt.timedelta(seconds=5)
+# A dispatcher gets this long, or the time left before the hard stop, whichever is shorter.
+SOURCE_DISPATCH_TIMEOUT = dt.timedelta(seconds=30)
+# Time kept between a dispatcher's timeout and the hard stop, so the child closes first.
+SOURCE_DISPATCH_HEADROOM = dt.timedelta(seconds=1)
+
@frozen
class AlertsProductInputs:
@@ -32,7 +53,7 @@ async def alerts_product_discover_demand_activity(inputs: DemandDiscoveryInputs)
@activity.defn
-async def alerts_product_check_due_activity() -> None:
+async def alerts_product_probe_postgres_activity() -> None:
try:
await sync_to_async(check_postgres_connection, thread_sensitive=False)()
except (OperationalError, InterfaceError):
@@ -58,15 +79,15 @@ class AlertsProductDeliverWorkflow(PostHogWorkflow):
)
[email protected](name="alerts-product-check-due")
-class AlertsProductCheckDueWorkflow(PostHogWorkflow):
[email protected](name="alerts-product-evaluate")
+class AlertsProductEvaluateWorkflow(PostHogWorkflow):
inputs_cls = AlertsProductInputs
@workflow.run
async def run(self, inputs: AlertsProductInputs) -> None:
try:
await workflow.execute_activity(
- alerts_product_check_due_activity,
+ alerts_product_probe_postgres_activity,
task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,
start_to_close_timeout=dt.timedelta(seconds=10),
schedule_to_close_timeout=dt.timedelta(seconds=30),
@@ -93,37 +114,135 @@ class AlertsProductCheckDueWorkflow(PostHogWorkflow):
)
[email protected](name="alerts-product-source-dispatch")
+class AlertsProductSourceDispatchWorkflow(PostHogWorkflow):
+ """One run per source per page. Receives all of the source's remaining demand, starts one
+ evaluation child for it, and reports what it did not take. Today it takes everything: no
+ adapter has said yet how much one evaluation can hold, so nothing remains and a tick is one page.
+
+ Never waits for evaluation. The child is started with ABANDON so it outlives this
+ workflow and the tick that owns it.
+ """
+
+ inputs_cls = SourceDispatchInputs
+
+ @workflow.run
+ async def run(self, inputs: SourceDispatchInputs) -> SourceDispatchReport:
+ evaluation_workflow_id: str | None = None
+ if inputs.configuration_ids:
+ # Members are not passed to evaluation until claims exist. The probe path stays as is.
+ evaluation_workflow_id = f"{workflow.info().workflow_id}-eval"
+ await workflow.start_child_workflow(
+ AlertsProductEvaluateWorkflow.run,
+ AlertsProductInputs(),
+ id=evaluation_workflow_id,
+ task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,
+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,
+ execution_timeout=dt.timedelta(seconds=40),
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ return SourceDispatchReport(
+ source=inputs.source,
+ page=inputs.page,
+ dispatched=len(inputs.configuration_ids),
+ remaining_ids=[],
+ evaluation_workflow_id=evaluation_workflow_id,
+ )
+
+
+def _should_continue_as_new() -> bool:
+ return workflow.info().is_continue_as_new_suggested()
+
+
@workflow.defn(name="alerts-product-orchestrate")
class AlertsProductOrchestrateWorkflow(PostHogWorkflow):
- inputs_cls = AlertsProductInputs
+ """One minute tick. Discovers demand once, then pages source dispatchers until the demand is
+ exhausted or the dispatch budget is spent. Dispatchers are part of the tick: they keep the
+ default TERMINATE close policy and their reports are awaited. Evaluation is never awaited.
+ """
+
+ inputs_cls = OrchestrateInputs
+ inputs_optional = True
@workflow.run
- async def run(self, inputs: AlertsProductInputs) -> None:
- if workflow.patched("alerts-product-discover-demand-v1"):
- info = workflow.info()
+ async def run(self, inputs: OrchestrateInputs) -> OrchestrateResult:
+ info = workflow.info()
+ if inputs.cutoff is None or inputs.deadline is None or inputs.hard_deadline is None:
cutoff = info.typed_search_attributes.get(
SearchAttributeKey.for_datetime("TemporalScheduledStartTime"), info.workflow_start_time
)
- await workflow.execute_activity(
+ now = workflow.now()
+ hard_stop = info.execution_timeout or (TICK_DISPATCH_BUDGET + TICK_HARD_STOP_MARGIN)
+ inputs = replace(
+ inputs,
+ cutoff=cutoff.isoformat(),
+ deadline=(now + TICK_DISPATCH_BUDGET).isoformat(),
+ hard_deadline=(now + hard_stop).isoformat(),
+ )
+ assert inputs.cutoff is not None and inputs.deadline is not None and inputs.hard_deadline is not None
+ deadline = dt.datetime.fromisoformat(inputs.deadline)
+ hard_deadline = dt.datetime.fromisoformat(inputs.hard_deadline)
+
+ if inputs.demand is None:
+ discovered = await workflow.execute_activity(
alerts_product_discover_demand_activity,
- DemandDiscoveryInputs(cutoff=cutoff.isoformat()),
+ DemandDiscoveryInputs(cutoff=inputs.cutoff),
start_to_close_timeout=dt.timedelta(seconds=5),
schedule_to_close_timeout=dt.timedelta(seconds=10),
retry_policy=RetryPolicy(maximum_attempts=3),
)
- await workflow.execute_child_workflow(
- AlertsProductCheckDueWorkflow.run,
- inputs,
- id=f"alerts-product-check-due-{workflow.info().run_id}",
- task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,
- execution_timeout=dt.timedelta(seconds=40),
- retry_policy=RetryPolicy(maximum_attempts=1),
- )
+ demand = discovered.configuration_ids_by_source
+ inputs = replace(inputs, omitted=sum(discovered.omitted_by_source.values()))
+ else:
+ demand = inputs.demand
+
+ pages = list(inputs.pages or [])
+ page = inputs.page
+ while demand:
+ # Check before a page starts, and never give a page more time than is left before the hard stop.
+ # A tick always runs its first page: the deadline is a stop rule, not an admission rule.
+ now = workflow.now()
+ page_timeout = min(SOURCE_DISPATCH_TIMEOUT, hard_deadline - now - SOURCE_DISPATCH_HEADROOM)
+ if (pages and now >= deadline) or page_timeout < SOURCE_DISPATCH_HEADROOM:
+ workflow.logger.info("Tick dispatch budget spent with work remaining; the next tick takes it")
+ remaining = sum(len(ids) for ids in demand.values()) + inputs.omitted
+ return OrchestrateResult(pages=pages, remaining=remaining, deadline_reached=True)
+ handles = [
+ await workflow.start_child_workflow(
+ AlertsProductSourceDispatchWorkflow.run,
+ SourceDispatchInputs(
+ tick_id=info.workflow_id,
+ source=source,
+ page=page,
+ configuration_ids=configuration_ids,
+ ),
+ id=f"{info.workflow_id}-{source.value}-p{page}",
+ task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,
+ execution_timeout=page_timeout,
+ retry_policy=RetryPolicy(maximum_attempts=1),
+ )
+ for source, configuration_ids in sorted(demand.items())
+ ]
+ reports: list[SourceDispatchReport] = await asyncio.gather(*handles)
+ demand = {report.source: report.remaining_ids for report in reports if report.remaining_ids}
+ pages.append(
+ TickPage(
+ page=page,
+ run_id=info.run_id,
+ dispatched=sum(report.dispatched for report in reports),
+ remaining=sum(len(report.remaining_ids) for report in reports),
+ )
+ )
+ page += 1
+ if demand and _should_continue_as_new():
+ workflow.continue_as_new(replace(inputs, page=page, demand=demand, pages=pages))
+
+ return OrchestrateResult(pages=pages, remaining=inputs.omitted, deadline_reached=False)
-SHARED_ORCHESTRATION_WORKFLOWS = [AlertsProductOrchestrateWorkflow]
-SHARED_ORCHESTRATION_ACTIVITIES = [alerts_product_discover_demand_activity]
-EVALUATION_WORKFLOWS = [AlertsProductCheckDueWorkflow]
-EVALUATION_ACTIVITIES = [alerts_product_check_due_activity]
-DELIVERY_WORKFLOWS = [AlertsProductDeliverWorkflow]
-DELIVERY_ACTIVITIES = [alerts_product_deliver_activity]
+SHARED_ORCHESTRATION_WORKFLOWS: list[type[PostHogWorkflow]] = [AlertsProductOrchestrateWorkflow]
+SHARED_ORCHESTRATION_ACTIVITIES: list[Callable[..., object]] = [alerts_product_discover_demand_activity]
+EVALUATION_WORKFLOWS: list[type[PostHogWorkflow]] = [AlertsProductEvaluateWorkflow, AlertsProductSourceDispatchWorkflow]
+EVALUATION_ACTIVITIES: list[Callable[..., object]] = [alerts_product_probe_postgres_activity]
+DELIVERY_WORKFLOWS: list[type[PostHogWorkflow]] = [AlertsProductDeliverWorkflow]
+DELIVERY_ACTIVITIES: list[Callable[..., object]] = [alerts_product_deliver_activity]
diff --git a/products/alerts/backend/tests/test_temporal_dispatch.py b/products/alerts/backend/tests/test_temporal_dispatch.py
new file mode 100644
index 000000000000..4053e56d4b6d
--- /dev/null
+++ b/products/alerts/backend/tests/test_temporal_dispatch.py
@@ -0,0 +1,364 @@
+"""PR 2 rules, each asserted against a real Temporal test server:
+
+- the real dispatcher takes everything, starts one abandoned evaluation, and reports nothing remaining
+- discovery runs once per tick chain, never in a continued run
+- the tick awaits dispatcher reports and never an evaluation child
+- the tick exits cleanly with remaining work once its dispatch budget is spent
+- a dispatcher that overruns times out before the tick's hard stop; a started evaluation survives
+- a continued run carries the demand and skips discovery
+
+The paging rules use a test dispatcher registered under the real dispatcher's name. It takes one ID
+per run and reports the rest, which the real dispatcher cannot do until an adapter sets a limit.
+"""
+
+import uuid
+import asyncio
+import datetime as dt
+from collections.abc import AsyncIterator, Awaitable, Callable, Iterator
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from django.conf import settings
+
+import pytest_asyncio
+from temporalio import activity, workflow
+from temporalio.api.enums.v1 import EventType, ParentClosePolicy
+from temporalio.api.history.v1 import HistoryEvent
+from temporalio.client import Client, WorkflowExecutionStatus, WorkflowFailureError, WorkflowHistory
+from temporalio.exceptions import ChildWorkflowError, TimeoutError
+from temporalio.testing import WorkflowEnvironment
+from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker
+
+from products.alerts.backend.facade.contracts import (
+ AlertDemand,
+ DemandDiscoveryInputs,
+ OrchestrateInputs,
+ OrchestrateResult,
+ SourceDispatchInputs,
+ SourceDispatchReport,
+ SourceKind,
+)
+from products.alerts.backend.facade.temporal import (
+ EVALUATION_ACTIVITIES,
+ EVALUATION_WORKFLOWS,
+ SHARED_ORCHESTRATION_WORKFLOWS,
+)
+from products.alerts.backend.temporal import postgres, workflows
+from products.alerts.backend.temporal.workflows import (
+ AlertsProductEvaluateWorkflow,
+ AlertsProductInputs,
+ AlertsProductOrchestrateWorkflow,
+ AlertsProductSourceDispatchWorkflow,
+)
+
+ORCHESTRATION_QUEUE = settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE
+EVALUATION_QUEUE = settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE
+
+
[email protected](name="alerts-product-source-dispatch")
+class PagingDispatcher:
+ """Stands in for the real dispatcher: takes one ID per run, reports the rest. Same child edge."""
+
+ @workflow.run
+ async def run(self, inputs: SourceDispatchInputs) -> SourceDispatchReport:
+ await workflow.execute_activity(
+ "test_page_gate", inputs.configuration_ids, start_to_close_timeout=dt.timedelta(seconds=30)
+ )
+ evaluation_workflow_id = f"{workflow.info().workflow_id}-eval"
+ await workflow.start_child_workflow(
+ AlertsProductEvaluateWorkflow.run,
+ AlertsProductInputs(),
+ id=evaluation_workflow_id,
+ task_queue=EVALUATION_QUEUE,
+ parent_close_policy=workflow.ParentClosePolicy.ABANDON,
+ )
+ return SourceDispatchReport(
+ source=inputs.source,
+ page=inputs.page,
+ dispatched=1,
+ remaining_ids=inputs.configuration_ids[1:],
+ evaluation_workflow_id=evaluation_workflow_id,
+ )
+
+
+@pytest_asyncio.fixture(scope="module")
+async def environment() -> AsyncIterator[WorkflowEnvironment]:
+ async with await WorkflowEnvironment.start_time_skipping() as env:
+ yield env
+
+
+@pytest_asyncio.fixture(scope="module")
+async def local_environment() -> AsyncIterator[WorkflowEnvironment]:
+ """A real dev server. The time-skipping server does not cascade parent-close policies after a parent times out."""
+ async with await WorkflowEnvironment.start_local() as env:
+ yield env
+
+
[email protected](autouse=True)
+def postgres_cursor() -> Iterator[MagicMock]:
+ with patch.object(postgres, "execute_with_timeout") as execute:
+ execute.return_value.__enter__.return_value.fetchone.return_value = (1,)
+ yield execute.return_value.__enter__.return_value
+
+
+DiscoverActivity = Callable[[DemandDiscoveryInputs], Awaitable[AlertDemand]]
+GateActivity = Callable[[list[str]], Awaitable[None]]
+
+
+def demand_activity(
+ demand: dict[SourceKind, list[str]], omitted: dict[SourceKind, int] | None = None
+) -> DiscoverActivity:
+ @activity.defn(name="alerts_product_discover_demand_activity")
+ async def discover(inputs: DemandDiscoveryInputs) -> AlertDemand:
+ return AlertDemand(configuration_ids_by_source=demand, omitted_by_source=omitted or {})
+
+ return discover
+
+
[email protected](name="test_page_gate")
+async def open_gate(configuration_ids: list[str]) -> None:
+ pass
+
+
+def workers(
+ client: Client, discover: DiscoverActivity, *, paging: bool, gate: GateActivity = open_gate
+) -> tuple[Worker, Worker]:
+ runner = UnsandboxedWorkflowRunner()
+ evaluation_workflows: list[type] = (
+ [AlertsProductEvaluateWorkflow, PagingDispatcher] if paging else list(EVALUATION_WORKFLOWS)
+ )
+ return (
+ Worker(
+ client,
+ task_queue=ORCHESTRATION_QUEUE,
+ workflows=SHARED_ORCHESTRATION_WORKFLOWS,
+ activities=[discover],
+ workflow_runner=runner,
+ ),
+ Worker(
+ client,
+ task_queue=EVALUATION_QUEUE,
+ workflows=evaluation_workflows,
+ activities=[*EVALUATION_ACTIVITIES, gate],
+ workflow_runner=runner,
+ ),
+ )
+
+
+def events_of(history: WorkflowHistory, event_type: int) -> list[HistoryEvent]:
+ return [event for event in history.events if event.event_type == event_type]
+
+
+async def run_tick(client: Client, tick_id: str) -> OrchestrateResult:
+ return await client.execute_workflow(
+ AlertsProductOrchestrateWorkflow.run,
+ OrchestrateInputs(),
+ id=tick_id,
+ task_queue=ORCHESTRATION_QUEUE,
+ execution_timeout=dt.timedelta(seconds=50),
+ )
+
+
+async def test_real_dispatcher_takes_everything_and_abandons_one_evaluation(environment: WorkflowEnvironment) -> None:
+ client = environment.client
+ dispatcher_id = f"dispatch-{uuid.uuid4()}"
+ async with Worker(
+ client,
+ task_queue=EVALUATION_QUEUE,
+ workflows=EVALUATION_WORKFLOWS,
+ activities=EVALUATION_ACTIVITIES,
+ workflow_runner=UnsandboxedWorkflowRunner(),
+ ):
+ report: SourceDispatchReport = await client.execute_workflow(
+ AlertsProductSourceDispatchWorkflow.run,
+ SourceDispatchInputs(tick_id="tick", source=SourceKind.LOGS, page=0, configuration_ids=["a", "b", "c"]),
+ id=dispatcher_id,
+ task_queue=EVALUATION_QUEUE,
+ execution_timeout=dt.timedelta(seconds=30),
+ )
+ assert report == SourceDispatchReport(
+ source=SourceKind.LOGS,
+ page=0,
+ dispatched=3,
+ remaining_ids=[],
+ evaluation_workflow_id=f"{dispatcher_id}-eval",
+ )
+ history = await client.get_workflow_handle(dispatcher_id).fetch_history()
+ assert events_of(history, EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED) == []
+ initiated = events_of(history, EventType.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED)
+ assert len(initiated) == 1
+ child = initiated[0].start_child_workflow_execution_initiated_event_attributes
+ assert child.workflow_type.name == "alerts-product-evaluate"
+ assert child.parent_close_policy == ParentClosePolicy.PARENT_CLOSE_POLICY_ABANDON
+ assert child.workflow_execution_timeout.ToTimedelta() == dt.timedelta(seconds=40)
+ # The dispatcher completed without waiting for the evaluation; the evaluation finishes on its own.
+ assert events_of(history, EventType.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_COMPLETED) == []
+ evaluation = client.get_workflow_handle(f"{dispatcher_id}-eval")
+ assert await evaluation.result() is None
+ assert (await evaluation.describe()).status == WorkflowExecutionStatus.COMPLETED
+
+
+async def test_tick_with_real_dispatchers_is_one_page(environment: WorkflowEnvironment) -> None:
+ client = environment.client
+ tick_id = f"tick-{uuid.uuid4()}"
+ demand = {SourceKind.LOGS: ["l1", "l2", "l3"], SourceKind.INSIGHT: ["i1"]}
+ orchestration, evaluation = workers(client, demand_activity(demand), paging=False)
+ async with orchestration, evaluation:
+ result = await run_tick(client, tick_id)
+ assert [(page.page, page.dispatched, page.remaining) for page in result.pages] == [(0, 4, 0)]
+ assert result == OrchestrateResult(pages=result.pages, remaining=0, deadline_reached=False)
+
+
+async def test_tick_counts_omitted_demand_as_remaining(environment: WorkflowEnvironment) -> None:
+ """Discovery bounds its manifest. What it left out is still due, so the tick reports it as remaining."""
+ client = environment.client
+ tick_id = f"tick-{uuid.uuid4()}"
+ orchestration, evaluation = workers(
+ client, demand_activity({SourceKind.LOGS: ["l1"]}, omitted={SourceKind.LOGS: 5}), paging=False
+ )
+ async with orchestration, evaluation:
+ result = await run_tick(client, tick_id)
+ assert [(page.page, page.dispatched, page.remaining) for page in result.pages] == [(0, 1, 0)]
+ assert result.remaining == 5 and not result.deadline_reached
+
+
+async def test_tick_pages_until_demand_is_exhausted(environment: WorkflowEnvironment) -> None:
+ client = environment.client
+ tick_id = f"tick-{uuid.uuid4()}"
+ demand = {SourceKind.LOGS: ["l1", "l2", "l3"], SourceKind.INSIGHT: ["i1"]}
+ orchestration, evaluation = workers(client, demand_activity(demand), paging=True)
+ async with orchestration, evaluation:
+ result = await run_tick(client, tick_id)
+ assert [(page.page, page.dispatched, page.remaining) for page in result.pages] == [
+ (0, 2, 2),
+ (1, 1, 1),
+ (2, 1, 0),
+ ]
+ assert result.remaining == 0 and not result.deadline_reached
+ assert len({page.run_id for page in result.pages}) == 1
+
+ history = await client.get_workflow_handle(tick_id).fetch_history()
+ await Replayer(
+ workflows=SHARED_ORCHESTRATION_WORKFLOWS, workflow_runner=UnsandboxedWorkflowRunner()
+ ).replay_workflow(history)
+ scheduled = events_of(history, EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED)
+ assert [event.activity_task_scheduled_event_attributes.activity_type.name for event in scheduled] == [
+ "alerts_product_discover_demand_activity"
+ ]
+ started = events_of(history, EventType.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_STARTED)
+ children = {
+ event.child_workflow_execution_started_event_attributes.workflow_execution.workflow_id: (
+ event.child_workflow_execution_started_event_attributes.workflow_type.name
+ )
+ for event in started
+ }
+ assert children == {
+ f"{tick_id}-insight-p0": "alerts-product-source-dispatch",
+ f"{tick_id}-logs-p0": "alerts-product-source-dispatch",
+ f"{tick_id}-logs-p1": "alerts-product-source-dispatch",
+ f"{tick_id}-logs-p2": "alerts-product-source-dispatch",
+ }
+ for event in events_of(history, EventType.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED):
+ attributes = event.start_child_workflow_execution_initiated_event_attributes
+ assert attributes.parent_close_policy == ParentClosePolicy.PARENT_CLOSE_POLICY_TERMINATE
+ assert attributes.task_queue.name == EVALUATION_QUEUE
+ assert attributes.workflow_execution_timeout.ToTimedelta() == dt.timedelta(seconds=30)
+ # The tick awaited every dispatcher report. Evaluations are grandchildren and never awaited here.
+ assert len(events_of(history, EventType.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_COMPLETED)) == 4
+ for dispatcher_id in children:
+ evaluation_status = (await client.get_workflow_handle(f"{dispatcher_id}-eval").describe()).status
+ assert evaluation_status == WorkflowExecutionStatus.COMPLETED
+
+
+async def test_tick_exits_cleanly_when_dispatch_budget_is_spent(environment: WorkflowEnvironment) -> None:
+ client = environment.client
+ tick_id = f"tick-{uuid.uuid4()}"
+ orchestration, evaluation = workers(client, demand_activity({SourceKind.LOGS: ["l1", "l2", "l3"]}), paging=True)
+ with patch.object(workflows, "TICK_DISPATCH_BUDGET", dt.timedelta(0)):
+ async with orchestration, evaluation:
+ result = await run_tick(client, tick_id)
+ assert result.deadline_reached
+ assert [(page.page, page.dispatched, page.remaining) for page in result.pages] == [(0, 1, 2)]
+ assert result.remaining == 2
+ assert (await client.get_workflow_handle(tick_id).describe()).status == WorkflowExecutionStatus.COMPLETED
+
+
+async def test_continued_run_carries_demand_and_skips_discovery(environment: WorkflowEnvironment) -> None:
+ client = environment.client
+ tick_id = f"tick-{uuid.uuid4()}"
+ orchestration, evaluation = workers(client, demand_activity({SourceKind.LOGS: ["l1", "l2"]}), paging=True)
+ with patch.object(workflows, "_should_continue_as_new", return_value=True):
+ async with orchestration, evaluation:
+ result = await run_tick(client, tick_id)
+ run_ids = [page.run_id for page in result.pages]
+ assert len(result.pages) == 2 and run_ids[0] != run_ids[1]
+ assert result.remaining == 0
+
+ first = await client.get_workflow_handle(tick_id, run_id=run_ids[0]).fetch_history()
+ assert first.events[-1].event_type == EventType.EVENT_TYPE_WORKFLOW_EXECUTION_CONTINUED_AS_NEW
+ assert len(events_of(first, EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED)) == 1
+ continued = first.events[-1].workflow_execution_continued_as_new_event_attributes
+ carried = await client.data_converter.decode(continued.input.payloads, [OrchestrateInputs])
+ assert carried[0].demand == {SourceKind.LOGS: ["l2"]}
+ assert carried[0].page == 1 and carried[0].cutoff is not None
+ assert carried[0].deadline is not None and carried[0].hard_deadline is not None
+
+ second = await client.get_workflow_handle(tick_id, run_id=run_ids[1]).fetch_history()
+ assert events_of(second, EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED) == []
+ assert len(events_of(second, EventType.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_STARTED)) == 1
+
+
+async def test_overrunning_dispatcher_times_out_before_the_tick_hard_stop(
+ local_environment: WorkflowEnvironment,
+) -> None:
+ """The tick has a 3 s execution timeout, so each page gets at most 2 s. Page 1 blocks. Its dispatcher
+ times out first, the tick fails with that child error instead of being terminated mid-page, and
+ the evaluation page 0 started keeps running."""
+ client = local_environment.client
+ tick_id = f"tick-{uuid.uuid4()}"
+ page_one_started = asyncio.Event()
+ release = asyncio.Event()
+
+ @activity.defn(name="test_page_gate")
+ async def block_page_one(configuration_ids: list[str]) -> None:
+ if configuration_ids == ["l2"]:
+ page_one_started.set()
+ await release.wait()
+
+ orchestration, evaluation = workers(
+ client, demand_activity({SourceKind.LOGS: ["l1", "l2"]}), paging=True, gate=block_page_one
+ )
+ async with orchestration, evaluation:
+ handle = await client.start_workflow(
+ AlertsProductOrchestrateWorkflow.run,
+ OrchestrateInputs(),
+ id=tick_id,
+ task_queue=ORCHESTRATION_QUEUE,
+ execution_timeout=dt.timedelta(seconds=3),
+ )
+ await asyncio.wait_for(page_one_started.wait(), timeout=20)
+ with pytest.raises(WorkflowFailureError) as failure:
+ await handle.result()
+ release.set() # let the blocked activity return so the worker can shut down
+ assert isinstance(failure.value.cause, ChildWorkflowError)
+ assert isinstance(failure.value.cause.cause, TimeoutError)
+
+ tick_status = (await handle.describe()).status
+ statuses = {
+ name: (await client.get_workflow_handle(f"{tick_id}-{name}").describe()).status
+ for name in ("logs-p0", "logs-p1", "logs-p0-eval")
+ }
+ page_one = await client.get_workflow_handle(f"{tick_id}-logs-p1").describe()
+ evaluation_history = await client.get_workflow_handle(f"{tick_id}-logs-p0-eval").fetch_history()
+ delivery_id = events_of(evaluation_history, EventType.EVENT_TYPE_CHILD_WORKFLOW_EXECUTION_STARTED)[
+ 0
+ ].child_workflow_execution_started_event_attributes.workflow_execution.workflow_id
+ delivery_status = (await client.get_workflow_handle(delivery_id).describe()).status
+ assert tick_status == WorkflowExecutionStatus.FAILED # its own child error, not the execution timeout
+ assert statuses["logs-p0"] == WorkflowExecutionStatus.COMPLETED
+ assert statuses["logs-p1"] == WorkflowExecutionStatus.TIMED_OUT
+ assert page_one.start_time is not None and page_one.close_time is not None
+ assert page_one.close_time - page_one.start_time < dt.timedelta(seconds=3)
+ assert statuses["logs-p0-eval"] == WorkflowExecutionStatus.COMPLETED
+ assert delivery_status == WorkflowExecutionStatus.RUNNING # abandoned grandchild, no delivery worker here
diff --git a/products/alerts/backend/tests/test_temporal_postgres.py b/products/alerts/backend/tests/test_temporal_postgres.py
index 78cd067a18cc..30836ec4a7ef 100644
--- a/products/alerts/backend/tests/test_temporal_postgres.py
+++ b/products/alerts/backend/tests/test_temporal_postgres.py
@@ -18,7 +18,7 @@ from temporalio.exceptions import ApplicationError, CancelledError
from temporalio.testing import ActivityEnvironment
from products.alerts.backend.temporal import postgres
-from products.alerts.backend.temporal.workflows import POSTGRES_PROBE_FAILURE, alerts_product_check_due_activity
+from products.alerts.backend.temporal.workflows import POSTGRES_PROBE_FAILURE, alerts_product_probe_postgres_activity
if TYPE_CHECKING:
from pytest_django.fixtures import Settings
@@ -62,11 +62,11 @@ async def test_probe_uses_database_thread_and_sanitizes_only_expected_errors(
):
environment = ActivityEnvironment()
if error is None:
- await environment.run(alerts_product_check_due_activity)
+ await environment.run(alerts_product_probe_postgres_activity)
cursor.fetchone.assert_called_once_with()
elif isinstance(error, (OperationalError, InterfaceError)):
with pytest.raises(ApplicationError) as caught:
- await environment.run(alerts_product_check_due_activity)
+ await environment.run(alerts_product_probe_postgres_activity)
assert caught.value.type == POSTGRES_PROBE_FAILURE
failure = Failure()
DefaultFailureConverter().to_failure(caught.value, DefaultPayloadConverter(), failure)
@@ -74,7 +74,7 @@ async def test_probe_uses_database_thread_and_sanitizes_only_expected_errors(
assert "sensitive" not in str(failure)
else:
with pytest.raises(type(error)) as caught_unrelated:
- await environment.run(alerts_product_check_due_activity)
+ await environment.run(alerts_product_probe_postgres_activity)
assert caught_unrelated.value is error
cursor.execute.assert_called_once_with("SELECT 1")
@@ -114,10 +114,10 @@ async def test_probe_cancellation_and_concurrent_activity_cleanup(settings: Sett
patch.object(postgres, "execute_with_timeout", execute_with_timeout),
patch("django.db.connections.all", return_value=[connection]),
):
- task = asyncio.create_task(ActivityEnvironment().run(alerts_product_check_due_activity))
+ task = asyncio.create_task(ActivityEnvironment().run(alerts_product_probe_postgres_activity))
try:
await asyncio.wait_for(entered.wait(), timeout=5)
- await asyncio.wait_for(ActivityEnvironment().run(alerts_product_check_due_activity), timeout=5)
+ await asyncio.wait_for(ActivityEnvironment().run(alerts_product_probe_postgres_activity), timeout=5)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
diff --git a/products/alerts/backend/tests/test_temporal_schedule.py b/products/alerts/backend/tests/test_temporal_schedule.py
index 7c22c0ba7758..a4f79bc46ba6 100644
--- a/products/alerts/backend/tests/test_temporal_schedule.py
+++ b/products/alerts/backend/tests/test_temporal_schedule.py
@@ -7,7 +7,7 @@ from django.test import override_settings
from temporalio.client import Client, ScheduleActionStartWorkflow, ScheduleOverlapPolicy, ScheduleState
-from products.alerts.backend.temporal.schedule import SCHEDULE_ID, create_alerts_product_check_due_schedule
+from products.alerts.backend.temporal.schedule import SCHEDULE_ID, create_alerts_product_tick_schedule
MODULE = "products.alerts.backend.temporal.schedule"
@@ -22,7 +22,7 @@ async def test_schedule_does_not_access_temporal_outside_dev(deployment: str | N
patch(f"{MODULE}.a_create_schedule") as create,
patch(f"{MODULE}.a_update_schedule") as update,
):
- await create_alerts_product_check_due_schedule(client)
+ await create_alerts_product_tick_schedule(client)
exists.assert_not_awaited()
create.assert_not_awaited()
update.assert_not_awaited()
@@ -46,7 +46,7 @@ async def test_dev_schedule_creates_or_updates_with_bounded_policy(already_exist
patch(f"{MODULE}.a_create_schedule") as create,
patch(f"{MODULE}.a_update_schedule") as update,
):
- await create_alerts_product_check_due_schedule(client)
+ await create_alerts_product_tick_schedule(client)
exists.assert_awaited_once_with(client, SCHEDULE_ID)
called = update if already_exists else create
diff --git a/products/alerts/backend/tests/test_temporal_workflows.py b/products/alerts/backend/tests/test_temporal_workflows.py
index 8cf2912363fb..29545ab6fa14 100644
--- a/products/alerts/backend/tests/test_temporal_workflows.py
+++ b/products/alerts/backend/tests/test_temporal_workflows.py
@@ -3,7 +3,6 @@ import asyncio
import logging
import datetime as dt
from collections.abc import AsyncIterator, Iterator
-from contextlib import nullcontext
from typing import Literal
import pytest
@@ -32,7 +31,13 @@ from temporalio.runtime import MetricBuffer, Runtime, TelemetryConfig
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Replayer, UnsandboxedWorkflowRunner, Worker
-from products.alerts.backend.facade.contracts import AlertDemand, DemandDiscoveryInputs, SourceKind
+from products.alerts.backend.facade.contracts import (
+ AlertDemand,
+ DemandDiscoveryInputs,
+ OrchestrateInputs,
+ OrchestrateResult,
+ SourceKind,
+)
from products.alerts.backend.facade.temporal import (
DELIVERY_ACTIVITIES,
DELIVERY_WORKFLOWS,
@@ -45,7 +50,7 @@ from products.alerts.backend.facade.temporal import (
from products.alerts.backend.logic import demand
from products.alerts.backend.temporal import postgres
from products.alerts.backend.temporal.workflows import (
- AlertsProductCheckDueWorkflow,
+ AlertsProductEvaluateWorkflow,
AlertsProductInputs,
AlertsProductOrchestrateWorkflow,
)
@@ -55,7 +60,7 @@ from products.alerts.backend.temporal.workflows import (
class CloseAfterChildStartWorkflow:
@workflow.run
async def run(self, close_mode: str) -> None:
- await AlertsProductCheckDueWorkflow().run(AlertsProductInputs())
+ await AlertsProductEvaluateWorkflow().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)
@@ -88,14 +93,6 @@ def postgres_cursor() -> Iterator[MagicMock]:
@pytest.mark.asyncio
@pytest.mark.parametrize("database_error", [False, True])
- "tick_workflow, tick_queue, demand_enabled",
- [
- ("alerts-product-check-due", settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE, False),
- ("alerts-product-orchestrate", settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE, True),
- ("alerts-product-orchestrate", settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE, False),
- ],
-)
async def test_each_tick_starts_independent_delivery(
environment: WorkflowEnvironment,
caplog: pytest.LogCaptureFixture,
@@ -104,9 +101,6 @@ async def test_each_tick_starts_independent_delivery(
activity_logs,
postgres_cursor: MagicMock,
database_error: bool,
- tick_workflow: str,
- tick_queue: str,
- demand_enabled: bool,
) -> None:
if database_error:
postgres_cursor.execute.side_effect = OperationalError("sensitive connection details")
@@ -141,63 +135,16 @@ async def test_each_tick_starts_independent_delivery(
),
):
for _ in range(2):
- with nullcontext() if demand_enabled else patch.object(workflow, "patched", return_value=False):
- parent = await client.start_workflow(
- tick_workflow,
- AlertsProductInputs(),
- id=workflow_id,
- task_queue=tick_queue,
- execution_timeout=dt.timedelta(seconds=10),
- )
- assert await parent.result() is None
+ parent = await client.start_workflow(
+ "alerts-product-evaluate",
+ 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()
evaluation_run_id = parent.first_execution_run_id
- if tick_workflow == "alerts-product-orchestrate":
- discovery_events = [
- event.activity_task_scheduled_event_attributes
- for event in history.events
- if event.event_type == EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED
- ]
- assert len(discovery_events) == int(demand_enabled)
- if demand_enabled:
- assert discovery_events[0].activity_type.name == "alerts_product_discover_demand_activity"
- assert (
- discovery_events[0].task_queue.name == settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE
- )
- discovery_inputs = await client.data_converter.decode(
- discovery_events[0].input.payloads, [DemandDiscoveryInputs]
- )
- assert dt.datetime.fromisoformat(discovery_inputs[0].cutoff) == history.events[
- 0
- ].event_time.ToDatetime(tzinfo=dt.UTC)
- completed_discovery = next(
- event.activity_task_completed_event_attributes
- for event in history.events
- if event.event_type == EventType.EVENT_TYPE_ACTIVITY_TASK_COMPLETED
- )
- discovered = await client.data_converter.decode(completed_discovery.result.payloads, [AlertDemand])
- assert discovered[0] == demand.discover_synthetic_demand(discovery_inputs[0].cutoff)
- await Replayer(
- workflows=SHARED_ORCHESTRATION_WORKFLOWS, workflow_runner=UnsandboxedWorkflowRunner()
- ).replay_workflow(history)
- evaluations = [
- event.start_child_workflow_execution_initiated_event_attributes
- for event in history.events
- if event.event_type == EventType.EVENT_TYPE_START_CHILD_WORKFLOW_EXECUTION_INITIATED
- ]
- assert len(evaluations) == 1
- evaluation_event = evaluations[0]
- assert evaluation_event.workflow_type.name == "alerts-product-check-due"
- assert evaluation_event.task_queue.name == settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE
- assert evaluation_event.workflow_execution_timeout.ToTimedelta() == dt.timedelta(seconds=40)
- assert evaluation_event.retry_policy.maximum_attempts == 1
- assert parent.first_execution_run_id is not None
- assert parent.first_execution_run_id in evaluation_event.workflow_id
- evaluation_handle = client.get_workflow_handle(evaluation_event.workflow_id)
- evaluation_description = await evaluation_handle.describe()
- assert evaluation_description.status == WorkflowExecutionStatus.COMPLETED
- evaluation_run_id = evaluation_description.run_id
- history = await evaluation_handle.fetch_history()
scheduled = [
event.activity_task_scheduled_event_attributes
for event in history.events
@@ -253,7 +200,7 @@ async def test_each_tick_starts_independent_delivery(
updates = sdk_metrics.retrieve_updates()
for metric_name in ("temporal_activity_schedule_to_start_latency", "temporal_activity_execution_latency"):
for task_queue, expected_attempts in (
- (settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE, 2 if demand_enabled else 0),
+ (settings.ALERTS_PRODUCT_SHARED_ORCHESTRATION_TASK_QUEUE, 0),
(settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE, 2),
(settings.ALERTS_PRODUCT_DELIVERY_TASK_QUEUE, 4),
):
@@ -270,26 +217,18 @@ async def test_each_tick_starts_independent_delivery(
assert len(spans_by_id) == len(spans)
workflow_spans = [span for span in spans if span.name.startswith("RunWorkflow:")]
activity_spans = [span for span in spans if span.name.startswith("RunActivity:")]
- assert len(workflow_spans) == (6 if tick_workflow == "alerts-product-orchestrate" else 4)
- assert len(activity_spans) == (8 if demand_enabled else 6)
+ assert len(workflow_spans) == 4
+ assert len(activity_spans) == 6
for delivery in (span for span in workflow_spans if span.name == "RunWorkflow:alerts-product-deliver"):
assert delivery.parent is not None
child_start = spans_by_id[delivery.parent.span_id]
assert child_start.parent is not None
evaluation = spans_by_id[child_start.parent.span_id]
assert child_start.name == "StartChildWorkflow:alerts-product-deliver"
- assert evaluation.name == "RunWorkflow:alerts-product-check-due"
+ assert evaluation.name == "RunWorkflow:alerts-product-evaluate"
assert delivery.context.trace_id == child_start.context.trace_id == evaluation.context.trace_id
assert evaluation.end_time is not None and delivery.start_time is not None
assert evaluation.end_time <= delivery.start_time
- if tick_workflow == "alerts-product-orchestrate":
- assert evaluation.parent is not None
- evaluation_start = spans_by_id[evaluation.parent.span_id]
- assert evaluation_start.name == "StartChildWorkflow:alerts-product-check-due"
- assert evaluation_start.parent is not None
- orchestration = spans_by_id[evaluation_start.parent.span_id]
- assert orchestration.name == "RunWorkflow:alerts-product-orchestrate"
- assert evaluation.context.trace_id == evaluation_start.context.trace_id == orchestration.context.trace_id
for attempt_span in activity_spans:
assert attempt_span.parent is not None
activity_start = spans_by_id[attempt_span.parent.span_id]
@@ -305,9 +244,6 @@ async def test_each_tick_starts_independent_delivery(
for entry in activity_logs
if entry.get("span_id") == trace.format_span_id(attempt_span.context.span_id)
]
- if attempt_span.name == "RunActivity:alerts_product_discover_demand_activity":
- assert entries == []
- continue
assert [entry["event"] for entry in entries] == [
"alerts_product_activity_started",
"alerts_product_activity_finished",
@@ -318,7 +254,7 @@ async def test_each_tick_starts_independent_delivery(
"failure"
if (
(attempt_span.name == "RunActivity:alerts_product_deliver_activity" and entries[1]["attempt"] == 1)
- or (attempt_span.name == "RunActivity:alerts_product_check_due_activity" and database_error)
+ or (attempt_span.name == "RunActivity:alerts_product_probe_postgres_activity" and database_error)
)
else "success"
)
@@ -382,7 +318,7 @@ async def test_probe_timeout_still_starts_independent_delivery(
activity_started = asyncio.Event()
release_activity = asyncio.Event()
- @activity.defn(name="alerts_product_check_due_activity")
+ @activity.defn(name="alerts_product_probe_postgres_activity")
async def blocked_probe() -> None:
activity_started.set()
await release_activity.wait()
@@ -395,7 +331,7 @@ async def test_probe_timeout_still_starts_independent_delivery(
workflow_runner=UnsandboxedWorkflowRunner(),
):
parent = await client.start_workflow(
- AlertsProductCheckDueWorkflow.run,
+ AlertsProductEvaluateWorkflow.run,
AlertsProductInputs(),
id=str(uuid.uuid4()),
task_queue=settings.ALERTS_PRODUCT_EVALUATION_TASK_QUEUE,
@@ -460,7 +396,7 @@ async def test_probe_unrelated_activity_failures_do_not_start_delivery(cause: Ex
scheduled_event_id=1,
started_event_id=2,
identity="test-worker",
- activity_type="alerts_product_check_due_activity",
+ activity_type="alerts_product_probe_postgres_activity",
activity_id="1",
retry_state=None,
)
@@ -470,7 +406,7 @@ async def test_probe_unrelated_activity_failures_do_not_start_delivery(cause: Ex
patch.object(workflow, "start_child_workflow", AsyncMock()) as start_delivery,
pytest.raises(ActivityError) as caught,
):
- await AlertsProductCheckDueWorkflow().run(AlertsProductInputs())
+ await AlertsProductEvaluateWorkflow().run(AlertsProductInputs())
assert caught.value is error
start_delivery.assert_not_awaited()
@@ -481,7 +417,7 @@ async def test_probe_workflow_cancellation_does_not_start_delivery() -> None:
patch.object(workflow, "start_child_workflow", AsyncMock()) as start_delivery,
pytest.raises(asyncio.CancelledError),
):
- await AlertsProductCheckDueWorkflow().run(AlertsProductInputs())
+ await AlertsProductEvaluateWorkflow().run(AlertsProductInputs())
start_delivery.assert_not_awaited()
@@ -516,6 +452,21 @@ def test_discovery_rejects_invalid_cutoff(cutoff: str) -> None:
demand.discover_synthetic_demand(cutoff)
+def test_discovery_bounds_ids_per_source_and_counts_the_rest() -> None:
+ cutoff = dt.datetime(2026, 9, 16, 10, tzinfo=dt.UTC).isoformat()
+ bounded = demand.discover_synthetic_demand(cutoff, limit_per_source=1)
+ assert bounded == AlertDemand(
+ configuration_ids_by_source={
+ SourceKind.LOGS: ["00000000-0000-4000-8000-000000000001"],
+ SourceKind.INSIGHT: ["00000000-0000-4000-8000-000000000003"],
+ },
+ omitted_by_source={SourceKind.LOGS: 1},
+ )
+ assert demand.discover_synthetic_demand(cutoff).omitted_by_source == {}
+ with pytest.raises(ValueError):
+ demand.discover_synthetic_demand(cutoff, limit_per_source=0)
+
+
@pytest.mark.parametrize("scheduled", [False, True])
async def test_discovery_uses_scheduled_cutoff_or_manual_start(scheduled: bool) -> None:
tick_time = dt.datetime(2026, 9, 16, 10, tzinfo=dt.UTC)
@@ -525,20 +476,25 @@ async def test_discovery_uses_scheduled_cutoff_or_manual_start(scheduled: bool)
if scheduled
else []
)
+ info = MagicMock(
+ workflow_start_time=actual_start,
+ typed_search_attributes=attributes,
+ workflow_id="tick",
+ run_id="run",
+ execution_timeout=None,
+ )
with (
+ patch.object(workflow, "info", return_value=info),
+ patch.object(workflow, "now", return_value=actual_start),
patch.object(
- workflow,
- "info",
- return_value=MagicMock(workflow_start_time=actual_start, typed_search_attributes=attributes),
- ),
- patch.object(workflow, "patched", return_value=True),
- patch.object(workflow, "execute_activity", AsyncMock()) as discover,
- patch.object(workflow, "execute_child_workflow", AsyncMock()) as evaluate,
+ workflow, "execute_activity", AsyncMock(return_value=AlertDemand(configuration_ids_by_source={}))
+ ) as discover,
+ patch.object(workflow, "start_child_workflow", AsyncMock()) as dispatch,
):
- await AlertsProductOrchestrateWorkflow().run(AlertsProductInputs())
+ result = await AlertsProductOrchestrateWorkflow().run(OrchestrateInputs())
assert discover.await_args is not None
assert discover.await_args.args[1] == DemandDiscoveryInputs(
cutoff=(tick_time if scheduled else actual_start).isoformat()
)
- assert evaluate.await_args is not None
- assert evaluate.await_args.args[1] == AlertsProductInputs()
+ dispatch.assert_not_awaited()
+ assert result == OrchestrateResult(pages=[], remaining=0, deadline_reached=False)